text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import type { ParserOptions, TransformOptions, types as t } from '@babel/core'
import * as babel from '@babel/core'
import { createFilter } from '@rollup/pluginutils'
import resolve from 'resolve'
import type { Plugin, PluginOption } from 'vite'
import {
addRefreshWrapper,
isRefreshBoundary,
preambleCode,
runtimeCode,
runtimePublicPath
} from './fast-refresh'
import { babelImportToRequire } from './jsx-runtime/babel-import-to-require'
import { restoreJSX } from './jsx-runtime/restore-jsx'
export interface Options {
include?: string | RegExp | Array<string | RegExp>
exclude?: string | RegExp | Array<string | RegExp>
/**
* Enable `react-refresh` integration. Vite disables this in prod env or build mode.
* @default true
*/
fastRefresh?: boolean
/**
* Set this to `"automatic"` to use [vite-react-jsx](https://github.com/alloc/vite-react-jsx).
* @default "automatic"
*/
jsxRuntime?: 'classic' | 'automatic'
/**
* Control where the JSX factory is imported from.
* This option is ignored when `jsxRuntime` is not `"automatic"`.
* @default "react"
*/
jsxImportSource?: string
/**
* Set this to `true` to annotate the JSX factory with `\/* @__PURE__ *\/`.
* This option is ignored when `jsxRuntime` is not `"automatic"`.
* @default true
*/
jsxPure?: boolean
/**
* Babel configuration applied in both dev and prod.
*/
babel?: BabelOptions
}
export type BabelOptions = Omit<
TransformOptions,
| 'ast'
| 'filename'
| 'root'
| 'sourceFileName'
| 'sourceMaps'
| 'inputSourceMap'
>
/**
* The object type used by the `options` passed to plugins with
* an `api.reactBabel` method.
*/
export interface ReactBabelOptions extends BabelOptions {
plugins: Extract<BabelOptions['plugins'], any[]>
presets: Extract<BabelOptions['presets'], any[]>
overrides: Extract<BabelOptions['overrides'], any[]>
parserOpts: ParserOptions & {
plugins: Extract<ParserOptions['plugins'], any[]>
}
}
declare module 'vite' {
export interface Plugin {
api?: {
/**
* Manipulate the Babel options of `@vitejs/plugin-react`
*/
reactBabel?: (options: ReactBabelOptions, config: ResolvedConfig) => void
}
}
}
export default function viteReact(opts: Options = {}): PluginOption[] {
// Provide default values for Rollup compat.
let base = '/'
let filter = createFilter(opts.include, opts.exclude)
let isProduction = true
let projectRoot = process.cwd()
let skipFastRefresh = opts.fastRefresh === false
let skipReactImport = false
const useAutomaticRuntime = opts.jsxRuntime !== 'classic'
const babelOptions = {
babelrc: false,
configFile: false,
...opts.babel
} as ReactBabelOptions
babelOptions.plugins ||= []
babelOptions.presets ||= []
babelOptions.overrides ||= []
babelOptions.parserOpts ||= {} as any
babelOptions.parserOpts.plugins ||= []
// Support patterns like:
// - import * as React from 'react';
// - import React from 'react';
// - import React, {useEffect} from 'react';
const importReactRE = /(^|\n)import\s+(\*\s+as\s+)?React(,|\s+)/
// Any extension, including compound ones like '.bs.js'
const fileExtensionRE = /\.[^\/\s\?]+$/
const viteBabel: Plugin = {
name: 'vite:react-babel',
enforce: 'pre',
configResolved(config) {
base = config.base
projectRoot = config.root
filter = createFilter(opts.include, opts.exclude, {
resolve: projectRoot
})
isProduction = config.isProduction
skipFastRefresh ||= isProduction || config.command === 'build'
const jsxInject = config.esbuild && config.esbuild.jsxInject
if (jsxInject && importReactRE.test(jsxInject)) {
skipReactImport = true
config.logger.warn(
'[@vitejs/plugin-react] This plugin imports React for you automatically,' +
' so you can stop using `esbuild.jsxInject` for that purpose.'
)
}
config.plugins.forEach((plugin) => {
const hasConflict =
plugin.name === 'react-refresh' ||
(plugin !== viteReactJsx && plugin.name === 'vite:react-jsx')
if (hasConflict)
return config.logger.warn(
`[@vitejs/plugin-react] You should stop using "${plugin.name}" ` +
`since this plugin conflicts with it.`
)
if (plugin.api?.reactBabel) {
plugin.api.reactBabel(babelOptions, config)
}
})
},
async transform(code, id, options) {
const ssr = typeof options === 'boolean' ? options : options?.ssr === true
// File extension could be mocked/overriden in querystring.
const [filepath, querystring = ''] = id.split('?')
const [extension = ''] =
querystring.match(fileExtensionRE) ||
filepath.match(fileExtensionRE) ||
[]
if (/\.(mjs|[tj]sx?)$/.test(extension)) {
const isJSX = extension.endsWith('x')
const isNodeModules = id.includes('/node_modules/')
const isProjectFile =
!isNodeModules && (id[0] === '\0' || id.startsWith(projectRoot + '/'))
const plugins = isProjectFile ? [...babelOptions.plugins] : []
let useFastRefresh = false
if (!skipFastRefresh && !ssr && !isNodeModules) {
// Modules with .js or .ts extension must import React.
const isReactModule = isJSX || importReactRE.test(code)
if (isReactModule && filter(id)) {
useFastRefresh = true
plugins.push([
await loadPlugin('react-refresh/babel'),
{ skipEnvCheck: true }
])
}
}
let ast: t.File | null | undefined
if (!isProjectFile || isJSX) {
if (useAutomaticRuntime) {
// By reverse-compiling "React.createElement" calls into JSX,
// React elements provided by dependencies will also use the
// automatic runtime!
const [restoredAst, isCommonJS] =
!isProjectFile && !isJSX
? await restoreJSX(babel, code, id)
: [null, false]
if (isJSX || (ast = restoredAst)) {
plugins.push([
await loadPlugin(
'@babel/plugin-transform-react-jsx' +
(isProduction ? '' : '-development')
),
{
runtime: 'automatic',
importSource: opts.jsxImportSource,
pure: opts.jsxPure !== false
}
])
// Avoid inserting `import` statements into CJS modules.
if (isCommonJS) {
plugins.push(babelImportToRequire)
}
}
} else if (isProjectFile) {
// These plugins are only needed for the classic runtime.
if (!isProduction) {
plugins.push(
await loadPlugin('@babel/plugin-transform-react-jsx-self'),
await loadPlugin('@babel/plugin-transform-react-jsx-source')
)
}
// Even if the automatic JSX runtime is not used, we can still
// inject the React import for .jsx and .tsx modules.
if (!skipReactImport && !importReactRE.test(code)) {
code = `import React from 'react'; ` + code
}
}
}
// Plugins defined through this Vite plugin are only applied
// to modules within the project root, but "babel.config.js"
// files can define plugins that need to be applied to every
// module, including node_modules and linked packages.
const shouldSkip =
!plugins.length &&
!babelOptions.configFile &&
!(isProjectFile && babelOptions.babelrc)
if (shouldSkip) {
return // Avoid parsing if no plugins exist.
}
const parserPlugins: typeof babelOptions.parserOpts.plugins = [
...babelOptions.parserOpts.plugins,
'importMeta',
// This plugin is applied before esbuild transforms the code,
// so we need to enable some stage 3 syntax that is supported in
// TypeScript and some environments already.
'topLevelAwait',
'classProperties',
'classPrivateProperties',
'classPrivateMethods'
]
if (!extension.endsWith('.ts')) {
parserPlugins.push('jsx')
}
if (/\.tsx?$/.test(extension)) {
parserPlugins.push('typescript')
}
const transformAsync = ast
? babel.transformFromAstAsync.bind(babel, ast, code)
: babel.transformAsync.bind(babel, code)
const isReasonReact = extension.endsWith('.bs.js')
const result = await transformAsync({
...babelOptions,
ast: !isReasonReact,
root: projectRoot,
filename: id,
sourceFileName: filepath,
parserOpts: {
...babelOptions.parserOpts,
sourceType: 'module',
allowAwaitOutsideFunction: true,
plugins: parserPlugins
},
generatorOpts: {
...babelOptions.generatorOpts,
decoratorsBeforeExport: true
},
plugins,
sourceMaps: true,
// Vite handles sourcemap flattening
inputSourceMap: false as any
})
if (result) {
let code = result.code!
if (useFastRefresh && /\$RefreshReg\$\(/.test(code)) {
const accept = isReasonReact || isRefreshBoundary(result.ast!)
code = addRefreshWrapper(code, id, accept)
}
return {
code,
map: result.map
}
}
}
}
}
const viteReactRefresh: Plugin = {
name: 'vite:react-refresh',
enforce: 'pre',
config: () => ({
resolve: {
dedupe: ['react', 'react-dom']
}
}),
resolveId(id) {
if (id === runtimePublicPath) {
return id
}
},
load(id) {
if (id === runtimePublicPath) {
return runtimeCode
}
},
transformIndexHtml() {
if (!skipFastRefresh)
return [
{
tag: 'script',
attrs: { type: 'module' },
children: preambleCode.replace(`__BASE__`, base)
}
]
}
}
const runtimeId = 'react/jsx-runtime'
// Adapted from https://github.com/alloc/vite-react-jsx
const viteReactJsx: Plugin = {
name: 'vite:react-jsx',
enforce: 'pre',
config() {
return {
optimizeDeps: {
include: ['react/jsx-dev-runtime']
}
}
},
resolveId(id: string) {
return id === runtimeId ? id : null
},
load(id: string) {
if (id === runtimeId) {
const runtimePath = resolve.sync(runtimeId, {
basedir: projectRoot
})
const exports = ['jsx', 'jsxs', 'Fragment']
return [
`import * as jsxRuntime from ${JSON.stringify(runtimePath)}`,
// We can't use `export * from` or else any callsite that uses
// this module will be compiled to `jsxRuntime.exports.jsx`
// instead of the more concise `jsx` alias.
...exports.map((name) => `export const ${name} = jsxRuntime.${name}`)
].join('\n')
}
}
}
return [viteBabel, viteReactRefresh, useAutomaticRuntime && viteReactJsx]
}
viteReact.preambleCode = preambleCode
function loadPlugin(path: string): Promise<any> {
return import(path).then((module) => module.default || module)
}
// overwrite for cjs require('...')() usage
// The following lines are inserted by scripts/patchEsbuildDist.ts,
// this doesn't bundle correctly after esbuild 0.14.4
//
// module.exports = viteReact
// viteReact['default'] = viteReact | the_stack |
import isEqual from 'lodash/isEqual';
import {
isArray, isEmpty, isNumber, isObject, isString
} from './validator.functions';
import { hasOwn, uniqueItems, commonItems } from './utility.functions';
import { JsonPointer, Pointer } from './jsonpointer.functions';
/**
* 'mergeSchemas' function
*
* Merges multiple JSON schemas into a single schema with combined rules.
*
* If able to logically merge properties from all schemas,
* returns a single schema object containing all merged properties.
*
* Example: ({ a: b, max: 1 }, { c: d, max: 2 }) => { a: b, c: d, max: 1 }
*
* If unable to logically merge, returns an allOf schema object containing
* an array of the original schemas;
*
* Example: ({ a: b }, { a: d }) => { allOf: [ { a: b }, { a: d } ] }
*
* // schemas - one or more input schemas
* // - merged schema
*/
export function mergeSchemas(...schemas) {
schemas = schemas.filter(schema => !isEmpty(schema));
if (schemas.some(schema => !isObject(schema))) { return null; }
const combinedSchema: any = {};
for (const schema of schemas) {
for (const key of Object.keys(schema)) {
const combinedValue = combinedSchema[key];
const schemaValue = schema[key];
if (!hasOwn(combinedSchema, key) || isEqual(combinedValue, schemaValue)) {
combinedSchema[key] = schemaValue;
} else {
switch (key) {
case 'allOf':
// Combine all items from both arrays
if (isArray(combinedValue) && isArray(schemaValue)) {
combinedSchema.allOf = mergeSchemas(...combinedValue, ...schemaValue);
} else {
return { allOf: [ ...schemas ] };
}
break;
case 'additionalItems': case 'additionalProperties':
case 'contains': case 'propertyNames':
// Merge schema objects
if (isObject(combinedValue) && isObject(schemaValue)) {
combinedSchema[key] = mergeSchemas(combinedValue, schemaValue);
// additionalProperties == false in any schema overrides all other values
} else if (
key === 'additionalProperties' &&
(combinedValue === false || schemaValue === false)
) {
combinedSchema.combinedSchema = false;
} else {
return { allOf: [ ...schemas ] };
}
break;
case 'anyOf': case 'oneOf': case 'enum':
// Keep only items that appear in both arrays
if (isArray(combinedValue) && isArray(schemaValue)) {
combinedSchema[key] = combinedValue.filter(item1 =>
schemaValue.findIndex(item2 => isEqual(item1, item2)) > -1
);
if (!combinedSchema[key].length) { return { allOf: [ ...schemas ] }; }
} else {
return { allOf: [ ...schemas ] };
}
break;
case 'definitions':
// Combine keys from both objects
if (isObject(combinedValue) && isObject(schemaValue)) {
const combinedObject = { ...combinedValue };
for (const subKey of Object.keys(schemaValue)) {
if (!hasOwn(combinedObject, subKey) ||
isEqual(combinedObject[subKey], schemaValue[subKey])
) {
combinedObject[subKey] = schemaValue[subKey];
// Don't combine matching keys with different values
} else {
return { allOf: [ ...schemas ] };
}
}
combinedSchema.definitions = combinedObject;
} else {
return { allOf: [ ...schemas ] };
}
break;
case 'dependencies':
// Combine all keys from both objects
// and merge schemas on matching keys,
// converting from arrays to objects if necessary
if (isObject(combinedValue) && isObject(schemaValue)) {
const combinedObject = { ...combinedValue };
for (const subKey of Object.keys(schemaValue)) {
if (!hasOwn(combinedObject, subKey) ||
isEqual(combinedObject[subKey], schemaValue[subKey])
) {
combinedObject[subKey] = schemaValue[subKey];
// If both keys are arrays, include all items from both arrays,
// excluding duplicates
} else if (
isArray(schemaValue[subKey]) && isArray(combinedObject[subKey])
) {
combinedObject[subKey] =
uniqueItems(...combinedObject[subKey], ...schemaValue[subKey]);
// If either key is an object, merge the schemas
} else if (
(isArray(schemaValue[subKey]) || isObject(schemaValue[subKey])) &&
(isArray(combinedObject[subKey]) || isObject(combinedObject[subKey]))
) {
// If either key is an array, convert it to an object first
const required = isArray(combinedSchema.required) ?
combinedSchema.required : [];
const combinedDependency = isArray(combinedObject[subKey]) ?
{ required: uniqueItems(...required, combinedObject[subKey]) } :
combinedObject[subKey];
const schemaDependency = isArray(schemaValue[subKey]) ?
{ required: uniqueItems(...required, schemaValue[subKey]) } :
schemaValue[subKey];
combinedObject[subKey] =
mergeSchemas(combinedDependency, schemaDependency);
} else {
return { allOf: [ ...schemas ] };
}
}
combinedSchema.dependencies = combinedObject;
} else {
return { allOf: [ ...schemas ] };
}
break;
case 'items':
// If arrays, keep only items that appear in both arrays
if (isArray(combinedValue) && isArray(schemaValue)) {
combinedSchema.items = combinedValue.filter(item1 =>
schemaValue.findIndex(item2 => isEqual(item1, item2)) > -1
);
if (!combinedSchema.items.length) { return { allOf: [ ...schemas ] }; }
// If both keys are objects, merge them
} else if (isObject(combinedValue) && isObject(schemaValue)) {
combinedSchema.items = mergeSchemas(combinedValue, schemaValue);
// If object + array, combine object with each array item
} else if (isArray(combinedValue) && isObject(schemaValue)) {
combinedSchema.items =
combinedValue.map(item => mergeSchemas(item, schemaValue));
} else if (isObject(combinedValue) && isArray(schemaValue)) {
combinedSchema.items =
schemaValue.map(item => mergeSchemas(item, combinedValue));
} else {
return { allOf: [ ...schemas ] };
}
break;
case 'multipleOf':
// TODO: Adjust to correctly handle decimal values
// If numbers, set to least common multiple
if (isNumber(combinedValue) && isNumber(schemaValue)) {
const gcd = (x, y) => !y ? x : gcd(y, x % y);
const lcm = (x, y) => (x * y) / gcd(x, y);
combinedSchema.multipleOf = lcm(combinedValue, schemaValue);
} else {
return { allOf: [ ...schemas ] };
}
break;
case 'maximum': case 'exclusiveMaximum': case 'maxLength':
case 'maxItems': case 'maxProperties':
// If numbers, set to lowest value
if (isNumber(combinedValue) && isNumber(schemaValue)) {
combinedSchema[key] = Math.min(combinedValue, schemaValue);
} else {
return { allOf: [ ...schemas ] };
}
break;
case 'minimum': case 'exclusiveMinimum': case 'minLength':
case 'minItems': case 'minProperties':
// If numbers, set to highest value
if (isNumber(combinedValue) && isNumber(schemaValue)) {
combinedSchema[key] = Math.max(combinedValue, schemaValue);
} else {
return { allOf: [ ...schemas ] };
}
break;
case 'not':
// Combine not values into anyOf array
if (isObject(combinedValue) && isObject(schemaValue)) {
const notAnyOf = [combinedValue, schemaValue]
.reduce((notAnyOfArray, notSchema) =>
isArray(notSchema.anyOf) &&
Object.keys(notSchema).length === 1 ?
[ ...notAnyOfArray, ...notSchema.anyOf ] :
[ ...notAnyOfArray, notSchema ]
, []);
// TODO: Remove duplicate items from array
combinedSchema.not = { anyOf: notAnyOf };
} else {
return { allOf: [ ...schemas ] };
}
break;
case 'patternProperties':
// Combine all keys from both objects
// and merge schemas on matching keys
if (isObject(combinedValue) && isObject(schemaValue)) {
const combinedObject = { ...combinedValue };
for (const subKey of Object.keys(schemaValue)) {
if (!hasOwn(combinedObject, subKey) ||
isEqual(combinedObject[subKey], schemaValue[subKey])
) {
combinedObject[subKey] = schemaValue[subKey];
// If both keys are objects, merge them
} else if (
isObject(schemaValue[subKey]) && isObject(combinedObject[subKey])
) {
combinedObject[subKey] =
mergeSchemas(combinedObject[subKey], schemaValue[subKey]);
} else {
return { allOf: [ ...schemas ] };
}
}
combinedSchema.patternProperties = combinedObject;
} else {
return { allOf: [ ...schemas ] };
}
break;
case 'properties':
// Combine all keys from both objects
// unless additionalProperties === false
// and merge schemas on matching keys
if (isObject(combinedValue) && isObject(schemaValue)) {
const combinedObject = { ...combinedValue };
// If new schema has additionalProperties,
// merge or remove non-matching property keys in combined schema
if (hasOwn(schemaValue, 'additionalProperties')) {
Object.keys(combinedValue)
.filter(combinedKey => !Object.keys(schemaValue).includes(combinedKey))
.forEach(nonMatchingKey => {
if (schemaValue.additionalProperties === false) {
delete combinedObject[nonMatchingKey];
} else if (isObject(schemaValue.additionalProperties)) {
combinedObject[nonMatchingKey] = mergeSchemas(
combinedObject[nonMatchingKey],
schemaValue.additionalProperties
);
}
});
}
for (const subKey of Object.keys(schemaValue)) {
if (isEqual(combinedObject[subKey], schemaValue[subKey]) || (
!hasOwn(combinedObject, subKey) &&
!hasOwn(combinedObject, 'additionalProperties')
)) {
combinedObject[subKey] = schemaValue[subKey];
// If combined schema has additionalProperties,
// merge or ignore non-matching property keys in new schema
} else if (
!hasOwn(combinedObject, subKey) &&
hasOwn(combinedObject, 'additionalProperties')
) {
// If combinedObject.additionalProperties === false,
// do nothing (don't set key)
// If additionalProperties is object, merge with new key
if (isObject(combinedObject.additionalProperties)) {
combinedObject[subKey] = mergeSchemas(
combinedObject.additionalProperties, schemaValue[subKey]
);
}
// If both keys are objects, merge them
} else if (
isObject(schemaValue[subKey]) &&
isObject(combinedObject[subKey])
) {
combinedObject[subKey] =
mergeSchemas(combinedObject[subKey], schemaValue[subKey]);
} else {
return { allOf: [ ...schemas ] };
}
}
combinedSchema.properties = combinedObject;
} else {
return { allOf: [ ...schemas ] };
}
break;
case 'required':
// If arrays, include all items from both arrays, excluding duplicates
if (isArray(combinedValue) && isArray(schemaValue)) {
combinedSchema.required = uniqueItems(...combinedValue, ...schemaValue);
// If booleans, aet true if either true
} else if (
typeof schemaValue === 'boolean' &&
typeof combinedValue === 'boolean'
) {
combinedSchema.required = !!combinedValue || !!schemaValue;
} else {
return { allOf: [ ...schemas ] };
}
break;
case '$schema': case '$id': case 'id':
// Don't combine these keys
break;
case 'title': case 'description': case '$comment':
// Return the last value, overwriting any previous one
// These properties are not used for validation, so conflicts don't matter
combinedSchema[key] = schemaValue;
break;
case 'type':
if (
(isArray(schemaValue) || isString(schemaValue)) &&
(isArray(combinedValue) || isString(combinedValue))
) {
const combinedTypes = commonItems(combinedValue, schemaValue);
if (!combinedTypes.length) { return { allOf: [ ...schemas ] }; }
combinedSchema.type = combinedTypes.length > 1 ? combinedTypes : combinedTypes[0];
} else {
return { allOf: [ ...schemas ] };
}
break;
case 'uniqueItems':
// Set true if either true
combinedSchema.uniqueItems = !!combinedValue || !!schemaValue;
break;
default:
return { allOf: [ ...schemas ] };
}
}
}
}
return combinedSchema;
} | the_stack |
import assert from 'assert';
import * as ThingTalk from 'thingtalk';
import * as Tp from 'thingpedia';
import * as I18n from '../i18n';
import * as DB from './db';
import { AbstractDatabase, createDB } from './db';
import DeviceDatabase from './devices/database';
import SyncManager from './sync/manager';
import PairedEngineManager from './sync/pairing';
import * as Builtins from './devices/builtins';
import AppDatabase from './apps/database';
import AppRunner from './apps/runner';
import type AppExecutor from './apps/app_executor';
import AudioController from '../dialogue-agent/audio/controller';
import AssistantDispatcher from '../dialogue-agent/assistant_dispatcher';
import { NotificationConfig } from '../dialogue-agent/notifications';
import NotificationFormatter from '../dialogue-agent/notifications/formatter';
import * as Config from '../config';
import { ActivityMonitor, ActivityMonitorStatus } from './activity_monitor';
export {
DB,
DeviceDatabase,
SyncManager,
AppDatabase,
AppExecutor,
ActivityMonitor,
ActivityMonitorStatus
};
interface EngineModule {
start() : Promise<void>;
stop() : Promise<void>;
}
interface DeviceState {
kind : string;
accessToken ?: string;
refreshToken ?: string;
[key : string] : unknown;
}
/**
* Information about a running ThingTalk program (app).
*/
export interface AppInfo {
/**
* The unique ID of the app.
*/
uniqueId : string;
/**
* A short string identifying the app.
*/
name : string;
/**
* A longer description of the code in the app.
*/
description : string;
code : string;
/**
* The icon associated with the app (as a Thingpedia class ID).
*/
icon : string|null;
/**
* Whether the app is currently running (executing ThingTalk code).
*/
isRunning : boolean;
/**
* Whether the app is set to run in the background.
*/
isEnabled : boolean;
/**
* The last error reported by the app.
*/
error : string|null;
/**
* Configuration related to how notifications should be reported by the app.
*/
notifications ?: {
/**
* Identifier of the backend to use for notifications.
*/
backend : string;
/**
* Backend-specific information, such as the phone number or email
* address to send notifications to.
*/
config : Record<string, string>;
};
}
/**
* Information about a configured Thingpedia device.
*/
export interface DeviceInfo {
/**
* The unique ID of the device.
*/
uniqueId : string;
/**
* A short, human-readable string identifying the device.
*/
name : string;
/**
* A longer string describing the device.
*/
description : string;
/**
* The Thingpedia class ID this device belongs to (suitable to select an icon).
*/
kind : string;
/**
* The version of the class this device belongs to.
*/
version : number;
/**
* The coarse categorization of the device: `physical`, `online`, `data`, or `system`.
*/
class : 'physical' | 'online' | 'data' | 'system';
/**
* The ID of the engine that configured this device (for purposes of cloud sync).
*/
ownerTier : string;
/**
* `true` if this device was created on the fly by some discovery module, `false`
* if it was configured manually and is stored on disk.
*/
isTransient : boolean;
/**
* A string identifying the type of authentication used by this device.
*/
authType : string;
}
export interface AppResult {
raw : Record<string, unknown>;
type : string;
formatted : Tp.FormatObjects.FormattedObject[];
}
/**
* The core Genie engine.
*
* There is one engine instance per user. Multiple engine instances
* can run in the same process, but they must be associated with
* different platform objects.
*
*/
export default class AssistantEngine extends Tp.BaseEngine {
readonly _ : (x : string) => string;
private _db : AbstractDatabase;
// should be private, but it is accessed from @org.thingpedia.builtin.thingengine
_sync : SyncManager;
private _modules : EngineModule[];
private _langPack : I18n.LanguagePack;
private _devices : DeviceDatabase;
private _appdb : AppDatabase;
private _assistant : AssistantDispatcher;
private _audio : AudioController;
private _activityMonitor : ActivityMonitor;
private _running : boolean;
private _stopCallback : (() => void)|null;
/**
* Construct a new engine.
*
* @param {external:thingpedia.BasePlatform} platform - the platform associated with this engine
* @param {Object} options - additional options; this is also passed to the parent class
* @param {string} [options.cloudSyncUrl] - URL to use for cloud sync
*/
constructor(platform : Tp.BasePlatform, options : {
cloudSyncUrl ?: string;
nluModelUrl ?: string;
thingpediaUrl ?: string;
notifications ?: NotificationConfig;
activityMonitorOptions ?: {
idleTimeoutMillis ?: number;
quiesceTimeoutMillis ?: number;
}
} = {}) {
super(platform, options);
this._ = I18n.get(platform.locale).gettext;
this._langPack = I18n.get(platform.locale);
this._db = createDB(platform);
this._sync = new SyncManager(platform, options.cloudSyncUrl || Config.THINGENGINE_URL);
this._modules = [];
const deviceFactory = new Tp.DeviceFactory(this, this._thingpedia, this._loadBuiltins());
this._devices = new DeviceDatabase(platform, this._db, this._sync,
deviceFactory, this._schemas);
this._appdb = new AppDatabase(this);
this._assistant = new AssistantDispatcher(this, options.nluModelUrl, options.notifications||{});
this._audio = new AudioController(this._devices);
this._activityMonitor = new ActivityMonitor(this._appdb, options.activityMonitorOptions);
// in loading order
this._modules = [this._sync,
this._devices,
new PairedEngineManager(platform, this._devices, deviceFactory, this._sync),
this._appdb];
if (this._audio)
this._modules.push(this._audio);
this._modules.push(this._assistant,
new AppRunner(this._appdb));
this._modules.push(this._activityMonitor);
this._running = false;
this._stopCallback = null;
}
get platform() : Tp.BasePlatform {
this.updateActivity();
return this._platform;
}
get langPack() {
return this._langPack;
}
get db() {
this.updateActivity();
return this._db;
}
/**
* Return a unique identifier associated with this engine.
*
* This is a string composed of two parts: the high-level tier type
* (phone, cloud, server, desktop), and a unique identifier. The tier
* is used by the cloud sync subsystem, and can be used by devices
* that use local communication to distinguish which engine configured them.
*/
get ownTier() : string {
return this._sync.ownAddress;
}
/**
* Access the device database of this engine.
*/
get devices() {
this.updateActivity();
return this._devices;
}
/**
* Access the app database of this engine.
*/
get apps() {
this.updateActivity();
return this._appdb;
}
/**
* Access the assistant dispatcher of this engine.
*/
get assistant() {
this.updateActivity();
return this._assistant;
}
/**
* Access the audio controller to coordinate access to audio.
*/
get audio() {
this.updateActivity();
return this._audio;
}
/**
* Access the activity monitor for this engine.
*/
get activityMonitor() {
return this._activityMonitor;
}
updateActivity() {
if (this._activityMonitor)
this._activityMonitor.updateActivity();
}
private _loadBuiltins() {
// inject the abstract interfaces used by the builtin devices into the schema retriever
for (const kind in Builtins.interfaces) {
const iface = Builtins.interfaces[kind];
const parsed = ThingTalk.Syntax.parse(iface, ThingTalk.Syntax.SyntaxType.Normal, {
locale: 'en-US',
timezone: 'UTC'
});
assert(parsed instanceof ThingTalk.Ast.Library);
// TODO apply translations here
this._schemas.injectClass(parsed.classes[0]);
}
// load the concrete modules
const loaded : Record<string, { class : ThingTalk.Ast.ClassDef, module : Tp.BaseDevice.DeviceClass<Tp.BaseDevice> }> = {};
for (const kind in Builtins.modules) {
const builtin = Builtins.modules[kind];
const parsed = ThingTalk.Syntax.parse(builtin.class, ThingTalk.Syntax.SyntaxType.Normal, {
locale: 'en-US',
timezone: 'UTC'
});
assert(parsed instanceof ThingTalk.Ast.Library);
// TODO apply translations here
this._schemas.injectClass(parsed.classes[0]);
loaded[kind] = {
class: parsed.classes[0],
module: builtin.module
};
}
// load the platform device, if any
const platdev = this._platform.getPlatformDevice();
if (platdev) {
const parsed = ThingTalk.Syntax.parse(platdev.class, ThingTalk.Syntax.SyntaxType.Normal, {
locale: 'en-US',
timezone: 'UTC'
});
assert(parsed instanceof ThingTalk.Ast.Library);
// TODO apply translations here
loaded[platdev.kind] = {
class: parsed.classes[0],
module: platdev.module
};
}
return loaded;
}
private async _openSequential(modules : EngineModule[]) {
for (let i = 0; i < modules.length; i++) {
//console.log('Starting ' + modules[i].constructor.name);
await modules[i].start();
}
}
private async _closeSequential(modules : EngineModule[]) {
for (let i = 0; i < modules.length; i++) {
//console.log('Stopping ' + modules[i].constructor.name);
await modules[i].stop();
}
}
/**
* Initialize this engine.
*
* This will initialize all modules sequentially in the right
* order. It must be called before {@link run}.
*/
async open() : Promise<void> {
await this._db.ensureSchema();
await this._openSequential(this._modules);
console.log('Engine started');
}
/**
* Deinitialize this engine.
*
* This will sequentially close all modules, save the database
* and release all resources.
*
* This should not be called if {@link start} fails. After
* this method succeed, the engine is in undefined state and must
* not be used.
*/
close() : Promise<void> {
return this._closeSequential(this._modules).then(() => {
console.log('Engine closed');
});
}
/**
* Run ThingTalk rules.
*
* Kick start the engine by returning a promise that will
* run each rule in sequence, forever, without ever being
* fulfilled until {@link stop} is called.
*/
run() : Promise<void> {
this._running = true;
return new Promise((callback, errback) => {
if (!this._running) {
callback();
return;
}
this._stopCallback = callback;
});
}
/**
* Stop any rule execution at the next available moment.
*
* This will cause the {@link run} promise to be fulfilled.
*
* This method can be called multiple times and is idempotent.
* It can also be called before {@link run}.
*/
stop() : void {
console.log('Engine stopped');
this._running = false;
if (this._stopCallback)
this._stopCallback();
}
/**
* Begin configuring a device with an OAuth-like flow.
*
* @param {string} kind - the Thingpedia class ID of the device to configure.
* @return {Array} a tuple with the redirect URL and the session object.
*/
startOAuth(kind : string) : Promise<[string, Record<string, string>]> {
return this._devices.addFromOAuth(kind);
}
/**
* Complete OAuth-like configuration for a device.
*
* @param {string} kind - the Thingpedia class ID of the device to configure.
* @param {string} redirectUri - the OAuth redirect URI that was called at the end of the OAuth flow.
* @param {Object.<string,string>} session - an object with session information.
* @return {external:thingpedia.BaseDevice} the configured device, or null if configuration failed
*/
completeOAuth(kind : string,
redirectUri : string,
session : Record<string, string>) : Promise<Tp.BaseDevice|null> {
return this._devices.completeOAuth(kind, redirectUri, session);
}
/**
* Configure a simple device with no configuration information needed.
*
* @param {string} kind - the Thingpedia class ID of the device to configure.
* @return {external:thingpedia.BaseDevice} the configured device
*/
createSimpleDevice(kind : string) : Promise<Tp.BaseDevice> {
return this._devices.addSerialized({ kind });
}
/**
* Configure a device with direct configuration information.
*
* @param {Object} state - the configured device parameters.
* @param {string} state.kind - the Thingpedia class ID of the device to configure.
* @return {external:thingpedia.BaseDevice} the configured device
*/
createDevice(state : DeviceState) : Promise<Tp.BaseDevice> {
return this._devices.addSerialized(state);
}
/**
* Delete a device by ID.
*
* Deleting a device removes any stored credentials and configuration about that device.
*
* @param {string} uniqueId - the ID of the device to delete
* @return {boolean} true if the device was deleted successfully, false if it did not exist
*/
async deleteDevice(uniqueId : string) : Promise<boolean> {
const device = this._devices.getDevice(uniqueId);
if (device === undefined)
return false;
await this._devices.removeDevice(device);
return true;
}
/**
* Update all devices of the given type to the latest version in Thingpedia.
*
* @param {string} kind - the Thingpedia class ID of the devices to update
*/
async upgradeDevice(kind : string) : Promise<void> {
await this._devices.updateDevicesOfKind(kind);
}
/**
* Returns the list of all device classes that have been previously cached.
*/
getCachedDeviceClasses() : Promise<any[]> {
return this._devices.getCachedDeviceClasses();
}
/**
* Returns whether a specific device has been configured or not.
*
* @param {string} uniqueId - the device ID to check
* @return {boolean} true if the device exists, false otherwise
*/
hasDevice(uniqueId : string) : boolean {
return this._devices.hasDevice(uniqueId);
}
private _toDeviceInfo(d : Tp.BaseDevice) : DeviceInfo {
let deviceKlass : 'physical' | 'online' | 'data' | 'system' = 'physical';
if (d.hasKind('data-source'))
deviceKlass = 'data';
else if (d.hasKind('online-account'))
deviceKlass = 'online';
else if (d.hasKind('thingengine-system'))
deviceKlass = 'system';
return {
uniqueId: d.uniqueId!,
name: d.name || this._("Unknown device"),
description: d.description || this._("Description not available"),
kind: d.kind,
version: (d.constructor as typeof Tp.BaseDevice).metadata.version || 0,
class: deviceKlass,
ownerTier: d.ownerTier,
isTransient: d.isTransient,
authType: (d.constructor as typeof Tp.BaseDevice).metadata.auth.type || 'unknown',
};
}
/**
* Get information about all configured devices.
*
* @param {string} [kind] - filter only devices that have the specified kind
* @return {Array<DeviceInfo>} a list of device info objects, one per device
*/
getDeviceInfos(kind ?: string) : DeviceInfo[] {
const devices = this._devices.getAllDevices(kind);
return devices.map((d) => this._toDeviceInfo(d));
}
/**
* Get information about one configured device by ID.
*
* @param {string} uniqueId - the ID of the device to return info for
* @return information about that device
*/
getDeviceInfo(uniqueId : string) : DeviceInfo {
const d = this._devices.getDevice(uniqueId);
if (d === undefined)
throw new Error('Invalid device ' + uniqueId);
return this._toDeviceInfo(d);
}
/**
* Asynchronously check whether a device is available.
*
* @param {string} uniqueId - the ID of the device to check
* @return {external:thingpedia.Availability} whether the device is available
*/
async checkDeviceAvailable(uniqueId : string) : Promise<Tp.Availability> {
const d = this._devices.getDevice(uniqueId);
if (d === undefined)
return -1;
return d.checkAvailable();
}
private _toAppInfo(a : AppExecutor) : AppInfo {
return {
uniqueId: a.uniqueId!,
name: a.name,
description: a.description,
code: a.program.prettyprint(),
icon: a.icon || null,
isRunning: a.isRunning,
isEnabled: a.isEnabled,
error: a.error,
notifications: a.notifications,
};
}
/**
* Get information about all running ThingTalk programs (apps).
*
* @return {Array<AppInfo>} a list of app info objects, one per app
*/
getAppInfos() : AppInfo[] {
const apps = this._appdb.getAllApps();
return apps.map((a) => this._toAppInfo(a));
}
/**
* Get information about one running ThingTalk program (app) by ID.
*
* @param {string} uniqueId - the ID of the app to return info for
* @param {boolean} [throw_=true] - throw an error if there is no such app
* @return {AppInfo} information about that app
*/
getAppInfo(uniqueId : string, throw_ ?: true) : AppInfo;
getAppInfo(uniqueId : string, throw_ : boolean) : AppInfo|undefined;
getAppInfo(uniqueId : string, throw_ = true) {
const app = this._appdb.getApp(uniqueId);
if (app === undefined) {
if (throw_)
throw new Error('Invalid app ' + uniqueId);
else
return undefined;
}
return this._toAppInfo(app);
}
/**
* Stop (delete) the ThingTalk program (app) with the given ID.
*
* @param {string} uniqueId - the ID of the app to delete
* @return {boolean} true if the deletion occurred, false otherwise
*/
async deleteApp(uniqueId : string) : Promise<boolean> {
const app = this._appdb.getApp(uniqueId);
if (app === undefined)
return false;
await this._appdb.removeApp(app);
return true;
}
/**
* Create a new ThingTalk app.
*
* This is the main entry point to execute ThingTalk code.
*
* @param {string|external:thingtalk.Ast.Program} program - the ThingTalk code to execute,
* or the parsed ThingTalk program (AST)
* @param {Object} options
* @param {string} [options.uniqueId] - the ID to assign to the new app
* @param {string} [options.name] - the name of the new app
* @param {string} [options.description] - the human-readable description of the code
* being executed
* @param {string} [options.icon] - the icon of the new app (as a Thingpedia class ID)
* @param {string} [options.conversation] - the ID of the conversation associated with the new app
* @return {AppExecutor} the newly created program
*/
async createApp(programOrString : ThingTalk.Ast.Program|string, options ?: {
uniqueId ?: string;
name ?: string;
description ?: string;
icon ?: string;
conversation ?: string;
notifications ?: {
backend : string;
config : Record<string, string>;
};
}) : Promise<AppExecutor> {
let program : ThingTalk.Ast.Program;
if (typeof programOrString === 'string') {
const parsed = await ThingTalk.Syntax.parse(programOrString, ThingTalk.Syntax.SyntaxType.Normal, {
locale: this._platform.locale,
timezone: this._platform.timezone
}).typecheck(this.schemas, true);
assert(parsed instanceof ThingTalk.Ast.Program);
program = parsed;
} else {
program = programOrString;
}
return this._appdb.createApp(program, options);
}
/**
* Create a new ThingTalk app, and execute it to compute all results.
*
* This is a convenience wrapper over {@link createApp} that also
* iterates the results of the app and formats them.
*
* @param {string|external:thingtalk.Ast.Program} program - the ThingTalk code to execute,
* or the parsed ThingTalk program (AST)
* @param {Object} options
* @param {string} [options.uniqueId] - the ID to assign to the new app
* @param {string} [options.name] - the name of the new app
* @param {string} [options.description] - the human-readable description of the code
* being executed
* @param {string} [options.icon] - the icon of the new app (as a Thingpedia class ID)
* @param {string} [options.conversation] - the ID of the conversation associated with the new app
*/
async createAppAndReturnResults(programOrString : ThingTalk.Ast.Program|string, options ?: {
uniqueId ?: string;
name ?: string;
description ?: string;
icon ?: string;
conversation ?: string;
notifications ?: {
backend : string;
config : Record<string, string>;
};
}) {
const app = await this.createApp(programOrString, options);
const results : AppResult[] = [];
const errors : Error[] = [];
const formatter = new NotificationFormatter(this);
await formatter.initialize();
for await (const value of app.mainOutput) {
if (value instanceof Error) {
errors.push(value);
} else {
const messages = await formatter.formatNotification(null, app.program, value.outputType, value.outputValue);
results.push({ raw: value.outputValue, type: value.outputType, formatted: messages });
}
}
return {
uniqueId: app.uniqueId!,
description: app.description,
code: app.program.prettyprint(),
icon: app.icon,
results, errors
};
}
/**
* Configure cloud synchronization.
*
* This method can be called in non-cloud Almond to start synchronization
* with the cloud.
*
* @param {string} cloudId - the ID of the user in Web Almond
* @param {string} authToken - the access token
*/
async setCloudId(cloudId : string, authToken : string) : Promise<boolean> {
if (!this._platform.setAuthToken(authToken))
return false;
this._platform.getSharedPreferences().set('cloud-id', cloudId);
this._sync.addCloudConfig();
await this._sync.tryConnect('cloud');
return true;
}
/**
* Configure synchronization with a local server.
*
* This method can be called in a phone or desktop Almond to synchronize
* with a locally-setup home server Almond .
*
* @param {string} serverHost - the IP address or hostname of the server to connect to
* @param {number} serverPort - the port at which server is reachable
* @param {string} authToken - the access token
*/
async addServerAddress(serverHost : string, serverPort : number, authToken : string) : Promise<boolean> {
if (authToken !== null) {
if (!this._platform.setAuthToken(authToken))
return false;
}
this._devices.addSerialized({
kind: 'org.thingpedia.builtin.thingengine',
tier: 'server',
host: serverHost,
port: serverPort,
own: true });
return true;
}
} | the_stack |
import { utlGetSessionStorage, utlSetSessionStorage } from "@microsoft/applicationinsights-common";
import { IDiagnosticLogger, eLoggingSeverity, _eInternalMessageId, getJSON, arrForEach, isFunction, arrIndexOf, isString, dumpObj, isArray, getExceptionName, _throwInternal } from "@microsoft/applicationinsights-core-js";
import { ISenderConfig } from "./Interfaces";
import dynamicProto from "@microsoft/dynamicproto-js";
export interface ISendBuffer {
/**
* Enqueue the payload
*/
enqueue: (payload: string) => void;
/**
* Returns the number of elements in the buffer
*/
count: () => number;
/**
* Returns the current size of the serialized buffer
*/
size: () => number;
/**
* Clears the buffer
*/
clear: () => void;
/**
* Returns items stored in the buffer
*/
getItems: () => string[];
/**
* Build a batch of all elements in the payload array
*/
batchPayloads: (payload: string[]) => string;
/**
* Moves items to the SENT_BUFFER.
* The buffer holds items which were sent, but we haven't received any response from the backend yet.
*/
markAsSent: (payload: string[]) => void;
/**
* Removes items from the SENT_BUFFER. Should be called on successful response from the backend.
*/
clearSent: (payload: string[]) => void;
}
abstract class BaseSendBuffer {
protected _get: () => string[];
protected _set: (buffer: string[]) => string[];
constructor(logger: IDiagnosticLogger, config: ISenderConfig) {
let _buffer: string[] = [];
let _bufferFullMessageSent = false;
this._get = () => {
return _buffer;
};
this._set = (buffer: string[]) => {
_buffer = buffer;
return _buffer;
};
dynamicProto(BaseSendBuffer, this, (_self) => {
_self.enqueue = (payload: string) => {
if (_self.count() >= config.eventsLimitInMem()) {
// sent internal log only once per page view
if (!_bufferFullMessageSent) {
_throwInternal(logger,
eLoggingSeverity.WARNING,
_eInternalMessageId.InMemoryStorageBufferFull,
"Maximum in-memory buffer size reached: " + _self.count(),
true);
_bufferFullMessageSent = true;
}
return;
}
_buffer.push(payload);
};
_self.count = (): number => {
return _buffer.length;
};
_self.size = (): number => {
let size = _buffer.length;
for (let lp = 0; lp < _buffer.length; lp++) {
size += _buffer[lp].length;
}
if (!config.emitLineDelimitedJson()) {
size += 2;
}
return size;
};
_self.clear = () => {
_buffer = [];
_bufferFullMessageSent = false;
};
_self.getItems = (): string[] => {
return _buffer.slice(0)
};
_self.batchPayloads = (payload: string[]): string => {
if (payload && payload.length > 0) {
const batch = config.emitLineDelimitedJson() ?
payload.join("\n") :
"[" + payload.join(",") + "]";
return batch;
}
return null;
};
});
}
public enqueue(payload: string) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public count(): number {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return 0;
}
public size(): number {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return 0;
}
public clear() {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public getItems(): string[] {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
public batchPayloads(payload: string[]): string {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
}
/*
* An array based send buffer.
*/
export class ArraySendBuffer extends BaseSendBuffer implements ISendBuffer {
constructor(logger: IDiagnosticLogger, config: ISenderConfig) {
super(logger, config);
dynamicProto(ArraySendBuffer, this, (_self, _base) => {
_self.markAsSent = (payload: string[]) => {
_base.clear();
};
_self.clearSent = (payload: string[]) => {
// not supported
};
});
}
public markAsSent(payload: string[]) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public clearSent(payload: string[]) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
}
/*
* Session storage buffer holds a copy of all unsent items in the browser session storage.
*/
export class SessionStorageSendBuffer extends BaseSendBuffer implements ISendBuffer {
static BUFFER_KEY = "AI_buffer";
static SENT_BUFFER_KEY = "AI_sentBuffer";
// Maximum number of payloads stored in the buffer. If the buffer is full, new elements will be dropped.
static MAX_BUFFER_SIZE = 2000;
constructor(logger: IDiagnosticLogger, config: ISenderConfig) {
super(logger, config);
let _bufferFullMessageSent = false;
dynamicProto(SessionStorageSendBuffer, this, (_self, _base) => {
const bufferItems = _getBuffer(SessionStorageSendBuffer.BUFFER_KEY);
const notDeliveredItems = _getBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY);
let buffer = _self._set(bufferItems.concat(notDeliveredItems));
// If the buffer has too many items, drop items from the end.
if (buffer.length > SessionStorageSendBuffer.MAX_BUFFER_SIZE) {
buffer.length = SessionStorageSendBuffer.MAX_BUFFER_SIZE;
}
_setBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY, []);
_setBuffer(SessionStorageSendBuffer.BUFFER_KEY, buffer);
_self.enqueue = (payload: string) => {
if (_self.count() >= SessionStorageSendBuffer.MAX_BUFFER_SIZE) {
// sent internal log only once per page view
if (!_bufferFullMessageSent) {
_throwInternal(logger,
eLoggingSeverity.WARNING,
_eInternalMessageId.SessionStorageBufferFull,
"Maximum buffer size reached: " + _self.count(),
true);
_bufferFullMessageSent = true;
}
return;
}
_base.enqueue(payload);
_setBuffer(SessionStorageSendBuffer.BUFFER_KEY, _self._get());
};
_self.clear = () => {
_base.clear();
_setBuffer(SessionStorageSendBuffer.BUFFER_KEY, _self._get());
_setBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY, []);
_bufferFullMessageSent = false;
};
_self.markAsSent = (payload: string[]) => {
_setBuffer(SessionStorageSendBuffer.BUFFER_KEY,
_self._set(_removePayloadsFromBuffer(payload, _self._get())));
let sentElements = _getBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY);
if (sentElements instanceof Array && payload instanceof Array) {
sentElements = sentElements.concat(payload);
if (sentElements.length > SessionStorageSendBuffer.MAX_BUFFER_SIZE) {
// We send telemetry normally. If the SENT_BUFFER is too big we don't add new elements
// until we receive a response from the backend and the buffer has free space again (see clearSent method)
_throwInternal(logger,
eLoggingSeverity.CRITICAL,
_eInternalMessageId.SessionStorageBufferFull,
"Sent buffer reached its maximum size: " + sentElements.length,
true);
sentElements.length = SessionStorageSendBuffer.MAX_BUFFER_SIZE;
}
_setBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY, sentElements);
}
};
_self.clearSent = (payload: string[]) => {
let sentElements = _getBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY);
sentElements = _removePayloadsFromBuffer(payload, sentElements);
_setBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY, sentElements);
};
function _removePayloadsFromBuffer(payloads: string[], buffer: string[]): string[] {
const remaining: string[] = [];
arrForEach(buffer, (value) => {
if (!isFunction(value) && arrIndexOf(payloads, value) === -1) {
remaining.push(value);
}
});
return remaining;
}
function _getBuffer(key: string): string[] {
let prefixedKey = key;
try {
prefixedKey = config.namePrefix && config.namePrefix() ? config.namePrefix() + "_" + prefixedKey : prefixedKey;
const bufferJson = utlGetSessionStorage(logger, prefixedKey);
if (bufferJson) {
let buffer: string[] = getJSON().parse(bufferJson);
if (isString(buffer)) {
// When using some version prototype.js the stringify / parse cycle does not decode array's correctly
buffer = getJSON().parse(buffer as any);
}
if (buffer && isArray(buffer)) {
return buffer;
}
}
} catch (e) {
_throwInternal(logger, eLoggingSeverity.CRITICAL,
_eInternalMessageId.FailedToRestoreStorageBuffer,
" storage key: " + prefixedKey + ", " + getExceptionName(e),
{ exception: dumpObj(e) });
}
return [];
}
function _setBuffer(key: string, buffer: string[]) {
let prefixedKey = key;
try {
prefixedKey = config.namePrefix && config.namePrefix() ? config.namePrefix() + "_" + prefixedKey : prefixedKey;
const bufferJson = JSON.stringify(buffer);
utlSetSessionStorage(logger, prefixedKey, bufferJson);
} catch (e) {
// if there was an error, clear the buffer
// telemetry is stored in the _buffer array so we won't loose any items
utlSetSessionStorage(logger, prefixedKey, JSON.stringify([]));
_throwInternal(logger, eLoggingSeverity.WARNING,
_eInternalMessageId.FailedToSetStorageBuffer,
" storage key: " + prefixedKey + ", " + getExceptionName(e) + ". Buffer cleared",
{ exception: dumpObj(e) });
}
}
});
}
public enqueue(payload: string) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public clear() {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public markAsSent(payload: string[]) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public clearSent(payload: string[]) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
} | the_stack |
import * as React from 'react';
import { Component } from 'react';
import invariant from 'invariant';
import {
Animated,
StyleSheet,
View,
Keyboard,
StatusBar,
I18nManager,
StatusBarAnimation,
StyleProp,
ViewStyle,
LayoutChangeEvent,
NativeSyntheticEvent,
} from 'react-native';
import {
GestureEvent,
HandlerStateChangeEvent,
} from '../handlers/gestureHandlerCommon';
import {
PanGestureHandler,
PanGestureHandlerEventPayload,
} from '../handlers/PanGestureHandler';
import {
TapGestureHandler,
TapGestureHandlerEventPayload,
} from '../handlers/TapGestureHandler';
import { State } from '../State';
const DRAG_TOSS = 0.05;
const IDLE: DrawerState = 'Idle';
const DRAGGING: DrawerState = 'Dragging';
const SETTLING: DrawerState = 'Settling';
export type DrawerPosition = 'left' | 'right';
export type DrawerState = 'Idle' | 'Dragging' | 'Settling';
export type DrawerType = 'front' | 'back' | 'slide';
export type DrawerLockMode = 'unlocked' | 'locked-closed' | 'locked-open';
export type DrawerKeyboardDismissMode = 'none' | 'on-drag';
export interface DrawerLayoutProps {
/**
* This attribute is present in the standard implementation already and is one
* of the required params. Gesture handler version of DrawerLayout make it
* possible for the function passed as `renderNavigationView` to take an
* Animated value as a parameter that indicates the progress of drawer
* opening/closing animation (progress value is 0 when closed and 1 when
* opened). This can be used by the drawer component to animated its children
* while the drawer is opening or closing.
*/
renderNavigationView: (
progressAnimatedValue: Animated.Value
) => React.ReactNode;
drawerPosition?: DrawerPosition;
drawerWidth?: number;
drawerBackgroundColor?: string;
drawerLockMode?: DrawerLockMode;
keyboardDismissMode?: DrawerKeyboardDismissMode;
/**
* Called when the drawer is closed.
*/
onDrawerClose?: () => void;
/**
* Called when the drawer is opened.
*/
onDrawerOpen?: () => void;
/**
* Called when the status of the drawer changes.
*/
onDrawerStateChanged?: (
newState: DrawerState,
drawerWillShow: boolean
) => void;
useNativeAnimations?: boolean;
drawerType?: DrawerType;
/**
* Defines how far from the edge of the content view the gesture should
* activate.
*/
edgeWidth?: number;
minSwipeDistance?: number;
/**
* When set to true Drawer component will use
* {@link https://reactnative.dev/docs/statusbar StatusBar} API to hide the OS
* status bar whenever the drawer is pulled or when its in an "open" state.
*/
hideStatusBar?: boolean;
/**
* @default 'slide'
*
* Can be used when hideStatusBar is set to true and will select the animation
* used for hiding/showing the status bar. See
* {@link https://reactnative.dev/docs/statusbar StatusBar} documentation for
* more details
*/
statusBarAnimation?: StatusBarAnimation;
/**
* @default black
*
* Color of a semi-transparent overlay to be displayed on top of the content
* view when drawer gets open. A solid color should be used as the opacity is
* added by the Drawer itself and the opacity of the overlay is animated (from
* 0% to 70%).
*/
overlayColor?: string;
contentContainerStyle?: StyleProp<ViewStyle>;
drawerContainerStyle?: StyleProp<ViewStyle>;
/**
* Enables two-finger gestures on supported devices, for example iPads with
* trackpads. If not enabled the gesture will require click + drag, with
* `enableTrackpadTwoFingerGesture` swiping with two fingers will also trigger
* the gesture.
*/
enableTrackpadTwoFingerGesture?: boolean;
onDrawerSlide?: (position: number) => void;
onGestureRef?: (ref: PanGestureHandler) => void;
// implicit `children` prop has been removed in @types/react^18.0.0
children?:
| React.ReactNode
| ((openValue?: Animated.AnimatedInterpolation) => React.ReactNode);
}
export type DrawerLayoutState = {
dragX: Animated.Value;
touchX: Animated.Value;
drawerTranslation: Animated.Value;
containerWidth: number;
drawerState: DrawerState;
drawerOpened: boolean;
};
export type DrawerMovementOption = {
velocity?: number;
speed?: number;
};
export default class DrawerLayout extends Component<
DrawerLayoutProps,
DrawerLayoutState
> {
static defaultProps = {
drawerWidth: 200,
drawerPosition: 'left',
useNativeAnimations: true,
drawerType: 'front',
edgeWidth: 20,
minSwipeDistance: 3,
overlayColor: 'rgba(0, 0, 0, 0.7)',
drawerLockMode: 'unlocked',
enableTrackpadTwoFingerGesture: false,
};
constructor(props: DrawerLayoutProps) {
super(props);
const dragX = new Animated.Value(0);
const touchX = new Animated.Value(0);
const drawerTranslation = new Animated.Value(0);
this.state = {
dragX,
touchX,
drawerTranslation,
containerWidth: 0,
drawerState: IDLE,
drawerOpened: false,
};
this.updateAnimatedEvent(props, this.state);
}
UNSAFE_componentWillUpdate(
props: DrawerLayoutProps,
state: DrawerLayoutState
) {
if (
this.props.drawerPosition !== props.drawerPosition ||
this.props.drawerWidth !== props.drawerWidth ||
this.props.drawerType !== props.drawerType ||
this.state.containerWidth !== state.containerWidth
) {
this.updateAnimatedEvent(props, state);
}
}
private openValue?: Animated.AnimatedInterpolation;
private onGestureEvent?: (
event: GestureEvent<PanGestureHandlerEventPayload>
) => void;
private accessibilityIsModalView = React.createRef<View>();
private pointerEventsView = React.createRef<View>();
private panGestureHandler = React.createRef<PanGestureHandler | null>();
private drawerShown = false;
static positions = {
Left: 'left',
Right: 'right',
};
private updateAnimatedEvent = (
props: DrawerLayoutProps,
state: DrawerLayoutState
) => {
// Event definition is based on
const { drawerPosition, drawerWidth, drawerType } = props;
const {
dragX: dragXValue,
touchX: touchXValue,
drawerTranslation,
containerWidth,
} = state;
let dragX = dragXValue;
let touchX = touchXValue;
if (drawerPosition !== 'left') {
// Most of the code is written in a way to handle left-side drawer. In
// order to handle right-side drawer the only thing we need to do is to
// reverse events coming from gesture handler in a way they emulate
// left-side drawer gestures. E.g. dragX is simply -dragX, and touchX is
// calulcated by subtracing real touchX from the width of the container
// (such that when touch happens at the right edge the value is simply 0)
dragX = Animated.multiply(
new Animated.Value(-1),
dragXValue
) as Animated.Value; // TODO(TS): (for all "as" in this file) make sure we can map this
touchX = Animated.add(
new Animated.Value(containerWidth),
Animated.multiply(new Animated.Value(-1), touchXValue)
) as Animated.Value; // TODO(TS): make sure we can map this;
touchXValue.setValue(containerWidth);
} else {
touchXValue.setValue(0);
}
// While closing the drawer when user starts gesture outside of its area (in greyed
// out part of the window), we want the drawer to follow only once finger reaches the
// edge of the drawer.
// E.g. on the diagram below drawer is illustrate by X signs and the greyed out area by
// dots. The touch gesture starts at '*' and moves left, touch path is indicated by
// an arrow pointing left
// 1) +---------------+ 2) +---------------+ 3) +---------------+ 4) +---------------+
// |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|
// |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|
// |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|
// |XXXXXXXX|......| |XXXXXXXX|.<-*..| |XXXXXXXX|<--*..| |XXXXX|<-----*..|
// |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|
// |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|
// |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|
// +---------------+ +---------------+ +---------------+ +---------------+
//
// For the above to work properly we define animated value that will keep
// start position of the gesture. Then we use that value to calculate how
// much we need to subtract from the dragX. If the gesture started on the
// greyed out area we take the distance from the edge of the drawer to the
// start position. Otherwise we don't subtract at all and the drawer be
// pulled back as soon as you start the pan.
//
// This is used only when drawerType is "front"
//
let translationX = dragX;
if (drawerType === 'front') {
const startPositionX = Animated.add(
touchX,
Animated.multiply(new Animated.Value(-1), dragX)
);
const dragOffsetFromOnStartPosition = startPositionX.interpolate({
inputRange: [drawerWidth! - 1, drawerWidth!, drawerWidth! + 1],
outputRange: [0, 0, 1],
});
translationX = Animated.add(
dragX,
dragOffsetFromOnStartPosition
) as Animated.Value; // TODO: as above
}
this.openValue = Animated.add(translationX, drawerTranslation).interpolate({
inputRange: [0, drawerWidth!],
outputRange: [0, 1],
extrapolate: 'clamp',
});
const gestureOptions: {
useNativeDriver: boolean;
// TODO: make sure it is correct
listener?: (
ev: NativeSyntheticEvent<PanGestureHandlerEventPayload>
) => void;
} = {
useNativeDriver: props.useNativeAnimations!,
};
if (this.props.onDrawerSlide) {
gestureOptions.listener = (ev) => {
const translationX = Math.floor(Math.abs(ev.nativeEvent.translationX));
const position = translationX / this.state.containerWidth;
this.props.onDrawerSlide?.(position);
};
}
this.onGestureEvent = Animated.event(
[{ nativeEvent: { translationX: dragXValue, x: touchXValue } }],
gestureOptions
);
};
private handleContainerLayout = ({ nativeEvent }: LayoutChangeEvent) => {
this.setState({ containerWidth: nativeEvent.layout.width });
};
private emitStateChanged = (
newState: DrawerState,
drawerWillShow: boolean
) => {
this.props.onDrawerStateChanged?.(newState, drawerWillShow);
};
private openingHandlerStateChange = ({
nativeEvent,
}: HandlerStateChangeEvent<PanGestureHandlerEventPayload>) => {
if (nativeEvent.oldState === State.ACTIVE) {
this.handleRelease({ nativeEvent });
} else if (nativeEvent.state === State.ACTIVE) {
this.emitStateChanged(DRAGGING, false);
this.setState({ drawerState: DRAGGING });
if (this.props.keyboardDismissMode === 'on-drag') {
Keyboard.dismiss();
}
if (this.props.hideStatusBar) {
StatusBar.setHidden(true, this.props.statusBarAnimation || 'slide');
}
}
};
private onTapHandlerStateChange = ({
nativeEvent,
}: HandlerStateChangeEvent<TapGestureHandlerEventPayload>) => {
if (
this.drawerShown &&
nativeEvent.oldState === State.ACTIVE &&
this.props.drawerLockMode !== 'locked-open'
) {
this.closeDrawer();
}
};
private handleRelease = ({
nativeEvent,
}: HandlerStateChangeEvent<PanGestureHandlerEventPayload>) => {
const { drawerWidth, drawerPosition, drawerType } = this.props;
const { containerWidth } = this.state;
let { translationX: dragX, velocityX, x: touchX } = nativeEvent;
if (drawerPosition !== 'left') {
// See description in _updateAnimatedEvent about why events are flipped
// for right-side drawer
dragX = -dragX;
touchX = containerWidth - touchX;
velocityX = -velocityX;
}
const gestureStartX = touchX - dragX;
let dragOffsetBasedOnStart = 0;
if (drawerType === 'front') {
dragOffsetBasedOnStart =
gestureStartX > drawerWidth! ? gestureStartX - drawerWidth! : 0;
}
const startOffsetX =
dragX + dragOffsetBasedOnStart + (this.drawerShown ? drawerWidth! : 0);
const projOffsetX = startOffsetX + DRAG_TOSS * velocityX;
const shouldOpen = projOffsetX > drawerWidth! / 2;
if (shouldOpen) {
this.animateDrawer(startOffsetX, drawerWidth!, velocityX);
} else {
this.animateDrawer(startOffsetX, 0, velocityX);
}
};
private updateShowing = (showing: boolean) => {
this.drawerShown = showing;
this.accessibilityIsModalView.current?.setNativeProps({
accessibilityViewIsModal: showing,
});
this.pointerEventsView.current?.setNativeProps({
pointerEvents: showing ? 'auto' : 'none',
});
const { drawerPosition, minSwipeDistance, edgeWidth } = this.props;
const fromLeft = drawerPosition === 'left';
// gestureOrientation is 1 if the expected gesture is from left to right and
// -1 otherwise e.g. when drawer is on the left and is closed we expect left
// to right gesture, thus orientation will be 1.
const gestureOrientation =
(fromLeft ? 1 : -1) * (this.drawerShown ? -1 : 1);
// When drawer is closed we want the hitSlop to be horizontally shorter than
// the container size by the value of SLOP. This will make it only activate
// when gesture happens not further than SLOP away from the edge
const hitSlop = fromLeft
? { left: 0, width: showing ? undefined : edgeWidth }
: { right: 0, width: showing ? undefined : edgeWidth };
// @ts-ignore internal API, maybe could be fixed in handler types
this.panGestureHandler.current?.setNativeProps({
hitSlop,
activeOffsetX: gestureOrientation * minSwipeDistance!,
});
};
private animateDrawer = (
fromValue: number | null | undefined,
toValue: number,
velocity: number,
speed?: number
) => {
this.state.dragX.setValue(0);
this.state.touchX.setValue(
this.props.drawerPosition === 'left' ? 0 : this.state.containerWidth
);
if (fromValue != null) {
let nextFramePosition = fromValue;
if (this.props.useNativeAnimations) {
// When using native driver, we predict the next position of the
// animation because it takes one frame of a roundtrip to pass RELEASE
// event from native driver to JS before we can start animating. Without
// it, it is more noticable that the frame is dropped.
if (fromValue < toValue && velocity > 0) {
nextFramePosition = Math.min(fromValue + velocity / 60.0, toValue);
} else if (fromValue > toValue && velocity < 0) {
nextFramePosition = Math.max(fromValue + velocity / 60.0, toValue);
}
}
this.state.drawerTranslation.setValue(nextFramePosition);
}
const willShow = toValue !== 0;
this.updateShowing(willShow);
this.emitStateChanged(SETTLING, willShow);
this.setState({ drawerState: SETTLING });
if (this.props.hideStatusBar) {
StatusBar.setHidden(willShow, this.props.statusBarAnimation || 'slide');
}
Animated.spring(this.state.drawerTranslation, {
velocity,
bounciness: 0,
toValue,
useNativeDriver: this.props.useNativeAnimations!,
speed: speed ?? undefined,
}).start(({ finished }) => {
if (finished) {
this.emitStateChanged(IDLE, willShow);
this.setState({ drawerOpened: willShow });
if (this.state.drawerState !== DRAGGING) {
// it's possilbe that user started drag while the drawer
// was settling, don't override state in this case
this.setState({ drawerState: IDLE });
}
if (willShow) {
this.props.onDrawerOpen?.();
} else {
this.props.onDrawerClose?.();
}
}
});
};
openDrawer = (options: DrawerMovementOption = {}) => {
this.animateDrawer(
// TODO: decide if it should be null or undefined is the proper value
undefined,
this.props.drawerWidth!,
options.velocity ? options.velocity : 0,
options.speed
);
// We need to force the update, otherwise the overlay is not rerendered and
// it would not be clickable
this.forceUpdate();
};
closeDrawer = (options: DrawerMovementOption = {}) => {
// TODO: decide if it should be null or undefined is the proper value
this.animateDrawer(
undefined,
0,
options.velocity ? options.velocity : 0,
options.speed
);
// We need to force the update, otherwise the overlay is not rerendered and
// it would be still clickable
this.forceUpdate();
};
private renderOverlay = () => {
/* Overlay styles */
invariant(this.openValue, 'should be set');
let overlayOpacity;
if (this.state.drawerState !== IDLE) {
overlayOpacity = this.openValue;
} else {
overlayOpacity = this.state.drawerOpened ? 1 : 0;
}
const dynamicOverlayStyles = {
opacity: overlayOpacity,
backgroundColor: this.props.overlayColor,
};
return (
<TapGestureHandler onHandlerStateChange={this.onTapHandlerStateChange}>
<Animated.View
pointerEvents={this.drawerShown ? 'auto' : 'none'}
ref={this.pointerEventsView}
style={[styles.overlay, dynamicOverlayStyles]}
/>
</TapGestureHandler>
);
};
private renderDrawer = () => {
const {
drawerBackgroundColor,
drawerWidth,
drawerPosition,
drawerType,
drawerContainerStyle,
contentContainerStyle,
} = this.props;
const fromLeft = drawerPosition === 'left';
const drawerSlide = drawerType !== 'back';
const containerSlide = drawerType !== 'front';
// we rely on row and row-reverse flex directions to position the drawer
// properly. Apparently for RTL these are flipped which requires us to use
// the opposite setting for the drawer to appear from left or right
// according to the drawerPosition prop
const reverseContentDirection = I18nManager.isRTL ? fromLeft : !fromLeft;
const dynamicDrawerStyles = {
backgroundColor: drawerBackgroundColor,
width: drawerWidth,
};
const openValue = this.openValue;
invariant(openValue, 'should be set');
let containerStyles;
if (containerSlide) {
const containerTranslateX = openValue.interpolate({
inputRange: [0, 1],
outputRange: fromLeft ? [0, drawerWidth!] : [0, -drawerWidth!],
extrapolate: 'clamp',
});
containerStyles = {
transform: [{ translateX: containerTranslateX }],
};
}
let drawerTranslateX: number | Animated.AnimatedInterpolation = 0;
if (drawerSlide) {
const closedDrawerOffset = fromLeft ? -drawerWidth! : drawerWidth!;
if (this.state.drawerState !== IDLE) {
drawerTranslateX = openValue.interpolate({
inputRange: [0, 1],
outputRange: [closedDrawerOffset, 0],
extrapolate: 'clamp',
});
} else {
drawerTranslateX = this.state.drawerOpened ? 0 : closedDrawerOffset;
}
}
const drawerStyles: {
transform: { translateX: number | Animated.AnimatedInterpolation }[];
flexDirection: 'row-reverse' | 'row';
} = {
transform: [{ translateX: drawerTranslateX }],
flexDirection: reverseContentDirection ? 'row-reverse' : 'row',
};
return (
<Animated.View style={styles.main} onLayout={this.handleContainerLayout}>
<Animated.View
style={[
drawerType === 'front'
? styles.containerOnBack
: styles.containerInFront,
containerStyles,
contentContainerStyle,
]}
importantForAccessibility={
this.drawerShown ? 'no-hide-descendants' : 'yes'
}>
{typeof this.props.children === 'function'
? this.props.children(this.openValue)
: this.props.children}
{this.renderOverlay()}
</Animated.View>
<Animated.View
pointerEvents="box-none"
ref={this.accessibilityIsModalView}
accessibilityViewIsModal={this.drawerShown}
style={[styles.drawerContainer, drawerStyles, drawerContainerStyle]}>
<View style={dynamicDrawerStyles}>
{this.props.renderNavigationView(this.openValue as Animated.Value)}
</View>
</Animated.View>
</Animated.View>
);
};
private setPanGestureRef = (ref: PanGestureHandler) => {
// TODO(TS): make sure it is OK taken from
// https://github.com/DefinitelyTyped/DefinitelyTyped/issues/31065#issuecomment-596081842
(this
.panGestureHandler as React.MutableRefObject<PanGestureHandler>).current = ref;
this.props.onGestureRef?.(ref);
};
render() {
const {
drawerPosition,
drawerLockMode,
edgeWidth,
minSwipeDistance,
} = this.props;
const fromLeft = drawerPosition === 'left';
// gestureOrientation is 1 if the expected gesture is from left to right and
// -1 otherwise e.g. when drawer is on the left and is closed we expect left
// to right gesture, thus orientation will be 1.
const gestureOrientation =
(fromLeft ? 1 : -1) * (this.drawerShown ? -1 : 1);
// When drawer is closed we want the hitSlop to be horizontally shorter than
// the container size by the value of SLOP. This will make it only activate
// when gesture happens not further than SLOP away from the edge
const hitSlop = fromLeft
? { left: 0, width: this.drawerShown ? undefined : edgeWidth }
: { right: 0, width: this.drawerShown ? undefined : edgeWidth };
return (
<PanGestureHandler
// @ts-ignore could be fixed in handler types
ref={this.setPanGestureRef}
hitSlop={hitSlop}
activeOffsetX={gestureOrientation * minSwipeDistance!}
failOffsetY={[-15, 15]}
onGestureEvent={this.onGestureEvent}
onHandlerStateChange={this.openingHandlerStateChange}
enableTrackpadTwoFingerGesture={
this.props.enableTrackpadTwoFingerGesture
}
enabled={
drawerLockMode !== 'locked-closed' && drawerLockMode !== 'locked-open'
}>
{this.renderDrawer()}
</PanGestureHandler>
);
}
}
const styles = StyleSheet.create({
drawerContainer: {
...StyleSheet.absoluteFillObject,
zIndex: 1001,
flexDirection: 'row',
},
containerInFront: {
...StyleSheet.absoluteFillObject,
zIndex: 1002,
},
containerOnBack: {
...StyleSheet.absoluteFillObject,
},
main: {
flex: 1,
zIndex: 0,
overflow: 'hidden',
},
overlay: {
...StyleSheet.absoluteFillObject,
zIndex: 1000,
},
}); | the_stack |
import isEqual from './util/deep_equal';
const operations = {
/*
* { command: 'setStyle', args: [stylesheet] }
*/
setStyle: 'setStyle',
/*
* { command: 'addLayer', args: [layer, 'beforeLayerId'] }
*/
addLayer: 'addLayer',
/*
* { command: 'removeLayer', args: ['layerId'] }
*/
removeLayer: 'removeLayer',
/*
* { command: 'setPaintProperty', args: ['layerId', 'prop', value] }
*/
setPaintProperty: 'setPaintProperty',
/*
* { command: 'setLayoutProperty', args: ['layerId', 'prop', value] }
*/
setLayoutProperty: 'setLayoutProperty',
/*
* { command: 'setFilter', args: ['layerId', filter] }
*/
setFilter: 'setFilter',
/*
* { command: 'addSource', args: ['sourceId', source] }
*/
addSource: 'addSource',
/*
* { command: 'removeSource', args: ['sourceId'] }
*/
removeSource: 'removeSource',
/*
* { command: 'setGeoJSONSourceData', args: ['sourceId', data] }
*/
setGeoJSONSourceData: 'setGeoJSONSourceData',
/*
* { command: 'setLayerZoomRange', args: ['layerId', 0, 22] }
*/
setLayerZoomRange: 'setLayerZoomRange',
/*
* { command: 'setLayerProperty', args: ['layerId', 'prop', value] }
*/
setLayerProperty: 'setLayerProperty',
/*
* { command: 'setCenter', args: [[lon, lat]] }
*/
setCenter: 'setCenter',
/*
* { command: 'setZoom', args: [zoom] }
*/
setZoom: 'setZoom',
/*
* { command: 'setBearing', args: [bearing] }
*/
setBearing: 'setBearing',
/*
* { command: 'setPitch', args: [pitch] }
*/
setPitch: 'setPitch',
/*
* { command: 'setSprite', args: ['spriteUrl'] }
*/
setSprite: 'setSprite',
/*
* { command: 'setGlyphs', args: ['glyphsUrl'] }
*/
setGlyphs: 'setGlyphs',
/*
* { command: 'setTransition', args: [transition] }
*/
setTransition: 'setTransition',
/*
* { command: 'setLighting', args: [lightProperties] }
*/
setLight: 'setLight'
};
function addSource(sourceId, after, commands) {
commands.push({command: operations.addSource, args: [sourceId, after[sourceId]]});
}
function removeSource(sourceId, commands, sourcesRemoved) {
commands.push({command: operations.removeSource, args: [sourceId]});
sourcesRemoved[sourceId] = true;
}
function updateSource(sourceId, after, commands, sourcesRemoved) {
removeSource(sourceId, commands, sourcesRemoved);
addSource(sourceId, after, commands);
}
function canUpdateGeoJSON(before, after, sourceId) {
let prop;
for (prop in before[sourceId]) {
if (!Object.prototype.hasOwnProperty.call(before[sourceId], prop)) continue;
if (prop !== 'data' && !isEqual(before[sourceId][prop], after[sourceId][prop])) {
return false;
}
}
for (prop in after[sourceId]) {
if (!Object.prototype.hasOwnProperty.call(after[sourceId], prop)) continue;
if (prop !== 'data' && !isEqual(before[sourceId][prop], after[sourceId][prop])) {
return false;
}
}
return true;
}
function diffSources(before, after, commands, sourcesRemoved) {
before = before || {};
after = after || {};
let sourceId;
// look for sources to remove
for (sourceId in before) {
if (!Object.prototype.hasOwnProperty.call(before, sourceId)) continue;
if (!Object.prototype.hasOwnProperty.call(after, sourceId)) {
removeSource(sourceId, commands, sourcesRemoved);
}
}
// look for sources to add/update
for (sourceId in after) {
if (!Object.prototype.hasOwnProperty.call(after, sourceId)) continue;
if (!Object.prototype.hasOwnProperty.call(before, sourceId)) {
addSource(sourceId, after, commands);
} else if (!isEqual(before[sourceId], after[sourceId])) {
if (before[sourceId].type === 'geojson' && after[sourceId].type === 'geojson' && canUpdateGeoJSON(before, after, sourceId)) {
commands.push({command: operations.setGeoJSONSourceData, args: [sourceId, after[sourceId].data]});
} else {
// no update command, must remove then add
updateSource(sourceId, after, commands, sourcesRemoved);
}
}
}
}
function diffLayerPropertyChanges(before, after, commands, layerId, klass, command) {
before = before || {};
after = after || {};
let prop;
for (prop in before) {
if (!Object.prototype.hasOwnProperty.call(before, prop)) continue;
if (!isEqual(before[prop], after[prop])) {
commands.push({command, args: [layerId, prop, after[prop], klass]});
}
}
for (prop in after) {
if (!Object.prototype.hasOwnProperty.call(after, prop) || Object.prototype.hasOwnProperty.call(before, prop)) continue;
if (!isEqual(before[prop], after[prop])) {
commands.push({command, args: [layerId, prop, after[prop], klass]});
}
}
}
function pluckId(layer) {
return layer.id;
}
function indexById(group, layer) {
group[layer.id] = layer;
return group;
}
function diffLayers(before, after, commands) {
before = before || [];
after = after || [];
// order of layers by id
const beforeOrder = before.map(pluckId);
const afterOrder = after.map(pluckId);
// index of layer by id
const beforeIndex = before.reduce(indexById, {});
const afterIndex = after.reduce(indexById, {});
// track order of layers as if they have been mutated
const tracker = beforeOrder.slice();
// layers that have been added do not need to be diffed
const clean = Object.create(null);
let i, d, layerId, beforeLayer, afterLayer, insertBeforeLayerId, prop;
// remove layers
for (i = 0, d = 0; i < beforeOrder.length; i++) {
layerId = beforeOrder[i];
if (!Object.prototype.hasOwnProperty.call(afterIndex, layerId)) {
commands.push({command: operations.removeLayer, args: [layerId]});
tracker.splice(tracker.indexOf(layerId, d), 1);
} else {
// limit where in tracker we need to look for a match
d++;
}
}
// add/reorder layers
for (i = 0, d = 0; i < afterOrder.length; i++) {
// work backwards as insert is before an existing layer
layerId = afterOrder[afterOrder.length - 1 - i];
if (tracker[tracker.length - 1 - i] === layerId) continue;
if (Object.prototype.hasOwnProperty.call(beforeIndex, layerId)) {
// remove the layer before we insert at the correct position
commands.push({command: operations.removeLayer, args: [layerId]});
tracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1);
} else {
// limit where in tracker we need to look for a match
d++;
}
// add layer at correct position
insertBeforeLayerId = tracker[tracker.length - i];
commands.push({command: operations.addLayer, args: [afterIndex[layerId], insertBeforeLayerId]});
tracker.splice(tracker.length - i, 0, layerId);
clean[layerId] = true;
}
// update layers
for (i = 0; i < afterOrder.length; i++) {
layerId = afterOrder[i];
beforeLayer = beforeIndex[layerId];
afterLayer = afterIndex[layerId];
// no need to update if previously added (new or moved)
if (clean[layerId] || isEqual(beforeLayer, afterLayer)) continue;
// If source, source-layer, or type have changes, then remove the layer
// and add it back 'from scratch'.
if (!isEqual(beforeLayer.source, afterLayer.source) || !isEqual(beforeLayer['source-layer'], afterLayer['source-layer']) || !isEqual(beforeLayer.type, afterLayer.type)) {
commands.push({command: operations.removeLayer, args: [layerId]});
// we add the layer back at the same position it was already in, so
// there's no need to update the `tracker`
insertBeforeLayerId = tracker[tracker.lastIndexOf(layerId) + 1];
commands.push({command: operations.addLayer, args: [afterLayer, insertBeforeLayerId]});
continue;
}
// layout, paint, filter, minzoom, maxzoom
diffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, null, operations.setLayoutProperty);
diffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, null, operations.setPaintProperty);
if (!isEqual(beforeLayer.filter, afterLayer.filter)) {
commands.push({command: operations.setFilter, args: [layerId, afterLayer.filter]});
}
if (!isEqual(beforeLayer.minzoom, afterLayer.minzoom) || !isEqual(beforeLayer.maxzoom, afterLayer.maxzoom)) {
commands.push({command: operations.setLayerZoomRange, args: [layerId, afterLayer.minzoom, afterLayer.maxzoom]});
}
// handle all other layer props, including paint.*
for (prop in beforeLayer) {
if (!Object.prototype.hasOwnProperty.call(beforeLayer, prop)) continue;
if (prop === 'layout' || prop === 'paint' || prop === 'filter' ||
prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') continue;
if (prop.indexOf('paint.') === 0) {
diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty);
} else if (!isEqual(beforeLayer[prop], afterLayer[prop])) {
commands.push({command: operations.setLayerProperty, args: [layerId, prop, afterLayer[prop]]});
}
}
for (prop in afterLayer) {
if (!Object.prototype.hasOwnProperty.call(afterLayer, prop) || Object.prototype.hasOwnProperty.call(beforeLayer, prop)) continue;
if (prop === 'layout' || prop === 'paint' || prop === 'filter' ||
prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') continue;
if (prop.indexOf('paint.') === 0) {
diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty);
} else if (!isEqual(beforeLayer[prop], afterLayer[prop])) {
commands.push({command: operations.setLayerProperty, args: [layerId, prop, afterLayer[prop]]});
}
}
}
}
/**
* Diff two stylesheet
*
* Creates semanticly aware diffs that can easily be applied at runtime.
* Operations produced by the diff closely resemble the maplibre-gl-js API. Any
* error creating the diff will fall back to the 'setStyle' operation.
*
* Example diff:
* [
* { command: 'setConstant', args: ['@water', '#0000FF'] },
* { command: 'setPaintProperty', args: ['background', 'background-color', 'black'] }
* ]
*
* @private
* @param {*} [before] stylesheet to compare from
* @param {*} after stylesheet to compare to
* @returns Array list of changes
*/
function diffStyles(before, after) {
if (!before) return [{command: operations.setStyle, args: [after]}];
let commands = [];
try {
// Handle changes to top-level properties
if (!isEqual(before.version, after.version)) {
return [{command: operations.setStyle, args: [after]}];
}
if (!isEqual(before.center, after.center)) {
commands.push({command: operations.setCenter, args: [after.center]});
}
if (!isEqual(before.zoom, after.zoom)) {
commands.push({command: operations.setZoom, args: [after.zoom]});
}
if (!isEqual(before.bearing, after.bearing)) {
commands.push({command: operations.setBearing, args: [after.bearing]});
}
if (!isEqual(before.pitch, after.pitch)) {
commands.push({command: operations.setPitch, args: [after.pitch]});
}
if (!isEqual(before.sprite, after.sprite)) {
commands.push({command: operations.setSprite, args: [after.sprite]});
}
if (!isEqual(before.glyphs, after.glyphs)) {
commands.push({command: operations.setGlyphs, args: [after.glyphs]});
}
if (!isEqual(before.transition, after.transition)) {
commands.push({command: operations.setTransition, args: [after.transition]});
}
if (!isEqual(before.light, after.light)) {
commands.push({command: operations.setLight, args: [after.light]});
}
// Handle changes to `sources`
// If a source is to be removed, we also--before the removeSource
// command--need to remove all the style layers that depend on it.
const sourcesRemoved = {};
// First collect the {add,remove}Source commands
const removeOrAddSourceCommands = [];
diffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved);
// Push a removeLayer command for each style layer that depends on a
// source that's being removed.
// Also, exclude any such layers them from the input to `diffLayers`
// below, so that diffLayers produces the appropriate `addLayers`
// command
const beforeLayers = [];
if (before.layers) {
before.layers.forEach((layer) => {
if (sourcesRemoved[layer.source]) {
commands.push({command: operations.removeLayer, args: [layer.id]});
} else {
beforeLayers.push(layer);
}
});
}
commands = commands.concat(removeOrAddSourceCommands);
// Handle changes to `layers`
diffLayers(beforeLayers, after.layers, commands);
} catch (e) {
// fall back to setStyle
console.warn('Unable to compute style diff:', e);
commands = [{command: operations.setStyle, args: [after]}];
}
return commands;
}
export default diffStyles;
export {operations}; | the_stack |
import {
ReactNativeZoomableViewProps,
ReactNativeZoomableViewState,
ZoomableViewEvent,
} from '@dudigital/react-native-zoomable-view';
import React, { Component } from 'react';
import { View, StyleSheet, PanResponder } from 'react-native';
const initialState = {
lastZoomLevel: 1,
offsetX: 0,
offsetY: 0,
lastX: 0,
lastY: 0,
lastMovePinch: false,
originalWidth: null,
originalHeight: null,
};
class ReactNativeZoomableView extends Component<ReactNativeZoomableViewProps, ReactNativeZoomableViewState> {
gestureHandlers: any;
distance: number;
isDistanceSet: boolean;
lastPressHolder: number;
gestureType: 'pinch' | 'shift' | 'null';
contextState = {
distanceLeft: 0,
distanceRight: 0,
distanceTop: 0,
distanceBottom: 0,
};
static defaultProps = {
zoomEnabled: true,
initialZoom: 1,
initialOffsetX: 0,
initialOffsetY: 0,
maxZoom: 1.5,
minZoom: 0.5,
pinchToZoomInSensitivity: 3,
pinchToZoomOutSensitivity: 1,
zoomCenteringLevelDistance: 0.5,
movementSensibility: 1.9,
doubleTapDelay: 300,
bindToBorders: true,
zoomStep: 0.5,
onLongPress: null,
longPressDuration: 700,
captureEvent: false,
};
constructor(props) {
super(props);
this.gestureHandlers = PanResponder.create({
onStartShouldSetPanResponder: this._handleStartShouldSetPanResponder,
onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder,
onPanResponderGrant: this._handlePanResponderGrant,
onPanResponderMove: this._handlePanResponderMove,
onPanResponderRelease: this._handlePanResponderEnd,
onPanResponderTerminate: props.onPanResponderTerminate,
onPanResponderTerminationRequest: props.onPanResponderTerminationRequest ?? ((evt) => false),
onShouldBlockNativeResponder: (evt) => false,
});
this.state = {
...initialState,
zoomLevel: props.initialZoom,
lastZoomLevel: props.initialZoom || initialState.lastZoomLevel,
offsetX: props.initialOffsetX,
offsetY: props.initialOffsetY,
};
this.distance = 150;
this.isDistanceSet = true;
this.gestureType = null;
this.contextState = {
distanceLeft: 0,
distanceRight: 0,
distanceTop: 0,
distanceBottom: 0,
};
}
componentDidUpdate(prevProps) {
const { zoomEnabled, initialZoom } = this.props;
if (prevProps.zoomEnabled && !zoomEnabled) {
this.setState({
zoomLevel: initialZoom,
...initialState,
});
}
}
/**
* Last press time (used to evaluate whether user double tapped)
* @type {number}
*/
longPressTimeout = null;
/**
* Current position of zoom center
* @type { x: number, y: number }
*/
pinchZoomPosition = null;
/**
* Returns additional information about components current state for external event hooks
*
* @returns {{}}
* @private
*/
_getZoomableViewEventObject(overwriteObj = {}): ZoomableViewEvent {
return {
...this.state,
...this.contextState,
...overwriteObj,
} as ZoomableViewEvent;
}
/**
* Get the original box dimensions and save them for later use.
* (They will be used to calculate boxBorders)
*
* @param layoutEvent
* @private
*/
_getBoxDimensions = (layoutEvent) => {
const { x, y, height, width } = layoutEvent.nativeEvent.layout;
this.setState({
originalWidth: width,
originalHeight: height,
});
};
/**
* Handles the start of touch events and checks for taps
*
* @param e
* @param gestureState
* @returns {boolean}
*
* @private
*/
_handleStartShouldSetPanResponder = (e, gestureState) => {
this._doubleTapCheck(e, gestureState);
if (this.props.onStartShouldSetPanResponder) {
this.props.onStartShouldSetPanResponder(e, gestureState, this._getZoomableViewEventObject(), false);
}
return this.props.captureEvent;
};
/**
* Checks if the movement responder should be triggered
*
* @param e
* @param gestureState
* @returns {Boolean|boolean}
*/
_handleMoveShouldSetPanResponder = (e, gestureState) => {
let baseComponentResult =
this.props.zoomEnabled &&
(Math.abs(gestureState.dx) > 2 || Math.abs(gestureState.dy) > 2 || gestureState.numberActiveTouches === 2);
if (this.props.onMoveShouldSetPanResponder) {
baseComponentResult = this.props.onMoveShouldSetPanResponder(
e,
gestureState,
this._getZoomableViewEventObject(),
baseComponentResult,
);
}
return baseComponentResult;
};
/**
* Calculates pinch distance
*
* @param e
* @param gestureState
* @private
*/
_handlePanResponderGrant = (e, gestureState) => {
this.isDistanceSet = false;
if (gestureState.numberActiveTouches === 2) {
let dx = Math.abs(e.nativeEvent.touches[0].pageX - e.nativeEvent.touches[1].pageX);
let dy = Math.abs(e.nativeEvent.touches[0].pageY - e.nativeEvent.touches[1].pageY);
let distant = Math.sqrt(dx * dx + dy * dy);
this.distance = distant;
this.isDistanceSet = true;
}
if (this.props.onLongPress) {
this.longPressTimeout = setTimeout(() => {
if (this.props.onLongPress) {
this.props.onLongPress(e, gestureState, this._getZoomableViewEventObject());
this.longPressTimeout = null;
}
}, this.props.longPressDuration);
}
if (this.props.onPanResponderGrant) {
this.props.onPanResponderGrant(e, gestureState, this._getZoomableViewEventObject());
}
};
/**
* Handles the end of touch events
*
* @param e
* @param gestureState
*
* @private
*/
_handlePanResponderEnd = (e, gestureState) => {
this.setState({
lastX: this.state.offsetX,
lastY: this.state.offsetY,
lastZoomLevel: this.state.zoomLevel,
});
if (this.longPressTimeout) {
clearTimeout(this.longPressTimeout);
this.longPressTimeout = null;
}
if (this.props.onPanResponderEnd) {
this.props.onPanResponderEnd(e, gestureState, this._getZoomableViewEventObject());
}
if (this.gestureType === 'pinch') {
this.pinchZoomPosition = null;
if (this.props.onZoomEnd) {
this.props.onZoomEnd(e, gestureState, this._getZoomableViewEventObject());
}
} else if (this.gestureType === 'shift') {
if (this.props.onShiftingEnd) {
this.props.onShiftingEnd(e, gestureState, this._getZoomableViewEventObject());
}
}
this.gestureType = null;
};
/**
* Takes a single offset value and calculates the correct offset value within our view to make
*
* @param {'x'|'y'} axis
* @param offsetValue
* @param containerSize
* @param elementSize
* @param zoomLevel
*
* @returns {number}
*/
_getBoundOffsetValue(
axis: 'x' | 'y',
offsetValue: number,
containerSize: number,
elementSize: number,
zoomLevel: number,
) {
const zoomLevelOffsetValue = zoomLevel * offsetValue;
const containerToScaledElementRatioSub = 1 - containerSize / elementSize;
const halfLengthPlusScaledHalf = 0.5 + 0.5 / zoomLevel;
const startBorder = containerSize * containerToScaledElementRatioSub * halfLengthPlusScaledHalf;
const endBorder = (containerSize + startBorder - containerSize) * -1;
// calculate distance to start and end borders
const distanceToStart = offsetValue - startBorder;
const distanceToEnd = (offsetValue + startBorder) * -1;
// set context for callback events
this._setContextStateDistances(axis, distanceToStart, distanceToEnd);
// if both sides (before and after the element) have a positive distance
// => (our zoomed content is smaller than the frame)
// => so center it
if (containerSize > elementSize) {
return containerSize / 2 - elementSize / 2 / zoomLevel;
}
// if everything above failed
// => (one side is outside of the borders)
// => find out which one it is and make sure it is 0
if (distanceToStart > 0) {
return startBorder;
}
// if there is distance to the end border
// => (it is outside of the box)
// => adjust offset to make sure it stays within
if (distanceToEnd > 0) {
return endBorder;
}
// if everything above failed
// => (everything is within borders)
// => just return the original offset value
return offsetValue;
}
/**
* Sets the distance to borders for callback events
*
* @param axis
* @param distanceToStart
* @param distanceToEnd
* @private
*/
_setContextStateDistances(axis: 'x' | 'y', distanceToStart: number, distanceToEnd: number) {
if (axis === 'x') {
this.contextState.distanceLeft = distanceToStart;
this.contextState.distanceRight = distanceToEnd;
return;
}
this.contextState.distanceTop = distanceToStart;
this.contextState.distanceBottom = distanceToEnd;
}
/**
* Takes a change object (that is going to be used in setState) and makes sure offsetX and
* offsetY are within our view borders. If that is not the case, they will be corrected.
*
* @param changeObj the object that is going to be modified.
* Needs to contain at least the following elements:
* {
* zoomLevel: numeric,
* offsetX: numeric,
* offsetY: numeric,
* }
* @private
*/
_bindOffsetValuesToBorders(changeObj, bindToBorders = null) {
// if bindToBorders is disabled -> nothing do here
if (bindToBorders === false || (bindToBorders === null && !this.props.bindToBorders)) {
return changeObj;
}
const { originalWidth, originalHeight } = this.state;
const currentElementWidth = originalWidth * changeObj.zoomLevel;
const currentElementHeight = originalHeight * changeObj.zoomLevel;
// make sure that view doesn't go out of borders
const offsetXBound = this._getBoundOffsetValue(
'x',
changeObj.offsetX,
originalWidth,
currentElementWidth,
changeObj.zoomLevel,
);
changeObj.offsetX = offsetXBound;
const offsetYBound = this._getBoundOffsetValue(
'y',
changeObj.offsetY,
originalHeight,
currentElementHeight,
changeObj.zoomLevel,
);
changeObj.offsetY = offsetYBound;
return changeObj;
}
/**
* Handles the acutal movement of our pan responder
*
* @param e
* @param gestureState
*
* @private
*/
_handlePanResponderMove = (e, gestureState) => {
if (this.props.onPanResponderMove) {
if (this.props.onPanResponderMove(e, gestureState, this._getZoomableViewEventObject())) {
return false;
}
}
if (gestureState.numberActiveTouches === 2) {
if (this.longPressTimeout) {
clearTimeout(this.longPressTimeout);
this.longPressTimeout = null;
}
if (!this.isDistanceSet) {
this._handlePanResponderGrant(e, gestureState);
}
this.gestureType = 'pinch';
this._handlePinching(e, gestureState);
} else if (gestureState.numberActiveTouches === 1) {
if (this.longPressTimeout && (Math.abs(gestureState.dx) > 5 || Math.abs(gestureState.dy) > 5)) {
clearTimeout(this.longPressTimeout);
this.longPressTimeout = null;
}
if (this.gestureType !== 'pinch') {
this.gestureType = 'shift';
}
this._handleMovement(e, gestureState);
}
};
/**
* Handles the pinch movement and zooming
*
* @param e
* @param gestureState
*
* @private
*/
_handlePinching = (e, gestureState) => {
const { maxZoom, minZoom, zoomCenteringLevelDistance, pinchToZoomInSensitivity, pinchToZoomOutSensitivity } =
this.props;
let dx = Math.abs(e.nativeEvent.touches[0].pageX - e.nativeEvent.touches[1].pageX);
let dy = Math.abs(e.nativeEvent.touches[0].pageY - e.nativeEvent.touches[1].pageY);
let distant = Math.sqrt(dx * dx + dy * dy);
if (this.props.onZoomBefore) {
if (this.props.onZoomBefore(e, gestureState, this._getZoomableViewEventObject())) {
return false;
}
}
// define the new zoom level and take zoom level sensitivity into consideration
const zoomChangeFromStartOfPinch = distant / this.distance;
const pinchToZoomSensitivity =
zoomChangeFromStartOfPinch < 1 ? pinchToZoomOutSensitivity : pinchToZoomInSensitivity;
let zoomLevel =
(zoomChangeFromStartOfPinch * this.state.lastZoomLevel + this.state.lastZoomLevel * pinchToZoomSensitivity) /
(pinchToZoomSensitivity + 1);
// make sure max and min zoom levels are respected
if (maxZoom !== null && zoomLevel > maxZoom) {
zoomLevel = maxZoom;
}
if (zoomLevel < minZoom) {
zoomLevel = minZoom;
}
// only use the first position we get by pinching, or the screen will "wobble" during zoom action
if (this.pinchZoomPosition === null) {
const pinchToZoomCenterX = Math.min(e.nativeEvent.touches[0].pageX, e.nativeEvent.touches[1].pageX) + dx / 2;
const pinchToZoomCenterY = Math.min(e.nativeEvent.touches[0].pageY, e.nativeEvent.touches[1].pageY) + dy / 2;
this.pinchZoomPosition = this._getOffsetAdjustedPosition(pinchToZoomCenterX, pinchToZoomCenterY);
}
// make sure we shift the layer slowly during our zoom movement
const zoomStage = Math.abs(zoomLevel - this.state.lastZoomLevel) / zoomCenteringLevelDistance;
const ratioOffsetX = this.state.lastX + zoomStage * this.pinchZoomPosition.x;
const ratioOffsetY = this.state.lastY + zoomStage * this.pinchZoomPosition.y;
// define the changeObject and make sure the offset values are bound to view
const changeStateObj = this._bindOffsetValuesToBorders(
{
zoomLevel,
lastMovePinch: true,
offsetX: ratioOffsetX,
offsetY: ratioOffsetY,
},
null,
);
this.setState(changeStateObj, () => {
if (this.props.onZoomAfter) {
this.props.onZoomAfter(e, gestureState, this._getZoomableViewEventObject());
}
});
};
/**
* Handles movement by tap and move
*
* @param e
* @param gestureState
*
* @private
*/
_handleMovement = (e, gestureState) => {
const { movementSensibility } = this.props;
// make sure not to accidentally move after pinch to zoom
if (this.pinchZoomPosition) {
return;
}
let offsetX = this.state.lastX + gestureState.dx / this.state.zoomLevel / movementSensibility;
let offsetY = this.state.lastY + gestureState.dy / this.state.zoomLevel / movementSensibility;
this._setNewOffsetPosition(offsetX, offsetY);
};
/**
* Set the state to offset moved
*
* @param {number} newOffsetX
* @param {number} newOffsetY
* @param {bool} bindToBorders
* @param {bool} updateLastCoords should the last coordinates be updated as well?
* @param {() => void)} callbk
* @returns
*/
_setNewOffsetPosition = (
newOffsetX: number,
newOffsetY: number,
bindToBorders = true,
updateLastCoords = false,
callbk = null,
) => {
const { onShiftingBefore, onShiftingAfter } = this.props;
if (onShiftingBefore) {
if (onShiftingBefore(null, null, this._getZoomableViewEventObject())) {
return false;
}
}
const changeStateObj = this._bindOffsetValuesToBorders(
{
lastMovePinch: false,
zoomLevel: this.state.zoomLevel,
offsetX: newOffsetX,
offsetY: newOffsetY,
},
bindToBorders,
);
// if we want to update last coords as well -> do that
if (updateLastCoords) {
changeStateObj.lastX = changeStateObj.offsetX;
changeStateObj.lastY = changeStateObj.offsetY;
}
this.setState(changeStateObj, () => {
if (callbk) {
callbk();
}
if (onShiftingAfter) {
if (onShiftingAfter(null, null, this._getZoomableViewEventObject())) {
return false;
}
}
});
};
/**
* Wraps the check for double tap
*
* @param e
* @param gestureState
*
* @private
*/
_doubleTapCheck = (e, gestureState) => {
const now = new Date().getTime();
if (this.lastPressHolder && now - this.lastPressHolder < this.props.doubleTapDelay) {
delete this.lastPressHolder;
this._handleDoubleTap(e, gestureState);
} else {
this.lastPressHolder = now;
}
};
/**
* Handles the double tap event
*
* @param event
* @param gestureState
*
* @private
*/
_handleDoubleTap(e, gestureState) {
const { onDoubleTapBefore, onDoubleTapAfter, doubleTapZoomToCenter } = this.props;
// ignore more than 2 touches
if (gestureState.numberActiveTouches > 1 || !this.props.zoomEnabled) {
return;
}
if (onDoubleTapBefore) {
onDoubleTapBefore(e, gestureState, this._getZoomableViewEventObject());
}
const nextZoomStep = this._getNextZoomStep();
// define new zoom position coordinates
const zoomPositionCoordinates = {
x: e.nativeEvent.locationX,
y: e.nativeEvent.locationY,
};
// if doubleTapZoomToCenter enabled -> always zoom to center instead
if (doubleTapZoomToCenter) {
zoomPositionCoordinates.x = 0;
zoomPositionCoordinates.y = 0;
}
this._zoomToLocation(zoomPositionCoordinates.x, zoomPositionCoordinates.y, nextZoomStep, true, () => {
if (onDoubleTapAfter) {
onDoubleTapAfter(
e,
gestureState,
this._getZoomableViewEventObject({
zoomLevel: nextZoomStep,
}),
);
}
});
}
/**
* Returns the next zoom step based on current step and zoomStep property.
* If we are zoomed all the way in -> return to initialzoom
*
* @returns {*}
*/
_getNextZoomStep() {
const { zoomStep, maxZoom, initialZoom } = this.props;
const { zoomLevel } = this.state;
if (zoomLevel === maxZoom) {
return initialZoom;
}
let nextZoomStep = zoomLevel + zoomLevel * zoomStep;
if (maxZoom !== null && nextZoomStep > maxZoom) {
return maxZoom;
}
return nextZoomStep;
}
/**
* Converts touch events x and y coordinates into the context of our element center
*
* @param x
* @param y
* @returns {{x: number, y: number}}
*
* @private
*/
_getOffsetAdjustedPosition(x: number, y: number) {
const { originalWidth, originalHeight } = this.state;
if (x === 0 && y === 0) {
return {
x: 0,
y: 0,
};
}
const returnObj = {
x: -x + originalWidth / 2,
y: -y + originalHeight / 2,
};
return returnObj;
}
/**
* Zooms to a specific location in our view
*
* @param x
* @param y
* @param newZoomLevel
* @param bindToBorders
* @param callbk
*
* @private
*/
_zoomToLocation(x: number, y: number, newZoomLevel: number, bindToBorders = true, callbk = null) {
const offsetAdjustedPosition = this._getOffsetAdjustedPosition(x, y);
if (this.props.onZoomBefore) {
this.props.onZoomBefore(null, null, this._getZoomableViewEventObject());
}
// define the changeObject and make sure the offset values are bound to view
const changeStateObj = this._bindOffsetValuesToBorders(
{
zoomLevel: newZoomLevel,
offsetX: offsetAdjustedPosition.x,
offsetY: offsetAdjustedPosition.y,
lastZoomLevel: newZoomLevel,
lastX: offsetAdjustedPosition.x,
lastY: offsetAdjustedPosition.y,
},
bindToBorders,
);
this.setState(changeStateObj, () => {
if (callbk) {
callbk();
}
if (this.props.onZoomAfter) {
this.props.onZoomAfter(null, null, this._getZoomableViewEventObject());
}
});
}
/**
* Zooms to a specificied zoom level.
* Returns a promise if everything was updated and a boolean, whether it could be updated or if it exceeded the min/max zoom limits.
*
* @param {number} newZoomLevel
* @param {bool} bindToBorders
*
* @return {Promise<bool>}
*/
zoomTo(newZoomLevel: number, bindToBorders = true): Promise<boolean> {
return new Promise((resolve) => {
// if we would go out of our min/max limits -> abort
if (newZoomLevel >= this.props.maxZoom || newZoomLevel <= this.props.minZoom) {
resolve(false);
return;
}
this._zoomToLocation(0, 0, newZoomLevel, bindToBorders, () => {
resolve(true);
});
});
}
/**
* Zooms in or out by a specificied change level
* Use a positive number for `zoomLevelChange` to zoom in
* Use a negative number for `zoomLevelChange` to zoom out
*
* Returns a promise if everything was updated and a boolean, whether it could be updated or if it exceeded the min/max zoom limits.
*
* @param {number} newZoomLevel
* @param {bool} bindToBorders
*
* @return {Promise<bool>}
*/
zoomBy(zoomLevelChange: number = null, bindToBorders = true): Promise<boolean> {
// if no zoom level Change given -> just use zoom step
if (!zoomLevelChange) {
zoomLevelChange = this.props.zoomStep;
}
return this.zoomTo(this.state.zoomLevel + zoomLevelChange, bindToBorders);
}
/**
* Moves the zoomed view to a specified position
* Returns a promise when finished
*
* @param {number} newOffsetX the new position we want to move it to (x-axis)
* @param {number} newOffsetY the new position we want to move it to (y-axis)
* @param {bool} bindToBorders
*
* @return {Promise<bool>}
*/
moveTo(newOffsetX: number, newOffsetY: number, bindToBorders = true): Promise<void> {
const { zoomLevel, originalWidth, originalHeight } = this.state;
let offsetX = (newOffsetX - originalWidth / 2) / zoomLevel;
let offsetY = (newOffsetY - originalHeight / 2) / zoomLevel;
return new Promise((resolve) => {
this._setNewOffsetPosition(-offsetX, -offsetY, bindToBorders, true, () => {
resolve();
});
});
}
/**
* Moves the zoomed view by a certain amount.
*
* Returns a promise when finished
*
* @param {number} offsetChangeX the amount we want to move the offset by (x-axis)
* @param {number} offsetChangeXY the amount we want to move the offset by (y-axis)
* @param {bool} bindToBorders
*
* @return {Promise<bool>}
*/
moveBy(offsetChangeX: number, offsetChangeY: number, bindToBorders = true): Promise<void> {
const { zoomLevel, lastX, lastY } = this.state;
let offsetX = lastX - offsetChangeX / zoomLevel;
let offsetY = lastY - offsetChangeY / zoomLevel;
return new Promise((resolve) => {
this._setNewOffsetPosition(offsetX, offsetY, bindToBorders, true, () => {
resolve();
});
});
}
render() {
return (
<View style={styles.container} {...this.gestureHandlers.panHandlers} onLayout={this._getBoxDimensions}>
<View
style={[
styles.wrapper,
this.props.style,
{
transform: [
{ scale: this.state.zoomLevel },
{ scale: this.state.zoomLevel },
{ translateX: this.state.offsetX },
{ translateY: this.state.offsetY },
],
},
]}
>
{this.props.children}
</View>
</View>
);
}
}
/*
TODO: delete them if not needed anymore
ReactNativeZoomableView.propTypes = {
...View.propTypes,
zoomEnabled: PropTypes.bool,
initialZoom: PropTypes.number,
initialOffsetX: PropTypes.number,
initialOffsetY: PropTypes.number,
maxZoom: PropTypes.number,
minZoom: PropTypes.number,
pinchToZoomInSensitivity: PropTypes.number, // the level of resistance (sensitivity) to zoom in (0 - 10) - higher is less sensitive - default: 3
pinchToZoomOutSensitivity: PropTypes.number, // the level of resistance (sensitivity) to zoom out (0 - 10) - higher is less sensitive default: 1
zoomCenteringLevelDistance: PropTypes.number, // the (zoom level - 0 - maxZoom) distance for pinch to zoom actions until they are shifted on new pinch to zoom center - higher means it centeres slower - default 0.5
movementSensibility: PropTypes.number, // how resistant should shifting the view around be? (0.5 - 5) - higher is less sensitive - default: 1.9
doubleTapDelay: PropTypes.number, // how much delay will still be recognized as double press
bindToBorders: PropTypes.bool, // makes sure that the object stays within box borders
zoomStep: PropTypes.number, // how much zoom should be applied on double tap
onZoomBefore: PropTypes.func, // triggered before pinch movement
onZoomAfter: PropTypes.func, // triggered after pinch movement
onZoomEnd: PropTypes.func, // triggered after pinch movement ended
onDoubleTapBefore: PropTypes.func,
onDoubleTapAfter: PropTypes.func,
onShiftingBefore: PropTypes.func, // triggered before shift movement
onShiftingAfter: PropTypes.func, // triggered after shift movement
onShiftingEnd: PropTypes.func, // triggered after shift movement ended
onStartShouldSetPanResponder: PropTypes.func,
onMoveShouldSetPanResponder: PropTypes.func,
onPanResponderGrant: PropTypes.func,
onPanResponderEnd: PropTypes.func,
onPanResponderMove: PropTypes.func,
onLongPress: PropTypes.func,
longPressDuration: PropTypes.number
};
ReactNativeZoomableView.defaultProps = {
zoomEnabled: true,
initialZoom: 1,
initialOffsetX: 0,
initialOffsetY: 0,
maxZoom: 1.5,
minZoom: 0.5,
pinchToZoomInSensitivity: 3,
pinchToZoomOutSensitivity: 1,
zoomCenteringLevelDistance: 0.5,
movementSensibility: 1.9,
doubleTapDelay: 300,
bindToBorders: true,
zoomStep: 0.5,
onLongPress: null,
longPressDuration: 700,
captureEvent: false,
}; */
const styles = StyleSheet.create({
wrapper: {
flex: 1,
width: '100%',
justifyContent: 'center',
},
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
position: 'relative',
},
});
export default ReactNativeZoomableView; | the_stack |
import {co, component, Coroutine, Entity, field, System, SystemType, World} from '../src';
let counter = 0;
let coroutine: () => Generator;
let wrapperHandle: Coroutine;
let coroutineHandle: Coroutine;
@component class Foo {
@field.int32 declare bar: number;
}
class StartCoroutine extends System {
q = this.query(q => q.using(Foo));
initialize(): void {
coroutineHandle = this.start(coroutine);
}
}
class StartNestedCoroutine extends System {
initialize(): void {
wrapperHandle = this.wrap();
}
@co *wrap() {
counter += 1;
const v = (yield coroutineHandle = this.start(coroutine)) as number;
counter += v;
}
}
class CatchNestedCoroutine extends System {
initialize(): void {
this.wrap();
}
@co *wrap() {
try {
yield this.start(coroutine);
} catch (e) {
counter += 1;
}
}
}
class StartTwoCoroutines extends System {
turn = 0;
declare deco1: (routine: Coroutine) => void;
declare deco2: (routine: Coroutine) => void;
execute() {
switch (this.turn++) {
case 0: this.deco1(this.start(this.fn1)); break;
case 1: this.deco2(this.start(this.fn2)); break;
}
}
*fn1() {
counter += 1;
yield;
counter += 1;
}
*fn2() {
counter += 10;
yield;
counter += 10;
}
}
async function createWorld(...systems: SystemType<System>[] | any): Promise<World> {
return World.create({
maxEntities: 100, defaultComponentStorage: 'sparse', defs: systems
});
}
function sleep(seconds: number) {
return new Promise(resolve => setTimeout(resolve, seconds * 1000));
}
beforeEach(() => {
counter = 0;
});
describe('test running', () => {
it('executes a coroutine', async () => {
coroutine = function*() {
counter += 1;
yield;
};
const world = await createWorld(StartCoroutine);
await world.execute();
expect(counter).toBe(1);
});
it('propagates an exception', async () => {
coroutine = function*() {
throw new Error('foo');
yield;
};
const world = await createWorld(StartCoroutine);
await expect(world.execute()).rejects.toThrow('foo');
});
it('executes a nested coroutine with return value', async () => {
coroutine = function*() {
counter += 1;
yield;
return 5;
};
const world = await createWorld(StartNestedCoroutine);
await world.execute();
expect(counter).toBe(2);
await world.execute();
expect(counter).toBe(7);
});
it('propagates a nested exception', async () => {
coroutine = function*() {
throw new Error('foo');
yield;
};
const world = await createWorld(StartNestedCoroutine);
// First execute starts wrapper, starts nested coroutine, and throws error.
await world.execute();
// Second execute advances wrapper and rethrows the exception.
await expect(world.execute()).rejects.toThrow('foo');
});
it('catches a nested exception', async () => {
coroutine = function*() {
throw new Error('foo');
yield;
};
const world = await createWorld(CatchNestedCoroutine);
await world.execute();
await world.execute();
expect(counter).toBe(1);
});
});
describe('test waiting', () => {
it('waits for the next frame on yield', async () => {
coroutine = function*() {
counter += 1;
yield;
counter += 1;
};
const world = await createWorld(StartCoroutine);
await world.execute();
expect(counter).toBe(1);
await world.execute();
expect(counter).toBe(2);
});
it('skips a frame', async () => {
coroutine = function*() {
counter += 1;
yield co.waitForFrames(2);
counter += 1;
};
const world = await createWorld(StartCoroutine);
await world.execute();
expect(counter).toBe(1);
await world.execute();
expect(counter).toBe(1);
await world.execute();
expect(counter).toBe(2);
});
it('waits for seconds', async () => {
coroutine = function*() {
counter += 1;
yield co.waitForSeconds(0.05);
counter += 1;
};
const world = await createWorld(StartCoroutine);
await world.execute();
expect(counter).toBe(1);
await world.execute();
expect(counter).toBe(1);
await sleep(0.5);
await world.execute();
expect(counter).toBe(2);
});
it('waits for condition', async () => {
let resume = false;
coroutine = function*() {
counter += 1;
yield co.waitUntil(() => resume);
counter += 1;
};
const world = await createWorld(StartCoroutine);
await world.execute();
expect(counter).toBe(1);
await world.execute();
expect(counter).toBe(1);
resume = true;
await world.execute();
expect(counter).toBe(2);
});
});
describe('test cancelling', () => {
it('cancels a coroutine from outside', async () => {
coroutine = function*() {
counter += 1;
yield;
counter += 1;
};
const world = await createWorld(StartCoroutine);
await world.execute();
expect(counter).toBe(1);
coroutineHandle.cancel();
await world.execute();
expect(counter).toBe(1);
});
it('cancels a coroutine from inside', async () => {
coroutine = function*() {
counter += 1;
co.cancel();
yield;
counter += 1;
};
const world = await createWorld(StartCoroutine);
await world.execute();
expect(counter).toBe(1);
await world.execute();
expect(counter).toBe(1);
});
it('cancels a nested coroutine from the top', async () => {
coroutine = function*() {
counter += 1;
yield;
counter += 2;
return 5;
};
const world = await createWorld(StartNestedCoroutine);
await world.execute();
expect(counter).toBe(2);
wrapperHandle.cancel();
await world.execute();
expect(counter).toBe(2);
});
it('cancels a nested coroutine from the bottom, from outside', async () => {
coroutine = function*() {
counter += 1;
yield;
counter += 2;
return 5;
};
const world = await createWorld(StartNestedCoroutine);
await world.execute();
expect(counter).toBe(2);
coroutineHandle.cancel();
await world.execute();
expect(counter).toBe(2);
});
it('cancels a nested coroutine from the bottom, from inside', async () => {
coroutine = function*() {
counter += 1;
co.cancel();
yield;
counter += 2;
return 5;
};
const world = await createWorld(StartNestedCoroutine);
await world.execute();
expect(counter).toBe(2);
await world.execute();
expect(counter).toBe(2);
});
it('cancels a coroutine if a condition is true', async () => {
let abort = false;
coroutine = function*() {
co.cancelIf(() => abort);
counter += 1;
yield;
counter += 1;
};
const world = await createWorld(StartCoroutine);
await world.execute();
expect(counter).toBe(1);
abort = true;
await world.execute();
expect(counter).toBe(1);
});
it('cancels a coroutine if a condition is true when it is blocked on another', async () => {
let abort = false;
coroutine = function*() {
counter += 1;
yield;
counter += 1;
yield;
return 5;
};
const world = await createWorld(StartNestedCoroutine);
wrapperHandle.cancelIf(() => abort);
await world.execute();
expect(counter).toBe(2);
abort = true;
await world.execute();
expect(counter).toBe(2);
await world.execute();
expect(counter).toBe(2);
});
it('cancels a scoped coroutine if the entity has been deleted', async () => {
let entity: Entity;
coroutine = function*() {
counter += 1;
yield;
counter += 1;
};
const world = await createWorld(StartCoroutine);
world.build(sys => {
entity = sys.createEntity().hold();
coroutineHandle.scope(entity);
});
await world.execute();
expect(counter).toBe(1);
world.build(sys => {
entity.delete();
});
await world.execute();
expect(counter).toBe(1);
});
it('cancels a coroutine if a component has been removed', async () => {
let entity: Entity;
coroutine = function*() {
counter += 1;
yield;
counter += 1;
};
const world = await createWorld(StartCoroutine);
world.build(sys => {
entity = sys.createEntity(Foo).hold();
coroutineHandle.scope(entity).cancelIfComponentMissing(Foo);
});
await world.execute();
expect(counter).toBe(1);
world.build(sys => {
entity.remove(Foo);
});
await world.execute();
expect(counter).toBe(1);
});
it('cancels a coroutine if another coroutine starts', async () => {
let entity: Entity;
const world = await createWorld(StartTwoCoroutines, {
deco1: (co1: Coroutine) => co1.cancelIfCoroutineStarted(),
deco2: (co2: Coroutine) => co2
});
world.build(sys => {
entity = sys.createEntity().hold(); // eslint-disable-line @typescript-eslint/no-unused-vars
});
await world.execute();
expect(counter).toBe(1);
await world.execute();
expect(counter).toBe(11);
await world.execute();
expect(counter).toBe(21);
});
it('cancels a scoped coroutine if another coroutine with same scope starts', async () => {
let entity: Entity;
const world = await createWorld(StartTwoCoroutines, {
deco1: (co1: Coroutine) => co1.scope(entity).cancelIfCoroutineStarted(),
deco2: (co2: Coroutine) => co2.scope(entity)
});
world.build(sys => {
entity = sys.createEntity().hold(); // eslint-disable-line @typescript-eslint/no-unused-vars
});
await world.execute();
expect(counter).toBe(1);
await world.execute();
expect(counter).toBe(11);
await world.execute();
expect(counter).toBe(21);
});
it('does not cancel a scoped coroutine if another coroutine without scope starts', async () => {
let entity: Entity;
const world = await createWorld(StartTwoCoroutines, {
deco1: (co1: Coroutine) => co1.scope(entity).cancelIfCoroutineStarted(),
deco2: (co2: Coroutine) => co2
});
world.build(sys => {
entity = sys.createEntity().hold(); // eslint-disable-line @typescript-eslint/no-unused-vars
});
await world.execute();
expect(counter).toBe(1);
await world.execute();
expect(counter).toBe(12);
await world.execute();
expect(counter).toBe(22);
});
it('cancels a coroutine if the given coroutine starts', async () => {
let entity: Entity;
const world = await createWorld(StartTwoCoroutines, {
deco1: (co1: Coroutine) => co1.cancelIfCoroutineStarted(StartTwoCoroutines.prototype.fn2),
deco2: (co2: Coroutine) => co2
});
world.build(sys => {
entity = sys.createEntity().hold(); // eslint-disable-line @typescript-eslint/no-unused-vars
});
await world.execute();
expect(counter).toBe(1);
await world.execute();
expect(counter).toBe(11);
await world.execute();
expect(counter).toBe(21);
});
it('does not cancel a coroutine if a coroutine other than given starts', async () => {
let entity: Entity;
const world = await createWorld(StartTwoCoroutines, {
deco1: (co1: Coroutine) => co1.cancelIfCoroutineStarted(StartTwoCoroutines.prototype.fn1),
deco2: (co2: Coroutine) => co2
});
world.build(sys => {
entity = sys.createEntity().hold(); // eslint-disable-line @typescript-eslint/no-unused-vars
});
await world.execute();
expect(counter).toBe(1);
await world.execute();
expect(counter).toBe(12);
await world.execute();
expect(counter).toBe(22);
});
it('does not cancel itself', async () => {
let entity: Entity;
const world = await createWorld(StartTwoCoroutines, {
deco1: (co1: Coroutine) => co1.cancelIfCoroutineStarted(),
deco2: (co2: Coroutine) => co2.cancelIfCoroutineStarted()
});
world.build(sys => {
entity = sys.createEntity().hold(); // eslint-disable-line @typescript-eslint/no-unused-vars
});
await world.execute();
expect(counter).toBe(1);
await world.execute();
expect(counter).toBe(11);
await world.execute();
expect(counter).toBe(21);
});
}); | the_stack |
import { pick, remove } from "lodash";
import { graphql } from "react-relay";
import {
ConnectionHandler,
Environment,
RecordProxy,
RecordSourceSelectorProxy,
} from "relay-runtime";
import { getViewer, roleIsAtLeast } from "coral-framework/helpers";
import { CoralContext } from "coral-framework/lib/bootstrap";
import { globalErrorReporter } from "coral-framework/lib/errors";
import {
commitMutationPromiseNormalized,
createMutationContainer,
LOCAL_ID,
lookup,
MutationInput,
MutationResponsePromise,
} from "coral-framework/lib/relay";
import {
GQLComment,
GQLStory,
GQLSTORY_MODE,
GQLTAG,
GQLUSER_ROLE,
} from "coral-framework/schema";
import { MAX_REPLY_INDENT_DEPTH } from "coral-stream/constants";
import { CreateCommentReplyEvent } from "coral-stream/events";
import { CreateCommentReplyMutation as MutationTypes } from "coral-stream/__generated__/CreateCommentReplyMutation.graphql";
import {
determineDepthTillAncestor,
determineDepthTillStory,
getFlattenedReplyAncestorID,
incrementStoryCommentCounts,
isPublished,
lookupFlattenReplies,
lookupStoryConnectionKey,
lookupStoryConnectionOrderBy,
lookupStoryConnectionTag,
prependCommentEdgeToProfile,
} from "../../helpers";
export type CreateCommentReplyInput = Omit<
MutationInput<MutationTypes>,
"flattenReplies"
> & {
local?: boolean;
};
function sharedUpdater(
environment: Environment,
store: RecordSourceSelectorProxy,
input: CreateCommentReplyInput,
uuidGenerator: CoralContext["uuidGenerator"]
) {
const commentEdge = store
.getRootField("createCommentReply")!
.getLinkedRecord("edge")!;
const node = commentEdge.getLinkedRecord("node")!;
const status = node.getValue("status");
node.setValue("CREATE", "lastViewerAction");
// If comment is not published, we don't need to add it.
if (!isPublished(status)) {
return;
}
incrementStoryCommentCounts(store, input.storyID, commentEdge);
prependCommentEdgeToProfile(environment, store, commentEdge);
tagExpertAnswers(environment, store, input, commentEdge, uuidGenerator);
if (input.local) {
addLocalCommentReplyToStory(store, input, commentEdge);
} else {
addCommentReplyToStory(environment, store, input, commentEdge);
}
}
function tagExpertAnswers(
environment: Environment,
store: RecordSourceSelectorProxy,
input: CreateCommentReplyInput,
commentEdge: RecordProxy,
uuidGenerator: CoralContext["uuidGenerator"]
) {
const node = commentEdge.getLinkedRecord("node");
if (!node) {
return;
}
const story = store.get(input.storyID);
if (!story) {
return;
}
const storySettings = story.getLinkedRecord("settings");
const mode = storySettings?.getValue("mode");
if (mode !== GQLSTORY_MODE.QA) {
return;
}
const viewer = getViewer(environment)!;
const experts = storySettings?.getLinkedRecords("experts");
// if the author is an expert
if (experts && experts.some((exp) => exp.getValue("id") === viewer.id)) {
const tags = node.getLinkedRecords("tags");
if (tags) {
const featuredTag = store.create(uuidGenerator(), "Tag");
featuredTag.setValue(GQLTAG.FEATURED, "code");
commentEdge.setLinkedRecords(tags.concat(featuredTag), "tags");
}
const parentProxy = store.get(input.parentID);
const parentTags = parentProxy?.getLinkedRecords("tags");
const wasUnanswered =
parentTags &&
parentTags.find((t) => t.getValue("code") === GQLTAG.UNANSWERED);
if (wasUnanswered) {
// remove unanswered tag from parent
if (parentProxy && parentTags && wasUnanswered) {
parentProxy.setLinkedRecords(
remove(parentTags, (tag) => {
return tag.getValue("code") === GQLTAG.UNANSWERED;
}),
"tags"
);
}
const commentCountsRecord = story.getLinkedRecord("commentCounts");
if (!commentCountsRecord) {
return;
}
const tagsRecord = commentCountsRecord.getLinkedRecord("tags");
// increment answered questions and decrement unanswered questions
if (tagsRecord) {
tagsRecord.setValue(
(tagsRecord.getValue("UNANSWERED") as number) - 1,
"UNANSWERED"
);
tagsRecord.setValue(
(tagsRecord.getValue("FEATURED") as number) + 1,
"FEATURED"
);
}
}
}
}
/**
* update integrates new comment into the CommentConnection.
*/
function addCommentReplyToStory(
environment: Environment,
store: RecordSourceSelectorProxy,
input: CreateCommentReplyInput,
commentEdge: RecordProxy
) {
const flattenReplies = lookupFlattenReplies(environment);
const singleCommentID = lookup(environment, LOCAL_ID).commentID;
const comment = commentEdge.getLinkedRecord("node")!;
const depth = singleCommentID
? determineDepthTillAncestor(store, comment, singleCommentID)
: determineDepthTillStory(
store,
comment,
input.storyID,
lookupStoryConnectionOrderBy(environment),
lookupStoryConnectionKey(environment),
lookupStoryConnectionTag(environment)
);
if (depth === null) {
// could not trace back to ancestor, that should not happen.
globalErrorReporter.report(
new Error("Couldn't find reply parent in Relay store")
);
return;
}
const outsideOfView = depth >= MAX_REPLY_INDENT_DEPTH;
let parentProxy = store.get(input.parentID)!;
if (outsideOfView) {
if (!flattenReplies) {
// This should never happen!
globalErrorReporter.report(
new Error("Reply should have been a local reply")
);
return;
}
// In flatten replies we change the parent to the last level ancestor.
const ancestorID = getFlattenedReplyAncestorID(comment, depth)! as string;
parentProxy = store.get(ancestorID)!;
}
// Get parent proxy.
const connectionKey = "ReplyList_replies";
const filters = { orderBy: "CREATED_AT_ASC" };
if (parentProxy) {
const con = ConnectionHandler.getConnection(
parentProxy,
connectionKey,
filters
);
if (con) {
ConnectionHandler.insertEdgeAfter(con, commentEdge);
}
}
}
/**
* localUpdate is like update but updates the `localReplies` endpoint.
*/
function addLocalCommentReplyToStory(
store: RecordSourceSelectorProxy,
input: CreateCommentReplyInput,
commentEdge: RecordProxy
) {
const newComment = commentEdge.getLinkedRecord("node")!;
// Get parent proxy.
const parentProxy = store.get(input.parentID);
if (parentProxy) {
const localReplies = parentProxy.getLinkedRecords("localReplies");
const nextLocalReplies = localReplies
? localReplies.concat(newComment)
: [newComment];
parentProxy.setLinkedRecords(nextLocalReplies, "localReplies");
}
}
/** These are needed to be included when querying for the stream. */
// eslint-disable-next-line no-unused-expressions
graphql`
fragment CreateCommentReplyMutation_story on Story {
url
settings {
moderation
}
}
`;
// eslint-disable-next-line no-unused-expressions
graphql`
fragment CreateCommentReplyMutation_viewer on User {
role
badges
createdAt
status {
current
ban {
active
}
}
}
`;
/** end */
const mutation = graphql`
mutation CreateCommentReplyMutation(
$input: CreateCommentReplyInput!
$flattenReplies: Boolean!
) {
createCommentReply(input: $input) {
edge {
cursor
node {
...AllCommentsTabCommentContainer_comment
id
status
story {
settings {
# Load the story live settings so new comments can verify if live
# updates are still enabled (and enable then if they are).
live {
enabled
}
}
}
parent {
id
tags {
code
}
}
}
}
clientMutationId
}
}
`;
let clientMutationId = 0;
async function commit(
environment: Environment,
input: CreateCommentReplyInput,
{ uuidGenerator, relayEnvironment, eventEmitter }: CoralContext
) {
const parentComment = lookup<GQLComment>(environment, input.parentID)!;
const viewer = getViewer(environment)!;
const currentDate = new Date().toISOString();
const id = uuidGenerator();
const story = lookup<GQLStory>(relayEnvironment, input.storyID)!;
const storySettings = story.settings;
if (!storySettings || !storySettings.moderation) {
throw new Error("Moderation mode of the story was not included");
}
// TODO: Generate and use schema types.
const expectPremoderation =
!roleIsAtLeast(viewer.role, GQLUSER_ROLE.STAFF) &&
storySettings.moderation === "PRE";
const createCommentReplyEvent = CreateCommentReplyEvent.begin(eventEmitter, {
body: input.body,
parentID: input.parentID,
});
try {
const result = await commitMutationPromiseNormalized<MutationTypes>(
environment,
{
mutation,
variables: {
input: {
storyID: input.storyID,
parentID: input.parentID,
parentRevisionID: input.parentRevisionID,
body: input.body || "",
nudge: input.nudge,
clientMutationId: clientMutationId.toString(),
media: input.media,
},
flattenReplies: lookupFlattenReplies(environment),
},
optimisticResponse: {
createCommentReply: {
edge: {
cursor: currentDate,
node: {
id,
enteredLive: false,
createdAt: currentDate,
status: "NONE",
pending: false,
lastViewerAction: "CREATE",
hasTraversalFocus: false,
author: {
id: viewer.id,
username: viewer.username || null,
createdAt: viewer.createdAt,
bio: viewer.bio,
badges: viewer.badges,
ignoreable: false,
avatar: viewer.avatar,
},
body: input.body || "",
revision: {
id: uuidGenerator(),
media: null,
},
rating: null,
parent: {
id: parentComment.id,
author: parentComment.author
? pick(parentComment.author, "username", "id")
: null,
tags: parentComment.tags.map((tag) => ({ code: tag.code })),
},
editing: {
editableUntil: new Date(Date.now() + 10000).toISOString(),
edited: false,
},
actionCounts: {
reaction: {
total: 0,
},
},
tags: roleIsAtLeast(viewer.role, GQLUSER_ROLE.STAFF)
? [{ code: "STAFF" }]
: [],
viewerActionPresence: {
reaction: false,
dontAgree: false,
flag: false,
},
story: {
id: input.storyID,
url: story.url,
settings: {
live: {
enabled: storySettings.live.enabled,
},
},
},
site: {
id: uuidGenerator(),
},
replies: {
edges: [],
viewNewEdges: [],
pageInfo: { endCursor: null, hasNextPage: false },
},
deleted: false,
},
},
clientMutationId: (clientMutationId++).toString(),
},
// TODO: (cvle) fix types.
} as any,
optimisticUpdater: (store) => {
// Skip optimistic update if comment is probably premoderated.
if (expectPremoderation) {
return;
}
sharedUpdater(environment, store, input, uuidGenerator);
store.get(id)!.setValue(true, "pending");
},
updater: (store) => {
sharedUpdater(environment, store, input, uuidGenerator);
},
}
);
createCommentReplyEvent.success({
id: result.edge.node.id,
status: result.edge.node.status,
});
return result;
} catch (error) {
createCommentReplyEvent.error({ message: error.message, code: error.code });
throw error;
}
}
export const withCreateCommentReplyMutation = createMutationContainer(
"createCommentReply",
commit
);
export type CreateCommentReplyMutation = (
input: CreateCommentReplyInput
) => MutationResponsePromise<MutationTypes, "createCommentReply">; | the_stack |
import {visitNode} from "./visitor/visit/visit-node";
import {BeforeVisitorContext} from "./visitor/before-visitor-context";
import {BeforeVisitorOptions} from "./visitor/before-visitor-options";
import {check} from "reserved-words";
import {isNamedDeclaration} from "./util/is-named-declaration";
import {getLocalsForBindingName} from "./util/get-locals-for-binding-name";
import {shouldSkipEmit} from "./util/should-skip-emit";
import {ModuleExports} from "./module-exports/module-exports";
import {visitImportAndExportDeclarations} from "./visitor/visit/visit-import-and-export-declarations";
import {TS} from "../type/ts";
import {shouldDebug} from "./util/should-debug";
import path from "crosspath";
import {VisitorContext} from "./visitor-context";
export interface BeforeTransformerSourceFileStepResult {
sourceFile: TS.SourceFile;
exports: ModuleExports;
}
export function transformSourceFile(sourceFile: TS.SourceFile, context: VisitorContext): BeforeTransformerSourceFileStepResult {
// Take a fast path of the text of the SourceFile doesn't contain anything that can be transformed
if (!context.onlyExports && !sourceFile.text.includes("require") && !sourceFile.text.includes("exports")) {
return {sourceFile, exports: {namedExports: new Set(), hasDefaultExport: false}};
}
const {typescript, factory, transformationContext} = context;
// Prepare a VisitorContext
const visitorContext = ((): BeforeVisitorContext => {
const imports: Map<TS.ImportDeclaration, boolean> = new Map();
const leadingStatements: TS.Statement[] = [];
const trailingStatements: TS.Statement[] = [];
const moduleExportsMap: Map<string, ModuleExports> = new Map();
const localsMap = (sourceFile as {locals?: Map<string, symbol>}).locals;
const locals = localsMap == null ? new Set() : new Set(localsMap.keys());
const exportedLocals = new Set<string>();
let isDefaultExported = false;
const addImport = (declaration: TS.ImportDeclaration, noEmit = false): void => {
imports.set(declaration, noEmit);
};
const markLocalAsExported = (local: string): void => {
exportedLocals.add(local);
};
const isLocalExported = (local: string): boolean => exportedLocals.has(local);
const markDefaultAsExported = (): void => {
isDefaultExported = true;
};
const addLocal = (local: string): void => {
locals.add(local);
};
const getImportDeclarationWithModuleSpecifier = (moduleSpecifier: string): TS.ImportDeclaration | undefined =>
[...imports.keys()].find(
declaration => declaration.moduleSpecifier != null && typescript.isStringLiteralLike(declaration.moduleSpecifier) && declaration.moduleSpecifier.text === moduleSpecifier
);
const isModuleSpecifierImportedWithoutLocals = (moduleSpecifier: string): boolean => {
const matchingDeclaration = getImportDeclarationWithModuleSpecifier(moduleSpecifier);
if (matchingDeclaration == null) return false;
return matchingDeclaration.importClause == null || (matchingDeclaration.importClause.name == null && matchingDeclaration.importClause.namedBindings == null);
};
const getLocalForDefaultImportFromModule = (moduleSpecifier: string): string | undefined => {
const matchingDeclaration = getImportDeclarationWithModuleSpecifier(moduleSpecifier);
if (matchingDeclaration == null) return undefined;
if (matchingDeclaration.importClause == null || matchingDeclaration.importClause.name == null) return undefined;
return matchingDeclaration.importClause.name.text;
};
const hasLocalForDefaultImportFromModule = (moduleSpecifier: string): boolean => getLocalForDefaultImportFromModule(moduleSpecifier) != null;
const getLocalForNamespaceImportFromModule = (moduleSpecifier: string): string | undefined => {
const matchingDeclaration = getImportDeclarationWithModuleSpecifier(moduleSpecifier);
if (matchingDeclaration == null) {
return undefined;
}
if (
matchingDeclaration.importClause == null ||
matchingDeclaration.importClause.namedBindings == null ||
!typescript.isNamespaceImport(matchingDeclaration.importClause.namedBindings)
) {
return undefined;
}
return matchingDeclaration.importClause.namedBindings.name.text;
};
const hasLocalForNamespaceImportFromModule = (moduleSpecifier: string): boolean => getLocalForNamespaceImportFromModule(moduleSpecifier) != null;
const getLocalForNamedImportPropertyNameFromModule = (propertyName: string, moduleSpecifier: string): string | undefined => {
const matchingDeclaration = getImportDeclarationWithModuleSpecifier(moduleSpecifier);
if (matchingDeclaration == null) return undefined;
if (
matchingDeclaration.importClause == null ||
matchingDeclaration.importClause.namedBindings == null ||
!typescript.isNamedImports(matchingDeclaration.importClause.namedBindings)
) {
return undefined;
}
for (const element of matchingDeclaration.importClause.namedBindings.elements) {
if (element.propertyName != null && element.propertyName.text === propertyName) return element.name.text;
else if (element.propertyName == null && element.name.text === propertyName) return element.name.text;
}
return undefined;
};
const hasLocalForNamedImportPropertyNameFromModule = (propertyName: string, moduleSpecifier: string): boolean =>
getLocalForNamedImportPropertyNameFromModule(propertyName, moduleSpecifier) != null;
const addTrailingStatements = (...statements: TS.Statement[]): void => {
trailingStatements.push(...statements);
};
const addLeadingStatements = (...statements: TS.Statement[]): void => {
leadingStatements.push(...statements);
};
const isIdentifierFree = (identifier: string): boolean =>
// It should not be part of locals of the module already
!locals.has(identifier) &&
// It should not be a reserved word in any environment
!check(identifier, "es3", true) &&
!check(identifier, "es5", true) &&
!check(identifier, "es2015", true);
const ignoreIdentifier = (identifier: string): boolean => locals.delete(identifier);
const getFreeIdentifier = (candidate: string, force = false): string => {
const suffix = "$";
let counter = 0;
if (isIdentifierFree(candidate) && !force) {
addLocal(candidate);
return candidate;
}
while (true) {
const currentCandidate = candidate + suffix + counter;
if (!isIdentifierFree(currentCandidate)) {
counter++;
} else {
addLocal(currentCandidate);
return currentCandidate;
}
}
};
return {
...context,
exportsName: undefined,
addImport,
addLocal,
markLocalAsExported,
markDefaultAsExported,
isLocalExported,
isModuleSpecifierImportedWithoutLocals,
getImportDeclarationWithModuleSpecifier,
getLocalForDefaultImportFromModule,
hasLocalForDefaultImportFromModule,
getLocalForNamespaceImportFromModule,
hasLocalForNamespaceImportFromModule,
getLocalForNamedImportPropertyNameFromModule,
hasLocalForNamedImportPropertyNameFromModule,
addLeadingStatements,
addTrailingStatements,
isIdentifierFree,
getFreeIdentifier,
ignoreIdentifier,
getModuleExportsForPath: p => moduleExportsMap.get(path.normalize(p)),
addModuleExportsForPath: (p, exports) => moduleExportsMap.set(path.normalize(p), exports),
get imports() {
return [...imports.entries()].filter(([, noEmit]) => !noEmit).map(([declaration]) => declaration);
},
get leadingStatements() {
return leadingStatements;
},
get trailingStatements() {
return trailingStatements;
},
get isDefaultExported() {
return isDefaultExported;
},
get exportedLocals() {
return exportedLocals;
}
};
})();
const visitorBaseOptions: Pick<BeforeVisitorOptions<TS.Node>, Exclude<keyof BeforeVisitorOptions<TS.Node>, "node" | "sourceFile">> = {
context: visitorContext,
continuation: node =>
visitNode({
...visitorBaseOptions,
sourceFile,
node
}),
childContinuation: node =>
typescript.visitEachChild(
node,
cbNode => {
const visitResult = visitNode({
...visitorBaseOptions,
sourceFile,
node: cbNode
});
if (shouldSkipEmit(visitResult, typescript)) {
return factory.createNotEmittedStatement(cbNode);
}
return visitResult;
},
transformationContext
)
};
const importVisitorBaseOptions: Pick<BeforeVisitorOptions<TS.Node>, Exclude<keyof BeforeVisitorOptions<TS.Node>, "node" | "sourceFile">> = {
context: visitorContext,
continuation: node =>
visitImportAndExportDeclarations({
...importVisitorBaseOptions,
sourceFile,
node
}),
childContinuation: node =>
typescript.visitEachChild(
node,
cbNode => {
const visitResult = visitImportAndExportDeclarations({
...importVisitorBaseOptions,
sourceFile,
node: cbNode
});
if (shouldSkipEmit(visitResult, typescript)) {
return factory.createNotEmittedStatement(cbNode);
}
return visitResult;
},
transformationContext
)
};
// Visit all imports and exports first
visitImportAndExportDeclarations({...importVisitorBaseOptions, sourceFile, node: sourceFile});
let updatedSourceFile = visitNode({...visitorBaseOptions, sourceFile, node: sourceFile}) as TS.SourceFile;
const allImports: TS.Statement[] = [
...visitorContext.imports,
...visitorContext.leadingStatements.filter(typescript.isImportDeclaration),
...updatedSourceFile.statements.filter(typescript.isImportDeclaration),
...visitorContext.trailingStatements.filter(typescript.isImportDeclaration)
];
const allExports: TS.Statement[] = [
...visitorContext.leadingStatements.filter(statement => typescript.isExportDeclaration(statement) || typescript.isExportAssignment(statement)),
...updatedSourceFile.statements.filter(statement => typescript.isExportDeclaration(statement) || typescript.isExportAssignment(statement)),
...visitorContext.trailingStatements.filter(statement => typescript.isExportDeclaration(statement) || typescript.isExportAssignment(statement))
];
const allOtherStatements = [
...visitorContext.leadingStatements.filter(statement => !allImports.includes(statement) && !allExports.includes(statement)),
...updatedSourceFile.statements.filter(
statement => !allImports.includes(statement) && !allExports.includes(statement) && statement.kind !== typescript.SyntaxKind.NotEmittedStatement
),
...visitorContext.trailingStatements.filter(statement => !allImports.includes(statement) && !allExports.includes(statement))
];
updatedSourceFile = factory.updateSourceFile(
updatedSourceFile,
[...allImports, ...allOtherStatements, ...allExports],
sourceFile.isDeclarationFile,
sourceFile.referencedFiles,
sourceFile.typeReferenceDirectives,
sourceFile.hasNoDefaultLib,
sourceFile.libReferenceDirectives
);
// Update the SourceFile with the extra statements
const moduleExports: ModuleExports = {
hasDefaultExport: false,
namedExports: new Set()
};
for (const statement of updatedSourceFile.statements) {
if (typescript.isExportDeclaration(statement) && statement.exportClause != null && typescript.isNamedExports(statement.exportClause)) {
for (const element of statement.exportClause.elements) {
moduleExports.namedExports.add(element.name.text);
}
} else if (typescript.isExportAssignment(statement)) {
moduleExports.hasDefaultExport = true;
} else if (statement.modifiers != null && statement.modifiers.some((m: TS.Modifier) => m.kind === typescript.SyntaxKind.ExportKeyword)) {
if (statement.modifiers.some((m: TS.Modifier) => m.kind === typescript.SyntaxKind.DefaultKeyword)) {
moduleExports.hasDefaultExport = true;
} else if (typescript.isVariableStatement(statement)) {
for (const declaration of statement.declarationList.declarations) {
for (const local of getLocalsForBindingName(declaration.name, typescript)) {
moduleExports.namedExports.add(local);
}
}
} else if (isNamedDeclaration(statement, typescript) && statement.name != null && typescript.isIdentifier(statement.name)) {
moduleExports.namedExports.add(statement.name.text);
}
}
}
// Add the relevant module exports for the SourceFile
visitorContext.addModuleExportsForPath(path.normalize(sourceFile.fileName), moduleExports);
if (!visitorContext.onlyExports && shouldDebug(visitorContext.debug, sourceFile) && visitorContext.printer != null) {
visitorContext.logger.debug("===", path.native.normalize(sourceFile.fileName), "===");
visitorContext.logger.debug(visitorContext.printer.printFile(updatedSourceFile));
visitorContext.logger.debug("EXPORTS:", visitorContext.exportedLocals);
}
return {
sourceFile: updatedSourceFile,
exports: moduleExports
};
} | the_stack |
import { IMatrixJSON, Matrix } from './matrix';
import { Equation } from './matrix/equation';
import { defaults, RNN, RNNFunction } from './rnn';
import { DataFormatter } from '../utilities/data-formatter';
import { allMatrices } from '../test-utils';
function notZero(v: number) {
return v !== 0;
}
describe('RNN', () => {
describe('.constructor()', () => {
describe('when called without options.json', () => {
it('does not initialize model', () => {
const net = new RNN();
expect(net.model.isInitialized).toBe(false);
});
});
describe('when called with options.json', () => {
const getJSON = () => {
const net = new RNN({
hiddenLayers: [3],
inputSize: 3,
inputRange: 2,
outputSize: 2,
});
net.initialize();
return net.toJSON();
};
let fromJSONMock: jest.SpyInstance;
beforeEach(() => {
fromJSONMock = jest.spyOn(RNN.prototype, 'fromJSON');
});
afterEach(() => {
fromJSONMock.mockRestore();
});
it('calls this.fromJSON() with it', () => {
const json = getJSON();
const net = new RNN({ json });
expect(fromJSONMock).toBeCalledWith(json);
});
});
});
describe('.initialize()', () => {
describe('when creating hidden layers', () => {
let createHiddenLayersMock: jest.SpyInstance;
let getHiddenLayerMock: jest.SpyInstance;
beforeEach(() => {
createHiddenLayersMock = jest.spyOn(
RNN.prototype,
'createHiddenLayers'
);
getHiddenLayerMock = jest.spyOn(RNN.prototype, 'getHiddenLayer');
});
afterEach(() => {
createHiddenLayersMock.mockRestore();
getHiddenLayerMock.mockRestore();
});
it('calls createHiddenLayers', () => {
const net = new RNN();
net.initialize();
expect(createHiddenLayersMock).toBeCalled();
});
it('calls static getHiddenLayer method', () => {
const net = new RNN();
net.initialize();
expect(getHiddenLayerMock).toBeCalled();
});
});
it('initializes model', () => {
const net = new RNN();
net.initialize();
expect(net.model).not.toBe(null);
});
it('can setup different size hiddenLayers', () => {
const inputSize = 2;
const hiddenLayers = [5, 4, 3];
const networkOptions = {
learningRate: 0.001,
decayRate: 0.75,
inputSize: inputSize,
hiddenLayers,
outputSize: inputSize,
};
const net = new RNN(networkOptions);
net.initialize();
net.bindEquation();
expect(net.model.hiddenLayers.length).toBe(3);
expect(net.model.hiddenLayers[0].weight.columns).toBe(inputSize);
expect(net.model.hiddenLayers[0].weight.rows).toBe(hiddenLayers[0]);
expect(net.model.hiddenLayers[1].weight.columns).toBe(hiddenLayers[0]);
expect(net.model.hiddenLayers[1].weight.rows).toBe(hiddenLayers[1]);
expect(net.model.hiddenLayers[2].weight.columns).toBe(hiddenLayers[1]);
expect(net.model.hiddenLayers[2].weight.rows).toBe(hiddenLayers[2]);
});
});
describe('.createHiddenLayers()', () => {
it('creates hidden layers in the expected size', () => {
const net = new RNN({
inputSize: 1,
hiddenLayers: [15, 20],
outputSize: 1,
});
const hiddenLayers = net.createHiddenLayers();
expect(hiddenLayers.length).toEqual(2);
expect(hiddenLayers[0].weight.rows).toEqual(15);
expect(hiddenLayers[0].weight.columns).toEqual(1);
expect(hiddenLayers[0].bias.rows).toEqual(15);
expect(hiddenLayers[0].bias.columns).toEqual(1);
expect(hiddenLayers[0].transition.rows).toEqual(15);
expect(hiddenLayers[0].transition.columns).toEqual(15);
expect(hiddenLayers[1].weight.rows).toEqual(20);
expect(hiddenLayers[1].weight.columns).toEqual(15);
expect(hiddenLayers[1].bias.rows).toEqual(20);
expect(hiddenLayers[1].bias.columns).toEqual(1);
expect(hiddenLayers[1].transition.rows).toEqual(20);
expect(hiddenLayers[1].transition.columns).toEqual(20);
});
});
describe('.createOutputMatrices()', () => {
it('creates output layers in the expected size', () => {
const net = new RNN({
inputSize: 1,
hiddenLayers: [22],
outputSize: 1,
});
const { output, outputConnector } = net.createOutputMatrices();
expect(outputConnector.rows).toBe(2);
expect(outputConnector.columns).toBe(22);
expect(output.rows).toBe(2);
expect(output.columns).toBe(1);
});
});
describe('basic operations', () => {
it('starts with zeros in input.deltas', () => {
const net = new RNN();
net.initialize();
net.model.input.deltas.forEach((v) => {
expect(v === 0).toBeTruthy();
});
});
it('after initial run, does not have zeros in weights and produces error', () => {
const net = new RNN({
hiddenLayers: [3],
inputSize: 3,
inputRange: 2,
outputSize: 2,
});
net.initialize();
const error = net.trainInput([1, 1, 0]);
expect(net.model.input.weights.some(notZero)).toBeTruthy();
expect(
net.model.hiddenLayers[0].weight.weights.some(notZero)
).toBeTruthy();
expect(net.model.outputConnector.weights.some(notZero)).toBeTruthy();
expect(error).toBeGreaterThan(0);
expect(error).toBeLessThan(Infinity);
});
it('after initial run, input does not have zeros in deltas', () => {
const net = new RNN({
hiddenLayers: [3],
inputSize: 3,
inputRange: 2,
outputSize: 2,
});
net.initialize();
net.trainInput([1, 1, 0]);
net.model.input.deltas.forEach((v) => {
expect(v).toBe(0);
});
net.backpropagate([1, 1, 0]);
net.backpropagate([0, 1, 1]);
net.backpropagate([1, 0, 1]);
net.backpropagate([1, 1, 0]);
expect(net.model.input.deltas.some(notZero)).toBeTruthy();
});
it('can handle unrecognized input characters', () => {
const net = new RNN({ hiddenLayers: [3] });
net.train([
{ input: '1', output: '2' },
{ input: '2', output: '3' },
]);
expect(() => {
net.run('7');
}).not.toThrow();
});
});
describe('xor', () => {
function xorNet() {
const net = new RNN({
hiddenLayers: [20, 20],
inputSize: 3,
inputRange: 3,
outputSize: 3,
});
net.initialize();
net.train(xorNetValues, { iterations: 1 });
return net;
}
const xorNetValues = [
[0, 0, 0],
[0, 1, 1],
[1, 0, 1],
[1, 1, 0],
];
let predictTargetIndex: jest.SpyInstance;
let backpropagateIndex: jest.SpyInstance;
beforeEach(() => {
predictTargetIndex = jest.spyOn(Equation.prototype, 'predictTargetIndex');
backpropagateIndex = jest.spyOn(Equation.prototype, 'backpropagateIndex');
});
afterEach(() => {
predictTargetIndex.mockRestore();
backpropagateIndex.mockRestore();
});
it('properly provides values to equations[].predictTargetIndex', () => {
const net = xorNet();
predictTargetIndex.mockReset();
net.trainInput([0, 0, 0]);
// called in reverse
expect(predictTargetIndex).toHaveBeenNthCalledWith(1, 0, 1);
expect(predictTargetIndex).toHaveBeenNthCalledWith(2, 1, 1);
expect(predictTargetIndex).toHaveBeenNthCalledWith(3, 1, 1);
expect(predictTargetIndex).toHaveBeenNthCalledWith(4, 1, 0);
predictTargetIndex.mockReset();
net.trainInput([0, 1, 1]);
// called in reverse
expect(predictTargetIndex).toHaveBeenNthCalledWith(1, 0, 1);
expect(predictTargetIndex).toHaveBeenNthCalledWith(2, 1, 2);
expect(predictTargetIndex).toHaveBeenNthCalledWith(3, 2, 2);
expect(predictTargetIndex).toHaveBeenNthCalledWith(4, 2, 0);
});
it('properly provides values to equations[].runBackpropagate', () => {
const net = xorNet();
backpropagateIndex.mockReset();
net.trainInput([0, 0, 0]);
net.backpropagate([0, 0, 0]);
expect(backpropagateIndex).toBeCalledTimes(4);
// called in reverse
expect(backpropagateIndex).toHaveBeenNthCalledWith(1, 1);
expect(backpropagateIndex).toHaveBeenNthCalledWith(2, 1);
expect(backpropagateIndex).toHaveBeenNthCalledWith(3, 1);
expect(backpropagateIndex).toHaveBeenNthCalledWith(4, 0);
net.trainInput([0, 1, 1]);
backpropagateIndex.mockReset();
net.backpropagate([0, 1, 1]);
expect(backpropagateIndex).toBeCalledTimes(4);
// called in reverse
expect(backpropagateIndex).toHaveBeenNthCalledWith(1, 2);
expect(backpropagateIndex).toHaveBeenNthCalledWith(2, 2);
expect(backpropagateIndex).toHaveBeenNthCalledWith(3, 1);
expect(backpropagateIndex).toHaveBeenNthCalledWith(4, 0);
});
it('is fully connected and gives values in deltas', () => {
const net = xorNet();
net.initialize();
const input = xorNetValues[2];
net.model.allMatrices.forEach((m) => {
m.deltas.forEach((value) => {
expect(value).toBe(0);
});
});
net.trainInput(input);
net.model.input.deltas.forEach((v) => {
expect(v).toBe(0);
});
net.model.hiddenLayers.forEach((layer) => {
for (const p in layer) {
if (!layer.hasOwnProperty(p)) continue;
layer[p].deltas.forEach((v) => {
expect(v).toBe(0);
});
}
});
net.model.output.deltas.forEach((v) => {
expect(v).toBe(0);
});
net.backpropagate(input);
expect(net.model.input.deltas.some(notZero)).toBeTruthy();
net.model.hiddenLayers.forEach((layer) => {
for (const p in layer) {
if (!layer.hasOwnProperty(p)) continue;
// if (!layer[p].deltas.some(notZero)) console.log(p);
// assert(layer[p].deltas.some(notZero));
}
});
expect(net.model.output.deltas.some(notZero)).toBeTruthy();
net.model.equations.forEach((equation) => {
equation.states.forEach((state) => {
if (state.left?.deltas) state.left.deltas.some(notZero);
if (state.right?.deltas) state.right.deltas.some(notZero);
if (state.product?.deltas) state.product.deltas.some(notZero);
});
});
});
it('deltas and weights do not explode', () => {
const net = xorNet();
const input = xorNetValues[2];
function checkExploded() {
allMatrices(net.model, (values: Float32Array) => {
values.forEach((value) => {
if (isNaN(value)) throw new Error('exploded');
});
});
}
expect(() => {
for (let i = 0; i < 100; i++) {
checkExploded();
net.trainInput(input);
checkExploded();
net.backpropagate(input);
checkExploded();
net.adjustWeights();
checkExploded();
}
}).not.toThrow();
});
it('can learn xor (error goes down)', () => {
const net = xorNet();
let initialError = Infinity;
let error;
for (let i = 0; i < 10; i++) {
error = 0;
for (let j = 0; j < 4; j++) {
error += net.trainPattern(xorNetValues[j], true);
}
if (i === 0) {
initialError = error;
}
}
expect(error).toBeLessThan(initialError);
});
it('can predict xor', () => {
const net = xorNet();
for (let i = 0; i < 10; i++) {
xorNetValues.forEach(function (value) {
net.trainPattern(value, true);
});
}
expect(net.run().length).toBe(3);
});
});
describe('json', () => {
describe('.toJSON()', () => {
it('can export model as json', () => {
const net = new RNN({
inputSize: 6,
inputRange: 12,
outputSize: 6,
});
const json = net.toJSON();
function compare(left: IMatrixJSON, right: Matrix) {
left.weights.forEach((value, i) => {
expect(value).toBe(right.weights[i]);
});
expect(left.rows).toBe(right.rows);
expect(left.columns).toBe(right.columns);
}
compare(json.input, net.model.input);
net.model.hiddenLayers.forEach((layer, i) => {
compare(json.hiddenLayers[i].weight, layer.weight);
compare(json.hiddenLayers[i].transition, layer.transition);
compare(json.hiddenLayers[i].bias, layer.bias);
});
compare(json.output, net.model.output);
compare(json.outputConnector, net.model.outputConnector);
});
});
describe('.fromJSON()', () => {
it('can import model from json', () => {
const inputSize = 7;
const hiddenLayers = [10, 20];
const dataFormatter = new DataFormatter('abcdef'.split(''));
const jsonString = JSON.stringify(
new RNN({
inputSize, // <- length
hiddenLayers,
inputRange: dataFormatter.characters.length,
outputSize: dataFormatter.characters.length, // <- length
dataFormatter,
}).toJSON(),
null,
2
);
const clone = new RNN();
clone.fromJSON(JSON.parse(jsonString));
const cloneString = JSON.stringify(clone.toJSON(), null, 2);
expect(jsonString).toBe(cloneString);
expect(clone.options.inputSize).toBe(dataFormatter.characters.length);
expect(clone.options.inputRange).toBe(dataFormatter.characters.length);
expect(clone.options.outputSize).toBe(dataFormatter.characters.length);
expect(clone.model.hiddenLayers.length).toBe(2);
expect(clone.model.hiddenLayers[0].weight.columns).toBe(inputSize);
expect(clone.model.hiddenLayers[0].weight.rows).toBe(hiddenLayers[0]);
expect(clone.model.hiddenLayers[1].weight.columns).toBe(
hiddenLayers[0]
);
expect(clone.model.hiddenLayers[1].weight.rows).toBe(hiddenLayers[1]);
});
it('can import model from json using .fromJSON()', () => {
const dataFormatter = new DataFormatter('abcdef'.split(''));
const jsonString = JSON.stringify(
new RNN({
inputSize: dataFormatter.characters.length, // <- length
inputRange: dataFormatter.characters.length,
outputSize: dataFormatter.characters.length, // <- length
}).toJSON()
);
const clone = new RNN();
clone.fromJSON(JSON.parse(jsonString));
expect(jsonString).toBe(JSON.stringify(clone.toJSON()));
expect(clone.options.inputSize).toBe(7);
expect(clone.options.inputRange).toBe(dataFormatter.characters.length);
expect(clone.options.outputSize).toBe(dataFormatter.characters.length);
});
it('will not initialize when importing json', () => {
const dataFormatter = new DataFormatter('abcdef'.split(''));
const original = new RNN({
inputSize: 6, // <- length
inputRange: dataFormatter.characters.length,
hiddenLayers: [3, 3],
outputSize: dataFormatter.characters.length, // <- length
dataFormatter,
});
original.initialize();
const jsonString = JSON.stringify(original.toJSON());
const json = JSON.parse(jsonString);
const clone = new RNN();
clone.fromJSON(json);
expect(jsonString).toBe(JSON.stringify(clone.toJSON()));
expect(clone.options.inputSize).toBe(7);
expect(clone.options.inputRange).toBe(dataFormatter.characters.length);
expect(clone.options.outputSize).toBe(dataFormatter.characters.length);
});
it('can import model from json and train again', () => {
const dataFormatter = new DataFormatter('abcdef'.split(''));
const net = new RNN({
inputSize: 6, // <- length
inputRange: dataFormatter.characters.length,
outputSize: dataFormatter.characters.length, // <- length
dataFormatter,
});
net.initialize();
// over fit on purpose
for (let i = 0; i < 10; i++) {
net.trainPattern([0, 1, 1]);
net.trainPattern([1, 0, 1]);
net.trainPattern([1, 1, 0]);
net.trainPattern([0, 0, 0]);
}
const error = net.trainPattern([0, 1, 1], true);
const jsonString = JSON.stringify(net.toJSON());
const clone = new RNN();
clone.fromJSON(JSON.parse(jsonString));
expect(jsonString).toBe(JSON.stringify(clone.toJSON()));
const newError = clone.trainPattern([0, 1, 1], true);
expect(error - newError < 0.02).toBeTruthy();
expect(jsonString).not.toBe(JSON.stringify(clone.toJSON()));
expect(clone.options.inputSize).toBe(7);
expect(clone.options.inputRange).toBe(dataFormatter.characters.length);
expect(clone.options.outputSize).toBe(dataFormatter.characters.length);
});
});
});
describe('.trainPattern()', () => {
it('changes the neural net when ran', () => {
const net = new RNN({
dataFormatter: new DataFormatter([0, 1]),
hiddenLayers: [2],
});
const netBeforeTraining = JSON.stringify(net.toJSON());
net.train(
[
[0, 0, 0],
[0, 1, 1],
[1, 0, 1],
[1, 1, 0],
],
{ iterations: 10 }
);
const netAfterTraining = JSON.stringify(net.toJSON());
expect(netBeforeTraining).not.toBe(netAfterTraining);
});
});
describe('maxPredictionLength', () => {
it('gets a default value', () => {
expect(new RNN().options.maxPredictionLength).toBe(
defaults().maxPredictionLength
);
});
it('restores option', () => {
const maxPredictionLength = Math.random();
expect(new RNN({ maxPredictionLength }).options.maxPredictionLength).toBe(
maxPredictionLength
);
});
it('can be set multiple times', () => {
const net = new RNN({ maxPredictionLength: 5 });
expect(net.options.maxPredictionLength).toBe(5);
net.options.maxPredictionLength = 1;
expect(net.options.maxPredictionLength).toBe(1);
});
it('shortens returned values', () => {
const net = new RNN({ maxPredictionLength: 3 });
net.train([{ input: '123', output: '456' }], { errorThresh: 0.011 });
const output1 = net.run('123');
expect(output1.length).toBe(3);
net.options.maxPredictionLength = 1;
const output2 = net.run('123');
expect(output2.length).toBe(1);
});
});
describe('.toFunction()', () => {
describe('without callback argument', () => {
it('returns function that works still produces stable output', () => {
const net = new RNN({
hiddenLayers: [3],
});
net.train([
{ input: '1', output: '2' },
{ input: '2', output: '3' },
]);
const expected1 = net.run('1');
const expected2 = net.run('2');
const fn = net.toFunction();
expect(fn('1')).toBe(expected1);
expect(fn('2')).toBe(expected2);
});
});
describe('with callback argument', () => {
it('returns string, which expects a result that makes a function that works still produces stable output', async () => {
const net = new RNN({
hiddenLayers: [3],
});
net.train([
{ input: '1', output: '2' },
{ input: '2', output: '3' },
]);
const expected1 = net.run('1');
const expected2 = net.run('2');
const fn = await new Promise<RNNFunction>((resolve, reject) => {
try {
resolve(
net.toFunction((_fnBody) => {
expect(typeof _fnBody).toBe('string');
return _fnBody;
})
);
} catch (e) {
reject(e);
}
});
expect(fn('1')).toBe(expected1);
expect(fn('2')).toBe(expected2);
});
});
it('can output same as run method', () => {
const dataFormatter = new DataFormatter(['h', 'i', ' ', 'm', 'o', '!']);
const net = new RNN({
inputSize: 7,
inputRange: dataFormatter.characters.length,
outputSize: 7,
dataFormatter,
});
net.initialize();
for (let i = 0; i < 100; i++) {
net.trainPattern(dataFormatter.toIndexes('hi mom!'));
// if (i % 10) {
// console.log(dataFormatter.toCharacters(net.run()).join(''));
// }
}
const lastOutput = net.run();
expect(net.toFunction()()).toBe(lastOutput);
});
it('can include the DataFormatter', () => {
const net = new RNN();
net.train(['hi mom!'], { errorThresh: 0.011 });
const expected = net.run('hi');
const newNet = net.toFunction();
expect(newNet('hi')).toBe(expected);
});
});
describe('.bindEquation()', () => {
let getEquation: jest.SpyInstance;
beforeEach(() => {
getEquation = jest.spyOn(RNN.prototype, 'getEquation');
});
afterEach(() => {
getEquation.mockRestore();
});
it('calls static getEquation method', () => {
const net = new RNN();
net.initialize();
net.bindEquation();
expect(getEquation).toBeCalled();
});
});
}); | the_stack |
'use strict';
import * as dbg from 'debug';
const debug = dbg('azure-iot-device:ModuleClient');
const debugErrors = dbg('azure-iot-device:ModuleClients:Errors');
import * as fs from 'fs';
import { results, Message, RetryOperation, ConnectionString, AuthenticationProvider, Callback, callbackToPromise, DoubleValueCallback } from 'azure-iot-common';
import { InternalClient, DeviceTransport } from './internal_client';
import { errors } from 'azure-iot-common';
import { SharedAccessKeyAuthenticationProvider } from './sak_authentication_provider';
import { SharedAccessSignatureAuthenticationProvider } from './sas_authentication_provider';
import { IotEdgeAuthenticationProvider } from './iotedge_authentication_provider';
import { MethodParams, MethodCallback, MethodClient, DeviceMethodRequest, DeviceMethodResponse, MethodResult } from './device_method';
import { DeviceClientOptions } from './interfaces';
function safeCallback(callback?: (err?: Error, result?: any) => void, error?: Error, result?: any): void {
if (callback) callback(error, result);
}
/**
* IoT Hub device client used to connect a device with an Azure IoT hub.
*
* Users of the SDK should call one of the factory methods,
* {@link azure-iot-device.Client.fromConnectionString|fromConnectionString}
* or {@link azure-iot-device.Client.fromSharedAccessSignature|fromSharedAccessSignature}
* to create an IoT Hub device client.
*/
export class ModuleClient extends InternalClient {
private _inputMessagesEnabled: boolean;
private _moduleDisconnectHandler: (err?: Error, result?: any) => void;
private _methodClient: MethodClient;
/**
* @private
* @constructor
* @param {Object} transport An object that implements the interface
* expected of a transport object, e.g.,
* {@link azure-iot-device-mqtt.Mqtt|Mqtt}.
* @param {Object} restApiClient the RestApiClient object to use for HTTP calls
*/
constructor(transport: DeviceTransport, methodClient: MethodClient) {
super(transport, undefined);
this._inputMessagesEnabled = false;
this._methodClient = methodClient;
/* Codes_SRS_NODE_MODULE_CLIENT_18_012: [ The `inputMessage` event shall be emitted when an inputMessage is received from the IoT Hub service. ]*/
/* Codes_SRS_NODE_MODULE_CLIENT_18_013: [ The `inputMessage` event parameters shall be the inputName for the message and a `Message` object. ]*/
this._transport.on('inputMessage', (inputName, msg) => {
this.emit('inputMessage', inputName, msg);
});
this.on('removeListener', (eventName) => {
if (eventName === 'inputMessage' && this.listeners('inputMessage').length === 0) {
/* Codes_SRS_NODE_MODULE_CLIENT_18_015: [ The client shall stop listening for messages from the service whenever the last listener unsubscribes from the `inputMessage` event. ]*/
this._disableInputMessages((err) => {
if (err) {
this.emit('error', err);
}
});
}
});
this.on('newListener', (eventName) => {
if (eventName === 'inputMessage') {
/* Codes_SRS_NODE_MODULE_CLIENT_18_014: [ The client shall start listening for messages from the service whenever there is a listener subscribed to the `inputMessage` event. ]*/
this._enableInputMessages((err) => {
if (err) {
/*Codes_SRS_NODE_MODULE_CLIENT_18_017: [The client shall emit an `error` if connecting the transport fails while subscribing to `inputMessage` events.]*/
this.emit('error', err);
}
});
}
});
this._moduleDisconnectHandler = (err) => {
if (err) {
debugErrors('transport disconnect event: ' + err);
} else {
debug('transport disconnect event: no error');
}
if (err && this._retryPolicy.shouldRetry(err)) {
if (this._inputMessagesEnabled) {
this._inputMessagesEnabled = false;
debug('re-enabling input message link');
this._enableInputMessages((err) => {
if (err) {
debugErrors('Error re-enabling input messages: ' + err);
/*Codes_SRS_NODE_MODULE_CLIENT_16_102: [If the retry policy fails to reestablish the C2D functionality a `disconnect` event shall be emitted with a `results.Disconnected` object.]*/
this.emit('disconnect', new results.Disconnected(err));
}
});
}
}
};
/*Codes_SRS_NODE_MODULE_CLIENT_16_045: [If the transport successfully establishes a connection the `open` method shall subscribe to the `disconnect` event of the transport.]*/
this._transport.on('disconnect', this._moduleDisconnectHandler);
}
/**
* Sends an event to the given module output
* @param outputName Name of the output to send the event to
* @param message Message to send to the given output
* @param [callback] Optional function to call when the operation has been queued.
* @returns {Promise<results.MessageEnqueued> | void} Promise if no callback function was passed, void otherwise.
*/
sendOutputEvent(outputName: string, message: Message, callback: Callback<results.MessageEnqueued>): void;
sendOutputEvent(outputName: string, message: Message): Promise<results.MessageEnqueued>;
sendOutputEvent(outputName: string, message: Message, callback?: Callback<results.MessageEnqueued>): Promise<results.MessageEnqueued> | void {
return callbackToPromise((_callback) => {
const retryOp = new RetryOperation('sendOutputEvent', this._retryPolicy, this._maxOperationTimeout);
retryOp.retry((opCallback) => {
/* Codes_SRS_NODE_MODULE_CLIENT_18_010: [ The `sendOutputEvent` method shall send the event indicated by the `message` argument via the transport associated with the Client instance. ]*/
this._transport.sendOutputEvent(outputName, message, opCallback);
}, (err, result) => {
/*Codes_SRS_NODE_MODULE_CLIENT_18_018: [ When the `sendOutputEvent` method completes, the `callback` function shall be invoked with the same arguments as the underlying transport method's callback. ]*/
/*Codes_SRS_NODE_MODULE_CLIENT_18_019: [ The `sendOutputEvent` method shall not throw if the `callback` is not passed. ]*/
safeCallback(_callback, err, result);
});
}, callback);
}
/**
* Sends an array of events to the given module output
* @param outputName Name of the output to send the events to
* @param message Messages to send to the given output
* @param [callback] Function to call when the operations have been queued.
* @returns {Promise<results.MessageEnqueued> | void} Optional promise if no callback function was passed, void otherwise.
*/
sendOutputEventBatch(outputName: string, messages: Message[], callback: Callback<results.MessageEnqueued>): void;
sendOutputEventBatch(outputName: string, messages: Message[]): Promise<results.MessageEnqueued>;
sendOutputEventBatch(outputName: string, messages: Message[], callback?: Callback<results.MessageEnqueued>): Promise<results.MessageEnqueued> | void {
return callbackToPromise((_callback) => {
const retryOp = new RetryOperation('sendOutputEventBatch', this._retryPolicy, this._maxOperationTimeout);
retryOp.retry((opCallback) => {
/* Codes_SRS_NODE_MODULE_CLIENT_18_011: [ The `sendOutputEventBatch` method shall send the list of events (indicated by the `messages` argument) via the transport associated with the Client instance. ]*/
this._transport.sendOutputEventBatch(outputName, messages, opCallback);
}, (err, result) => {
/*Codes_SRS_NODE_MODULE_CLIENT_18_021: [ When the `sendOutputEventBatch` method completes the `_callback` function shall be invoked with the same arguments as the underlying transport method's callback. ]*/
/*Codes_SRS_NODE_MODULE_CLIENT_18_022: [ The `sendOutputEventBatch` method shall not throw if the `_callback` is not passed. ]*/
safeCallback(_callback, err, result);
});
}, callback);
}
/**
* Closes the transport connection and destroys the client resources.
*
* *Note: After calling this method the ModuleClient object cannot be reused.*
*
* @param [closeCallback] Optional function to call once the transport is disconnected and the client closed.
* @returns {Promise<results.Disconnected> | void} Promise if no callback function was passed, void otherwise.
*/
close(closeCallback: Callback<results.Disconnected>): void;
close(): Promise<results.Disconnected>;
close(closeCallback?: Callback<results.Disconnected>): Promise<results.Disconnected> | void {
return callbackToPromise((_callback) => {
this._transport.removeListener('disconnect', this._moduleDisconnectHandler);
super.close(_callback);
}, closeCallback);
}
_invokeMethod(deviceId: string, methodParams: MethodParams, callback: MethodCallback): void;
_invokeMethod(deviceId: string, moduleId: string, methodParams: MethodParams, callback: MethodCallback): void;
_invokeMethod(deviceId: string, moduleIdOrMethodParams: string | MethodParams, methodParamsOrCallback: MethodParams | MethodCallback, callback?: MethodCallback): void {
/*Codes_SRS_NODE_MODULE_CLIENT_16_093: [`invokeMethod` shall throw a `ReferenceError` if the `deviceId` argument is falsy.]*/
if (!deviceId) {
throw new ReferenceError('deviceId cannot be \'' + deviceId + '\'');
}
/*Codes_SRS_NODE_MODULE_CLIENT_16_094: [`invokeMethod` shall throw a `ReferenceError` if the `moduleIdOrMethodParams` argument is falsy.]*/
if (!moduleIdOrMethodParams) {
throw new ReferenceError('The second parameter cannot be \'' + moduleIdOrMethodParams + '\'');
}
const actualModuleId = typeof moduleIdOrMethodParams === 'string' ? moduleIdOrMethodParams : null;
const actualMethodParams = typeof moduleIdOrMethodParams === 'object' ? moduleIdOrMethodParams : methodParamsOrCallback;
const actualCallback = typeof methodParamsOrCallback === 'function' ? methodParamsOrCallback : callback;
/*Codes_SRS_NODE_MODULE_CLIENT_16_095: [`invokeMethod` shall throw a `ReferenceError` if the `deviceId` and `moduleIdOrMethodParams` are strings and the `methodParamsOrCallback` argument is falsy.]*/
if (!actualMethodParams || typeof actualMethodParams !== 'object') {
throw new ReferenceError('methodParams cannot be \'' + actualMethodParams + '\'');
}
/*Codes_SRS_NODE_MODULE_CLIENT_16_096: [`invokeMethod` shall throw a `ArgumentError` if the `methodName` property of the `MethodParams` argument is falsy.]*/
if (!(actualMethodParams as MethodParams).methodName) {
throw new errors.ArgumentError('the name property of the methodParams argument cannot be \'' + (actualMethodParams as MethodParams).methodName + '\'');
}
/*Codes_SRS_NODE_MODULE_CLIENT_16_097: [`invokeMethod` shall call the `invokeMethod` API of the `MethodClient` API that was created for the `ModuleClient` instance.]*/
this._methodClient.invokeMethod(deviceId, actualModuleId, actualMethodParams as MethodParams, actualCallback);
}
/**
* Invokes a method on a downstream device or on another module on the same IoTEdge device. Please note that this feature only works when
* the module is being run as part of an IoTEdge device.
*
* @param deviceId target device identifier
* @param moduleId target module identifier on the device identified with the `deviceId` argument
* @param methodParams parameters of the direct method call
* @param [callback] optional callback that will be invoked either with an Error object or the result of the method call.
* @returns {Promise<MethodResult> | void} Promise if no callback function was passed, void otherwise.
*/
invokeMethod(deviceId: string, methodParams: MethodParams, callback: Callback<MethodResult>): void;
invokeMethod(deviceId: string, moduleId: string, methodParams: MethodParams, callback: Callback<MethodResult>): void;
invokeMethod(deviceId: string, methodParams: MethodParams): Promise<MethodResult>;
invokeMethod(deviceId: string, moduleId: string, methodParams: MethodParams): Promise<MethodResult>;
invokeMethod(deviceId: string, moduleIdOrMethodParams: string | MethodParams, methodParamsOrCallback?: MethodParams | Callback<MethodResult>, callback?: Callback<MethodResult>): Promise<MethodResult> | void {
if (callback) {
return this._invokeMethod(deviceId, moduleIdOrMethodParams as string, methodParamsOrCallback as MethodParams, callback);
} else if (typeof methodParamsOrCallback === 'function') {
return this._invokeMethod(deviceId, moduleIdOrMethodParams as MethodParams, methodParamsOrCallback as Callback<MethodResult>);
}
return callbackToPromise((_callback) => this._invokeMethod(deviceId, moduleIdOrMethodParams as any, methodParamsOrCallback as MethodParams, _callback));
}
/**
* Registers a callback for a method named `methodName`.
*
* @param methodName Name of the method that will be handled by the callback
* @param callback Function that shall be called whenever a method request for the method called `methodName` is received.
*/
onMethod(methodName: string, callback: DoubleValueCallback<DeviceMethodRequest, DeviceMethodResponse>): void {
this._onDeviceMethod(methodName, callback);
}
/**
* Passes options to the `ModuleClient` object that can be used to configure the transport.
* @param options A {@link DeviceClientOptions} object.
* @param [done] Optional callback to call once the options have been set.
* @returns {Promise<results.TransportConfigured> | void} Promise if no callback function was passed, void otherwise.
*/
setOptions(options: DeviceClientOptions, done: Callback<results.TransportConfigured>): void;
setOptions(options: DeviceClientOptions): Promise<results.TransportConfigured>;
setOptions(options: DeviceClientOptions, done?: Callback<results.TransportConfigured>): Promise<results.TransportConfigured> | void {
return callbackToPromise((_callback) => {
/*Codes_SRS_NODE_MODULE_CLIENT_16_098: [The `setOptions` method shall call the `setOptions` method with the `options` argument on the `MethodClient` object of the `ModuleClient`.]*/
if (this._methodClient) {
this._methodClient.setOptions(options);
}
/*Codes_SRS_NODE_MODULE_CLIENT_16_042: [The `setOptions` method shall throw a `ReferenceError` if the options object is falsy.]*/
/*Codes_SRS_NODE_MODULE_CLIENT_16_043: [The `_callback` callback shall be invoked with no parameters when it has successfully finished setting the client and/or transport options.]*/
/*Codes_SRS_NODE_MODULE_CLIENT_16_044: [The `_callback` callback shall be invoked with a standard javascript `Error` object and no result object if the client could not be configured as requested.]*/
super.setOptions(options, _callback);
}, done);
}
private _disableInputMessages(callback: (err?: Error) => void): void {
if (this._inputMessagesEnabled) {
this._transport.disableInputMessages((err) => {
if (!err) {
this._inputMessagesEnabled = false;
}
callback(err);
});
} else {
callback();
}
}
private _enableInputMessages(callback: (err?: Error) => void): void {
if (!this._inputMessagesEnabled) {
const retryOp = new RetryOperation('_enableInputMessages', this._retryPolicy, this._maxOperationTimeout);
retryOp.retry((opCallback) => {
/* Codes_SRS_NODE_MODULE_CLIENT_18_016: [ The client shall connect the transport if needed in order to receive inputMessages. ]*/
this._transport.enableInputMessages(opCallback);
}, (err) => {
if (!err) {
this._inputMessagesEnabled = true;
}
callback(err);
});
} else {
callback();
}
}
/**
* Creates an IoT Hub device client from the given connection string using the given transport type.
*
* @param {String} connStr A connection string which encapsulates "device connect" permissions on an IoT hub.
* @param {Function} transportCtor A transport constructor.
*
* @throws {ReferenceError} If the connStr parameter is falsy.
*
* @returns {module:azure-iot-device.ModuleClient}
*/
static fromConnectionString(connStr: string, transportCtor: any): ModuleClient {
/*Codes_SRS_NODE_MODULE_CLIENT_05_003: [The fromConnectionString method shall throw ReferenceError if the connStr argument is falsy.]*/
if (!connStr) throw new ReferenceError('connStr is \'' + connStr + '\'');
const cn = ConnectionString.parse(connStr);
/*Codes_SRS_NODE_MODULE_CLIENT_16_087: [The `fromConnectionString` method shall create a new `SharedAccessKeyAuthorizationProvider` object with the connection string passed as argument if it contains a SharedAccessKey parameter and pass this object to the transport constructor.]*/
let authenticationProvider: AuthenticationProvider;
if (cn.SharedAccessKey) {
authenticationProvider = SharedAccessKeyAuthenticationProvider.fromConnectionString(connStr);
} else {
/*Codes_SRS_NODE_MODULE_CLIENT_16_001: [The `fromConnectionString` method shall throw a `NotImplementedError` if the connection string does not contain a `SharedAccessKey` field because x509 authentication is not supported yet for modules.]*/
throw new errors.NotImplementedError('ModuleClient only supports SAS Token authentication');
}
/*Codes_SRS_NODE_MODULE_CLIENT_05_006: [The fromConnectionString method shall return a new instance of the Client object, as by a call to new Client(new transportCtor(...)).]*/
return new ModuleClient(new transportCtor(authenticationProvider), new MethodClient(authenticationProvider));
}
/**
* Creates an IoT Hub module client from the given shared access signature using the given transport type.
*
* @param {String} sharedAccessSignature A shared access signature which encapsulates "device
* connect" permissions on an IoT hub.
* @param {Function} Transport A transport constructor.
*
* @throws {ReferenceError} If the connStr parameter is falsy.
*
* @returns {module:azure-iothub.Client}
*/
static fromSharedAccessSignature(sharedAccessSignature: string, transportCtor: any): ModuleClient {
/*Codes_SRS_NODE_MODULE_CLIENT_16_029: [The fromSharedAccessSignature method shall throw a ReferenceError if the sharedAccessSignature argument is falsy.] */
if (!sharedAccessSignature) throw new ReferenceError('sharedAccessSignature is \'' + sharedAccessSignature + '\'');
/*Codes_SRS_NODE_MODULE_CLIENT_16_088: [The `fromSharedAccessSignature` method shall create a new `SharedAccessSignatureAuthorizationProvider` object with the shared access signature passed as argument, and pass this object to the transport constructor.]*/
const authenticationProvider = SharedAccessSignatureAuthenticationProvider.fromSharedAccessSignature(sharedAccessSignature);
/*Codes_SRS_NODE_MODULE_CLIENT_16_030: [The fromSharedAccessSignature method shall return a new instance of the Client object] */
return new ModuleClient(new transportCtor(authenticationProvider), new MethodClient(authenticationProvider));
}
/**
* Creates an IoT Hub module client from the given authentication method and using the given transport type.
* @param authenticationProvider Object used to obtain the authentication parameters for the IoT hub.
* @param transportCtor Transport protocol used to connect to IoT hub.
*/
static fromAuthenticationProvider(authenticationProvider: AuthenticationProvider, transportCtor: any): ModuleClient {
/*Codes_SRS_NODE_MODULE_CLIENT_16_089: [The `fromAuthenticationProvider` method shall throw a `ReferenceError` if the `authenticationProvider` argument is falsy.]*/
if (!authenticationProvider) {
throw new ReferenceError('authenticationMethod cannot be \'' + authenticationProvider + '\'');
}
/*Codes_SRS_NODE_MODULE_CLIENT_16_092: [The `fromAuthenticationProvider` method shall throw a `ReferenceError` if the `transportCtor` argument is falsy.]*/
if (!transportCtor) {
throw new ReferenceError('transportCtor cannot be \'' + transportCtor + '\'');
}
/*Codes_SRS_NODE_MODULE_CLIENT_16_090: [The `fromAuthenticationProvider` method shall pass the `authenticationProvider` object passed as argument to the transport constructor.]*/
/*Codes_SRS_NODE_MODULE_CLIENT_16_091: [The `fromAuthenticationProvider` method shall return a `Client` object configured with a new instance of a transport created using the `transportCtor` argument.]*/
return new ModuleClient(new transportCtor(authenticationProvider), new MethodClient(authenticationProvider));
}
/**
* Creates an IoT Hub module client by using configuration information from the environment.
*
* If an environment variable called `EdgeHubConnectionString` or `IotHubConnectionString` exists, then that value is used and behavior is identical
* to calling `fromConnectionString` passing that in. If those environment variables do not exist then the following variables MUST be defined:
*
* - IOTEDGE_WORKLOADURI URI for iotedged's workload API
* - IOTEDGE_DEVICEID Device identifier
* - IOTEDGE_MODULEID Module identifier
* - IOTEDGE_MODULEGENERATIONID Module generation identifier
* - IOTEDGE_IOTHUBHOSTNAME IoT Hub host name
* - IOTEDGE_AUTHSCHEME Authentication scheme to use; must be "sasToken"
*
* @param transportCtor Transport protocol used to connect to IoT hub.
* @param [callback] Optional callback to invoke when the ModuleClient has been constructured or if an
* error occurs while creating the client.
* @returns {Promise<ModuleClient> | void} Promise if no callback function was passed, void otherwise.
*/
static fromEnvironment(transportCtor: any, callback: Callback<ModuleClient>): void;
static fromEnvironment(transportCtor: any): Promise<ModuleClient>;
static fromEnvironment(transportCtor: any, callback?: Callback<ModuleClient>): Promise<ModuleClient> | void {
return callbackToPromise((_callback) => {
// Codes_SRS_NODE_MODULE_CLIENT_13_033: [ The fromEnvironment method shall throw a ReferenceError if the callback argument is falsy or is not a function. ]
if (!_callback || typeof (_callback) !== 'function') {
throw new ReferenceError('callback cannot be \'' + _callback + '\'');
}
// Codes_SRS_NODE_MODULE_CLIENT_13_026: [ The fromEnvironment method shall invoke callback with a ReferenceError if the transportCtor argument is falsy. ]
if (!transportCtor) {
_callback(new ReferenceError('transportCtor cannot be \'' + transportCtor + '\''));
return;
}
// Codes_SRS_NODE_MODULE_CLIENT_13_028: [ The fromEnvironment method shall delegate to ModuleClient.fromConnectionString if an environment variable called EdgeHubConnectionString or IotHubConnectionString exists. ]
// if the environment has a value for EdgeHubConnectionString then we use that
const connectionString = process.env.EdgeHubConnectionString || process.env.IotHubConnectionString;
if (connectionString) {
ModuleClient._fromEnvironmentNormal(connectionString, transportCtor, _callback);
} else {
ModuleClient._fromEnvironmentEdge(transportCtor, _callback);
}
}, callback);
}
private static _fromEnvironmentEdge(transportCtor: any, callback: (err?: Error, client?: ModuleClient) => void): void {
// make sure all the environment variables we need have been provided
const validationError = ModuleClient.validateEnvironment();
if (validationError) {
callback(validationError);
return;
}
const authConfig = {
workloadUri: process.env.IOTEDGE_WORKLOADURI,
deviceId: process.env.IOTEDGE_DEVICEID,
moduleId: process.env.IOTEDGE_MODULEID,
iothubHostName: process.env.IOTEDGE_IOTHUBHOSTNAME,
authScheme: process.env.IOTEDGE_AUTHSCHEME,
gatewayHostName: process.env.IOTEDGE_GATEWAYHOSTNAME,
generationId: process.env.IOTEDGE_MODULEGENERATIONID
};
// Codes_SRS_NODE_MODULE_CLIENT_13_032: [ The fromEnvironment method shall create a new IotEdgeAuthenticationProvider object and pass this to the transport constructor. ]
const authenticationProvider = new IotEdgeAuthenticationProvider(authConfig);
// get trust bundle
authenticationProvider.getTrustBundle((err, ca) => {
if (err) {
callback(err);
} else {
const transport = new transportCtor(authenticationProvider);
// Codes_SRS_NODE_MODULE_CLIENT_13_035: [ If the client is running in IoTEdge mode then the IotEdgeAuthenticationProvider.getTrustBundle method shall be invoked to retrieve the CA cert and the returned value shall be set as the CA cert for the transport via the transport's setOptions method passing in the CA value for the ca property in the options object. ]
transport.setOptions({ ca });
const methodClient = new MethodClient(authenticationProvider);
methodClient.setOptions({ ca });
// Codes_SRS_NODE_MODULE_CLIENT_13_031: [ The fromEnvironment method shall invoke the callback with a new instance of the ModuleClient object. ]
callback(null, new ModuleClient(transport, methodClient));
}
});
}
private static _fromEnvironmentNormal(connectionString: string, transportCtor: any, callback: (err?: Error, client?: ModuleClient) => void): void {
let ca = '';
if (process.env.EdgeModuleCACertificateFile) {
fs.readFile(process.env.EdgeModuleCACertificateFile, 'utf8', (err, data) => {
if (err) {
callback(err);
} else {
// Codes_SRS_NODE_MODULE_CLIENT_13_034: [ If the client is running in a non-IoTEdge mode and an environment variable named EdgeModuleCACertificateFile exists then its file contents shall be set as the CA cert for the transport via the transport's setOptions method passing in the CA as the value for the ca property in the options object. ]
ca = data;
const moduleClient = ModuleClient.fromConnectionString(connectionString, transportCtor);
moduleClient.setOptions({ ca }, (err) => {
if (err) {
callback(err);
} else {
callback(null, moduleClient);
}
});
}
});
} else {
callback(null, ModuleClient.fromConnectionString(connectionString, transportCtor));
}
}
private static validateEnvironment(): ReferenceError {
// Codes_SRS_NODE_MODULE_CLIENT_13_029: [ If environment variables EdgeHubConnectionString and IotHubConnectionString do not exist then the following environment variables must be defined: IOTEDGE_WORKLOADURI, IOTEDGE_DEVICEID, IOTEDGE_MODULEID, IOTEDGE_IOTHUBHOSTNAME, IOTEDGE_AUTHSCHEME and IOTEDGE_MODULEGENERATIONID. ]
const keys = [
'IOTEDGE_WORKLOADURI',
'IOTEDGE_DEVICEID',
'IOTEDGE_MODULEID',
'IOTEDGE_IOTHUBHOSTNAME',
'IOTEDGE_AUTHSCHEME',
'IOTEDGE_MODULEGENERATIONID'
];
for (const key of keys) {
if (!process.env[key]) {
return new ReferenceError(
`Environment variable ${key} was not provided.`
);
}
}
// Codes_SRS_NODE_MODULE_CLIENT_13_030: [ The value for the environment variable IOTEDGE_AUTHSCHEME must be sasToken. ]
// we only support sas token auth scheme at this time
if (process.env.IOTEDGE_AUTHSCHEME.toLowerCase() !== 'sastoken') {
return new ReferenceError(
`Authentication scheme ${
process.env.IOTEDGE_AUTHSCHEME
} is not a supported scheme.`
);
}
}
} | the_stack |
import * as React from 'react';
import * as _ from 'lodash';
import {
ControlElement,
HorizontalLayout,
} from '@jsonforms/core';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
import Enzyme, { mount, ReactWrapper } from 'enzyme';
import { JsonFormsStateProvider } from '@jsonforms/react';
import TableArrayControl, { tableArrayControlTester, } from '../../src/complex/TableArrayControl';
import HorizontalLayoutRenderer from '../../src/layouts/HorizontalLayout';
import '../../src';
import { initCore, TestEmitter } from '../util';
import IntegerCell, { integerCellTester } from '../../src/cells/IntegerCell';
Enzyme.configure({ adapter: new Adapter() });
const fixture = {
schema: {
type: 'object',
properties: {
test: {
type: 'array',
items: {
type: 'object',
properties: {
x: { type: 'integer' },
y: { type: 'integer' }
}
}
}
}
},
uischema: {
type: 'Control',
scope: '#/properties/test'
},
data: {
test: [{ x: 1, y: 3 }]
}
};
const fixture2 = {
schema: {
type: 'object',
properties: {
test: {
type: 'array',
items: {
type: 'object',
properties: {
x: {
type: 'integer',
title: 'Column X',
},
y: { type: 'integer' }
}
}
}
}
},
uischema: {
type: 'Control',
scope: '#/properties/test'
},
data: {
test: [{ x: 1, y: 3 }]
}
};
describe('Table array tester', () => {
test('tester with recursive document ref only', () => {
const control: ControlElement = {
type: 'Control',
scope: '#'
};
expect(tableArrayControlTester(control, undefined)).toBe(-1);
});
test(' tester with prop of wrong type', () => {
const control: ControlElement = {
type: 'Control',
scope: '#/properties/x'
};
expect(
tableArrayControlTester(
control,
{
type: 'object',
properties: {
x: { type: 'integer' }
}
}
)
).toBe(-1);
});
test('tester with correct prop type, but without items', () => {
const control: ControlElement = {
type: 'Control',
scope: '#/properties/foo'
};
expect(
tableArrayControlTester(
control,
{
type: 'object',
properties: {
foo: { type: 'array' }
}
}
)
).toBe(-1);
});
test('tester with correct prop type, but different item types', () => {
const control: ControlElement = {
type: 'Control',
scope: '#/properties/foo'
};
expect(
tableArrayControlTester(
control,
{
type: 'object',
properties: {
foo: {
type: 'array',
items: [
{ type: 'integer' },
{ type: 'string' },
]
}
}
}
)
).toBe(-1);
});
test('tester with primitive item type', () => {
const control: ControlElement = {
type: 'Control',
scope: '#/properties/foo'
};
expect(
tableArrayControlTester(
control,
{
type: 'object',
properties: {
foo: {
type: 'array',
items: { type: 'integer' }
}
}
}
)
).toBe(3);
});
test('tester', () => {
const uischema: ControlElement = {
type: 'Control',
scope: '#/properties/test'
};
expect(tableArrayControlTester(uischema, fixture.schema)).toBe(3);
});
test('tester - wrong type', () => expect(tableArrayControlTester({ type: 'Foo' }, null)).toBe(-1));
});
describe('Table array control', () => {
let wrapper: ReactWrapper;
afterEach(() => wrapper.unmount());
test('render two children', () => {
const cells = [{ tester: integerCellTester, cell: IntegerCell }];
const core = initCore(fixture.schema, fixture.uischema, fixture.data);
wrapper = mount(
<JsonFormsStateProvider initState={{ core, cells }}>
<TableArrayControl
schema={fixture.schema}
uischema={fixture.uischema}
/>
</JsonFormsStateProvider>
);
const header = wrapper.find('header').getDOMNode();
const legendChildren = header.children;
const label = legendChildren.item(0);
expect(label.tagName).toBe('LABEL');
expect(label.innerHTML).toBe('Test');
const button = legendChildren.item(1);
expect(button.tagName).toBe('BUTTON');
expect(button.innerHTML).toBe('Add to Test');
const table = wrapper.find('table').getDOMNode() as HTMLInputElement;
const tableChildren = table.children;
expect(tableChildren).toHaveLength(2);
const tHead = tableChildren.item(0);
expect(tHead.tagName).toBe('THEAD');
expect(tHead.children).toHaveLength(1);
const headRow = tHead.children.item(0);
expect(headRow.tagName).toBe('TR');
// two data columns + validation column + delete column
expect(headRow.children).toHaveLength(4);
const headColumn1 = headRow.children.item(0);
expect(headColumn1.tagName).toBe('TH');
expect((headColumn1 as HTMLTableHeaderCellElement).textContent).toBe('X');
const headColumn2 = headRow.children.item(1);
expect(headColumn2.tagName).toBe('TH');
expect((headColumn2 as HTMLTableHeaderCellElement).textContent).toBe('Y');
const tBody = tableChildren.item(1);
expect(tBody.tagName).toBe('TBODY');
expect(tBody.children).toHaveLength(1);
const bodyRow = tBody.children.item(0);
expect(bodyRow.tagName).toBe('TR');
// two data columns + validation column + delete column
expect(bodyRow.children).toHaveLength(4);
const tds = wrapper.find('td');
expect(tds).toHaveLength(4);
expect(tds.at(0).getDOMNode().children).toHaveLength(1);
expect(tds.at(0).getDOMNode().children[0].id).toBe('');
expect(tds.at(1).getDOMNode().children).toHaveLength(1);
expect(tds.at(1).getDOMNode().children[0].id).toBe('');
});
test('render empty data', () => {
const control: ControlElement = {
label: false,
type: 'Control',
scope: '#/properties/test'
};
const core = initCore(fixture.schema, control, {});
wrapper = mount(
<JsonFormsStateProvider initState={{ core }}>
<TableArrayControl
schema={fixture.schema}
uischema={control}
/>
</JsonFormsStateProvider>
);
const header = wrapper.find('header').getDOMNode();
const legendChildren = header.children;
const label = legendChildren.item(0) as HTMLLabelElement;
expect(label.tagName).toBe('LABEL');
expect(label.textContent).toBe('');
const button = legendChildren.item(1);
expect(button.tagName).toBe('BUTTON');
expect(button.textContent).toBe('Add to Test');
const table = wrapper.find('table').getDOMNode();
const tableChildren = table.children;
expect(tableChildren).toHaveLength(2);
const tHead = tableChildren.item(0);
expect(tHead.tagName).toBe('THEAD');
expect(tHead.children).toHaveLength(1);
const headRow = tHead.children.item(0);
expect(headRow.tagName).toBe('TR');
// two data columns + validation column + delete column
expect(headRow.children).toHaveLength(4);
const headColumn1 = headRow.children.item(0);
expect(headColumn1.tagName).toBe('TH');
expect((headColumn1 as HTMLTableHeaderCellElement).textContent).toBe('X');
const headColumn2 = headRow.children.item(1);
expect(headColumn2.tagName).toBe('TH');
expect((headColumn2 as HTMLTableHeaderCellElement).textContent).toBe('Y');
const tBody = tableChildren.item(1);
expect(tBody.tagName).toBe('TBODY');
expect(tBody.children).toHaveLength(1);
const noDataRow = tBody.children[0];
expect(noDataRow.tagName).toBe('TR');
expect(noDataRow.children).toHaveLength(1);
const noDataColumn = noDataRow.children[0];
expect(noDataColumn.tagName).toBe('TD');
expect(noDataColumn.textContent).toBe('No data');
});
test('use property title as a column header if it exists', () => {
const cells = [{ tester: integerCellTester, cell: IntegerCell }];
const core = initCore(fixture2.schema, fixture2.uischema, fixture2.data);
wrapper = mount(
<JsonFormsStateProvider initState={{ core, cells }}>
<TableArrayControl
schema={fixture2.schema}
uischema={fixture2.uischema}
/>
</JsonFormsStateProvider>
);
//column headings are wrapped in a <thead> tag
const headers = wrapper.find('thead').find('th');
// the first property has a title, so we expect it to be rendered as the first column heading
expect(headers.at(0).text()).toEqual("Column X");
// the second property has no title, so we expect to see the property name in start case
expect(headers.at(1).text()).toEqual("Y");
});
test('render new child (empty init data)', () => {
const onChangeData: any = {
data: undefined
};
const core = initCore(fixture.schema, fixture.uischema, { test: [] });
wrapper = mount(
<JsonFormsStateProvider initState={{ core }}>
<TestEmitter
onChange={({ data }) => {
onChangeData.data = data;
}}
/>
<TableArrayControl
schema={fixture.schema}
uischema={fixture.uischema}
/>
</JsonFormsStateProvider>
);
const control = wrapper.find('.root_properties_test');
expect(control).toBeDefined();
const button = wrapper.find('button');
button.simulate('click');
expect(onChangeData.data.test).toHaveLength(1);
});
test('render new child (undefined data)', () => {
const onChangeData: any = {
data: undefined
};
const core = initCore(fixture.schema, fixture.uischema, { test: undefined });
wrapper = mount(
<JsonFormsStateProvider initState={{ core }}>
<TestEmitter
onChange={({ data }) => {
onChangeData.data = data;
}}
/>
<TableArrayControl
schema={fixture.schema}
uischema={fixture.uischema}
/>
</JsonFormsStateProvider>
);
const control = wrapper.find('.root_properties_test');
expect(control).toBeDefined();
const button = wrapper.find('button');
button.simulate('click');
expect(onChangeData.data.test).toHaveLength(1);
});
test('render new child (null data)', () => {
const onChangeData: any = {
data: undefined
};
const core = initCore(fixture.schema, fixture.uischema, { test: null });
wrapper = mount(
<JsonFormsStateProvider initState={{ core }}>
<TestEmitter
onChange={({ data }) => {
onChangeData.data = data;
}}
/>
<TableArrayControl
schema={fixture.schema}
uischema={fixture.uischema}
/>
</JsonFormsStateProvider>
);
const control = wrapper.find('.root_properties_test');
expect(control).toBeDefined();
const button = wrapper.find('button');
button.simulate('click');
expect(onChangeData.data.test).toHaveLength(1);
});
test('render new child', () => {
const onChangeData: any = {
data: undefined
};
const core = initCore(fixture.schema, fixture.uischema, fixture.data);
wrapper = mount(
<JsonFormsStateProvider initState={{ core }}>
<TestEmitter
onChange={({ data }) => {
onChangeData.data = data;
}}
/>
<TableArrayControl
schema={fixture.schema}
uischema={fixture.uischema}
/>
</JsonFormsStateProvider>
);
const addButton = wrapper.find('button').first();
addButton.simulate('click');
expect(onChangeData.data.test).toHaveLength(2);
});
test('render primitives ', () => {
const schema = {
type: 'object',
properties: {
test: {
type: 'array',
items: {
type: 'string',
maxLength: 3
}
}
}
};
const uischema: ControlElement = {
type: 'Control',
scope: '#/properties/test'
};
const core = initCore(schema, uischema, { test: ['foo', 'bars'] });
wrapper = mount(
<JsonFormsStateProvider initState={{ core }}>
<TableArrayControl
schema={schema}
uischema={uischema}
/>
</JsonFormsStateProvider>
);
const rows = wrapper.find('tr');
const lastRow = rows.last().getDOMNode() as HTMLTableRowElement;
expect(lastRow.children.item(1).textContent).toBe('must NOT have more than 3 characters');
expect(rows).toHaveLength(3);
});
test('update via action', () => {
const core = initCore(fixture.schema, fixture.uischema, fixture.data);
wrapper = mount(
<JsonFormsStateProvider initState={{ core }}>
<TableArrayControl
schema={fixture.schema}
uischema={fixture.uischema}
/>
</JsonFormsStateProvider>
);
const children = wrapper.find('tbody').getDOMNode();
expect(children.childNodes).toHaveLength(1);
core.data = { ...core.data, test: [{ x: 1, y: 3 }, { x: 2, y: 3 }] };
wrapper.setProps({ initState: { core }} );
wrapper.update();
expect(children.childNodes).toHaveLength(2);
core.data = { ...core.data, undefined: [{ x: 1, y: 3 }, { x: 2, y: 3 }, { x: 3, y: 3 }] };
wrapper.setProps({ initState: { core }} );
wrapper.update();
expect(children.childNodes).toHaveLength(2);
});
test('hide', () => {
const core = initCore(fixture.schema, fixture.uischema, fixture.data);
wrapper = mount(
<JsonFormsStateProvider initState={{ core }}>
<TableArrayControl
schema={fixture.schema}
uischema={fixture.uischema}
visible={false}
/>
</JsonFormsStateProvider>
);
const control = wrapper.find('.control').getDOMNode() as HTMLElement;
expect(control.hidden).toBe(true);
});
test('show by default', () => {
const core = initCore(fixture.schema, fixture.uischema, fixture.data);
wrapper = mount(
<JsonFormsStateProvider initState={{ core }}>
<TableArrayControl
schema={fixture.schema}
uischema={fixture.uischema}
/>
</JsonFormsStateProvider>
);
const control = wrapper.find('.control').getDOMNode() as HTMLElement;
expect(control.hidden).toBe(false);
});
test('single error', () => {
const core = initCore(fixture.schema, fixture.uischema, fixture.data);
wrapper = mount(
<JsonFormsStateProvider initState={{ core }}>
<TableArrayControl
schema={fixture.schema}
uischema={fixture.uischema}
/>
</JsonFormsStateProvider>
);
core.data = { ...core.data, test: 2 };
wrapper.setProps({ initState: { core }} );
wrapper.update();
const validation = wrapper.find('.validation').getDOMNode();
expect(validation.textContent).toBe('must be array');
});
test('multiple errors', () => {
const core = initCore(fixture.schema, fixture.uischema, fixture.data);
wrapper = mount(
<JsonFormsStateProvider initState={{ core }}>
<TableArrayControl
schema={fixture.schema}
uischema={fixture.uischema}
/>
</JsonFormsStateProvider>
);
core.data = { ...core.data, test: 3 };
wrapper.setProps({ initState: { core }} );
wrapper.update();
const validation = wrapper.find('.validation').getDOMNode();
expect(validation.textContent).toBe('must be array');
});
test('empty errors by default', () => {
const core = initCore(fixture.schema, fixture.uischema, fixture.data);
wrapper = mount(
<JsonFormsStateProvider initState={{ core }}>
<TableArrayControl
schema={fixture.schema}
uischema={fixture.uischema}
/>
</JsonFormsStateProvider>
);
const validation = wrapper.find('.validation').getDOMNode();
expect(validation.textContent).toBe('');
});
test('reset validation message', () => {
const core = initCore(fixture.schema, fixture.uischema, fixture.data);
wrapper = mount(
<JsonFormsStateProvider initState={{ core }}>
<TableArrayControl
schema={fixture.schema}
uischema={fixture.uischema}
/>
</JsonFormsStateProvider>
);
const validation = wrapper.find('.validation').getDOMNode();
core.data = { ...core.data, test: 3 };
wrapper.setProps({ initState: { core }} );
wrapper.update();
expect(validation.textContent).toBe('must be array');
core.data = { ...core.data, test: [] };
wrapper.setProps({ initState: { core }} );
wrapper.update();
expect(validation.textContent).toBe('');
});
// must be thought through as to where to show validation errors
test.skip('validation of nested schema', () => {
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
personalData: {
type: 'object',
properties: {
middleName: { type: 'string' },
lastName: { type: 'string' }
},
required: ['middleName', 'lastName']
}
},
required: ['name']
};
const firstControl: ControlElement = {
type: 'Control',
scope: '#/properties/name'
};
const secondControl: ControlElement = {
type: 'Control',
scope: '#/properties/personalData/properties/middleName'
};
const thirdControl: ControlElement = {
type: 'Control',
scope: '#/properties/personalData/properties/lastName'
};
const uischema: HorizontalLayout = {
type: 'HorizontalLayout',
elements: [firstControl, secondControl, thirdControl]
};
const core = initCore(fixture.schema, fixture.uischema, {name: 'John Doe', personalData: {} });
wrapper = mount(
<JsonFormsStateProvider initState={{ core }}>
<HorizontalLayoutRenderer schema={schema} uischema={uischema} />
</JsonFormsStateProvider>
);
const validation = wrapper.find('.valdiation');
expect(validation.at(0).getDOMNode().textContent).toBe('');
expect(validation.at(1).getDOMNode().textContent).toBe('is a required property');
expect(validation.at(2).getDOMNode().textContent).toBe('is a required property');
});
}); | the_stack |
import { ethers, upgrades, waffle } from "hardhat";
import { Signer, BigNumberish, utils, Wallet, BigNumber } from "ethers";
import chai from "chai";
import { solidity } from "ethereum-waffle";
import "@openzeppelin/test-helpers";
import {
AlpacaToken,
AlpacaToken__factory,
CakeToken,
CakeToken__factory,
DebtToken,
DebtToken__factory,
FairLaunch,
FairLaunch__factory,
MockERC20,
MockERC20__factory,
PancakeFactory,
PancakeFactory__factory,
PancakeMasterChef,
PancakeMasterChef__factory,
PancakePair,
PancakePair__factory,
PancakeRouter,
PancakeRouter__factory,
PancakeswapV2RestrictedStrategyAddTwoSidesOptimal,
PancakeswapV2RestrictedStrategyAddTwoSidesOptimal__factory,
PancakeswapV2StrategyLiquidate,
PancakeswapV2StrategyLiquidate__factory,
PancakeswapWorker,
PancakeswapWorker__factory,
SimpleVaultConfig,
SimpleVaultConfig__factory,
SyrupBar,
SyrupBar__factory,
Vault,
Vault__factory,
WETH,
WETH__factory,
WNativeRelayer,
WNativeRelayer__factory,
MockVaultForRestrictedAddTwosideOptimalStrat,
MockVaultForRestrictedAddTwosideOptimalStrat__factory,
MockPancakeswapV2Worker,
MockPancakeswapV2Worker__factory,
PancakeswapV2StrategyAddTwoSidesOptimal__factory,
PancakeswapV2StrategyAddTwoSidesOptimal,
PancakeswapV2Worker,
} from "../../../../../typechain";
import * as Assert from "../../../../helpers/assert";
import { parseEther } from "@ethersproject/units";
chai.use(solidity);
const { expect } = chai;
describe("Pancakeswapv2RestrictedStrategyAddTwoSideOptimal", () => {
const FOREVER = "2000000000";
const MAX_ROUNDING_ERROR = Number("15");
/// Pancakeswap-related instance(s)
let factoryV2: PancakeFactory;
let routerV2: PancakeRouter;
/// Token-related instance(s)
let wbnb: WETH;
let baseToken: MockERC20;
let farmingToken: MockERC20;
let mockedVault: MockVaultForRestrictedAddTwosideOptimalStrat;
// V2
let mockPancakeswapV2WorkerAsBob: MockPancakeswapV2Worker;
let mockPancakeswapV2WorkerAsAlice: MockPancakeswapV2Worker;
let mockPancakeswapV2EvilWorkerAsBob: MockPancakeswapV2Worker;
let mockPancakeswapV2Worker: MockPancakeswapV2Worker;
let mockPancakeswapV2EvilWorker: MockPancakeswapV2Worker;
// Accounts
let deployer: Signer;
let alice: Signer;
let bob: Signer;
let liqStrat: PancakeswapV2StrategyLiquidate;
let addRestrictedStrat: PancakeswapV2RestrictedStrategyAddTwoSidesOptimal;
let addRestrictedStratAsDeployer: PancakeswapV2RestrictedStrategyAddTwoSidesOptimal;
// Contract Signer
let addRestrictedStratAsBob: PancakeswapV2RestrictedStrategyAddTwoSidesOptimal;
let baseTokenAsBob: MockERC20;
let farmingTokenAsAlice: MockERC20;
let lpV2: PancakePair;
const setupFullFlowTest = async () => {
// Setup Pancakeswap
const PancakeFactoryV2 = (await ethers.getContractFactory("PancakeFactory", deployer)) as PancakeFactory__factory;
factoryV2 = await PancakeFactoryV2.deploy(await deployer.getAddress());
await factoryV2.deployed();
const WBNB = (await ethers.getContractFactory("WETH", deployer)) as WETH__factory;
wbnb = await WBNB.deploy();
await wbnb.deployed();
const PancakeRouterV2 = (await ethers.getContractFactory("PancakeRouterV2", deployer)) as PancakeRouter__factory;
routerV2 = await PancakeRouterV2.deploy(factoryV2.address, wbnb.address);
await routerV2.deployed();
/// Setup token stuffs
const MockERC20 = (await ethers.getContractFactory("MockERC20", deployer)) as MockERC20__factory;
baseToken = (await upgrades.deployProxy(MockERC20, ["BTOKEN", "BTOKEN", 18])) as MockERC20;
await baseToken.deployed();
await baseToken.mint(await deployer.getAddress(), ethers.utils.parseEther("100"));
await baseToken.mint(await alice.getAddress(), ethers.utils.parseEther("100"));
await baseToken.mint(await bob.getAddress(), ethers.utils.parseEther("100"));
farmingToken = (await upgrades.deployProxy(MockERC20, ["FTOKEN", "FTOKEN", 18])) as MockERC20;
await farmingToken.deployed();
await farmingToken.mint(await deployer.getAddress(), ethers.utils.parseEther("100"));
await farmingToken.mint(await alice.getAddress(), ethers.utils.parseEther("100"));
await farmingToken.mint(await bob.getAddress(), ethers.utils.parseEther("100"));
/// Setup BTOKEN-FTOKEN pair on Pancakeswap
await factoryV2.createPair(farmingToken.address, baseToken.address);
lpV2 = PancakePair__factory.connect(await factoryV2.getPair(farmingToken.address, baseToken.address), deployer);
await lpV2.deployed();
/// Setup BTOKEN-FTOKEN pair on Pancakeswap
await factoryV2.createPair(wbnb.address, farmingToken.address);
const PancakeswapV2StrategyLiquidate = (await ethers.getContractFactory(
"PancakeswapV2StrategyLiquidate",
deployer
)) as PancakeswapV2StrategyLiquidate__factory;
liqStrat = (await upgrades.deployProxy(PancakeswapV2StrategyLiquidate, [
routerV2.address,
])) as PancakeswapV2StrategyLiquidate;
await liqStrat.deployed();
// Deployer adds 0.1 FTOKEN + 1 BTOKEN
await baseToken.approve(routerV2.address, ethers.utils.parseEther("1"));
await farmingToken.approve(routerV2.address, ethers.utils.parseEther("0.1"));
await routerV2.addLiquidity(
baseToken.address,
farmingToken.address,
ethers.utils.parseEther("1"),
ethers.utils.parseEther("0.1"),
"0",
"0",
await deployer.getAddress(),
FOREVER
);
// Deployer adds 1 BTOKEN + 1 NATIVE
await baseToken.approve(routerV2.address, ethers.utils.parseEther("1"));
await routerV2.addLiquidityETH(
baseToken.address,
ethers.utils.parseEther("1"),
"0",
"0",
await deployer.getAddress(),
FOREVER,
{ value: ethers.utils.parseEther("1") }
);
};
const setupRestrictedTest = async () => {
const MockVaultForRestrictedAddTwosideOptimalStrat = (await ethers.getContractFactory(
"MockVaultForRestrictedAddTwosideOptimalStrat",
deployer
)) as MockVaultForRestrictedAddTwosideOptimalStrat__factory;
mockedVault = (await upgrades.deployProxy(
MockVaultForRestrictedAddTwosideOptimalStrat
)) as MockVaultForRestrictedAddTwosideOptimalStrat;
await mockedVault.deployed();
const PancakeswapV2RestrictedStrategyAddTwoSidesOptimal = (await ethers.getContractFactory(
"PancakeswapV2RestrictedStrategyAddTwoSidesOptimal",
deployer
)) as PancakeswapV2RestrictedStrategyAddTwoSidesOptimal__factory;
addRestrictedStrat = (await upgrades.deployProxy(PancakeswapV2RestrictedStrategyAddTwoSidesOptimal, [
routerV2.address,
mockedVault.address,
])) as PancakeswapV2RestrictedStrategyAddTwoSidesOptimal;
await addRestrictedStrat.deployed();
/// Setup MockPancakeswapV2Worker
const MockPancakeswapV2Worker = (await ethers.getContractFactory(
"MockPancakeswapV2Worker",
deployer
)) as MockPancakeswapV2Worker__factory;
mockPancakeswapV2Worker = (await MockPancakeswapV2Worker.deploy(
lpV2.address,
baseToken.address,
farmingToken.address
)) as MockPancakeswapV2Worker;
await mockPancakeswapV2Worker.deployed();
mockPancakeswapV2EvilWorker = (await MockPancakeswapV2Worker.deploy(
lpV2.address,
baseToken.address,
farmingToken.address
)) as MockPancakeswapV2Worker;
await mockPancakeswapV2EvilWorker.deployed();
};
const setupContractSigner = async () => {
// Contract signer
addRestrictedStratAsBob = PancakeswapV2RestrictedStrategyAddTwoSidesOptimal__factory.connect(
addRestrictedStrat.address,
bob
);
addRestrictedStratAsDeployer = PancakeswapV2RestrictedStrategyAddTwoSidesOptimal__factory.connect(
addRestrictedStrat.address,
deployer
);
baseTokenAsBob = MockERC20__factory.connect(baseToken.address, bob);
farmingTokenAsAlice = MockERC20__factory.connect(farmingToken.address, alice);
mockPancakeswapV2WorkerAsBob = MockPancakeswapV2Worker__factory.connect(mockPancakeswapV2Worker.address, bob);
mockPancakeswapV2WorkerAsAlice = MockPancakeswapV2Worker__factory.connect(mockPancakeswapV2Worker.address, alice);
mockPancakeswapV2EvilWorkerAsBob = MockPancakeswapV2Worker__factory.connect(
mockPancakeswapV2EvilWorker.address,
bob
);
};
async function fixture() {
[deployer, alice, bob] = await ethers.getSigners();
await setupFullFlowTest();
await setupRestrictedTest();
await setupContractSigner();
await addRestrictedStratAsDeployer.setWorkersOk([mockPancakeswapV2Worker.address], true);
}
beforeEach(async () => {
await waffle.loadFixture(fixture);
});
describe("full flow test", async () => {
context("when strategy execution is not in the scope", async () => {
it("should revert", async () => {
await expect(
addRestrictedStratAsBob.execute(
await bob.getAddress(),
"0",
ethers.utils.defaultAbiCoder.encode(["uint256", "uint256"], ["0", "0"])
)
).to.be.reverted;
});
});
context("when bad calldata", async () => {
it("should revert", async () => {
await mockedVault.setMockOwner(await alice.getAddress());
await baseToken.mint(mockPancakeswapV2Worker.address, ethers.utils.parseEther("1"));
await expect(
mockPancakeswapV2WorkerAsAlice.work(
0,
await alice.getAddress(),
ethers.utils.parseEther("1"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[addRestrictedStrat.address, ethers.utils.defaultAbiCoder.encode(["address"], [await bob.getAddress()])]
)
)
).to.reverted;
});
});
it("should convert all BTOKEN to LP tokens at best rate", async () => {
// Now Alice leverage 2x on her 1 BTOKEN.
// So totally Alice will take 1 BTOKEN from the pool and 1 BTOKEN from her pocket to
// Provide liquidity in the BTOKEN-FTOKEN pool on Pancakeswap
await mockedVault.setMockOwner(await alice.getAddress());
await baseToken.mint(mockPancakeswapV2Worker.address, ethers.utils.parseEther("2"));
await mockPancakeswapV2WorkerAsAlice.work(
0,
await alice.getAddress(),
ethers.utils.parseEther("0"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
addRestrictedStrat.address,
ethers.utils.defaultAbiCoder.encode(["uint256", "uint256"], ["0", ethers.utils.parseEther("0.01")]),
]
)
);
// the calculation is ratio between balance and reserve * total supply
// let total supply = sqrt(1 * 0.1) = 0.31622776601683794
// current reserve after swap is 1732967258967755614
// ths lp will be (1267032741032244386 (optimal swap amount) / 1732967258967755614 (reserve)) * 0.31622776601683794
// lp will be 0.23120513736969137
const stratLPBalance = await lpV2.balanceOf(mockPancakeswapV2Worker.address);
Assert.assertAlmostEqual(stratLPBalance.toString(), ethers.utils.parseEther("0.23120513736969137").toString());
expect(stratLPBalance).to.above(ethers.utils.parseEther("0"));
expect(await farmingToken.balanceOf(addRestrictedStrat.address)).to.be.below(MAX_ROUNDING_ERROR);
// Now Alice leverage 2x on her 0.1 BTOKEN.
// So totally Alice will take 0.1 BTOKEN from the pool and 0.1 BTOKEN from her pocket to
// Provide liquidity in the BTOKEN-FTOKEN pool on Pancakeswap
await baseToken.mint(mockPancakeswapV2Worker.address, ethers.utils.parseEther("0.1"));
await mockPancakeswapV2WorkerAsAlice.work(
0,
await alice.getAddress(),
ethers.utils.parseEther("0.1"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
addRestrictedStrat.address,
ethers.utils.defaultAbiCoder.encode(["uint256", "uint256"], ["0", ethers.utils.parseEther("0")]),
]
)
);
// the calculation is ratio between balance and reserve * total supply
// let total supply = 0.556470668763341270 coming from 0.31622776601683794 + 0.23120513736969137
// current reserve after swap is 3049652202279806938
// ths lp will be (50347797720193062 (optimal swap amount) / 3049652202279806938 (reserve)) * 0.556470668763341270
// lp will be 0.009037765376812014
// thus the accum lp will be 0.009037765376812014 + 0.23120513736969137 = 0.240242902746503337
Assert.assertAlmostEqual(
(await lpV2.balanceOf(mockPancakeswapV2Worker.address)).toString(),
ethers.utils.parseEther("0.240242902746503337").toString()
);
expect(await lpV2.balanceOf(mockPancakeswapV2Worker.address)).to.above(stratLPBalance);
expect(await farmingToken.balanceOf(addRestrictedStrat.address)).to.be.below(MAX_ROUNDING_ERROR);
});
it("should convert some BTOKEN and some FTOKEN to LP tokens at best rate", async () => {
// Now Alice leverage 2x on her 1 BTOKEN.
// So totally Alice will take 1 BTOKEN from the pool and 1 BTOKEN from her pocket to
// Provide liquidity in the BTOKEN-FTOKEN pool on Pancakeswap
await mockedVault.setMockOwner(await alice.getAddress());
await baseToken.mint(mockPancakeswapV2Worker.address, ethers.utils.parseEther("2"));
await farmingTokenAsAlice.approve(mockedVault.address, ethers.utils.parseEther("1"));
await mockPancakeswapV2WorkerAsAlice.work(
0,
await alice.getAddress(),
ethers.utils.parseEther("0"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
addRestrictedStrat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256"],
[ethers.utils.parseEther("0.05"), ethers.utils.parseEther("0")]
),
]
)
);
// the calculation is ratio between balance and reserve * total supply
// let total supply = sqrt(1 * 0.1) = 0.31622776601683794
// current reserve after swap is 1414732072482656002
// ths lp will be (1585267927517343998 (optimal swap amount) / 1414732072482656002 (reserve)) * 0.31622776601683794
// lp will be 0.354346766435591663
const stratLPBalance = await lpV2.balanceOf(mockPancakeswapV2Worker.address);
Assert.assertAlmostEqual(stratLPBalance.toString(), ethers.utils.parseEther("0.354346766435591663").toString());
expect(stratLPBalance).to.above(ethers.utils.parseEther("0"));
expect(await farmingToken.balanceOf(addRestrictedStrat.address)).to.be.below(MAX_ROUNDING_ERROR);
// Now Alice leverage 2x on her 0.1 BTOKEN.
// So totally Alice will take 0.1 BTOKEN from the pool and 0.1 BTOKEN from her pocket to
// Provide liquidity in the BTOKEN-FTOKEN pool on Pancakeswap
await baseToken.mint(mockPancakeswapV2Worker.address, ethers.utils.parseEther("1"));
await farmingTokenAsAlice.approve(mockedVault.address, ethers.utils.parseEther("1"));
await mockPancakeswapV2WorkerAsAlice.work(
0,
await alice.getAddress(),
ethers.utils.parseEther("1"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
addRestrictedStrat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256"],
[ethers.utils.parseEther("1"), ethers.utils.parseEther("0.1")]
),
]
)
);
// the calculation is ratio between balance and reserve * total supply
// let total supply = 0.31622776601683794 + 0.354346766435591663 = 0.6705745324524296
// current reserve after swap is 1251999642993914466
// ths lp will be (2748000357006085534 (optimal swap amount) / 1251999642993914466 (reserve)) * 0.6705745324524296
// lp will be 0.1471836725266080870
// thus, the accum lp will be 1.471836725266080870 + 0.354346766435591663 = 1.8261834917016726
Assert.assertAlmostEqual(
(await lpV2.balanceOf(mockPancakeswapV2Worker.address)).toString(),
ethers.utils.parseEther("1.8261834917016726").toString()
);
expect(await lpV2.balanceOf(mockPancakeswapV2Worker.address)).to.above(stratLPBalance);
expect(await farmingToken.balanceOf(addRestrictedStrat.address)).to.be.below(MAX_ROUNDING_ERROR);
});
});
describe("restricted test", async () => {
context("When the setOkWorkers caller is not an owner", async () => {
it("should be reverted", async () => {
await expect(addRestrictedStratAsBob.setWorkersOk([mockPancakeswapV2EvilWorkerAsBob.address], true)).to
.reverted;
});
});
context("When the caller worker is not whitelisted", async () => {
it("should revert", async () => {
await baseTokenAsBob.transfer(mockPancakeswapV2EvilWorkerAsBob.address, ethers.utils.parseEther("0.01"));
await expect(
mockPancakeswapV2EvilWorkerAsBob.work(
0,
await bob.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
addRestrictedStrat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256"],
[ethers.utils.parseEther("0"), ethers.utils.parseEther("0.01")]
),
]
)
)
).to.revertedWith("PancakeswapV2RestrictedStrategyAddTwoSidesOptimal::onlyWhitelistedWorkers:: bad worker");
});
});
context("When the caller worker has been revoked from callable", async () => {
it("should revert", async () => {
await baseTokenAsBob.transfer(mockPancakeswapV2EvilWorkerAsBob.address, ethers.utils.parseEther("0.01"));
await addRestrictedStratAsDeployer.setWorkersOk([mockPancakeswapV2Worker.address], false);
await expect(
mockPancakeswapV2WorkerAsBob.work(
0,
await bob.getAddress(),
0,
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
addRestrictedStrat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256"],
[ethers.utils.parseEther("0"), ethers.utils.parseEther("0.01")]
),
]
)
)
).to.revertedWith("PancakeswapV2RestrictedStrategyAddTwoSidesOptimal::onlyWhitelistedWorkers:: bad worker");
});
});
});
}); | the_stack |
import { of, EMPTY } from 'rxjs';
import { delayWhen, tap } from 'rxjs/operators';
import { TestScheduler } from 'rxjs/testing';
import { observableMatcher } from '../helpers/observableMatcher';
import { expect } from 'chai';
/** @test {delayWhen} */
describe('delayWhen', () => {
let testScheduler: TestScheduler;
beforeEach(() => {
testScheduler = new TestScheduler(observableMatcher);
});
it('should delay by duration selector', () => {
testScheduler.run(({ cold, hot, expectObservable, expectSubscriptions }) => {
const e1 = hot(' ---a---b---c--| ');
const expected = '-----a------c----(b|)';
const subs = ' ^-------------! ';
const selector = [
cold(' --x--| '),
cold(' ----------(x|)'),
cold(' -x--| '),
];
const selectorSubs = [
' ---^-! ',
' -------^---------! ',
' -----------^! ',
];
let idx = 0;
function durationSelector(x: any) {
return selector[idx++];
}
const result = e1.pipe(delayWhen(durationSelector));
expectObservable(result).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(subs);
expectSubscriptions(selector[0].subscriptions).toBe(selectorSubs[0]);
expectSubscriptions(selector[1].subscriptions).toBe(selectorSubs[1]);
expectSubscriptions(selector[2].subscriptions).toBe(selectorSubs[2]);
});
});
it('should delay by selector', () => {
testScheduler.run(({ cold, hot, expectObservable, expectSubscriptions }) => {
const e1 = hot(' --a--b--| ');
const expected = ' ---a--b-| ';
const subs = ' ^-------! ';
const selector = cold('-x--| ');
// -x--|
// prettier-ignore
const selectorSubs = [
' --^! ',
' -----^! ',
];
const result = e1.pipe(delayWhen((x: any) => selector));
expectObservable(result).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(subs);
expectSubscriptions(selector.subscriptions).toBe(selectorSubs);
});
});
it('should raise error if source raises error', () => {
testScheduler.run(({ cold, hot, expectObservable, expectSubscriptions }) => {
const e1 = hot(' --a--# ');
const expected = ' ---a-# ';
const subs = ' ^----! ';
const selector = cold(' -x--|');
const selectorSubs = '--^! ';
const result = e1.pipe(delayWhen((x: any) => selector));
expectObservable(result).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(subs);
expectSubscriptions(selector.subscriptions).toBe(selectorSubs);
});
});
it('should raise error if selector raises error', () => {
testScheduler.run(({ cold, hot, expectObservable, expectSubscriptions }) => {
const e1 = hot(' --a--b--|');
const expected = ' ---# ';
const subs = ' ^--! ';
const selector = cold(' -# ');
const selectorSubs = '--^! ';
const result = e1.pipe(delayWhen((x: any) => selector));
expectObservable(result).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(subs);
expectSubscriptions(selector.subscriptions).toBe(selectorSubs);
});
});
it('should delay by selector and completes after value emits', () => {
testScheduler.run(({ cold, hot, expectObservable, expectSubscriptions }) => {
const e1 = hot(' --a--b--| ');
const expected = ' ---------a--(b|)';
const subs = ' ^-------! ';
const selector = cold('-------x--| ');
// -------x--|
// prettier-ignore
const selectorSubs = [
' --^------! ',
' -----^------! '
];
const result = e1.pipe(delayWhen((x: any) => selector));
expectObservable(result).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(subs);
expectSubscriptions(selector.subscriptions).toBe(selectorSubs);
});
});
it('should delay, but not emit if the selector never emits a notification', () => {
testScheduler.run(({ cold, hot, expectObservable, expectSubscriptions }) => {
const e1 = hot(' --a--b--| ');
const expected = ' -----------|';
const subs = ' ^-------! ';
const selector = cold('------| ');
// ------|
// prettier-ignore
const selectorSubs = [
' --^-----! ',
' -----^-----!'
];
const result = e1.pipe(delayWhen((x: any) => selector));
expectObservable(result).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(subs);
expectSubscriptions(selector.subscriptions).toBe(selectorSubs);
});
});
it('should not emit for async source and sync empty selector', () => {
testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => {
const e1 = hot(' a--|');
const expected = '---|';
const subs = ' ^--!';
const result = e1.pipe(delayWhen((x: any) => EMPTY));
expectObservable(result).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(subs);
});
});
it('should not emit if selector never emits', () => {
testScheduler.run(({ cold, hot, expectObservable, expectSubscriptions }) => {
const e1 = hot(' --a--b--|');
const expected = ' - ';
const subs = ' ^-------!';
const selector = cold('- ');
// -
// prettier-ignore
const selectorSubs = [
' --^ ',
' -----^ ',
];
const result = e1.pipe(delayWhen((x: any) => selector));
expectObservable(result).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(subs);
expectSubscriptions(selector.subscriptions).toBe(selectorSubs);
});
});
it('should delay by first value from selector', () => {
testScheduler.run(({ cold, hot, expectObservable, expectSubscriptions }) => {
const e1 = hot(' --a--b--| ');
const expected = ' ------a--(b|) ';
const subs = ' ^-------! ';
const selector = cold('----x--y--| ');
// ----x--y--|
// prettier-ignore
const selectorSubs = [
' --^---! ',
' -----^---! ',
];
const result = e1.pipe(delayWhen((x: any) => selector));
expectObservable(result).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(subs);
expectSubscriptions(selector.subscriptions).toBe(selectorSubs);
});
});
it('should delay by selector that does not completes', () => {
testScheduler.run(({ cold, hot, expectObservable, expectSubscriptions }) => {
const e1 = hot(' --a--b--| ');
const expected = ' ------a--(b|) ';
const subs = ' ^-------! ';
const selector = cold('----x-----y--- ');
// ----x-----y---
// prettier-ignore
const selectorSubs = [
' --^---! ',
' -----^---! '
];
const result = e1.pipe(delayWhen((x: any) => selector));
expectObservable(result).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(subs);
expectSubscriptions(selector.subscriptions).toBe(selectorSubs);
});
});
it('should raise error if selector throws', () => {
testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => {
const e1 = hot(' --a--b--|');
const e1subs = ' ^-! ';
const expected = '--# ';
const err = new Error('error');
const result = e1.pipe(
delayWhen(<any>((x: any) => {
throw err;
}))
);
expectObservable(result).toBe(expected, null, err);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
it('should start subscription when subscription delay emits', () => {
testScheduler.run(({ cold, hot, expectObservable, expectSubscriptions }) => {
const e1 = hot(' -----a---b---| ');
const expected = ' -------a---b-| ';
const subs = ' ---^---------! ';
const selector = cold(' --x--| ');
// --x--|
// prettier-ignore
const selectorSubs = [
' -----^-! ',
' ---------^-! '
];
const subDelay = cold('---x--| ');
const subDelaySub = ' ^--! ';
const result = e1.pipe(delayWhen((x: any) => selector, subDelay));
expectObservable(result).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(subs);
expectSubscriptions(selector.subscriptions).toBe(selectorSubs);
expectSubscriptions(subDelay.subscriptions).toBe(subDelaySub);
});
});
it('should start subscription when subscription delay completes without emit value', () => {
testScheduler.run(({ cold, hot, expectObservable, expectSubscriptions }) => {
const e1 = hot(' -----a---b---| ');
const expected = ' -------a---b-| ';
const subs = ' ---^---------! ';
const selector = cold(' --x--| ');
// --x--|
// prettier-ignore
const selectorSubs = [
' -----^-! ',
' ---------^-! '
];
const subDelay = cold('---| ');
const subDelaySub = ' ^--! ';
const result = e1.pipe(delayWhen((x: any) => selector, subDelay));
expectObservable(result).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(subs);
expectSubscriptions(selector.subscriptions).toBe(selectorSubs);
expectSubscriptions(subDelay.subscriptions).toBe(subDelaySub);
});
});
it('should raise error when subscription delay raises error', () => {
testScheduler.run(({ cold, hot, expectObservable, expectSubscriptions }) => {
const e1 = hot(' -----a---b---|');
const expected = ' ---# ';
const selector = cold(' --x--| ');
const subDelay = cold('---# ');
const subDelaySub = ' ^--! ';
const result = e1.pipe(delayWhen((x: any) => selector, subDelay));
expectObservable(result).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe([]);
expectSubscriptions(selector.subscriptions).toBe([]);
expectSubscriptions(subDelay.subscriptions).toBe(subDelaySub);
});
});
it('should complete when duration selector returns synchronous observable', () => {
let next: boolean = false;
let complete: boolean = false;
of(1)
.pipe(delayWhen(() => of(2)))
.subscribe(
() => (next = true),
null,
() => (complete = true)
);
expect(next).to.be.true;
expect(complete).to.be.true;
});
it('should call predicate with indices starting at 0', () => {
testScheduler.run(({ cold, hot, expectObservable, expectSubscriptions }) => {
const e1 = hot(' --a--b--c--|');
const e1subs = ' ^----------!';
const expected = ' --a--b--c--|';
const selector = cold(' (x|)');
// (x|)
// (x|)
let indices: number[] = [];
const predicate = (value: string, index: number) => {
indices.push(index);
return selector;
};
const result = e1.pipe(delayWhen(predicate));
expectObservable(
result.pipe(
tap(null, null, () => {
expect(indices).to.deep.equal([0, 1, 2]);
})
)
).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
}); | the_stack |
import {Component, ElementRef, EventEmitter, Injector, OnDestroy, OnInit, Output} from '@angular/core';
import {Alert} from '@common/util/alert.util';
import {AbstractComponent} from '@common/component/abstract.component';
import {PageResult} from '@domain/common/page';
import {WorkspaceService} from '../../../workspace/service/workspace.service';
import {DatasourceService} from '../../../datasource/service/datasource.service';
import {DataconnectionService} from '@common/service/dataconnection.service';
@Component({
selector: 'app-set-workspace-published',
templateUrl: './set-workspace-published.component.html'
})
export class SetWorkspacePublishedComponent extends AbstractComponent implements OnInit, OnDestroy {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 연결된 타입
private linkedType: string;
private linkedId: string;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 팝업 플래그
public showFl: boolean = false;
// mode
public mode: string;
@Output()
public complete = new EventEmitter();
// personal 검색
public searchPersonal: string = '';
// public 검색
public searchPublic: string = '';
// tab change
public tabChange: string = 'PRIVATE';
// personal workspaces
public personalWorkspaces: Workspace;
// public workspaces
public publicWorkspaces: Workspace;
// 추가할 워크스페이스 아이디
public addWorkspaces: any[] = [];
// 제거할 워크스페이스 아이디
public deleteWorkspaces: any[] = [];
// filter workspace
public filterPersonalFl: boolean = false;
public filterPublicFl: boolean = false;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 생성자
constructor(private workspaceService: WorkspaceService,
private datasourceService: DatasourceService,
private connectionService: DataconnectionService,
protected elementRef: ElementRef,
protected injector: Injector) {
super(elementRef, injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
public ngOnInit() {
super.ngOnInit();
}
public ngOnDestroy() {
super.ngOnDestroy();
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 연결된 개인 워크스페이스 수
* @returns {number}
*/
public getLinkedPersonalWorkspace(): number {
let count = 0;
if (this.mode === 'create') {
count += this.addWorkspaces.filter((workspace) => {
return workspace.publicType === 'PRIVATE';
}).length;
count -= this.deleteWorkspaces.filter((workspace) => {
return workspace.publicType === 'PRIVATE';
}).length;
} else if (this.mode === 'update' && this.personalWorkspaces.count) {
count += this.personalWorkspaces.count.linked;
}
return count;
}
/**
* 연결된 공유 워크스페이스 수
* @returns {number}
*/
public getLinkedPublicWorkspace(): number {
let count = 0;
if (this.mode === 'create') {
count += this.addWorkspaces.filter((workspace) => {
return workspace.publicType === 'SHARED';
}).length;
count -= this.deleteWorkspaces.filter((workspace) => {
return workspace.publicType === 'SHARED';
}).length;
} else if (this.mode === 'update' && this.publicWorkspaces.count) {
count += this.publicWorkspaces.count.linked;
}
return count;
}
/**
* 개인 워크스페이스 전체 수
* @returns {number}
*/
public getTotalPersonalWorkspace(): number {
return this.personalWorkspaces.hasOwnProperty('count') ? this.personalWorkspaces.count.total : 0;
}
/**
* 공유 워크스페이스 전체 수
* @returns {number}
*/
public getTotalPublicWorkspace(): number {
return this.publicWorkspaces.hasOwnProperty('count') ? this.publicWorkspaces.count.total : 0;
}
/**
* 공유 워크스페이스 리스트
* @returns {any[]}
*/
public publicWorkspaceList() {
// 생성모드는 추가할 워크스페이스 리스트만 반환
if (this.mode === 'create' && this.filterPublicFl) {
// 공유 워크스페이스와 정렬 된 상태로 리스트
let result = this.addWorkspaces.filter((workspace) => {
return workspace.publicType === 'SHARED';
}).sort((prev, next) => {
// 내림 차순
if (this.publicWorkspaces.sort === 'name,desc') {
return prev.name > next.name ? -1 : prev.name < next.name ? 1 : 0;
} else {
return prev.name < next.name ? -1 : prev.name > next.name ? 1 : 0;
}
});
// search
if (this.searchPublic.trim() !== '') {
result = result.filter((workspace) => {
if (workspace.name.toLowerCase().includes(this.searchPublic.toLowerCase().trim())) {
return workspace;
}
});
}
return result;
} else {
return this.publicWorkspaces.workspace;
}
}
/**
* 개인 워크스페이스 리스트
* @returns {any[]}
*/
public personalWorkspaceList() {
// 생성모드는 추가할 워크스페이스 리스트만 반환
if (this.mode === 'create' && this.filterPersonalFl) {
// 개인 워크스페이스와 정렬 된 상태로 리스트
let result = this.addWorkspaces.filter((workspace) => {
return workspace.publicType === 'PRIVATE';
}).sort((prev, next) => {
// 내림 차순
if (this.personalWorkspaces.sort === 'name,desc') {
return prev.name > next.name ? -1 : prev.name < next.name ? 1 : 0;
} else {
return prev.name < next.name ? -1 : prev.name > next.name ? 1 : 0;
}
});
// search
if (this.searchPersonal.trim() !== '') {
result = result.filter((workspace) => {
if (workspace.name.toLowerCase().includes(this.searchPersonal.toLowerCase().trim())) {
return workspace;
}
});
}
return result;
} else {
return this.personalWorkspaces.workspace;
}
}
/**
* 생성일때 체크표시가 모두 되있는 상태인지
* @returns {boolean}
*/
public checkAllWorkspace(): boolean {
const result = [];
if (this.tabChange === 'PRIVATE') {
this.personalWorkspaceList().forEach((workspace) => {
this.addWorkspaces.forEach((item) => {
if (workspace.id === item.id) {
result.push(item);
}
});
});
return result.length !== 0 && result.length === this.personalWorkspaceList().length;
} else {
this.publicWorkspaceList().forEach((workspace) => {
this.addWorkspaces.forEach((item) => {
if (workspace.id === item.id) {
result.push(item);
}
});
});
return result.length !== 0 && result.length === this.publicWorkspaceList().length;
}
}
/**
* init
* @param {string} linkedType
* @param {string} mode
* @param param
*/
public init(linkedType: string, mode: string, param: any) {
// 초기화
this.initView();
// create or update
this.mode = mode;
if (this.mode === 'create') {
// 데이터
this.addWorkspaces = Object.assign([], param.addWorkspaces);
this.deleteWorkspaces = Object.assign([], param.deleteWorkspaces);
} else {
// 연결된 아이디
this.linkedId = param;
}
// 호출한 타입
this.linkedType = linkedType;
// 로딩 show
this.loadingShow();
// 워크스페이스 조회
Promise.all([this.getWorkspaces('PRIVATE'), this.getWorkspaces('SHARED')])
.then(() => {
// 로딩 hide
this.loadingHide();
})
.catch(() => {
// 로딩 hide
this.loadingHide();
});
}
/**
* 닫기 버튼
*/
public close() {
this.showFl = false;
}
/**
* 적용 버튼
*/
public done() {
this.showFl = false;
// let result = {
// addWorkspaces: this.addWorkspaces,
// deleteWorkspaces: this.deleteWorkspaces
// };
const result = this.mode === 'create' ? this.addWorkspaces : this.publicWorkspaces.count.linked + this.personalWorkspaces.count.linked;
// 완료
this.complete.emit(result);
}
/**
* 체크박스 클릭 이벤트
* @param workspace
* @param workspaceType
*/
public onCheckedWorkspace(workspace, workspaceType) {
// 생성 모드일경우 addWorkspace 만 사용
if (this.mode === 'create') {
this.onCheckWorkspaceInCreateMode(workspace);
} else {
this.onCheckWorkspaceInUpdateMode(workspace, workspaceType);
}
}
/**
* 전체체크박스 클릭 이벤트
* @param {boolean} checkFl
* @param {string} mode
*/
public onCheckAll(checkFl: boolean, mode: string) {
let index;
if (mode === 'PRIVATE') {
// 개인 워크스페이스
this.personalWorkspaceList().forEach((workspace) => {
index = this.getFindIndexWorkspace(this.addWorkspaces, workspace.id);
// 체크된 상태인 경우
if (checkFl && index !== -1) {
this.addWorkspaces.splice(index, 1);
} else if (!checkFl && index === -1) {
this.addWorkspaces.push(workspace);
}
});
} else {
// 공유 워크스페이스
this.publicWorkspaceList().forEach((workspace) => {
index = this.getFindIndexWorkspace(this.addWorkspaces, workspace.id);
// 체크된 상태인 경우
if (checkFl && index !== -1) {
this.addWorkspaces.splice(index, 1);
} else if (!checkFl && index === -1) {
this.addWorkspaces.push(workspace);
}
});
}
}
/**
* 체크표시 여부
* @param workspace
* @returns {boolean}
*/
public checkInWorkspaces(workspace) {
// workspace id
const workspaceId = workspace.id;
// 생성 모드일경우 addWorkspace 만 사용
if (this.mode === 'create') {
return this.checkInAddWorkspaces(workspaceId);
} else {
// linked 된 워크스페이스 인지
const linkedFl = workspace.linked;
// linked 되었지만 변경될 워크스페이스에 없을 경우
if (linkedFl && !this.checkInAddWorkspaces(workspaceId) && !this.checkInDeleteWorkspaces(workspaceId)) {
return true;
}
return linkedFl ? !this.checkInDeleteWorkspaces(workspaceId) : this.checkInAddWorkspaces(workspaceId);
}
}
/**
* Changed personal search keyword
* @param keyword
*/
public onChangedPersonalSearchKeyword(keyword: string): void {
// set search keyword
this.searchPersonal = keyword;
// search personal workspace
this.getWorkspaces('PRIVATE');
}
/**
* Changed public search keyword
* @param keyword
*/
public onChangedPublicSearchKeyword(keyword: string): void {
// set search keyword
this.searchPublic = keyword;
// search public workspace
this.getWorkspaces('SHARED');
}
/**
* 정렬 이벤트
* @param {string} type
*/
public sort(type: string) {
if (type === 'PRIVATE') {
this.personalWorkspaces.sort = this.personalWorkspaces.sort === 'name,desc' ? 'name,asc' : 'name,desc';
this.personalWorkspaces.page.number = 0;
} else {
this.publicWorkspaces.sort = this.publicWorkspaces.sort === 'name,desc' ? 'name,asc' : 'name,desc';
this.publicWorkspaces.page.number = 0;
}
// 재조회
this.getWorkspaces(type);
}
/**
* 더보기 버튼 이벤트
* @param {string} type
*/
public moreWorkspace(type: string) {
// 페이지 초기화
type === 'PRIVATE' ? this.personalWorkspaces.page.number += 1 : this.publicWorkspaces.page.number += 1;
// 재조회
this.getWorkspaces(type);
}
/**
* 필터링 버튼 이벤트
* @param {string} type
*/
public filtering(type: string) {
// create
if (this.mode === 'create') {
type === 'SHARED' ? this.filterPublicFl = !this.filterPublicFl : this.filterPersonalFl = !this.filterPersonalFl;
} else {
type === 'SHARED' ? this.filterPublicFl = !this.filterPublicFl : this.filterPersonalFl = !this.filterPersonalFl;
// 재조회
this.getWorkspaces(type);
}
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 워크스페이스 내 index 찾기
* @param {any[]} workspaceList
* @param workspaceId
* @returns {number}
*/
private getFindIndexWorkspace(workspaceList: any[], workspaceId): number {
return workspaceList.findIndex((workspace) => {
return workspace.id === workspaceId;
});
}
/**
* 워크스페이스 에서 워크스페이스 아이디랑 일치하는 아이템 제거
* @param {any[]} workspace
* @param {string} workspaceId
*/
private spliceWorkspace(workspace: any[], workspaceId: string) {
// index
const index = this.getFindIndexWorkspace(workspace, workspaceId);
// 존재할때만 제거
if (index !== -1) {
workspace.splice(index, 1);
}
}
/**
* 데이터 커넥션에서 워크스페이스 연결 해제
* @param workspace
* @param workspaceType
*/
private deleteWorkspaceInDataconnection(workspace, workspaceType) {
// id
const workspaceId = workspace.id;
this.deleteWorkspaceInDataconnectionForServer(this.linkedId, [workspaceId])
.then(() => {
// 연결된 워크스페이스에서 제거
workspace.linked = false;
// 타입이 private 라면
if (workspaceType === 'PRIVATE') {
// 현재 연결된 워크스페이스 수 감소
this.personalWorkspaces.count.linked -= 1;
// 선택된 워크스페이스만 보기 필터일 경우에만 제거
if (this.filterPersonalFl) {
this.spliceWorkspace(this.personalWorkspaces.workspace, workspaceId);
}
} else {
// 현재 연결된 워크스페이스 수 감소
this.publicWorkspaces.count.linked -= 1;
// 선택된 워크스페이스만 보기 필터일 경우에만 제거
if (this.filterPublicFl) {
this.spliceWorkspace(this.publicWorkspaces.workspace, workspaceId);
}
}
}).catch((error) => {
Alert.error(error);
});
}
/**
* 데이터 소스에서 워크스페이스 연결 해제
* @param workspace
* @param workspaceType
*/
private deleteWorkspaceInDatasource(workspace, workspaceType) {
// id
const workspaceId = workspace.id;
this.deleteWorkspaceInDatasourceForServer(this.linkedId, [workspaceId])
.then(() => {
// 연결된 워크스페이스에서 제거
workspace.linked = false;
// 타입이 private 라면
if (workspaceType === 'PRIVATE') {
// 현재 연결된 워크스페이스 수 감소
this.personalWorkspaces.count.linked -= 1;
// 선택된 워크스페이스만 보기 필터일 경우에만 제거
if (this.filterPersonalFl) {
this.spliceWorkspace(this.personalWorkspaces.workspace, workspaceId);
}
} else {
// 현재 연결된 워크스페이스 수 감소
this.publicWorkspaces.count.linked -= 1;
// 선택된 워크스페이스만 보기 필터일 경우에만 제거
if (this.filterPublicFl) {
this.spliceWorkspace(this.publicWorkspaces.workspace, workspaceId);
}
}
}).catch((error) => {
Alert.error(error);
});
}
/**
* 데이터 커넥션에서 워크스페이스 연결
* @param workspace
* @param workspaceType
*/
private addWorkspaceInDataconnection(workspace, workspaceType) {
// id
const workspaceId = workspace.id;
this.addWorkspaceInDataconnectionForServer(this.linkedId, [workspaceId])
.then(() => {
// 연결된 워크스페이스에 추가
workspace.linked = true;
// 타입이 private 라면
if (workspaceType === 'PRIVATE') {
// 현재 연결된 워크스페이스 수 증가
this.personalWorkspaces.count.linked += 1;
} else {
// 현재 연결된 워크스페이스 수 증가
this.publicWorkspaces.count.linked += 1;
}
}).catch((error) => {
Alert.error(error);
})
}
/**
* 데이터 소스에서 워크스페이스 연결
* @param workspace
* @param workspaceType
*/
private addWorkspaceInDatasource(workspace, workspaceType) {
// id
const workspaceId = workspace.id;
this.addWorkspaceInDatasourceForServer(this.linkedId, [workspaceId])
.then(() => {
// 연결된 워크스페이스에 추가
workspace.linked = true;
// 타입이 private 라면
if (workspaceType === 'PRIVATE') {
// 현재 연결된 워크스페이스 수 증가
this.personalWorkspaces.count.linked += 1;
} else {
// 현재 연결된 워크스페이스 수 증가
this.publicWorkspaces.count.linked += 1;
}
}).catch((error) => {
Alert.error(error);
});
}
/**
* 생성모드 일때 체크박스 클릭 이벤트
* @param workspace
*/
private onCheckWorkspaceInCreateMode(workspace) {
const index = this.getFindIndexWorkspace(this.addWorkspaces, workspace.id);
index === -1 ? this.addWorkspaces.push(workspace) : this.addWorkspaces.splice(index, 1);
}
/**
* 수정모드 일때 체크박스 클릭 이벤트
* @param workspace
* @param workspaceType
*/
private onCheckWorkspaceInUpdateMode(workspace, workspaceType) {
// linked 된 워크스페이스 인지
const linkedFl = workspace.linked;
// 연결된 워크스페이스 라면
if (linkedFl) {
// 커넥션 or 소스
this.linkedType === 'connection'
? this.deleteWorkspaceInDataconnection(workspace, workspaceType)
: this.deleteWorkspaceInDatasource(workspace, workspaceType);
} else {
// 연결된 워크스페이스가 아니라면
// 커넥션 or 소스
this.linkedType === 'connection'
? this.addWorkspaceInDataconnection(workspace, workspaceType)
: this.addWorkspaceInDatasource(workspace, workspaceType);
}
}
/**
* 데이터소스에 워크스페이스 추가
* @param {string} connId
* @param id
* @returns {Promise<any>}
*/
private addWorkspaceInDatasourceForServer(connId: string, id: any): Promise<any> {
return new Promise((resolve, reject) => {
this.loadingShow();
this.datasourceService.addDatasourceWorkspaces(connId, id)
.then((result) => {
this.loadingHide();
resolve(result);
})
.catch((error) => {
this.loadingHide();
reject(error);
});
});
}
/**
* 데이터소스에 워크스페이스 제거
* @param {string} connId
* @param id
* @returns {Promise<any>}
*/
private deleteWorkspaceInDatasourceForServer(connId: string, id: any): Promise<any> {
return new Promise((resolve, reject) => {
this.loadingShow();
this.datasourceService.deleteDatasourceWorkspaces(connId, id)
.then((result) => {
this.loadingHide();
resolve(result);
})
.catch((error) => {
this.loadingHide();
reject(error);
});
});
}
/**
* 데이터커넥션에 워크스페이스 추가
* @param {string} connId
* @param id
* @returns {Promise<any>}
*/
private addWorkspaceInDataconnectionForServer(connId: string, id: any): Promise<any> {
return new Promise((resolve, reject) => {
// 로딩 show
this.loadingShow();
this.connectionService.addConnectionWorkspaces(connId, id)
.then((result) => {
// 로딩 hide
this.loadingHide();
resolve(result);
})
.catch((error) => {
// 로딩 hide
this.loadingHide();
reject(error);
});
});
}
/**
* 데이터커넥션에 워크스페이스 제거
* @param {string} connId
* @param id
* @returns {Promise<any>}
*/
private deleteWorkspaceInDataconnectionForServer(connId: string, id: any): Promise<any> {
return new Promise((resolve, reject) => {
// 로딩 show
this.loadingShow();
this.connectionService.deleteConnectionWorkspaces(connId, id)
.then((result) => {
// 로딩 hide
this.loadingHide();
resolve(result);
})
.catch((error) => {
// 로딩 hide
this.loadingHide();
reject(error);
});
});
}
/**
* 워크스페이스가 추가될 목록에 있다면
* @param {string} workspaceId
* @returns {boolean}
*/
private checkInAddWorkspaces(workspaceId: string) {
const result = this.addWorkspaces.filter((workspace) => {
return workspaceId === workspace.id;
});
// 목록에 있다면 true
return result.length !== 0;
}
/**
* 워크스페이스가 제거될 목록에 있다면
* @param {string} workspaceId
* @returns {boolean}
*/
private checkInDeleteWorkspaces(workspaceId: string) {
const result = this.deleteWorkspaces.filter((workspace) => {
return workspaceId === workspace.id;
});
// 목록에 있다면 true
return result.length !== 0;
}
/**
* 워크스페이스 조회
* @param {string} type
*/
private getWorkspaces(type: string) {
// 로딩 show
this.loadingShow();
const params = {
publicType: type,
linkedType: this.linkedType
};
params['size'] = type === 'PRIVATE' ? this.personalWorkspaces.page.size : this.publicWorkspaces.page.size;
params['page'] = type === 'PRIVATE' ? this.personalWorkspaces.page.number : this.publicWorkspaces.page.number;
params['sort'] = type === 'PRIVATE' ? this.personalWorkspaces.sort : this.publicWorkspaces.sort;
// 검색어 있다면
if (type === 'PRIVATE' && this.searchPersonal.trim() !== '') {
params['nameContains'] = this.searchPersonal;
} else if (type === 'SHARED' && this.searchPublic.trim() !== '') {
params['nameContains'] = this.searchPublic;
}
// 연결된 아이디가 있다면
if (this.linkedId) {
params['linkedId'] = this.linkedId;
}
// create 가 아닌경우
if (this.mode !== 'create' && type === 'PRIVATE' && this.filterPersonalFl) params['onlyLinked'] = true;
if (this.mode !== 'create' && type === 'SHARED' && this.filterPublicFl) params['onlyLinked'] = true;
this.workspaceService.getWorkSpaceAll(params, 'forListView')
.then((result) => {
if (type === 'PRIVATE') {
// 페이지가 처음일경우
if (this.personalWorkspaces.page.number === 0) {
this.personalWorkspaces.workspace = [];
}
this.personalWorkspaces.workspace = result._embedded ? this.personalWorkspaces.workspace.concat(result._embedded.workspaces) : [];
this.personalWorkspaces.page = result.page;
// workspace count
this.personalWorkspaces.count = result.workspace;
} else {
// 페이지가 처음일경우
if (this.publicWorkspaces.page.number === 0) {
this.publicWorkspaces.workspace = [];
}
this.publicWorkspaces.workspace = result._embedded ? this.publicWorkspaces.workspace.concat(result._embedded.workspaces) : [];
this.publicWorkspaces.page = result.page;
// workspace count
this.publicWorkspaces.count = result.workspace;
}
// 로딩 hide
this.loadingHide();
})
.catch(() => {
// 로딩 hide
this.loadingHide();
});
}
// ui init
private initView() {
// show true
this.showFl = true;
// tabChange
this.tabChange = 'PRIVATE';
// 초기화
this.publicWorkspaces = new Workspace();
this.personalWorkspaces = new Workspace();
// 검색어 초기화
this.searchPersonal = '';
this.searchPersonal = '';
}
}
class Workspace {
workspace: any[] = [];
page: PageResult;
sort: string;
count: any;
constructor() {
this.page = new PageResult();
this.page.size = 20;
this.page.number = 0;
this.sort = 'name,desc';
}
} | the_stack |
import { CloudErrorMapper, BaseResourceMapper } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export const CloudError = CloudErrorMapper;
export const BaseResource = BaseResourceMapper;
export const OperationDisplay: msRest.CompositeMapper = {
serializedName: "Operation_display",
type: {
name: "Composite",
className: "OperationDisplay",
modelProperties: {
description: {
readOnly: true,
serializedName: "description",
type: {
name: "String"
}
},
operation: {
readOnly: true,
serializedName: "operation",
type: {
name: "String"
}
},
provider: {
readOnly: true,
serializedName: "provider",
type: {
name: "String"
}
},
resource: {
readOnly: true,
serializedName: "resource",
type: {
name: "String"
}
}
}
}
};
export const Operation: msRest.CompositeMapper = {
serializedName: "Operation",
type: {
name: "Composite",
className: "Operation",
modelProperties: {
name: {
readOnly: true,
serializedName: "name",
type: {
name: "String"
}
},
display: {
serializedName: "display",
type: {
name: "Composite",
className: "OperationDisplay"
}
}
}
}
};
export const Service: msRest.CompositeMapper = {
serializedName: "Service",
type: {
name: "Composite",
className: "Service",
modelProperties: {
id: {
readOnly: true,
serializedName: "id",
type: {
name: "String"
}
},
name: {
readOnly: true,
serializedName: "name",
type: {
name: "String"
}
},
type: {
readOnly: true,
serializedName: "type",
type: {
name: "String"
}
},
displayName: {
serializedName: "properties.displayName",
type: {
name: "String"
}
},
resourceTypes: {
serializedName: "properties.resourceTypes",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
}
}
}
};
export const ProblemClassification: msRest.CompositeMapper = {
serializedName: "ProblemClassification",
type: {
name: "Composite",
className: "ProblemClassification",
modelProperties: {
id: {
readOnly: true,
serializedName: "id",
type: {
name: "String"
}
},
name: {
readOnly: true,
serializedName: "name",
type: {
name: "String"
}
},
type: {
readOnly: true,
serializedName: "type",
type: {
name: "String"
}
},
displayName: {
serializedName: "properties.displayName",
type: {
name: "String"
}
}
}
}
};
export const CheckNameAvailabilityInput: msRest.CompositeMapper = {
serializedName: "CheckNameAvailabilityInput",
type: {
name: "Composite",
className: "CheckNameAvailabilityInput",
modelProperties: {
name: {
required: true,
serializedName: "name",
type: {
name: "String"
}
},
type: {
required: true,
serializedName: "type",
type: {
name: "Enum",
allowedValues: [
"Microsoft.Support/supportTickets",
"Microsoft.Support/communications"
]
}
}
}
}
};
export const CheckNameAvailabilityOutput: msRest.CompositeMapper = {
serializedName: "CheckNameAvailabilityOutput",
type: {
name: "Composite",
className: "CheckNameAvailabilityOutput",
modelProperties: {
nameAvailable: {
readOnly: true,
serializedName: "nameAvailable",
type: {
name: "Boolean"
}
},
reason: {
readOnly: true,
serializedName: "reason",
type: {
name: "String"
}
},
message: {
readOnly: true,
serializedName: "message",
type: {
name: "String"
}
}
}
}
};
export const ContactProfile: msRest.CompositeMapper = {
serializedName: "ContactProfile",
type: {
name: "Composite",
className: "ContactProfile",
modelProperties: {
firstName: {
required: true,
serializedName: "firstName",
type: {
name: "String"
}
},
lastName: {
required: true,
serializedName: "lastName",
type: {
name: "String"
}
},
preferredContactMethod: {
required: true,
serializedName: "preferredContactMethod",
type: {
name: "String"
}
},
primaryEmailAddress: {
required: true,
serializedName: "primaryEmailAddress",
type: {
name: "String"
}
},
additionalEmailAddresses: {
serializedName: "additionalEmailAddresses",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
},
phoneNumber: {
serializedName: "phoneNumber",
type: {
name: "String"
}
},
preferredTimeZone: {
required: true,
serializedName: "preferredTimeZone",
type: {
name: "String"
}
},
country: {
required: true,
serializedName: "country",
type: {
name: "String"
}
},
preferredSupportLanguage: {
required: true,
serializedName: "preferredSupportLanguage",
type: {
name: "String"
}
}
}
}
};
export const ServiceLevelAgreement: msRest.CompositeMapper = {
serializedName: "ServiceLevelAgreement",
type: {
name: "Composite",
className: "ServiceLevelAgreement",
modelProperties: {
startTime: {
readOnly: true,
serializedName: "startTime",
type: {
name: "DateTime"
}
},
expirationTime: {
readOnly: true,
serializedName: "expirationTime",
type: {
name: "DateTime"
}
},
slaMinutes: {
readOnly: true,
serializedName: "slaMinutes",
type: {
name: "Number"
}
}
}
}
};
export const SupportEngineer: msRest.CompositeMapper = {
serializedName: "SupportEngineer",
type: {
name: "Composite",
className: "SupportEngineer",
modelProperties: {
emailAddress: {
readOnly: true,
serializedName: "emailAddress",
type: {
name: "String"
}
}
}
}
};
export const TechnicalTicketDetails: msRest.CompositeMapper = {
serializedName: "TechnicalTicketDetails",
type: {
name: "Composite",
className: "TechnicalTicketDetails",
modelProperties: {
resourceId: {
serializedName: "resourceId",
type: {
name: "String"
}
}
}
}
};
export const QuotaChangeRequest: msRest.CompositeMapper = {
serializedName: "QuotaChangeRequest",
type: {
name: "Composite",
className: "QuotaChangeRequest",
modelProperties: {
region: {
serializedName: "region",
type: {
name: "String"
}
},
payload: {
serializedName: "payload",
type: {
name: "String"
}
}
}
}
};
export const QuotaTicketDetails: msRest.CompositeMapper = {
serializedName: "QuotaTicketDetails",
type: {
name: "Composite",
className: "QuotaTicketDetails",
modelProperties: {
quotaChangeRequestSubType: {
serializedName: "quotaChangeRequestSubType",
type: {
name: "String"
}
},
quotaChangeRequestVersion: {
serializedName: "quotaChangeRequestVersion",
type: {
name: "String"
}
},
quotaChangeRequests: {
serializedName: "quotaChangeRequests",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "QuotaChangeRequest"
}
}
}
}
}
}
};
export const SupportTicketDetails: msRest.CompositeMapper = {
serializedName: "SupportTicketDetails",
type: {
name: "Composite",
className: "SupportTicketDetails",
modelProperties: {
id: {
readOnly: true,
serializedName: "id",
type: {
name: "String"
}
},
name: {
readOnly: true,
serializedName: "name",
type: {
name: "String"
}
},
type: {
readOnly: true,
serializedName: "type",
type: {
name: "String"
}
},
supportTicketId: {
serializedName: "properties.supportTicketId",
type: {
name: "String"
}
},
description: {
required: true,
serializedName: "properties.description",
type: {
name: "String"
}
},
problemClassificationId: {
required: true,
serializedName: "properties.problemClassificationId",
type: {
name: "String"
}
},
problemClassificationDisplayName: {
readOnly: true,
serializedName: "properties.problemClassificationDisplayName",
type: {
name: "String"
}
},
severity: {
required: true,
serializedName: "properties.severity",
type: {
name: "String"
}
},
enrollmentId: {
readOnly: true,
serializedName: "properties.enrollmentId",
type: {
name: "String"
}
},
require24X7Response: {
serializedName: "properties.require24X7Response",
type: {
name: "Boolean"
}
},
contactDetails: {
required: true,
serializedName: "properties.contactDetails",
type: {
name: "Composite",
className: "ContactProfile"
}
},
serviceLevelAgreement: {
serializedName: "properties.serviceLevelAgreement",
type: {
name: "Composite",
className: "ServiceLevelAgreement"
}
},
supportEngineer: {
serializedName: "properties.supportEngineer",
type: {
name: "Composite",
className: "SupportEngineer"
}
},
supportPlanType: {
readOnly: true,
serializedName: "properties.supportPlanType",
type: {
name: "String"
}
},
title: {
required: true,
serializedName: "properties.title",
type: {
name: "String"
}
},
problemStartTime: {
serializedName: "properties.problemStartTime",
type: {
name: "DateTime"
}
},
serviceId: {
required: true,
serializedName: "properties.serviceId",
type: {
name: "String"
}
},
serviceDisplayName: {
readOnly: true,
serializedName: "properties.serviceDisplayName",
type: {
name: "String"
}
},
status: {
readOnly: true,
serializedName: "properties.status",
type: {
name: "String"
}
},
createdDate: {
readOnly: true,
serializedName: "properties.createdDate",
type: {
name: "DateTime"
}
},
modifiedDate: {
readOnly: true,
serializedName: "properties.modifiedDate",
type: {
name: "DateTime"
}
},
technicalTicketDetails: {
serializedName: "properties.technicalTicketDetails",
type: {
name: "Composite",
className: "TechnicalTicketDetails"
}
},
quotaTicketDetails: {
serializedName: "properties.quotaTicketDetails",
type: {
name: "Composite",
className: "QuotaTicketDetails"
}
}
}
}
};
export const CommunicationDetails: msRest.CompositeMapper = {
serializedName: "CommunicationDetails",
type: {
name: "Composite",
className: "CommunicationDetails",
modelProperties: {
id: {
readOnly: true,
serializedName: "id",
type: {
name: "String"
}
},
name: {
readOnly: true,
serializedName: "name",
type: {
name: "String"
}
},
type: {
readOnly: true,
serializedName: "type",
type: {
name: "String"
}
},
communicationType: {
readOnly: true,
serializedName: "properties.communicationType",
type: {
name: "String"
}
},
communicationDirection: {
readOnly: true,
serializedName: "properties.communicationDirection",
type: {
name: "String"
}
},
sender: {
serializedName: "properties.sender",
type: {
name: "String"
}
},
subject: {
required: true,
serializedName: "properties.subject",
type: {
name: "String"
}
},
body: {
required: true,
serializedName: "properties.body",
type: {
name: "String"
}
},
createdDate: {
readOnly: true,
serializedName: "properties.createdDate",
type: {
name: "DateTime"
}
}
}
}
};
export const ServiceErrorDetail: msRest.CompositeMapper = {
serializedName: "ServiceErrorDetail",
type: {
name: "Composite",
className: "ServiceErrorDetail",
modelProperties: {
code: {
readOnly: true,
serializedName: "code",
type: {
name: "String"
}
},
message: {
readOnly: true,
serializedName: "message",
type: {
name: "String"
}
},
target: {
serializedName: "target",
type: {
name: "String"
}
}
}
}
};
export const ServiceError: msRest.CompositeMapper = {
serializedName: "ServiceError",
type: {
name: "Composite",
className: "ServiceError",
modelProperties: {
code: {
serializedName: "code",
type: {
name: "String"
}
},
message: {
serializedName: "message",
type: {
name: "String"
}
},
target: {
serializedName: "target",
type: {
name: "String"
}
},
details: {
readOnly: true,
serializedName: "details",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ServiceErrorDetail"
}
}
}
}
}
}
};
export const ExceptionResponse: msRest.CompositeMapper = {
serializedName: "ExceptionResponse",
type: {
name: "Composite",
className: "ExceptionResponse",
modelProperties: {
error: {
serializedName: "error",
type: {
name: "Composite",
className: "ServiceError"
}
}
}
}
};
export const UpdateContactProfile: msRest.CompositeMapper = {
serializedName: "UpdateContactProfile",
type: {
name: "Composite",
className: "UpdateContactProfile",
modelProperties: {
firstName: {
serializedName: "firstName",
type: {
name: "String"
}
},
lastName: {
serializedName: "lastName",
type: {
name: "String"
}
},
preferredContactMethod: {
serializedName: "preferredContactMethod",
type: {
name: "String"
}
},
primaryEmailAddress: {
serializedName: "primaryEmailAddress",
type: {
name: "String"
}
},
additionalEmailAddresses: {
serializedName: "additionalEmailAddresses",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
},
phoneNumber: {
serializedName: "phoneNumber",
type: {
name: "String"
}
},
preferredTimeZone: {
serializedName: "preferredTimeZone",
type: {
name: "String"
}
},
country: {
serializedName: "country",
type: {
name: "String"
}
},
preferredSupportLanguage: {
serializedName: "preferredSupportLanguage",
type: {
name: "String"
}
}
}
}
};
export const UpdateSupportTicket: msRest.CompositeMapper = {
serializedName: "UpdateSupportTicket",
type: {
name: "Composite",
className: "UpdateSupportTicket",
modelProperties: {
severity: {
serializedName: "severity",
type: {
name: "String"
}
},
status: {
serializedName: "status",
type: {
name: "String"
}
},
contactDetails: {
serializedName: "contactDetails",
type: {
name: "Composite",
className: "UpdateContactProfile"
}
}
}
}
};
export const OperationsListResult: msRest.CompositeMapper = {
serializedName: "OperationsListResult",
type: {
name: "Composite",
className: "OperationsListResult",
modelProperties: {
value: {
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Operation"
}
}
}
}
}
}
};
export const ServicesListResult: msRest.CompositeMapper = {
serializedName: "ServicesListResult",
type: {
name: "Composite",
className: "ServicesListResult",
modelProperties: {
value: {
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Service"
}
}
}
}
}
}
};
export const ProblemClassificationsListResult: msRest.CompositeMapper = {
serializedName: "ProblemClassificationsListResult",
type: {
name: "Composite",
className: "ProblemClassificationsListResult",
modelProperties: {
value: {
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ProblemClassification"
}
}
}
}
}
}
};
export const SupportTicketsListResult: msRest.CompositeMapper = {
serializedName: "SupportTicketsListResult",
type: {
name: "Composite",
className: "SupportTicketsListResult",
modelProperties: {
value: {
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "SupportTicketDetails"
}
}
}
},
nextLink: {
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
};
export const CommunicationsListResult: msRest.CompositeMapper = {
serializedName: "CommunicationsListResult",
type: {
name: "Composite",
className: "CommunicationsListResult",
modelProperties: {
value: {
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "CommunicationDetails"
}
}
}
},
nextLink: {
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
}; | the_stack |
import { createContext } from "react";
import { ApolloClient } from "@bluelibs/ui-apollo-bundle";
import { EventManager, Inject } from "@bluelibs/core";
import { gql } from "graphql-tag";
import {
AuthenticationTokenUpdateEvent,
UserLoggedInEvent,
UserLoggedOutEvent,
} from "../../events";
import { LOCAL_STORAGE_TOKEN_KEY } from "../../constants";
import { Smart } from "@bluelibs/smart";
import { ObjectId } from "@bluelibs/ejson";
import { GuardianUserRetrievedEvent } from "../events/GuardianUserRetrievedEvent";
export type State<UserType = GuardianUserType> = {
/**
* This represents the fact that we're currently fetching for the user data
*/
fetchingUserData: boolean;
/**
* This marks if the user is successfully marked as logged in
*/
isLoggedIn: boolean;
/**
* When the user has an expired token or one that couldn't retrieve the user
*/
hasInvalidToken: boolean;
user: UserType;
/**
* This is done the first time when the token is read and user is fetched. After that it will stay initialised.
*/
initialised: boolean;
};
const GuardianContext = createContext(null);
export interface IUserMandatory {
_id: string | object | number;
roles: string[];
}
export type GuardianUserType = {
_id: string | object | number;
profile: {
firstName: string;
lastName: string;
};
fullName: string;
roles: string[];
email: string;
};
export type GuardianUserRegistrationType = {
firstName: string;
lastName: string;
email: string;
password: string;
};
export class GuardianSmart<
TUserType extends IUserMandatory = GuardianUserType,
TUserRegistrationType = GuardianUserRegistrationType
> extends Smart<State<TUserType>, any> {
protected authenticationToken: string;
state: State<TUserType> = {
fetchingUserData: false,
isLoggedIn: false,
hasInvalidToken: false,
user: null,
initialised: false,
};
@Inject()
apolloClient: ApolloClient;
@Inject()
eventManager: EventManager;
async init() {
return this.load()
.then(() => {
this.updateState({
initialised: true,
});
})
.catch(() => {
this.updateState({
initialised: true,
});
});
}
protected async load() {
await this.retrieveToken();
if (!this.authenticationToken) {
// Nothing to do without a token
return;
}
this.updateState({
fetchingUserData: true,
});
if (this.authenticationToken) {
return this.retrieveUser()
.then((user) => {
this.updateState({
user,
isLoggedIn: true,
hasInvalidToken: false,
fetchingUserData: false,
});
})
.catch((err) => {
return this.handleUserRetrievalError(err);
});
}
}
protected handleUserRetrievalError(err: any) {
console.error(
`[Authentication] There was an error fetching the user: ${err.toString()}`
);
// I am very sorry it is like this, we should improve the erroring mechanism somehow
const errors = err.networkError?.result?.errors;
if (errors && errors[0] && errors[0].code) {
if (["SESSION_TOKEN_EXPIRED", "INVALID_TOKEN"].includes(errors[0].code)) {
console.warn("[Authentication] Token was invalid or expired");
// We need to log him out
this.storeToken(null);
this.updateState({
hasInvalidToken: true,
fetchingUserData: false,
isLoggedIn: false,
});
}
}
// There might be some other error, like the API is down, no reason to log him out
this.updateState({ fetchingUserData: false });
}
public async reissueToken(token: string) {
const newToken = await this.apolloClient
.mutate({
mutation: gql`
mutation ($token: String!) {
reissueToken(token: $token)
}
`,
variables: {
token,
},
})
.then((response) => response.data.reissueToken as string);
await this.storeToken(newToken);
await this.load();
}
protected async retrieveUser(): Promise<TUserType> {
return this.apolloClient
.query({
query: gql`
query me {
me {
_id
email
profile {
firstName
lastName
}
roles
}
}
`,
fetchPolicy: "network-only",
})
.then(async (response) => {
let user = Object.assign({}, response.data.me);
try {
user._id = new ObjectId(user._id as any);
} catch (e) {
console.error(
`We could not transform user._id in an ObjectId for value: ${user._id}`,
e
);
}
await this.eventManager.emit(new GuardianUserRetrievedEvent({ user }));
return user;
});
}
protected async retrieveToken() {
this.authenticationToken =
localStorage.getItem(LOCAL_STORAGE_TOKEN_KEY) || null;
await this.eventManager.emit(
new AuthenticationTokenUpdateEvent({ token: this.authenticationToken })
);
}
async storeToken(token: string | null) {
await this.eventManager.emit(new AuthenticationTokenUpdateEvent({ token }));
if (token === null) {
localStorage.removeItem(LOCAL_STORAGE_TOKEN_KEY);
} else {
localStorage.setItem(LOCAL_STORAGE_TOKEN_KEY, token);
}
}
public getToken() {
return this.authenticationToken;
}
async login(username: string, password: string) {
this.updateState({
hasInvalidToken: false,
});
await this.storeToken(null);
return this.apolloClient
.mutate({
mutation: gql`
mutation login($input: LoginInput!) {
login(input: $input) {
token
}
}
`,
variables: {
input: {
username,
password,
},
},
})
.then(async (response) => {
const { token } = response.data.login;
await this.eventManager.emit(new UserLoggedInEvent({ token }));
// We await this as storing the token might be blocking
await this.storeToken(token);
await this.load();
return token;
});
}
/**
* Registers and returns the token if the user isn't required to verify the email first
* @param user
*/
async register(user: TUserRegistrationType): Promise<string | null> {
return this.apolloClient
.mutate({
mutation: gql`
mutation register($input: RegistrationInput!) {
register(input: $input) {
token
}
}
`,
variables: {
input: user,
},
})
.then((response) => {
const { token } = response.data.register;
if (token) {
this.storeToken(token);
}
return token;
});
}
async verifyEmail(emailToken: string): Promise<string> {
return this.apolloClient
.mutate({
mutation: gql`
mutation verifyEmail($input: VerifyEmailInput!) {
verifyEmail(input: $input) {
token
}
}
`,
variables: {
input: {
token: emailToken,
},
},
})
.then(async (response) => {
const { token } = response.data.verifyEmail;
await this.storeToken(token);
return token;
});
}
async forgotPassword(email: string): Promise<void> {
return this.apolloClient
.mutate({
mutation: gql`
mutation forgotPassword($input: ForgotPasswordInput!) {
forgotPassword(input: $input)
}
`,
variables: {
input: {
email,
},
},
})
.then(() => {
return;
});
}
async resetPassword(
username: string,
token: string,
newPassword: string
): Promise<string> {
return this.apolloClient
.mutate({
mutation: gql`
mutation resetPassword($input: ResetPasswordInput!) {
resetPassword(input: $input) {
token
}
}
`,
variables: {
input: {
username,
token,
newPassword,
},
},
})
.then((response) => {
const { token } = response.data.resetPassword;
this.storeToken(token);
return token;
});
}
/**
* Changes the password of the current user
* @param oldPassword
* @param newPassword
*/
async changePassword(
oldPassword: string,
newPassword: string
): Promise<void> {
return this.apolloClient
.mutate({
mutation: gql`
mutation changePassword($input: ChangePasswordInput!) {
changePassword(input: $input)
}
`,
variables: {
input: {
oldPassword,
newPassword,
},
},
})
.then(() => {
return;
});
}
/**
* Logs the user out and cleans up the tokens
*/
async logout(): Promise<void> {
return this.apolloClient
.mutate({
mutation: gql`
mutation logout {
logout
}
`,
})
.then(async () => {
const { _id } = this.state.user;
await this.eventManager.emit(
new UserLoggedOutEvent({
userId: _id,
})
);
await this.storeToken(null);
this.updateState({
isLoggedIn: false,
user: null,
fetchingUserData: false,
});
return;
});
}
hasRole(role: string | string[]): boolean {
const currentRoles = this.state.user?.roles;
if (!currentRoles) {
return false;
}
if (Array.isArray(role)) {
return role.some((_role) => currentRoles.includes(_role));
}
return currentRoles.includes(role);
}
static getContext() {
return GuardianContext;
}
} | the_stack |
import Constants from 'expo-constants';
import { Platform, UnavailabilityError } from 'expo-modules-core';
import invariant from 'invariant';
import qs from 'qs';
import { useEffect, useState } from 'react';
import URL from 'url-parse';
import NativeLinking from './ExpoLinking';
import { CreateURLOptions, ParsedURL, QueryParams, URLListener } from './Linking.types';
import { hasCustomScheme, resolveScheme } from './Schemes';
function validateURL(url: string): void {
invariant(typeof url === 'string', 'Invalid URL: should be a string. Was: ' + url);
invariant(url, 'Invalid URL: cannot be empty');
}
function getHostUri(): string | null {
if (Constants.manifest?.hostUri) {
return Constants.manifest.hostUri;
} else if (Constants.manifest2?.extra?.expoClient?.hostUri) {
return Constants.manifest2.extra.expoClient.hostUri;
} else if (!hasCustomScheme()) {
// we're probably not using up-to-date xdl, so just fake it for now
// we have to remove the /--/ on the end since this will be inserted again later
return removeScheme(Constants.linkingUri).replace(/\/--($|\/.*$)/, '');
} else {
return null;
}
}
function isExpoHosted(): boolean {
const hostUri = getHostUri();
return !!(
hostUri &&
(/^(.*\.)?(expo\.io|exp\.host|exp\.direct|expo\.test)(:.*)?(\/.*)?$/.test(hostUri) ||
Constants.manifest?.developer)
);
}
function removeScheme(url: string): string {
return url.replace(/^[a-zA-Z0-9+.-]+:\/\//, '');
}
function removePort(url: string): string {
return url.replace(/(?=([a-zA-Z0-9+.-]+:\/\/)?[^/]):\d+/, '');
}
function removeLeadingSlash(url: string): string {
return url.replace(/^\//, '');
}
function removeTrailingSlashAndQueryString(url: string): string {
return url.replace(/\/?\?.*$/, '');
}
function ensureTrailingSlash(input: string, shouldAppend: boolean): string {
const hasSlash = input.endsWith('/');
if (hasSlash && !shouldAppend) {
return input.substring(0, input.length - 1);
} else if (!hasSlash && shouldAppend) {
return `${input}/`;
}
return input;
}
function ensureLeadingSlash(input: string, shouldAppend: boolean): string {
const hasSlash = input.startsWith('/');
if (hasSlash && !shouldAppend) {
return input.substring(1);
} else if (!hasSlash && shouldAppend) {
return `/${input}`;
}
return input;
}
/**
* Create a URL that works for the environment the app is currently running in.
* The scheme in bare and standalone must be defined in the app.json under `expo.scheme`.
*
* **Examples**
*
* - Bare: empty string
* - Standalone, Custom: `yourscheme:///path`
* - Web (dev): `https://localhost:19006/path`
* - Web (prod): `https://myapp.com/path`
* - Expo Client (dev): `exp://128.0.0.1:19000/--/path`
* - Expo Client (prod): `exp://exp.host/@yourname/your-app/--/path`
*
* @param path addition path components to append to the base URL.
* @param queryParams An object of parameters that will be converted into a query string.
*/
export function makeUrl(path: string = '', queryParams?: QueryParams, scheme?: string): string {
return createURL(path, { queryParams, scheme, isTripleSlashed: true });
}
/**
* Create a URL that works for the environment the app is currently running in.
* The scheme in bare and standalone must be defined in the Expo config (app.config.js or app.json) under `expo.scheme`.
*
* **Examples**
*
* - Bare: `<scheme>://path` -- uses provided scheme or scheme from Expo config `scheme`.
* - Standalone, Custom: `yourscheme://path`
* - Web (dev): `https://localhost:19006/path`
* - Web (prod): `https://myapp.com/path`
* - Expo Client (dev): `exp://128.0.0.1:19000/--/path`
* - Expo Client (prod): `exp://exp.host/@yourname/your-app/--/path`
*
* @param path addition path components to append to the base URL.
* @param scheme URI protocol `<scheme>://` that must be built into your native app.
* @param queryParams An object of parameters that will be converted into a query string.
*/
export function createURL(
path: string,
{ scheme, queryParams = {}, isTripleSlashed = false }: CreateURLOptions = {}
): string {
if (Platform.OS === 'web') {
if (!Platform.isDOMAvailable) return '';
const origin = ensureTrailingSlash(window.location.origin, false);
let queryString = qs.stringify(queryParams);
if (queryString) {
queryString = `?${queryString}`;
}
let outputPath = path;
if (outputPath) outputPath = ensureLeadingSlash(path, true);
return encodeURI(`${origin}${outputPath}${queryString}`);
}
const resolvedScheme = resolveScheme({ scheme });
let hostUri = getHostUri() || '';
if (hasCustomScheme() && isExpoHosted()) {
hostUri = '';
}
if (path) {
if (isExpoHosted() && hostUri) {
path = `/--/${removeLeadingSlash(path)}`;
}
if (isTripleSlashed && !path.startsWith('/')) {
path = `/${path}`;
}
} else {
path = '';
}
// merge user-provided query params with any that were already in the hostUri
// e.g. release-channel
let queryString = '';
const queryStringMatchResult = hostUri.match(/(.*)\?(.+)/);
if (queryStringMatchResult) {
hostUri = queryStringMatchResult[1];
queryString = queryStringMatchResult[2];
let paramsFromHostUri = {};
try {
const parsedParams = qs.parse(queryString);
if (typeof parsedParams === 'object') {
paramsFromHostUri = parsedParams;
}
} catch (e) {}
queryParams = {
...queryParams,
...paramsFromHostUri,
};
}
queryString = qs.stringify(queryParams);
if (queryString) {
queryString = `?${queryString}`;
}
hostUri = ensureLeadingSlash(hostUri, !isTripleSlashed);
return encodeURI(
`${resolvedScheme}:${isTripleSlashed ? '/' : ''}/${hostUri}${path}${queryString}`
);
}
/**
* Returns the components and query parameters for a given URL.
*
* @param url Input URL to parse
*/
export function parse(url: string): ParsedURL {
validateURL(url);
const parsed = URL(url, /* parseQueryString */ true);
for (const param in parsed.query) {
parsed.query[param] = decodeURIComponent(parsed.query[param]!);
}
const queryParams = parsed.query;
const hostUri = getHostUri() || '';
const hostUriStripped = removePort(removeTrailingSlashAndQueryString(hostUri));
let path = parsed.pathname || null;
let hostname = parsed.hostname || null;
let scheme = parsed.protocol || null;
if (scheme) {
// Remove colon at end
scheme = scheme.substring(0, scheme.length - 1);
}
if (path) {
path = removeLeadingSlash(path);
let expoPrefix: string | null = null;
if (hostUriStripped) {
const parts = hostUriStripped.split('/');
expoPrefix = parts.slice(1).concat(['--/']).join('/');
}
if (isExpoHosted() && !hasCustomScheme() && expoPrefix && path.startsWith(expoPrefix)) {
path = path.substring(expoPrefix.length);
hostname = null;
} else if (path.indexOf('+') > -1) {
path = path.substring(path.indexOf('+') + 1);
}
}
return {
hostname,
path,
queryParams,
scheme,
};
}
/**
* Add a handler to Linking changes by listening to the `url` event type
* and providing the handler
*
* See https://reactnative.dev/docs/linking.html#addeventlistener
*/
export function addEventListener(type: string, handler: URLListener) {
NativeLinking.addEventListener(type, handler);
}
/**
* Remove a handler by passing the `url` event type and the handler.
*
* See https://reactnative.dev/docs/linking.html#removeeventlistener
*/
export function removeEventListener(type: string, handler: URLListener) {
NativeLinking.removeEventListener(type, handler);
}
/**
* **Native:** Parses the link that opened the app. If no link opened the app, all the fields will be \`null\`.
* **Web:** Parses the current window URL.
*/
export async function parseInitialURLAsync(): Promise<ParsedURL> {
const initialUrl = await NativeLinking.getInitialURL();
if (!initialUrl) {
return {
scheme: null,
hostname: null,
path: null,
queryParams: null,
};
}
return parse(initialUrl);
}
/**
* Launch an Android intent with optional extras
*
* @platform android
*/
export async function sendIntent(
action: string,
extras?: { key: string; value: string | number | boolean }[]
): Promise<void> {
if (Platform.OS === 'android') {
return await NativeLinking.sendIntent(action, extras);
}
throw new UnavailabilityError('Linking', 'sendIntent');
}
/**
* Attempt to open the system settings for an the app.
*
* @platform ios
*/
export async function openSettings(): Promise<void> {
if (Platform.OS === 'web') {
throw new UnavailabilityError('Linking', 'openSettings');
}
if (NativeLinking.openSettings) {
return await NativeLinking.openSettings();
}
await openURL('app-settings:');
}
/**
* If the app launch was triggered by an app link,
* it will give the link url, otherwise it will give `null`
*/
export async function getInitialURL(): Promise<string | null> {
return (await NativeLinking.getInitialURL()) ?? null;
}
/**
* Try to open the given `url` with any of the installed apps.
*/
export async function openURL(url: string): Promise<true> {
validateURL(url);
return await NativeLinking.openURL(url);
}
/**
* Determine whether or not an installed app can handle a given URL.
* On web this always returns true because there is no API for detecting what URLs can be opened.
*/
export async function canOpenURL(url: string): Promise<boolean> {
validateURL(url);
return await NativeLinking.canOpenURL(url);
}
/**
* Returns the initial URL followed by any subsequent changes to the URL.
*/
export function useURL(): string | null {
const [url, setLink] = useState<string | null>(null);
function onChange(event: { url: string }) {
setLink(event.url);
}
useEffect(() => {
getInitialURL().then((url) => setLink(url));
addEventListener('url', onChange);
return () => removeEventListener('url', onChange);
}, []);
return url;
}
/**
* Returns the initial URL followed by any subsequent changes to the URL.
* @deprecated Use `useURL` instead.
*/
export function useUrl(): string | null {
console.warn(
`Linking.useUrl has been deprecated in favor of Linking.useURL. This API will be removed in SDK 44.`
);
return useURL();
}
export * from './Linking.types'; | the_stack |
import {
select as d3Select,
namespaces as d3Namespaces
} from "d3-selection";
import {document} from "../../module/browser";
import CLASS from "../../config/classes";
import {KEY} from "../../module/Cache";
import {callFn, isDefined, getOption, isEmpty, isFunction, notEmpty, tplProcess} from "../../module/util";
export default {
/**
* Initialize the legend.
* @private
*/
initLegend(): void {
const $$ = this;
const {config, $el} = $$;
$$.legendItemTextBox = {};
$$.state.legendHasRendered = false;
if (config.legend_show) {
if (!config.legend_contents_bindto) {
$el.legend = $$.$el.svg.append("g")
.classed(CLASS.legend, true)
.attr("transform", $$.getTranslate("legend"));
}
// MEMO: call here to update legend box and translate for all
// MEMO: translate will be updated by this, so transform not needed in updateLegend()
$$.updateLegend();
} else {
$$.state.hiddenLegendIds = $$.mapToIds($$.data.targets);
}
},
/**
* Update legend element
* @param {Array} targetIds ID's of target
* @param {object} options withTransform : Whether to use the transform property / withTransitionForTransform: Whether transition is used when using the transform property / withTransition : whether or not to transition.
* @param {object} transitions Return value of the generateTransitions
* @private
*/
updateLegend(targetIds, options, transitions): void {
const $$ = this;
const {config, state, scale, $el} = $$;
const optionz = options || {
withTransform: false,
withTransitionForTransform: false,
withTransition: false
};
optionz.withTransition = getOption(optionz, "withTransition", true);
optionz.withTransitionForTransform = getOption(optionz, "withTransitionForTransform", true);
if (config.legend_contents_bindto && config.legend_contents_template) {
$$.updateLegendTemplate();
} else {
$$.updateLegendElement(
targetIds || $$.mapToIds($$.data.targets),
optionz,
transitions
);
}
// toggle legend state
$el.legend.selectAll(`.${CLASS.legendItem}`)
.classed(CLASS.legendItemHidden, function(id) {
const hide = !$$.isTargetToShow(id);
if (hide) {
this.style.opacity = null;
}
return hide;
});
// Update size and scale
$$.updateScales(false, !scale.zoom);
$$.updateSvgSize();
// Update g positions
$$.transformAll(optionz.withTransitionForTransform, transitions);
state.legendHasRendered = true;
},
/**
* Update legend using template option
* @private
*/
updateLegendTemplate(): void {
const $$ = this;
const {config, $el} = $$;
const wrapper = d3Select(config.legend_contents_bindto);
const template = config.legend_contents_template;
if (!wrapper.empty()) {
const targets = $$.mapToIds($$.data.targets);
const ids: any[] = [];
let html = "";
targets.forEach(v => {
const content = isFunction(template) ?
template.bind($$.api)(v, $$.color(v), $$.api.data(v)[0].values) :
tplProcess(template, {
COLOR: $$.color(v),
TITLE: v
});
if (content) {
ids.push(v);
html += content;
}
});
const legendItem = wrapper.html(html)
.selectAll(function() { return this.childNodes; })
.data(ids);
$$.setLegendItem(legendItem);
$el.legend = wrapper;
}
},
/**
* Update the size of the legend.
* @param {Obejct} size Size object
* @private
*/
updateSizeForLegend(size): void {
const $$ = this;
const {config, state: {
isLegendTop, isLegendLeft, isLegendRight, isLegendInset, current
}} = $$;
const {width, height} = size;
const insetLegendPosition = {
top: isLegendTop ?
$$.getCurrentPaddingTop() + config.legend_inset_y + 5.5 :
current.height - height - $$.getCurrentPaddingBottom() - config.legend_inset_y,
left: isLegendLeft ?
$$.getCurrentPaddingLeft() + config.legend_inset_x + 0.5 :
current.width - width - $$.getCurrentPaddingRight() - config.legend_inset_x + 0.5
};
$$.state.margin3 = {
top: isLegendRight ?
0 : isLegendInset ? insetLegendPosition.top : current.height - height,
right: NaN,
bottom: 0,
left: isLegendRight ?
current.width - width : isLegendInset ? insetLegendPosition.left : 0
};
},
/**
* Transform Legend
* @param {boolean} withTransition whether or not to transition.
* @private
*/
transformLegend(withTransition): void {
const $$ = this;
const {$el: {legend}, $T} = $$;
$T(legend, withTransition)
.attr("transform", $$.getTranslate("legend"));
},
/**
* Update the legend step
* @param {number} step Step value
* @private
*/
updateLegendStep(step: number): void {
this.state.legendStep = step;
},
/**
* Update legend item width
* @param {number} width Width value
* @private
*/
updateLegendItemWidth(width: number): void {
this.state.legendItemWidth = width;
},
/**
* Update legend item height
* @param {number} height Height value
* @private
*/
updateLegendItemHeight(height): void {
this.state.legendItemHeight = height;
},
/**
* Update legend item color
* @param {string} id Corresponding data ID value
* @param {string} color Color value
* @private
*/
updateLegendItemColor(id: string, color: string): void {
const {legend} = this.$el;
if (legend) {
legend.select(`.${CLASS.legendItem}-${id} line`)
.style("stroke", color);
}
},
/**
* Get the width of the legend
* @returns {number} width
* @private
*/
getLegendWidth(): number {
const $$ = this;
const {current: {width}, isLegendRight, isLegendInset, legendItemWidth, legendStep} = $$.state;
return $$.config.legend_show ? (
isLegendRight || isLegendInset ?
legendItemWidth * (legendStep + 1) : width
) : 0;
},
/**
* Get the height of the legend
* @returns {number} height
* @private
*/
getLegendHeight(): number {
const $$ = this;
const {current, isLegendRight, legendItemHeight, legendStep} = $$.state;
return $$.config.legend_show ? (
isLegendRight ?
current.height : Math.max(20, legendItemHeight) * (legendStep + 1)
) : 0;
},
/**
* Get the opacity of the legend that is unfocused
* @param {d3.selection} legendItem Legend item node
* @returns {string|null} opacity
* @private
*/
opacityForUnfocusedLegend(legendItem): string | null {
return legendItem.classed(CLASS.legendItemHidden) ? null : "0.3";
},
/**
* Toggles the focus of the legend
* @param {Array} targetIds ID's of target
* @param {boolean} focus whether or not to focus.
* @private
*/
toggleFocusLegend(targetIds: string[], focus: boolean): void {
const $$ = this;
const {$el: {legend}, $T} = $$;
const targetIdz = $$.mapToTargetIds(targetIds);
legend && $T(legend.selectAll(`.${CLASS.legendItem}`)
.filter(id => targetIdz.indexOf(id) >= 0)
.classed(CLASS.legendItemFocused, focus))
.style("opacity", function() {
return focus ? null :
$$.opacityForUnfocusedLegend.call($$, d3Select(this));
});
},
/**
* Revert the legend to its default state
* @private
*/
revertLegend(): void {
const $$ = this;
const {$el: {legend}, $T} = $$;
legend && $T(legend.selectAll(`.${CLASS.legendItem}`)
.classed(CLASS.legendItemFocused, false))
.style("opacity", null);
},
/**
* Shows the legend
* @param {Array} targetIds ID's of target
* @private
*/
showLegend(targetIds: string[]): void {
const $$ = this;
const {config, $el, $T} = $$;
if (!config.legend_show) {
config.legend_show = true;
$el.legend ?
$el.legend.style("visibility", null) :
$$.initLegend();
!$$.state.legendHasRendered && $$.updateLegend();
}
$$.removeHiddenLegendIds(targetIds);
$T(
$el.legend.selectAll($$.selectorLegends(targetIds))
.style("visibility", null)
).style("opacity", null);
},
/**
* Hide the legend
* @param {Array} targetIds ID's of target
* @private
*/
hideLegend(targetIds: string[]): void {
const $$ = this;
const {config, $el: {legend}} = $$;
if (config.legend_show && isEmpty(targetIds)) {
config.legend_show = false;
legend.style("visibility", "hidden");
}
$$.addHiddenLegendIds(targetIds);
legend.selectAll($$.selectorLegends(targetIds))
.style("opacity", "0")
.style("visibility", "hidden");
},
/**
* Get legend item textbox dimension
* @param {string} id Data ID
* @param {HTMLElement|d3.selection} textElement Text node element
* @returns {object} Bounding rect
* @private
*/
getLegendItemTextBox(id?: string, textElement?) {
const $$ = this;
const {cache, state} = $$;
let data;
// do not prefix w/'$', to not be resetted cache in .load() call
const cacheKey = KEY.legendItemTextBox;
if (id) {
data = (!state.redrawing && cache.get(cacheKey)) || {};
if (!data[id]) {
data[id] = $$.getTextRect(textElement, CLASS.legendItem);
cache.add(cacheKey, data);
}
data = data[id];
}
return data;
},
/**
* Set legend item style & bind events
* @param {d3.selection} item Item node
* @private
*/
setLegendItem(item): void {
const $$ = this;
const {api, config, state} = $$;
const isTouch = state.inputType === "touch";
const hasGauge = $$.hasType("gauge");
item
.attr("class", function(id) {
const node = d3Select(this);
const itemClass = (!node.empty() && node.attr("class")) || "";
return itemClass + $$.generateClass(CLASS.legendItem, id);
})
.style("visibility", id => ($$.isLegendToShow(id) ? null : "hidden"));
if (config.interaction_enabled) {
item
.style("cursor", "pointer")
.on("click", function(event, id) {
if (!callFn(config.legend_item_onclick, api, id)) {
if (event.altKey) {
api.hide();
api.show(id);
} else {
api.toggle(id);
d3Select(this)
.classed(CLASS.legendItemFocused, false);
}
}
isTouch && $$.hideTooltip();
});
!isTouch && item
.on("mouseout", function(event, id) {
if (!callFn(config.legend_item_onout, api, id)) {
d3Select(this).classed(CLASS.legendItemFocused, false);
if (hasGauge) {
$$.undoMarkOverlapped($$, `.${CLASS.gaugeValue}`);
}
$$.api.revert();
}
})
.on("mouseover", function(event, id) {
if (!callFn(config.legend_item_onover, api, id)) {
d3Select(this).classed(CLASS.legendItemFocused, true);
if (hasGauge) {
$$.markOverlapped(id, $$, `.${CLASS.gaugeValue}`);
}
if (!state.transiting && $$.isTargetToShow(id)) {
api.focus(id);
}
}
});
}
},
/**
* Update the legend
* @param {Array} targetIds ID's of target
* @param {object} options withTransform : Whether to use the transform property / withTransitionForTransform: Whether transition is used when using the transform property / withTransition : whether or not to transition.
* @private
*/
updateLegendElement(targetIds: string[], options): void {
const $$ = this;
const {config, state, $el: {legend}, $T} = $$;
const paddingTop = 4;
const paddingRight = 10;
const posMin = 10;
const tileWidth = config.legend_item_tile_width + 5;
let maxWidth = 0;
let maxHeight = 0;
let xForLegend;
let yForLegend;
let totalLength = 0;
const offsets = {};
const widths = {};
const heights = {};
const margins = [0];
const steps = {};
let step = 0;
let background;
const isLegendRightOrInset = state.isLegendRight || state.isLegendInset;
// Skip elements when their name is set to null
const targetIdz = targetIds
.filter(id => !isDefined(config.data_names[id]) || config.data_names[id] !== null);
const withTransition = options.withTransition;
const updatePositions = function(textElement, id, index) {
const reset = index === 0;
const isLast = index === targetIdz.length - 1;
const box = $$.getLegendItemTextBox(id, textElement);
const itemWidth = box.width + tileWidth +
(isLast && !isLegendRightOrInset ? 0 : paddingRight) + config.legend_padding;
const itemHeight = box.height + paddingTop;
const itemLength = isLegendRightOrInset ? itemHeight : itemWidth;
const areaLength = isLegendRightOrInset ? $$.getLegendHeight() : $$.getLegendWidth();
let margin;
// MEMO: care about condifion of step, totalLength
const updateValues = function(id2, withoutStep?: boolean) {
if (!withoutStep) {
margin = (areaLength - totalLength - itemLength) / 2;
if (margin < posMin) {
margin = (areaLength - itemLength) / 2;
totalLength = 0;
step++;
}
}
steps[id2] = step;
margins[step] = state.isLegendInset ? 10 : margin;
offsets[id2] = totalLength;
totalLength += itemLength;
};
if (reset) {
totalLength = 0;
step = 0;
maxWidth = 0;
maxHeight = 0;
}
if (config.legend_show && !$$.isLegendToShow(id)) {
widths[id] = 0;
heights[id] = 0;
steps[id] = 0;
offsets[id] = 0;
return;
}
widths[id] = itemWidth;
heights[id] = itemHeight;
if (!maxWidth || itemWidth >= maxWidth) {
maxWidth = itemWidth;
}
if (!maxHeight || itemHeight >= maxHeight) {
maxHeight = itemHeight;
}
const maxLength = isLegendRightOrInset ? maxHeight : maxWidth;
if (config.legend_equally) {
Object.keys(widths).forEach(id2 => (widths[id2] = maxWidth));
Object.keys(heights).forEach(id2 => (heights[id2] = maxHeight));
margin = (areaLength - maxLength * targetIdz.length) / 2;
if (margin < posMin) {
totalLength = 0;
step = 0;
targetIdz.forEach(id2 => updateValues(id2));
} else {
updateValues(id, true);
}
} else {
updateValues(id);
}
};
if (state.isLegendInset) {
step = config.legend_inset_step ? config.legend_inset_step : targetIdz.length;
$$.updateLegendStep(step);
}
if (state.isLegendRight) {
xForLegend = id => maxWidth * steps[id];
yForLegend = id => margins[steps[id]] + offsets[id];
} else if (state.isLegendInset) {
xForLegend = id => maxWidth * steps[id] + 10;
yForLegend = id => margins[steps[id]] + offsets[id];
} else {
xForLegend = id => margins[steps[id]] + offsets[id];
yForLegend = id => maxHeight * steps[id];
}
const xForLegendText = (id, i?: number) => xForLegend(id, i) + 4 + config.legend_item_tile_width;
const xForLegendRect = (id, i?: number) => xForLegend(id, i);
const x1ForLegendTile = (id, i?: number) => xForLegend(id, i) - 2;
const x2ForLegendTile = (id, i?: number) => xForLegend(id, i) - 2 + config.legend_item_tile_width;
const yForLegendText = (id, i?: number) => yForLegend(id, i) + 9;
const yForLegendRect = (id, i?: number) => yForLegend(id, i) - 5;
const yForLegendTile = (id, i?: number) => yForLegend(id, i) + 4;
const pos = -200;
// Define g for legend area
const l = legend.selectAll(`.${CLASS.legendItem}`)
.data(targetIdz)
.enter()
.append("g");
$$.setLegendItem(l);
l.append("text")
.text(id => (isDefined(config.data_names[id]) ? config.data_names[id] : id))
.each(function(id, i) {
updatePositions(this, id, i);
})
.style("pointer-events", "none")
.attr("x", isLegendRightOrInset ? xForLegendText : pos)
.attr("y", isLegendRightOrInset ? pos : yForLegendText);
l.append("rect")
.attr("class", CLASS.legendItemEvent)
.style("fill-opacity", "0")
.attr("x", isLegendRightOrInset ? xForLegendRect : pos)
.attr("y", isLegendRightOrInset ? pos : yForLegendRect);
const getColor = id => {
const data = $$.getDataById(id);
return $$.levelColor ?
$$.levelColor(data.values[0].value) :
$$.color(data);
};
const usePoint = config.legend_usePoint;
if (usePoint) {
const ids: any[] = [];
l.append(d => {
const pattern = notEmpty(config.point_pattern) ?
config.point_pattern : [config.point_type];
ids.indexOf(d) === -1 && ids.push(d);
let point = pattern[ids.indexOf(d) % pattern.length];
if (point === "rectangle") {
point = "rect";
}
return document.createElementNS(d3Namespaces.svg, ("hasValidPointType" in $$) && $$.hasValidPointType(point) ? point : "use");
})
.attr("class", CLASS.legendItemPoint)
.style("fill", getColor)
.style("pointer-events", "none")
.attr("href", (data, idx, selection) => {
const node = selection[idx];
const nodeName = node.nodeName.toLowerCase();
return nodeName === "use" ? `#${state.datetimeId}-point-${data}` : undefined;
});
} else {
l.append("line")
.attr("class", CLASS.legendItemTile)
.style("stroke", getColor)
.style("pointer-events", "none")
.attr("x1", isLegendRightOrInset ? x1ForLegendTile : pos)
.attr("y1", isLegendRightOrInset ? pos : yForLegendTile)
.attr("x2", isLegendRightOrInset ? x2ForLegendTile : pos)
.attr("y2", isLegendRightOrInset ? pos : yForLegendTile)
.attr("stroke-width", config.legend_item_tile_height);
}
// Set background for inset legend
background = legend.select(`.${CLASS.legendBackground} rect`);
if (state.isLegendInset && maxWidth > 0 && background.size() === 0) {
background = legend.insert("g", `.${CLASS.legendItem}`)
.attr("class", CLASS.legendBackground)
.append("rect");
}
const texts = legend.selectAll("text")
.data(targetIdz)
.text(id => (isDefined(config.data_names[id]) ? config.data_names[id] : id)) // MEMO: needed for update
.each(function(id, i) {
updatePositions(this, id, i);
});
$T(texts, withTransition)
.attr("x", xForLegendText)
.attr("y", yForLegendText);
const rects = legend.selectAll(`rect.${CLASS.legendItemEvent}`)
.data(targetIdz);
$T(rects, withTransition)
.attr("width", id => widths[id])
.attr("height", id => heights[id])
.attr("x", xForLegendRect)
.attr("y", yForLegendRect);
if (usePoint) {
const tiles = legend.selectAll(`.${CLASS.legendItemPoint}`)
.data(targetIdz);
$T(tiles, withTransition)
.each(function() {
const nodeName = this.nodeName.toLowerCase();
const pointR = config.point_r;
let x = "x";
let y = "y";
let xOffset = 2;
let yOffset = 2.5;
let radius;
let width;
let height;
if (nodeName === "circle") {
const size = pointR * 0.2;
x = "cx";
y = "cy";
radius = pointR + size;
xOffset = pointR * 2;
yOffset = -size;
} else if (nodeName === "rect") {
const size = pointR * 2.5;
width = size;
height = size;
yOffset = 3;
}
d3Select(this)
.attr(x, d => x1ForLegendTile(d) + xOffset)
.attr(y, d => yForLegendTile(d) - yOffset)
.attr("r", radius)
.attr("width", width)
.attr("height", height);
});
} else {
const tiles = legend.selectAll(`line.${CLASS.legendItemTile}`)
.data(targetIdz);
$T(tiles, withTransition)
.style("stroke", getColor)
.attr("x1", x1ForLegendTile)
.attr("y1", yForLegendTile)
.attr("x2", x2ForLegendTile)
.attr("y2", yForLegendTile);
}
if (background) {
$T(background, withTransition)
.attr("height", $$.getLegendHeight() - 12)
.attr("width", maxWidth * (step + 1) + 10);
}
// Update all to reflect change of legend
$$.updateLegendItemWidth(maxWidth);
$$.updateLegendItemHeight(maxHeight);
$$.updateLegendStep(step);
}
}; | the_stack |
import { expect } from 'chai';
import { MongoClient } from 'mongodb';
import { eventually } from '../../../testing/eventually';
import { TestShell } from './test-shell';
import { startTestServer, skipIfServerVersion } from '../../../testing/integration-testing-hooks';
import { promises as fs, createReadStream } from 'fs';
import { promisify } from 'util';
import rimraf from 'rimraf';
import path from 'path';
import os from 'os';
import { readReplLogfile, setTemporaryHomeDirectory } from './repl-helpers';
import { bson } from '@mongosh/service-provider-core';
const { EJSON } = bson;
describe('e2e', function() {
const testServer = startTestServer('shared');
afterEach(TestShell.cleanup);
describe('--version', () => {
it('shows version', async() => {
const shell = TestShell.start({ args: [ '--version' ] });
await shell.waitForExit();
shell.assertNoErrors();
shell.assertContainsOutput(
require('../package.json').version
);
});
});
describe('--build-info', () => {
it('shows build info in JSON format', async() => {
const shell = TestShell.start({ args: [ '--build-info' ] });
await shell.waitForExit();
shell.assertNoErrors();
const data = JSON.parse(shell.output);
expect(Object.keys(data)).to.deep.equal([
'version', 'distributionKind', 'buildArch', 'buildPlatform',
'buildTarget', 'buildTime', 'gitVersion', 'nodeVersion'
]);
expect(data.version).to.be.a('string');
expect(data.nodeVersion).to.be.a('string');
expect(data.distributionKind).to.be.a('string');
expect(['unpackaged', 'packaged', 'compiled'].includes(data.distributionKind)).to.be.true;
expect(data.buildArch).to.be.a('string');
expect(data.buildPlatform).to.be.a('string');
expect(data.buildTarget).to.be.a('string');
if (data.distributionKind !== 'unpackaged') {
expect(data.buildTime).to.be.a('string');
expect(data.gitVersion).to.be.a('string');
} else {
expect(data.buildTime).to.equal(null);
expect(data.gitVersion).to.equal(null);
}
});
});
describe('--nodb', () => {
let shell: TestShell;
beforeEach(async() => {
shell = TestShell.start({
args: [ '--nodb' ]
});
await shell.waitForPrompt();
shell.assertNoErrors();
});
it('db throws', async() => {
await shell.executeLine('db');
shell.assertContainsError('MongoshInvalidInputError: [SHAPI-10004] No connected database');
});
it('show dbs throws InvalidInput', async() => {
await shell.executeLine('show dbs');
shell.assertContainsError('MongoshInvalidInputError: [SHAPI-10004] No connected database');
});
it('db.coll.find() throws InvalidInput', async() => {
await shell.executeLine('db.coll.find()');
shell.assertContainsError('MongoshInvalidInputError: [SHAPI-10004] No connected database');
// We're seeing the prompt and not a stack trace.
expect(shell.output).to.include('No connected database\n> ');
});
it('colorizes syntax errors', async() => {
shell = TestShell.start({
args: [ '--nodb' ],
env: { ...process.env, FORCE_COLOR: 'true', TERM: 'xterm-256color' },
forceTerminal: true
});
await shell.waitForPrompt();
shell.assertNoErrors();
await shell.executeLine(',cat,\n');
await eventually(() => {
expect(shell.rawOutput).to.match(/SyntaxError(\x1b\[.*m)+: Unexpected token/);
expect(shell.rawOutput).to.match(/>(\x1b\[.*m)+ 1 \|(\x1b\[.*m)+ (\x1b\[.*m)+,(\x1b\[.*m)+cat(\x1b\[.*m)+,(\x1b\[.*m)+/);
});
});
it('closes the shell when "exit" is entered', async() => {
const onExit = shell.waitForExit();
shell.writeInputLine('exit');
expect(await onExit).to.equal(0);
});
it('closes the shell when "quit" is entered', async() => {
const onExit = shell.waitForExit();
shell.writeInputLine('quit');
expect(await onExit).to.equal(0);
});
it('closes the shell with the specified exit code when "exit(n)" is entered', async() => {
const onExit = shell.waitForExit();
shell.writeInputLine('exit(42)');
expect(await onExit).to.equal(42);
});
it('closes the shell with the specified exit code when "quit(n)" is entered', async() => {
const onExit = shell.waitForExit();
shell.writeInputLine('quit(42)');
expect(await onExit).to.equal(42);
});
it('closes the shell with the pre-specified exit code when "exit" is entered', async() => {
const onExit = shell.waitForExit();
shell.writeInputLine('process.exitCode = 42; exit()');
expect(await onExit).to.equal(42);
});
it('closes the shell with the pre-specified exit code when "quit" is entered', async() => {
const onExit = shell.waitForExit();
shell.writeInputLine('process.exitCode = 42; quit()');
expect(await onExit).to.equal(42);
});
it('decorates internal errors with bug reporting information', async() => {
const err = await shell.executeLine('throw Object.assign(new Error("foo"), { code: "COMMON-90001" })');
expect(err).to.match(/^Error: foo$/m);
expect(err).to.match(/^This is an error inside mongosh\. Please file a bug report for the MONGOSH project here: https:\/\/jira.mongodb.org\/projects\/MONGOSH\/issues\.$/m);
expect(err).to.match(/^Please include the log file for this session \(.+[/\\][a-f0-9]{24}_log\)\.$/m);
});
it('does not expose parcelRequire', async() => {
const err = await shell.executeLine('parcelRequire');
expect(err).to.match(/ReferenceError: parcelRequire is not defined/);
});
it('parses code in sloppy mode by default (single line)', async() => {
const result = await shell.executeLine('"<\\101>"');
expect(result).to.match(/<A>/);
});
it('parses code in sloppy mode by default (multiline)', async() => {
const result = await shell.executeLine('"a"+\n"<\\101>"');
expect(result).to.match(/a<A>/);
});
it('handles \\r\\n newline input properly', async() => {
shell.writeInput('34+55\r\n');
await promisify(setTimeout)(100);
shell.writeInput('_+55\r\n');
await promisify(setTimeout)(100);
shell.writeInput('_+89\r\n');
await eventually(() => {
shell.assertContainsOutput('233');
});
});
});
describe('set db', () => {
for (const { mode, dbname, dbnameUri } of [
{ mode: 'no special characetrs', dbname: 'testdb1', dbnameUri: 'testdb1' },
{ mode: 'special characters', dbname: 'ä:-,🐈_\'[!?%', dbnameUri: 'ä:-,🐈_\'[!%3F%25' }
]) {
context(mode, () => {
describe('via host:port/test', () => {
let shell;
beforeEach(async() => {
shell = TestShell.start({ args: [`${await testServer.hostport()}/${dbname}`] });
await shell.waitForPrompt();
shell.assertNoErrors();
});
it('db set correctly', async() => {
expect(await shell.executeLine('db')).to.include(dbname);
shell.assertNoErrors();
});
});
describe('via mongodb://uri', () => {
let shell;
beforeEach(async() => {
shell = TestShell.start({ args: [`mongodb://${await testServer.hostport()}/${dbnameUri}`] });
await shell.waitForPrompt();
shell.assertNoErrors();
});
it('db set correctly', async() => {
expect(await shell.executeLine('db')).to.include(dbname);
shell.assertNoErrors();
});
});
describe('legacy db only', () => {
let shell;
beforeEach(async() => {
const port = await testServer.port();
shell = TestShell.start({ args: [dbname, `--port=${port}`] });
await shell.waitForPrompt();
shell.assertNoErrors();
});
it('db set correctly', async() => {
expect(await shell.executeLine('db')).to.include(dbname);
shell.assertNoErrors();
});
});
});
}
});
describe('with connection string', () => {
let db;
let client;
let shell: TestShell;
let dbName;
beforeEach(async() => {
const connectionString = await testServer.connectionString();
dbName = `test-${Date.now()}`;
shell = TestShell.start({ args: [ connectionString ] });
client = await MongoClient.connect(connectionString, {});
db = client.db(dbName);
await shell.waitForPrompt();
shell.assertNoErrors();
});
afterEach(async() => {
await db.dropDatabase();
client.close();
});
it('version', async() => {
const expected = require('../package.json').version;
await shell.executeLine('version()');
shell.assertContainsOutput(expected);
});
it('fle addon is available', async() => {
const result = await shell.executeLine(
'`<${typeof db._mongo._serviceProvider.fle.ClientEncryption}>`');
expect(result).to.include('<function>');
});
describe('error formatting', () => {
it('throws when a syntax error is encountered', async() => {
await shell.executeLine(',x');
shell.assertContainsError('SyntaxError: Unexpected token');
});
it('throws a runtime error', async() => {
await shell.executeLine('throw new Error(\'a errmsg\')');
shell.assertContainsError('Error: a errmsg');
});
it('recognizes a driver error as error', async() => {
await shell.executeLine('db.coll.initializeOrderedBulkOp().find({}).update({}, {}).execute()');
// output varies by server version
expect(shell.output).to.match(
/multi update (only works with \$ operators|is not supported for replacement-style update)/);
});
});
it('throws multiline input with a single line string', async() => {
// this is an unterminated string constant and should throw, since it does
// not pass: https://www.ecma-international.org/ecma-262/#sec-line-terminators
await shell.executeLine('"this is a multi\nline string');
shell.assertContainsError('SyntaxError: Unterminated string constant');
});
describe('literals', () => {
it('number', async() => {
expect(await shell.executeLine('1')).to.include('1');
shell.assertNoErrors();
it('string', async() => {
expect(await shell.executeLine('"string"')).to.include('string');
shell.assertNoErrors();
});
it('undefined', async() => {
await shell.executeLine('undefined');
shell.assertNoErrors();
});
it('null', async() => {
expect(await shell.executeLine('null')).to.include('null');
shell.assertNoErrors();
});
it('bool', async() => {
expect(await shell.executeLine('true')).to.include('true');
shell.assertNoErrors();
});
});
});
it('runs a complete function', async() => {
await shell.executeLine('function x () {\nconsole.log(\'y\')\n }');
shell.assertNoErrors();
});
it('runs an unterminated function', async() => {
shell.writeInputLine('function x () {');
await eventually(() => {
shell.assertContainsOutput('...');
});
shell.assertNoErrors();
});
it('runs help command', async() => {
expect(await shell.executeLine('help')).to.include('Shell Help');
shell.assertNoErrors();
});
it('db set correctly', async() => {
expect(await shell.executeLine('db')).to.include('test');
shell.assertNoErrors();
});
it('allows to find documents', async() => {
await shell.executeLine(`use ${dbName}`);
await db.collection('test').insertMany([
{ doc: 1 },
{ doc: 2 },
{ doc: 3 }
]);
const output = await shell.executeLine('db.test.find()');
expect(output).to.include('doc: 1');
expect(output).to.include('doc: 2');
expect(output).to.include('doc: 3');
shell.assertNotContainsOutput('CursorIterationResult');
shell.assertNoErrors();
});
it('allows to find documents using aggregate', async() => {
await shell.executeLine(`use ${dbName}`);
await db.collection('test').insertMany([
{ doc: 1 },
{ doc: 2 },
{ doc: 3 }
]);
const output = await shell.executeLine('db.test.aggregate({ $match: {} })');
expect(output).to.include('doc: 1');
expect(output).to.include('doc: 2');
expect(output).to.include('doc: 3');
shell.assertNotContainsOutput('CursorIterationResult');
shell.assertNoErrors();
});
it('allows collections with .', async() => {
await shell.executeLine(`use ${dbName}`);
await db.collection('test.dot').insertMany([
{ doc: 1 },
{ doc: 2 },
{ doc: 3 }
]);
const output = await shell.executeLine('db.test.dot.find()');
expect(output).to.include('doc: 1');
expect(output).to.include('doc: 2');
expect(output).to.include('doc: 3');
shell.assertNoErrors();
});
it('rewrites async for collections with .', async() => {
await shell.executeLine(`use ${dbName}`);
await shell.executeLine('const x = db.test.dot.insertOne({ d: 1 })');
expect(await shell.executeLine('x.insertedId')).to.include('ObjectId');
shell.assertNoErrors();
});
it('rewrites async for collections in the same statement', async() => {
await shell.executeLine(`use ${dbName}`);
expect(await shell.executeLine('db.test.insertOne({ d: 1 }).acknowledged')).to.include('true');
shell.assertNoErrors();
});
it('rewrites async properly for mapReduce', async function() {
if (process.env.MONGOSH_TEST_FORCE_API_STRICT) {
return this.skip(); // mapReduce is unversioned
}
await shell.executeLine(`use ${dbName}`);
await shell.executeLine('db.test.insertMany([{i:1},{i:2},{i:3},{i:4}]);');
const result = await shell.executeLine(`db.test.mapReduce(function() {
emit(this.i % 2, this.i);
}, function(key, values) {
return Array.sum(values);
}, { out: { inline: 1 } }).results`);
expect(result).to.include('{ _id: 0, value: 6 }');
expect(result).to.include('{ _id: 1, value: 4 }');
});
it('rewrites async properly for common libraries', async function() {
this.timeout(120_000);
await shell.executeLine(`use ${dbName}`);
await shell.executeLine('db.test.insertOne({ d: new Date("2021-04-07T11:24:54+02:00") })');
shell.writeInputLine(`load(${JSON.stringify(require.resolve('lodash'))})`);
shell.writeInputLine(`load(${JSON.stringify(require.resolve('moment'))})`);
shell.writeInputLine('print("loaded" + "scripts")');
await eventually(() => {
// Use eventually explicitly to get a bigger timeout, lodash is
// quite “big” in terms of async rewriting
shell.assertContainsOutput('loadedscripts');
}, { timeout: 60_000 });
const result = await shell.executeLine(
'moment(_.first(_.map(db.test.find().toArray(), "d"))).format("X")');
expect(result).to.include('1617787494');
shell.assertNotContainsOutput('[BABEL]');
});
it('expands explain output indefinitely', async() => {
await shell.executeLine('explainOutput = db.test.find().explain()');
await shell.executeLine('explainOutput.a = {b:{c:{d:{e:{f:{g:{h:{i:{j:{}}}}}}}}}}');
expect(await shell.executeLine('explainOutput')).to.match(/g:\s*\{\s*h:\s*\{\s*i:\s*\{\s*j:/);
});
it('expands explain output from aggregation indefinitely', async() => {
await shell.executeLine('explainOutput = db.test.aggregate([{ $limit: 1 }], {explain: "queryPlanner"})');
await shell.executeLine('explainOutput.a = {b:{c:{d:{e:{f:{g:{h:{i:{j:{}}}}}}}}}}');
expect(await shell.executeLine('explainOutput')).to.match(/g:\s*\{\s*h:\s*\{\s*i:\s*\{\s*j:/);
});
it('allows toJSON on results of db operations', async function() {
if (process.env.MONGOSH_TEST_FORCE_API_STRICT) {
return this.skip(); // listCommands is unversioned
}
expect(await shell.executeLine('typeof JSON.parse(JSON.stringify(db.listCommands())).ping.help')).to.include('string');
expect(await shell.executeLine('typeof JSON.parse(JSON.stringify(db.test.insertOne({}))).insertedId')).to.include('string');
});
describe('document validation errors', () => {
context('post-4.4', () => {
skipIfServerVersion(testServer, '<= 4.4');
it('displays errInfo to the user', async() => {
await shell.executeLine(`db.createCollection('contacts', {
validator: {
$and: [
{ phone: { $type: "string" } },
{ email: { $regex: /@mongodb\.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
]
}
});`);
const result = await shell.executeLine(`db.contacts.insertOne({
email: "test@mongodb.com", status: "Unknown"
});`);
expect(result).to.include('Additional information:');
expect(result).to.include("reason: 'field was missing'");
});
it('displays bulk result for failures to the user', async() => {
await shell.executeLine(`db.createCollection('contacts', {
validator: {
$and: [
{ phone: { $type: "string" } },
{ email: { $regex: /@mongodb\.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
]
}
});`);
const result = await shell.executeLine(`db.contacts.insertMany([
{ email: "test1@mongodb.com", status: "Unknown", phone: "123" },
{ email: "test2@mongodb.com", status: "Unknown" }
]);`);
expect(result).to.include('Result:');
expect(result).to.include('nInserted: 1');
});
});
});
describe('cursor transform operations', () => {
beforeEach(async() => {
await shell.executeLine(`use ${dbName}`);
await shell.executeLine('for (let i = 0; i < 3; i++) db.coll.insertOne({i})');
});
it('works with .map() with immediate .toArray() iteration', async() => {
const result = await shell.executeLine(`const cs = db.coll.find().map((doc) => {
print('mapped');
return db.coll.find({_id:doc._id}).toArray()
}); print('after'); cs.toArray()`);
expect(result).to.include('after');
expect(result).to.include('mapped');
expect(result).to.include('i: 1');
});
it('works with .map() with later .toArray() iteration', async() => {
const before = await shell.executeLine(`const cs = db.coll.find().map((doc) => {
print('mapped');
return db.coll.find({_id:doc._id}).toArray()
}); print('after');`);
expect(before).to.include('after');
expect(before).not.to.include('mapped');
const result = await shell.executeLine('cs.toArray()');
expect(result).to.include('mapped');
expect(result).to.include('i: 1');
});
it('works with .map() with implicit iteration', async() => {
const before = await shell.executeLine(`const cs = db.coll.find().map((doc) => {
print('mapped');
return db.coll.findOne({_id:doc._id});
}); print('after');`);
expect(before).to.include('after');
expect(before).not.to.include('mapped');
const result = await shell.executeLine('cs');
expect(result).to.include('mapped');
expect(result).to.include('i: 1');
});
it('works with .forEach() iteration', async() => {
await shell.executeLine('out = [];');
const before = await shell.executeLine(`db.coll.find().forEach((doc) => {
print('enter forEach');
out.push(db.coll.findOne({_id:doc._id}));
print('leave forEach');
}); print('after');`);
expect(before).to.match(/(enter forEach\r?\nleave forEach\r?\n){3}after/);
const result = await shell.executeLine('out[1]');
expect(result).to.include('i: 1');
});
});
});
describe('with --host', () => {
let shell: TestShell;
it('allows invalid hostnames with _', async() => {
shell = TestShell.start({
args: [ '--host', 'xx_invalid_domain_xx' ],
env: { ...process.env, FORCE_COLOR: 'true', TERM: 'xterm-256color' },
forceTerminal: true
});
const result = await Promise.race([
shell.waitForPromptOrExit(),
promisify(setTimeout)(5000)
]);
shell.assertNotContainsOutput('host');
if (typeof result === 'object') {
expect(result.state).to.equal('exit');
shell.assertContainsOutput('MongoNetworkError');
} else {
shell.kill(os.constants.signals.SIGKILL);
}
});
});
describe('Ctrl+C aka SIGINT', () => {
before(function() {
if (process.platform === 'win32') {
return this.skip(); // Cannot trigger SIGINT programmatically on Windows
}
});
let shell: TestShell;
beforeEach(async() => {
shell = TestShell.start({ args: [ '--nodb' ], removeSigintListeners: true });
await shell.waitForPrompt();
shell.assertNoErrors();
});
it('interrupts sync execution', async() => {
await shell.executeLine('void process.removeAllListeners("SIGINT")');
const result = shell.executeLine('while(true);');
setTimeout(() => shell.kill('SIGINT'), 1000);
await result;
shell.assertContainsError('interrupted');
});
it('interrupts async awaiting', async() => {
const result = shell.executeLine('new Promise(() => {});');
setTimeout(() => shell.kill('SIGINT'), 3000);
await result;
shell.assertContainsOutput('Stopping execution...');
});
it('interrupts load()', async() => {
const filename = path.resolve(__dirname, 'fixtures', 'load', 'infinite-loop.js');
const result = shell.executeLine(`load(${JSON.stringify(filename)})`);
setTimeout(() => shell.kill('SIGINT'), 3000);
await result;
// The while loop in the script is run as "sync" code
shell.assertContainsError('interrupted');
});
it('behaves normally after an exception', async() => {
await shell.executeLine('throw new Error()');
await new Promise((resolve) => setTimeout(resolve, 100));
shell.kill('SIGINT');
await shell.waitForPrompt();
await new Promise((resolve) => setTimeout(resolve, 100));
shell.assertNotContainsOutput('interrupted');
shell.assertNotContainsOutput('Stopping execution');
});
it('does not trigger MaxListenersExceededWarning', async() => {
await shell.executeLine('for (let i = 0; i < 11; i++) { console.log("hi"); }\n');
await shell.executeLine('for (let i = 0; i < 20; i++) (async() => { await sleep(0) })()');
shell.assertNotContainsOutput('MaxListenersExceededWarning');
});
});
describe('printing', () => {
let shell;
beforeEach(async() => {
shell = TestShell.start({ args: [ '--nodb' ] });
await shell.waitForPrompt();
shell.assertNoErrors();
});
it('console.log() prints output exactly once', async() => {
const result = await shell.executeLine('console.log(42);');
expect(result).to.match(/\b42\b/);
expect(result).not.to.match(/\b42[\s\r\n]*42\b/);
});
it('print() prints output exactly once', async() => {
const result = await shell.executeLine('print(42);');
expect(result).to.match(/\b42\b/);
expect(result).not.to.match(/\b42[\s\r\n]*42\b/);
});
});
describe('pipe from stdin', () => {
let shell: TestShell;
beforeEach(async() => {
shell = TestShell.start({ args: [ await testServer.connectionString() ] });
});
it('reads and runs code from stdin, with .write()', async() => {
const dbName = `test-${Date.now()}`;
shell.process.stdin.write(`
use ${dbName};
db.coll1.insertOne({ foo: 55 });
db.coll1.insertOne({ foo: 89 });
db.coll1.aggregate([{$group: {_id: null, total: {$sum: '$foo'}}}])
`);
await eventually(() => {
shell.assertContainsOutput('total: 144');
});
});
it('reads and runs code from stdin, with .end()', async() => {
const dbName = `test-${Date.now()}`;
shell.process.stdin.end(`
use ${dbName};
db.coll1.insertOne({ foo: 55 });
db.coll1.insertOne({ foo: 89 });
db.coll1.aggregate([{$group: {_id: null, total: {$sum: '$foo'}}}])
`);
await eventually(() => {
shell.assertContainsOutput('total: 144');
});
});
it('reads and runs the vscode extension example playground', async() => {
createReadStream(path.resolve(__dirname, 'fixtures', 'exampleplayground.js'))
.pipe(shell.process.stdin);
await eventually(() => {
shell.assertContainsOutput("{ _id: 'xyz', totalSaleAmount: 150 }");
});
});
it('treats piping a script into stdin line by line', async function() {
if (process.env.MONGOSH_TEST_FORCE_API_STRICT) {
return this.skip(); // collStats is unversioned
}
// This script doesn't work if evaluated as a whole, only when evaluated
// line-by-line, due to Automatic Semicolon Insertion (ASI).
createReadStream(path.resolve(__dirname, 'fixtures', 'asi-script.js'))
.pipe(shell.process.stdin);
await eventually(() => {
shell.assertContainsOutput('admin;system.version;');
});
});
});
describe('Node.js builtin APIs in the shell', () => {
let shell;
beforeEach(async() => {
shell = TestShell.start({
args: [ '--nodb' ],
cwd: path.resolve(__dirname, 'fixtures', 'require-base'),
env: {
...process.env,
NODE_PATH: path.resolve(__dirname, 'fixtures', 'node-path')
}
});
await shell.waitForPrompt();
shell.assertNoErrors();
});
it('require() searches the current working directory according to Node.js rules', async() => {
let result;
result = await shell.executeLine('require("a")');
expect(result).to.match(/Error: Cannot find module 'a'/);
result = await shell.executeLine('require("./a")');
expect(result).to.match(/^A$/m);
result = await shell.executeLine('require("b")');
expect(result).to.match(/^B$/m);
result = await shell.executeLine('require("c")');
expect(result).to.match(/^C$/m);
});
it('Can use Node.js APIs without any extra effort', async() => {
// Too lazy to write a fixture
const result = await shell.executeLine(
`fs.readFileSync(${JSON.stringify(__filename)}, 'utf8')`);
expect(result).to.include('Too lazy to write a fixture');
});
});
describe('files loaded from command line', () => {
context('file from disk', () => {
it('loads a file from the command line as requested', async() => {
const shell = TestShell.start({
args: [ '--nodb', './hello1.js' ],
cwd: path.resolve(__dirname, 'fixtures', 'load')
});
await eventually(() => {
shell.assertContainsOutput('hello one');
});
// We can't assert the exit code here currently because that breaks
// when run under coverage, as we currently specify the location of
// coverage files via a relative path and nyc fails to write to that
// when started from a changed cwd.
await shell.waitForExit();
shell.assertNoErrors();
});
it('drops into shell if --shell is used', async() => {
const shell = TestShell.start({
args: [ '--nodb', '--shell', './hello1.js' ],
cwd: path.resolve(__dirname, 'fixtures', 'load')
});
await shell.waitForPrompt();
shell.assertContainsOutput('hello one');
expect(await shell.executeLine('2 ** 16 + 1')).to.include('65537');
shell.assertNoErrors();
});
it('fails with the error if the loaded script throws', async() => {
const shell = TestShell.start({
args: [ '--nodb', '--shell', './throw.js' ],
cwd: path.resolve(__dirname, 'fixtures', 'load')
});
await eventually(() => {
shell.assertContainsOutput('Error: uh oh');
});
expect(await shell.waitForExit()).to.equal(1);
});
});
context('--eval', () => {
const script = 'const a = "hello", b = " one"; a + b';
it('loads a script from the command line as requested', async() => {
const shell = TestShell.start({
args: [ '--nodb', '--eval', script ]
});
await eventually(() => {
shell.assertContainsOutput('hello one');
});
expect(await shell.waitForExit()).to.equal(0);
shell.assertNoErrors();
});
it('drops into shell if --shell is used', async() => {
const shell = TestShell.start({
args: [ '--nodb', '--eval', script, '--shell' ]
});
await shell.waitForPrompt();
shell.assertContainsOutput('hello one');
expect(await shell.executeLine('2 ** 16 + 1')).to.include('65537');
shell.assertNoErrors();
});
it('fails with the error if the loaded script throws', async() => {
const shell = TestShell.start({
args: [ '--nodb', '--eval', 'throw new Error("uh oh")' ]
});
await eventually(() => {
shell.assertContainsOutput('Error: uh oh');
});
expect(await shell.waitForExit()).to.equal(1);
});
});
});
describe('config, logging and rc file', () => {
let homedir: string;
let env: Record<string, string>;
let shell: TestShell;
let configPath: string;
let logBasePath: string;
let logPath: string;
let historyPath: string;
let readConfig: () => Promise<any>;
let readLogfile: () => Promise<any[]>;
let startTestShell: (...extraArgs: string[]) => Promise<TestShell>;
beforeEach(() => {
const homeInfo = setTemporaryHomeDirectory();
homedir = homeInfo.homedir;
env = homeInfo.env;
if (process.platform === 'win32') {
logBasePath = path.resolve(homedir, 'local', 'mongodb', 'mongosh');
configPath = path.resolve(homedir, 'roaming', 'mongodb', 'mongosh', 'config');
historyPath = path.resolve(homedir, 'roaming', 'mongodb', 'mongosh', 'mongosh_repl_history');
} else {
logBasePath = path.resolve(homedir, '.mongodb', 'mongosh');
configPath = path.resolve(homedir, '.mongodb', 'mongosh', 'config');
historyPath = path.resolve(homedir, '.mongodb', 'mongosh', 'mongosh_repl_history');
}
readConfig = async() => EJSON.parse(await fs.readFile(configPath, 'utf8'));
readLogfile = async() => readReplLogfile(logPath);
startTestShell = async(...extraArgs: string[]) => {
const shell = TestShell.start({
args: [ '--nodb', ...extraArgs ],
env: env,
forceTerminal: true
});
await shell.waitForPrompt();
shell.assertNoErrors();
return shell;
};
});
afterEach(async function() {
await TestShell.killall.call(this);
try {
await promisify(rimraf)(homedir);
} catch (err) {
// On Windows in CI, this can fail with EPERM for some reason.
// If it does, just log the error instead of failing all tests.
console.error('Could not remove fake home directory:', err);
}
});
context('in fully accessible environment', () => {
beforeEach(async() => {
await fs.mkdir(homedir, { recursive: true });
shell = await startTestShell();
logPath = path.join(logBasePath, `${shell.logId}_log`);
});
describe('config file', () => {
it('sets up a config file', async() => {
const config = await readConfig();
expect(config.userId).to.match(/^[a-f0-9]{24}$/);
expect(config.enableTelemetry).to.be.true;
expect(config.disableGreetingMessage).to.be.true;
});
it('persists between sessions', async() => {
const config1 = await readConfig();
await startTestShell();
const config2 = await readConfig();
expect(config1.userId).to.equal(config2.userId);
});
});
describe('telemetry toggling', () => {
it('enableTelemetry() yields a success response', async() => {
expect(await shell.executeLine('enableTelemetry()')).to.include('Telemetry is now enabled');
expect((await readConfig()).enableTelemetry).to.equal(true);
});
it('disableTelemetry() yields a success response', async() => {
expect(await shell.executeLine('disableTelemetry();')).to.include('Telemetry is now disabled');
expect((await readConfig()).enableTelemetry).to.equal(false);
});
});
describe('log file', () => {
it('creates a log file that keeps track of session events', async() => {
expect(await shell.executeLine('print(123 + 456)')).to.include('579');
await eventually(async() => {
const log = await readLogfile();
expect(log.filter(logEntry => /Evaluating input/.test(logEntry.msg)))
.to.have.lengthOf(1);
});
});
it('includes information about the driver version', async() => {
const connectionString = await testServer.connectionString();
expect(await shell.executeLine(`connect(${JSON.stringify(connectionString)})`)).to.include('test');
const log = await readLogfile();
expect(log.filter(logEntry => typeof logEntry.attr?.driver?.version === 'string'))
.to.have.lengthOf(1);
});
});
describe('history file', () => {
it('persists between sessions', async function() {
if (process.arch === 's390x') {
return this.skip(); // https://jira.mongodb.org/browse/MONGOSH-746
}
await shell.executeLine('a = 42');
shell.writeInput('.exit\n');
await shell.waitForExit();
shell = await startTestShell();
// Arrow up twice to skip the .exit line
shell.writeInput('\u001b[A\u001b[A');
await eventually(() => {
expect(shell.output).to.include('a = 42');
});
shell.writeInput('\n.exit\n');
await shell.waitForExit();
expect(await fs.readFile(historyPath, 'utf8')).to.match(/^a = 42$/m);
});
it('is only user-writable (on POSIX)', async function() {
if (process.platform === 'win32') {
return this.skip(); // No sensible fs permissions on Windows
}
await shell.executeLine('a = 42');
shell.writeInput('.exit\n');
await shell.waitForExit();
expect((await fs.stat(historyPath)).mode & 0o077).to.equal(0);
});
});
describe('mongoshrc', () => {
beforeEach(async() => {
await fs.writeFile(path.join(homedir, '.mongoshrc.js'), 'print("hi from mongoshrc")');
});
it('loads .mongoshrc.js if it is there', async() => {
shell = await startTestShell();
shell.assertContainsOutput('hi from mongoshrc');
});
it('does not load .mongoshrc.js if --norc is passed', async() => {
shell = await startTestShell('--norc');
shell.assertNotContainsOutput('hi from mongoshrc');
});
});
});
context('in a restricted environment', () => {
it('keeps working when the home directory cannot be created at all', async() => {
await fs.writeFile(homedir, 'this is a file and not a directory');
const shell = await startTestShell();
await eventually(() => {
expect(shell.output).to.include('Warning: Could not access file:');
});
expect(await shell.executeLine('print(123 + 456)')).to.include('579');
});
it('keeps working when the log files cannot be created', async() => {
await fs.mkdir(path.dirname(logBasePath), { recursive: true });
await fs.writeFile(logBasePath, 'also not a directory');
const shell = await startTestShell();
await eventually(() => {
expect(shell.output).to.include('Warning: Could not access file:');
});
expect(await shell.executeLine('print(123 + 456)')).to.include('579');
expect(await shell.executeLine('enableTelemetry()')).to.include('Telemetry is now enabled');
});
it('keeps working when the config file is present but not writable', async function() {
if (process.platform === 'win32' || process.getuid() === 0 || process.geteuid() === 0) {
return this.skip(); // There is no meaningful chmod on Windows, and root can ignore permissions.
}
await fs.mkdir(path.dirname(configPath), { recursive: true });
await fs.writeFile(configPath, '{}');
await fs.chmod(configPath, 0); // Remove all permissions
const shell = await startTestShell();
await eventually(() => {
expect(shell.output).to.include('Warning: Could not access file:');
});
expect(await shell.executeLine('print(123 + 456)')).to.include('579');
});
});
});
describe('versioned API', () => {
let db;
let dbName;
let client;
beforeEach(async() => {
dbName = `test-${Date.now()}`;
client = await MongoClient.connect(await testServer.connectionString(), {});
db = client.db(dbName);
});
afterEach(async() => {
await db.dropDatabase();
client.close();
});
context('pre-4.4', () => {
skipIfServerVersion(testServer, '> 4.4');
it('errors if an API version is specified', async() => {
const shell = TestShell.start({ args: [
`${await testServer.connectionString()}/${dbName}`, '--apiVersion', '1'
] });
if ((await shell.waitForPromptOrExit()).state === 'prompt') {
await shell.executeLine('db.coll.find().toArray()');
}
expect(shell.output).to.match(/MongoServer(Selection)?Error/);
});
});
context('post-4.4', () => {
skipIfServerVersion(testServer, '<= 4.4');
it('can specify an API version', async() => {
const shell = TestShell.start({ args: [
`${await testServer.connectionString()}/${dbName}`, '--apiVersion', '1'
] });
await shell.waitForPrompt();
shell.assertContainsOutput('(API Version 1)');
expect(await shell.executeLine('db.coll.find().toArray()'))
.to.include('[]');
shell.assertNoErrors();
});
it('can specify an API version and strict mode', async function() {
const shell = TestShell.start({ args: [
`${await testServer.connectionString()}/${dbName}`, '--apiVersion', '1', '--apiStrict', '--apiDeprecationErrors'
] });
await shell.waitForPrompt();
shell.assertContainsOutput('(API Version 1)');
expect(await shell.executeLine('db.coll.find().toArray()'))
.to.include('[]');
shell.assertNoErrors();
});
it('can iterate cursors', async function() {
// Make sure SERVER-55593 doesn't happen to us.
const shell = TestShell.start({ args: [
`${await testServer.connectionString()}/${dbName}`, '--apiVersion', '1'
] });
await shell.waitForPrompt();
await shell.executeLine('for (let i = 0; i < 200; i++) db.coll.insert({i})');
await shell.executeLine('const cursor = db.coll.find().limit(100).batchSize(10);');
expect(await shell.executeLine('cursor.toArray()')).to.include('i: 5');
shell.assertNoErrors();
});
});
});
describe('fail-fast connections', () => {
it('fails fast for ENOTFOUND errors', async() => {
const shell = TestShell.start({ args: [
'mongodb://' + 'verymuchnonexistentdomainname'.repeat(10) + '.mongodb.net/'
] });
const exitCode = await shell.waitForExit();
expect(exitCode).to.equal(1);
});
it('fails fast for ECONNREFUSED errors to a single host', async() => {
const shell = TestShell.start({ args: [
'--port', '1'
] });
const result = await shell.waitForPromptOrExit();
expect(result).to.deep.equal({ state: 'exit', exitCode: 1 });
});
it('fails fast for ECONNREFUSED errors to multiple hosts', async function() {
if (process.platform === 'darwin') {
// On macOS, for some reason only connection that fails is the 127.0.0.1:1
// one, over and over. It should be fine to only skip the test there, as this
// isn't a shell-specific issue.
return this.skip();
}
const shell = TestShell.start({ args: [
'mongodb://127.0.0.1:1,127.0.0.2:1,127.0.0.3:1/?replicaSet=foo&readPreference=secondary'
] });
const result = await shell.waitForPromptOrExit();
expect(result).to.deep.equal({ state: 'exit', exitCode: 1 });
});
});
describe('collection names with types', () => {
let shell: TestShell;
beforeEach(async() => {
shell = TestShell.start({ args: [ await testServer.connectionString() ] });
await shell.waitForPrompt();
shell.assertNoErrors();
});
it('prints collections with their types', async() => {
const dbName = `test-${Date.now()}`;
await shell.executeLine(`use ${dbName};`);
await shell.executeLine('db.coll1.insertOne({ foo: 123 });');
expect(await shell.executeLine('show collections')).to.include('coll1');
});
context('post-5.0', () => {
skipIfServerVersion(testServer, '< 5.0');
it('prints collections with their types', async() => {
const dbName = `test-${Date.now()}`;
await shell.executeLine(`use ${dbName};`);
await shell.executeLine("db.coll2.insertOne({ some: 'field' });");
await shell.executeLine("db.createCollection('coll3', { timeseries: { timeField: 'time' } } );");
const result = await shell.executeLine('show collections');
expect(result).to.include('coll2');
expect(result).to.include('coll3');
expect(result).to.include('[time-series]');
});
});
});
describe('ask-for-connection-string mode', () => {
let shell: TestShell;
beforeEach(() => {
shell = TestShell.start({
args: [],
env: { ...process.env, MONGOSH_FORCE_CONNECTION_STRING_PROMPT: '1' },
forceTerminal: true
});
});
it('allows connecting to a host and running commands against it', async() => {
const connectionString = await testServer.connectionString();
await eventually(() => {
shell.assertContainsOutput('Please enter a MongoDB connection string');
});
shell.writeInputLine(connectionString);
await shell.waitForPrompt();
expect(await shell.executeLine('db.runCommand({ping: 1})')).to.include('ok: 1');
shell.writeInputLine('exit');
await shell.waitForExit();
shell.assertNoErrors();
});
});
describe('run Node.js scripts as-is', () => {
it('runs Node.js scripts as they are when using MONGOSH_RUN_NODE_SCRIPT', async() => {
const filename = path.resolve(__dirname, 'fixtures', 'simple-console-log.js');
const shell = TestShell.start({
args: [filename],
env: { ...process.env, MONGOSH_RUN_NODE_SCRIPT: '1' }
});
expect(await shell.waitForExit()).to.equal(0);
shell.assertContainsOutput('610');
});
});
}); | the_stack |
import { createElement, L10n, remove } from '@syncfusion/ej2-base';
import { Chart } from '../../../src/chart/chart';
import { Zoom } from '../../../src/chart/user-interaction/zooming';
import { LineSeries } from '../../../src/chart/series/line-series';
import { unbindResizeEvents } from '../base/data.spec';
import { ColumnSeries } from '../../../src/chart/series/column-series';
import { DataLabel } from '../../../src/chart/series/data-label';
import { seriesData1 } from '../base/data.spec';
import { EmitType } from '@syncfusion/ej2-base';
import { MouseEvents } from '../../chart/base/events.spec';
import { wheel } from '../../chart/user-interaction/zooming.spec';
import { ILoadedEventArgs } from '../../../src/chart/model/chart-interface';
import { profile , inMB, getMemoryProfile} from '../../common.spec';
import { Legend, Category } from '../../../src/index';
import { categoryData } from './data.spec';
import { Query } from '@syncfusion/ej2-data';
Chart.Inject(LineSeries, Zoom, ColumnSeries, DataLabel, Legend, Category);
describe('Chart Control', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
describe('Chart direct properties and its behavior', () => {
let chart: Chart;
let ele: HTMLElement;
let svg: HTMLElement;
let text: HTMLElement;
let trigger: MouseEvents = new MouseEvents();
let loaded: EmitType<ILoadedEventArgs>;
beforeAll((): void => {
ele = createElement('div', { id: 'container' });
document.body.appendChild(ele);
chart = new Chart();
});
afterAll((): void => {
chart.destroy();
ele.remove();
});
it('Checking chart instance creation', (done: Function) => {
loaded = (args: Object): void => {
expect(chart != null).toBe(true);
done();
}
chart.loaded = loaded;
chart.appendTo('#container');
});
it('Checking with empty options', () => {
let className: string = document.getElementById('container').className;
expect(className).toEqual('e-control e-chart e-lib e-touch');
});
it('Checking module name', () => {
expect(chart.getModuleName()).toBe('chart');
});
it('Checking with empty size property', () => {
svg = document.getElementById('container_svg');
expect(svg.getAttribute('width') != null).toBe(true);
});
it('Checking the null height of the chart', () => {
svg = document.getElementById('container_svg');
expect(svg.getAttribute('height')).toEqual('450');
});
it('Checking the null width of the chart', (done: Function) => {
chart.width = null;
ele.setAttribute('style', 'width:0px');
chart.loaded = (args: Object) => {
svg = document.getElementById('container_svg');
expect(svg.getAttribute('width')).toEqual('600');
done();
};
chart.getPersistData();
chart.refresh();
});
it('Checking the percentage size of the chart', (done: Function) => {
chart.width = '50%';
ele.setAttribute('style', 'width:900px');
chart.loaded = (args: Object) => {
svg = document.getElementById('container_svg');
expect(svg.getAttribute('width')).toEqual('450');
done();
};
chart.refresh();
});
it('Checking the width of the chart', () => {
chart.width = '500';
chart.loaded = null;
chart.dataBind();
svg = document.getElementById('container_svg');
expect(svg.getAttribute('width')).toEqual('500');
});
it('Checking the height of the chart', () => {
chart.height = '500';
chart.dataBind();
svg = document.getElementById('container_svg');
expect(svg.getAttribute('height')).toEqual('500');
});
it('Checking both height and width of the chart', () => {
chart.width = '500';
chart.height = '300';
chart.dataBind();
svg = document.getElementById('container_svg');
expect(svg.getAttribute('width')).toEqual('500');
expect(svg.getAttribute('height')).toEqual('300');
});
it('Checking with empty title', () => {
text = document.getElementById('container_ChartTitle');
expect(text == null).toBe(true);
});
it('Checking with title', () => {
chart.title = 'Syncfusion Chart Title';
chart.dataBind();
text = document.getElementById('container_ChartTitle');
expect(text.textContent == 'Syncfusion Chart Title').toBe(true);
expect(text.getAttribute('y') == '25' || text.getAttribute('y') == '22.75').toBe(true);
});
it('Checking textoverflow title none', () => {
chart.width = '100px';
chart.title = 'Efficiency of oil-fired power production';
chart.titleStyle.textOverflow = 'None';
chart.dataBind();
text = document.getElementById('container_ChartTitle');
expect(text.getAttribute('text-anchor')).toBe('middle');
expect(text.getAttribute('y') == '25' || text.getAttribute('y') == '22.75').toBe(true);
});
it('Checking textoverflow title wrap', () => {
chart.titleStyle.textOverflow = 'Wrap';
chart.dataBind();
text = document.getElementById('container_ChartTitle');
expect(text.getAttribute('y') == '25' || text.getAttribute('y') == '22.75').toBe(true);
});
it('Checking textoverflow title wrapwithtrim', () => {
chart.title = 'Efficiency of oil-fired power productionchart';
chart.dataBind();
text = document.getElementById('container_ChartTitle');
expect(text.textContent.indexOf('...') != -1).toBe(true);
expect(text.getAttribute('y') == '25' || text.getAttribute('y') == '22.75').toBe(true);
});
it('Checking textoverflow title trim', () => {
chart.titleStyle.textOverflow = 'Trim';
chart.dataBind();
text = document.getElementById('container_ChartTitle');
expect(text.textContent.indexOf('...') != -1).toBe(true);
expect(text.getAttribute('text-anchor')).toBe('middle');
expect(text.getAttribute('y') == '25' || text.getAttribute('y') == '22.75').toBe(true);
});
it('Checking title trim', () => {
chart.title = 'candidate joined in a year syncfusion Chart Title';
chart.width = '100';
chart.dataBind();
text = document.getElementById('container_ChartTitle');
expect(text.textContent.indexOf('...') != -1).toBe(true);
});
it('Trimmed text and mouse over and out', (done: Function) => {
loaded = (args: Object): void => {
chart.loaded = null;
text = document.getElementById('container_ChartTitle');
trigger.mousemoveEvent(text, 0, 0, 77, 25);
let tooltip: Element = document.getElementById('container_EJ2_Title_Tooltip');
expect(tooltip.textContent).toBe('candidate joined in a year syncfusion Chart Title');
expect(text.textContent.split('...').length).toEqual(2);
tooltip.remove();
chart.mouseEnd(<PointerEvent>trigger.onTouchEnd(text, 0, 0, null, null, 77, 25));
tooltip = document.getElementById('container_EJ2_Title_Tooltip');
expect(tooltip.textContent).toBe('candidate joined in a year syncfusion Chart Title');
expect(text.textContent.split('...').length).toEqual(2);
tooltip.remove();
//document.body.removeChild(tooltip);
done();
};
chart.width = '80';
chart.title = 'candidate joined in a year syncfusion Chart Title';
chart.loaded = loaded;
chart.refresh();
});
it('Trimmed text and mouse over and out for subtitle', (done: Function) => {
loaded = (args: Object): void => {
chart.loaded = null;
text = document.getElementById('container_ChartSubTitle');
trigger.mousemoveEvent(text, 0, 0, 77, 25);
let tooltip: Element = document.getElementById('container_EJ2_Title_Tooltip');
expect(tooltip.textContent).toBe('syncfusion Chart SubTitle');
tooltip.remove();
done();
};
chart.width = '80';
chart.subTitle = 'syncfusion Chart SubTitle';
chart.isTouch=false;
chart.loaded= loaded;
chart.refresh();
});
it('Checking the title font size', () => {
chart.title = 'Chart Title';
chart.titleStyle.size = '24px';
chart.dataBind();
text = document.getElementById('container_ChartTitle');
expect(text.getAttribute('font-size')).toEqual('24px');
});
it('Checking with subtitle', function () {
chart.width = '500px';
chart.subTitle = 'Chart SubTitle';
chart.dataBind();
text = document.getElementById('container_ChartSubTitle');
expect(text.textContent == 'Chart SubTitle').toBe(true);
expect(text.getAttribute('y') == '55.25' || text.getAttribute('y') == '49.25').toBe(true);
});
it('Checking textoverflow subtitle none', function () {
chart.subTitle = 'SubTitle';
chart.titleStyle.textOverflow = 'None';
chart.dataBind();
text = document.getElementById('container_ChartSubTitle');
expect(text.textContent == 'SubTitle').toBe(true);
expect(text.getAttribute('y') == '55.25' || text.getAttribute('y') == '49.25').toBe(true);
});
it('Checking textoverflow subtitle trim', function () {
chart.width = '100px';
chart.subTitle = 'Syncfusion Chart SubTitle';
chart.subTitleStyle.textOverflow = 'Trim';
chart.dataBind();
text = document.getElementById('container_ChartSubTitle');
expect(text.textContent.indexOf('...') != -1).toBe(true);
expect(text.getAttribute('y') == '55.25' || text.getAttribute('y') == '49.25').toBe(true);
});
it('Checking textoverflow subtitle wrap', function () {
chart.subTitleStyle.textOverflow = 'Wrap';
chart.dataBind();
text = document.getElementById('container_ChartSubTitle');
expect(text.childNodes.length == 2).toBe(true);
expect(text.getAttribute('y') == '55.25' || text.getAttribute('y') == '49.25').toBe(true);
});
it('Checking textAlignment subtitle center and subtitle is in Title width', function () {
chart.width = '500px';
chart.title = 'Syncfusion Chart SubTitle';
chart.subTitle = 'Checking Syncfusion Chart SubTitle width should be in Chart Title width';
chart.subTitleStyle.textOverflow = 'Trim';
chart.titleStyle.textOverflow = 'Wrap';
chart.dataBind();
text = document.getElementById('container_ChartSubTitle');
expect(text.textContent.indexOf('...') != -1).toBe(true);
expect(text.getAttribute('text-anchor')).toBe('middle');
});
it('Checking textAlignment subtitle Far', function () {
chart.subTitleStyle.textAlignment = 'Far';
chart.dataBind();
text = document.getElementById('container_ChartSubTitle');
expect(text.getAttribute('text-anchor')).toBe('end');
});
it('Checking textAlignment subtitle Near', function () {
chart.subTitleStyle.textAlignment = 'Near';
chart.dataBind();
text = document.getElementById('container_ChartSubTitle');
expect(text.getAttribute('text-anchor')).toBe('start');
});
it('Checking the subtitle font size', () => {
chart.subTitleStyle.size = '20px';
chart.dataBind();
text = document.getElementById('container_ChartSubTitle');
expect(text.getAttribute('font-size')).toEqual('20px');
});
it('Checking with empty subtitle', function () {
chart.subTitle= '';
chart.dataBind();
text = document.getElementById('container_ChartSubTitle');
expect(text == null).toBe(true);
});
it('Checking the border color', () => {
chart.border.width = 2;
chart.border.color = 'green';
chart.dataBind();
svg = document.getElementById('container_ChartBorder');
expect(svg.getAttribute('stroke') == 'green').toBe(true);
expect(svg.getAttribute('stroke-width') == '2').toBe(true);
});
it('Checking the Chart Area border color', () => {
chart.chartArea.border.color = 'red';
chart.chartArea.background = 'green';
chart.chartArea.opacity = 0.5;
chart.dataBind();
svg = document.getElementById('container_ChartAreaBorder');
expect(svg.getAttribute('stroke') == 'red').toBe(true);
expect(svg.getAttribute('fill') == 'green').toBe(true);
expect(svg.getAttribute('opacity') == '0.5').toBe(true);
});
it('Checking the Chart background', () => {
chart.background = 'yellow';
chart.dataBind();
svg = document.getElementById('container_ChartBorder');
expect(svg.getAttribute('fill') == 'yellow').toBe(true);
});
it('Checking context menu event', () => {
let menu: Event = document.createEvent('MouseEvent');
menu.initEvent('contextmenu', true, false);
ele.dispatchEvent(menu);
expect(ele).not.toBe(null);
});
it('Checking the chart Orientation', () => {
expect(chart.isOrientation()).toBe(false);
});
it('checking with title alignment default', (done: Function) => {
loaded = (args: ILoadedEventArgs) => {
text = document.getElementById('container_ChartTitle');
expect(text.getAttribute('text-anchor')).toBe('middle');
expect(text.getAttribute('x') == text.children[0].getAttribute('x')).toBe(true);
done();
};
chart.loaded = loaded;
chart.title = 'EfficiencyChart of oil power productionchart';
chart.titleStyle.textOverflow = 'Wrap';
chart.width = '300';
chart.refresh();
});
it('checking with title alignment Far', () => {
chart.titleStyle.textAlignment = 'Far';
chart.loaded = null;
chart.dataBind();
text = document.getElementById('container_ChartTitle');
expect(text.getAttribute('text-anchor')).toBe('end');
expect(text.getAttribute('x') == text.children[0].getAttribute('x')).toBe(true);
});
it('checking with title alignment Near', () => {
chart.titleStyle.textAlignment = 'Near';
chart.dataBind();
text = document.getElementById('container_ChartTitle');
expect(text.getAttribute('text-anchor')).toBe('start');
expect(text.getAttribute('x') == text.children[0].getAttribute('x')).toBe(true);
});
it('checking chart area background image', (done: Function) => {
setTimeout(() => {
let background: HTMLElement = document.getElementById('container_ChartAreaBackground');
expect(background.getAttribute('href') != null).toBe(true);
done();
}, 500);
chart.chartArea.backgroundImage =
'https://cdn.syncfusion.com/content/images/freetrials/essential-studio.png?v=03102019101652';
chart.refresh();
});
it('checking chart background image', (done: Function) => {
setTimeout(() => {
let background: HTMLElement = document.getElementById('container_ChartBackground');
expect(background.getAttribute('href') != null).toBe(true);
done();
}, 500);
chart.backgroundImage = 'https://cdn.syncfusion.com/content/images/freetrials/essential-studio.png?v=03102019101652';
chart.refresh();
});
});
describe('Chart checking localization', () => {
L10n.load({
'de-DE': {
'chart': {
ZoomIn: 'تكبير',
ZoomOut: 'تصغير',
Zoom: 'زوم',
Pan: 'مقلاة',
Reset: 'إعادة تعيين'
},
}
});
let chart: Chart;
let ele: HTMLElement;
let svg: HTMLElement;
let text: HTMLElement;
let trigger: MouseEvents = new MouseEvents();
let loaded: EmitType<ILoadedEventArgs>;
beforeAll((): void => {
ele = createElement('div', { id: 'container' });
document.body.appendChild(ele);
chart = new Chart();
chart.appendTo('#container');
});
afterAll((): void => {
chart.destroy();
ele.remove();
});
it('checking zooming tooltit with localization', (done: Function) => {
loaded = (args: ILoadedEventArgs) => {
chart.loaded = null;
trigger.draganddropEvent(ele, 100, 100, 400, 400);
let targetElement = document.getElementById('container_Zooming_KitCollection');
trigger.mousemoveEvent(targetElement, 800, 10, 805, 15);
targetElement = document.getElementById('container_Zooming_Zoom');
trigger.mouseoverEvent(targetElement);
expect(document.getElementById('EJ2_Chart_ZoomTip').innerHTML).toEqual(" زوم ");
done();
};
chart.loaded = loaded;
chart.zoomSettings = {
enablePinchZooming: true, enableDeferredZooming: true,
enableMouseWheelZooming: true, enableSelectionZooming: true
};
chart.locale = 'de-DE';
chart.refresh();
});
it('checking zooming tooltit without localization', () => {
remove(document.getElementById('EJ2_Chart_ZoomTip'));
chart.locale = '';
chart.dataBind();
trigger.draganddropEvent(ele, 100, 100, 400, 400);
let targetElement = document.getElementById('container_Zooming_KitCollection');
trigger.mousemoveEvent(targetElement, 800, 10, 805, 15);
targetElement = document.getElementById('container_Zooming_Zoom');
trigger.mouseoverEvent(targetElement);
expect(document.getElementById('EJ2_Chart_ZoomTip').innerHTML).toEqual(" Zoom ");
});
});
describe('Chart checking center aligned div', () => {
let chart: Chart;
let ele: HTMLElement;
let svg: HTMLElement;
let text: HTMLElement;
let trigger: MouseEvents = new MouseEvents();
let loaded: EmitType<ILoadedEventArgs>;
beforeAll((): void => {
ele = createElement('div', { id: 'container' });
ele.setAttribute('align', 'center');
document.body.appendChild(ele);
chart = new Chart({
primaryYAxis: {
rangePadding: 'Round'
},
series: [
{
dataSource: seriesData1, xName: 'x', yName: 'y', fill: 'orange', opacity: 0.7,
type: 'Column',
animation: { enable: false},
marker: {
dataLabel: {
visible: true,
position: 'Top',
template: '<div style="background-color:#ed7d31;border-radius: 3px;">${point.y}Million</div>'
}
}
}
],
zoomSettings: {
enableSelectionZooming: true,
enableMouseWheelZooming: true,
},
width: '400px'
});
chart.appendTo('#container');
});
afterAll((): void => {
chart.destroy();
ele.remove();
});
it('checking data label template and zooming', (done: Function) => {
let wheelArgs: unknown = {
preventDefault: () => {
// not applicable
},
wheelDelta: 120,
detail: 3,
clientX: 210,
clientY: 100
};
loaded = (args: ILoadedEventArgs) => {
chart.loaded = null;
let secondaryElement: HTMLDivElement = document.getElementById('container_Secondary_Element') as HTMLDivElement;
expect(parseInt(secondaryElement.style.top, 10)).toBe(0);
expect(parseInt(secondaryElement.style.left, 10) === 179 || parseInt(secondaryElement.style.left, 10) === 184).toBe(true);
let datalabel: HTMLDivElement = document.getElementById('container_Series_0_DataLabel_4') as HTMLDivElement;
expect(parseInt(datalabel.style.top, 10) === 227 || parseInt(datalabel.style.top, 10) === 228).toBe(true);
expect(parseInt(datalabel.style.left, 10)).toBe(174);
trigger.draganddropEvent(ele, 20, 100, 120, 300);
expect(chart.primaryXAxis.zoomFactor).toBe(1);
expect(chart.primaryYAxis.zoomFactor).toBe(1);
expect(chart.primaryXAxis.zoomPosition).toBe(0);
expect(chart.primaryYAxis.zoomPosition).toBe(0);
trigger.draganddropEvent(ele, 480, 100, 580, 300);
expect(chart.primaryXAxis.zoomFactor.toFixed(2)).toBe('0.28');
expect(chart.primaryYAxis.zoomFactor.toFixed(2) === '0.50' || chart.primaryYAxis.zoomFactor.toFixed(2) === '0.49').toBe(true);
expect(chart.primaryXAxis.zoomPosition.toFixed(2) === '0.72' || chart.primaryXAxis.zoomPosition.toFixed(2) === '0.71').toBe(true);
expect(chart.primaryYAxis.zoomPosition.toFixed(2)).toBe('0.30');
// checking for center aligned div mouse wheel zooming
chart.zoomModule.chartMouseWheel(<WheelEvent>wheelArgs);
expect(chart.primaryXAxis.zoomFactor.toFixed(2)).toBe('0.28');
let temp: string = chart.primaryYAxis.zoomFactor.toFixed(2);
expect(temp === '0.50' || temp === '0.49').toBe(true);
temp = chart.primaryXAxis.zoomPosition.toFixed(2);
expect(temp === '0.72' || temp === '0.71').toBe(true);
expect(chart.primaryYAxis.zoomPosition.toFixed(2)).toBe('0.30');
done();
};
chart.loaded = loaded;
chart.refresh();
});
});
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);
})
describe('Customer issue: series DataBind', () => {
let chart: Chart;
let ele: HTMLElement;
let loaded: EmitType<ILoadedEventArgs>;
let element: Element;
beforeAll((): void => {
ele = createElement('div', { id: 'seriesData' });
document.body.appendChild(ele);
chart = new Chart(
{
primaryXAxis: { valueType: 'Category', rangePadding: 'Normal' },
primaryYAxis: { title: 'PrimaryYAxis' },
series: [{ dataSource: categoryData, xName: 'x', yName: 'y', name: 'Gold', fill: 'red', animation: { enable: false }, type: 'Column' }],
height: '400', width: '900',
legendSettings: { visible: true, position: 'Right' }
});
});
afterAll((): void => {
chart.destroy();
ele.remove();
});
it('checking default fill property', (done: Function) => {
loaded = (args: ILoadedEventArgs) => {
element = document.getElementById('seriesData_Series_0_Point_1');
expect(element.getAttribute('fill')).toEqual('red');
done();
};
chart.loaded = loaded;
chart.appendTo(ele);
});
it('checking with changing fill', (done: Function) => {
loaded = (args: ILoadedEventArgs) => {
element = document.getElementById('seriesData_Series_0_Point_1');
expect(element.getAttribute('fill')).toEqual('blue');
done();
};
chart.loaded = loaded;
chart.series[0].fill = 'blue';
chart.dataBind();
});
it('checking before the legend name chage', () => {
element = document.getElementById('seriesData_chart_legend_element');
expect(element.getAttribute('x') === '832' || element.getAttribute('x') === '833').toBe(true);
element = document.getElementById('seriesData_chart_legend_text_0');
expect(element.textContent).toEqual('Gold');
});
it('checking with changing name', (done: Function) => {
loaded = (args: ILoadedEventArgs) => {
element = document.getElementById('seriesData_chart_legend_element');
expect(element.getAttribute('x') === '743' || element.getAttribute('x') === '752').toBe(true);
element = document.getElementById('seriesData_chart_legend_text_0');
expect(element.textContent).toEqual('Olymbic gold medal');
done();
};
chart.loaded = loaded;
chart.series[0].name = 'Olymbic gold medal';
chart.dataBind();
});
it('checking with local dataSource with query', (done: Function) => {
loaded = (args: ILoadedEventArgs) => {
element = document.getElementById('seriesDataSeriesGroup0');
expect(element.childElementCount).toEqual(3);
done();
};
chart.loaded = loaded;
chart.series[0].query = new Query().take(2);
chart.refresh();
});
it('checking materialDark', (done: Function) => {
loaded = (args: ILoadedEventArgs) => {
element = document.getElementById('seriesDataSeriesGroup0');
expect(element.childElementCount).toEqual(3);
done();
};
chart.loaded = loaded;
chart.theme = 'MaterialDark';
chart.refresh();
});
it('checking fabricDark', (done: Function) => {
loaded = (args: ILoadedEventArgs) => {
element = document.getElementById('seriesDataSeriesGroup0');
expect(element.childElementCount).toEqual(3);
done();
};
chart.loaded = loaded;
chart.theme = 'FabricDark';
chart.refresh();
});
it('checking bootstrapDark', (done: Function) => {
loaded = (args: ILoadedEventArgs) => {
element = document.getElementById('seriesDataSeriesGroup0');
expect(element.childElementCount).toEqual(3);
done();
};
chart.loaded = loaded;
chart.theme = 'BootstrapDark';
chart.refresh();
});
});
}); | the_stack |
import { BaseExtension } from '../baseExtension';
import { Extension } from '../extension';
import { MediaDao } from './mediaDao';
import { MediaTable } from './mediaTable';
import { SimpleAttributesDao } from './simpleAttributesDao';
import { SimpleAttributesTable } from './simpleAttributesTable';
import { UserMappingTable } from './userMappingTable';
import { UserMappingDao } from './userMappingDao';
import { UserCustomDao } from '../../user/custom/userCustomDao';
import { UserDao } from '../../user/userDao';
import { UserTableReader } from '../../user/userTableReader';
import { ExtendedRelationDao } from './extendedRelationDao';
import { RelationType } from './relationType';
import { Contents } from '../../core/contents/contents';
import { ColumnValues } from '../../dao/columnValues';
import { ExtendedRelation } from './extendedRelation';
import { OptionBuilder } from '../../optionBuilder';
import { GeoPackage } from '../../geoPackage';
import { UserRelatedTable } from './userRelatedTable';
import { UserRow } from '../../user/userRow';
import { UserMappingRow } from './userMappingRow';
import { MediaRow } from './mediaRow';
import { SimpleAttributesRow } from './simpleAttributesRow';
import {UserCustomTableReader} from "../../user/custom/userCustomTableReader";
import {AttributesDao} from "../../attributes/attributesDao";
import {AttributesRow} from "../../attributes/attributesRow";
import {FeatureDao} from "../../features/user/featureDao";
import {TileDao} from "../../tiles/user/tileDao";
/**
* Related Tables Extension
* @param {module:geoPackage~GeoPackage} geoPackage the GeoPackage object
* @class
* @extends BaseExtension
*/
export class RelatedTablesExtension extends BaseExtension {
extendedRelationDao: ExtendedRelationDao;
public static readonly EXTENSION_NAME: string = 'related_tables';
public static readonly EXTENSION_RELATED_TABLES_AUTHOR: string = 'gpkg';
public static readonly EXTENSION_RELATED_TABLES_NAME_NO_AUTHOR: string = 'related_tables';
public static readonly EXTENSION_RELATED_TABLES_DEFINITION: string = 'TBD';
constructor(geoPackage: GeoPackage) {
super(geoPackage);
this.extendedRelationDao = geoPackage.extendedRelationDao;
}
/**
* Get or create the extension
* @return {Promise}
*/
getOrCreateExtension(): Extension {
const extension = this.getOrCreate(
RelatedTablesExtension.EXTENSION_NAME,
'gpkgext_relations',
undefined,
RelatedTablesExtension.EXTENSION_RELATED_TABLES_DEFINITION,
Extension.READ_WRITE,
);
this.extendedRelationDao.createTable();
return extension;
}
/**
* Get or create the extension for the mapping table
* @param {string} mappingTableName user mapping table
* @return {Promise}
*/
getOrCreateMappingTable(mappingTableName: string): Extension {
this.getOrCreateExtension();
return this.getOrCreate(
RelatedTablesExtension.EXTENSION_NAME,
mappingTableName,
undefined,
RelatedTablesExtension.EXTENSION_RELATED_TABLES_DEFINITION,
Extension.READ_WRITE,
);
}
/**
* Set the contents in the UserRelatedTable
* @param {module:extension/relatedTables~UserRelatedTable} userRelatedTable user related table
*/
setContents(userRelatedTable: UserRelatedTable): boolean {
const contents = this.geoPackage.contentsDao.queryForId(userRelatedTable.getTableName());
return userRelatedTable.setContents(contents);
}
/**
* Reads the user table and creates a UserCustomDao
* @param {string} tableName table name to reader
* @param {string[]} requiredColumns required columns
* @return {module:user/custom~UserCustomDao}
*/
getUserDao(tableName: string): UserCustomDao<UserRow> {
return UserCustomDao.readTable(this.geoPackage, tableName);
}
/**
* Gets the UserMappingDao from the mapping table name
* @param {string | ExtendedRelation} tableName user mapping table name or ExtendedRelation object
* @return {module:extension/relatedTables~UserMappingDao}
*/
getMappingDao(tableName: string | ExtendedRelation): UserMappingDao<UserMappingRow> {
let mappingTableName;
if (tableName instanceof ExtendedRelation) {
mappingTableName = tableName.mapping_table_name;
} else {
mappingTableName = tableName;
}
return new UserMappingDao(this.getUserDao(mappingTableName), this.geoPackage);
}
/**
* Gets all relationships in the GeoPackage with an optional base table name and an optional base id
* @param {String} [baseTableName] base table name
* @return {module:extension/relatedTables~ExtendedRelation[]}
*/
getRelationships(baseTableName?: string): ExtendedRelation[] {
if (this.extendedRelationDao.isTableExists()) {
if (baseTableName) {
return this.geoPackage.extendedRelationDao.getBaseTableRelations(baseTableName);
}
return (this.extendedRelationDao.queryForAll() as unknown) as ExtendedRelation[];
}
return [];
}
/**
* Gets all relationships in the GeoPackage with an optional base table name and an optional base id
* @param {String} [baseTableName] base table name
* @param {String} [relatedTableName] related table name
* @param {String} [mappingTableName] mapping table name
* @return {Boolean}
*/
hasRelations(baseTableName?: string, relatedTableName?: string, mappingTableName?: string): boolean {
let relations = [];
if (this.extendedRelationDao.isTableExists()) {
relations = this.extendedRelationDao.getRelations(baseTableName, relatedTableName, mappingTableName);
}
return !!relations.length;
}
getRelatedRows(baseTableName: string, baseId: number): ExtendedRelation[] {
const relationships = this.getRelationships(baseTableName);
for (let i = 0; i < relationships.length; i++) {
const relation = relationships[i];
const mappingRows = this.getMappingRowsForBase(relation.mapping_table_name, baseId);
relation.mappingRows = mappingRows;
let userDao: UserDao<UserRow>;
switch (relation.relation_name) {
case RelationType.MEDIA.name:
userDao = MediaDao.readTable(this.geoPackage, relation.related_table_name);
break;
case RelationType.ATTRIBUTES.name:
userDao = AttributesDao.readTable(this.geoPackage, relation.related_table_name);
break;
case RelationType.FEATURES.name:
userDao = FeatureDao.readTable(this.geoPackage, relation.related_table_name);
break;
case RelationType.TILES.name:
userDao = TileDao.readTable(this.geoPackage, relation.related_table_name);
break;
case RelationType.SIMPLE_ATTRIBUTES.name:
userDao = SimpleAttributesDao.readTable(this.geoPackage, relation.related_table_name);
break;
default:
throw new Error('Relationship Unknown')
}
for (let m = 0; m < mappingRows.length; m++) {
const mappingRow = mappingRows[m];
mappingRow.row = userDao.queryForId(mappingRow.relatedId);
}
}
return relationships;
}
/**
* Convience object to build a Relationship object for querying and adding
* @typedef {Object} module:extension/relatedTables~Relationship
* @property {module:extension/relatedTables~RelationType} relationType type of relationship
* @property {string} baseTableName base table name
* @property {string} relatedTableName related table name
* @property {string} relationAuthor relationship author
* @property {string} mappingTableName mapping table name
* @property {module:extension/relatedTables~UserMappingTable} userMappingTable UserMappingTable
* @property {module:extension/relatedTables~UserRelatedTable} relatedTable UserRelatedTable
*/
getRelationshipBuilder(): any {
return RelatedTablesExtension.RelationshipBuilder();
}
/**
* Adds a relationship to the GeoPackage
* @param {module:extension/relatedTables~Relationship|module:extension/relatedTables~ExtendedRelation} relationship relationship to add
* @return {Promise<ExtendedRelation | undefined>}
*/
addRelationship(
relationship:
| ExtendedRelation
| {
relationType?: RelationType;
relationName?: string;
baseTableName?: string;
relatedTableName?: string;
relationAuthor?: string;
mappingTableName?: string;
userMappingTable?: UserMappingTable;
relatedTable?: UserRelatedTable;
},
): ExtendedRelation {
let extendedRelation = this.extendedRelationDao.createObject();
let userMappingTable: UserMappingTable;
if (relationship instanceof ExtendedRelation) {
extendedRelation = relationship;
userMappingTable = UserMappingTable.create(extendedRelation.mapping_table_name);
} else {
userMappingTable = relationship.userMappingTable;
if (relationship.relationType) {
relationship.relationName = relationship.relationType.name;
}
if (relationship.relationAuthor) {
relationship.relationName = this.buildRelationName(relationship.relationAuthor, relationship.relationName);
}
if (relationship.mappingTableName) {
userMappingTable = UserMappingTable.create(relationship.mappingTableName);
}
if (relationship.relatedTable) {
this.createRelatedTable(relationship.relatedTable);
relationship.relatedTableName = relationship.relatedTable.getTableName();
relationship.relationName = relationship.relatedTable.relation_name;
}
extendedRelation.base_table_name = relationship.baseTableName;
extendedRelation.base_primary_column = this.getPrimaryKeyColumnName(relationship.baseTableName);
extendedRelation.related_table_name = relationship.relatedTableName;
extendedRelation.related_primary_column = this.getPrimaryKeyColumnName(relationship.relatedTableName);
extendedRelation.mapping_table_name = userMappingTable.getTableName();
extendedRelation.relation_name = relationship.relationName;
}
if (
!this.validateRelationship(
extendedRelation.base_table_name,
extendedRelation.related_table_name,
extendedRelation.relation_name,
)
) {
return;
}
this.createUserMappingTable(userMappingTable);
const mappingTableRelations = this.extendedRelationDao.queryByMappingTableName(extendedRelation.mapping_table_name);
if (mappingTableRelations.length) {
return mappingTableRelations[0];
}
this.extendedRelationDao.create(extendedRelation);
return extendedRelation;
}
/**
* Get the primary key column name from the specified table
* @param {string} tableName table name
* @return {string}
*/
getPrimaryKeyColumnName(tableName: string): string {
const reader = new UserCustomTableReader(tableName);
const table = reader.readTable(this.geoPackage.database);
return table.getPkColumn().getName();
}
/**
* Adds a features relationship between the base feature and related feature
* table. Creates a default user mapping table if needed.
* @param {module:extension/relatedTables~Relationship|module:extension/relatedTables~ExtendedRelation} relationship relationship to add
* @return {Promise<ExtendedRelation>}
*/
addFeaturesRelationship(
relationship:
| ExtendedRelation
| {
relationType?: RelationType;
relationName?: string;
baseTableName?: string;
relatedTableName?: string;
relationAuthor?: string;
mappingTableName?: string;
userMappingTable?: UserMappingTable;
relatedTable?: UserRelatedTable;
},
): ExtendedRelation {
if (relationship instanceof ExtendedRelation) {
relationship.relation_name = relationship.relation_name || RelationType.FEATURES.name;
} else {
relationship.relationType = RelationType.FEATURES;
}
return this.addRelationship(relationship);
}
/**
* Adds a tiles relationship between the base table and related tile
* table. Creates a default user mapping table if needed.
* @param {module:extension/relatedTables~Relationship|module:extension/relatedTables~ExtendedRelation} relationship relationship to add
* @return {Promise<ExtendedRelation>}
*/
addTilesRelationship(
relationship:
| ExtendedRelation
| {
relationType?: RelationType;
relationName?: string;
baseTableName?: string;
relatedTableName?: string;
relationAuthor?: string;
mappingTableName?: string;
userMappingTable?: UserMappingTable;
relatedTable?: UserRelatedTable;
},
): ExtendedRelation {
if (relationship instanceof ExtendedRelation) {
relationship.relation_name = relationship.relation_name || RelationType.TILES.name;
} else {
relationship.relationType = RelationType.TILES;
}
return this.addRelationship(relationship);
}
/**
* Adds an attributes relationship between the base table and related attribute
* table. Creates a default user mapping table if needed.
* @param {module:extension/relatedTables~Relationship|module:extension/relatedTables~ExtendedRelation} relationship relationship to add
* @return {Promise<ExtendedRelation>}
*/
addAttributesRelationship(
relationship:
| ExtendedRelation
| {
relationType?: RelationType;
relationName?: string;
baseTableName?: string;
relatedTableName?: string;
relationAuthor?: string;
mappingTableName?: string;
userMappingTable?: UserMappingTable;
relatedTable?: UserRelatedTable;
},
): ExtendedRelation {
if (relationship instanceof ExtendedRelation) {
relationship.relation_name = relationship.relation_name || RelationType.ATTRIBUTES.name;
} else {
relationship.relationType = RelationType.ATTRIBUTES;
}
return this.addRelationship(relationship);
}
/**
* Adds a simple attributes relationship between the base table and user
* simple attributes related table. Creates a default user mapping table and
* the simple attributes table if needed.
* @param {module:extension/relatedTables~Relationship|module:extension/relatedTables~ExtendedRelation} relationship relationship to add
* @return {Promise<ExtendedRelation>}
*/
addSimpleAttributesRelationship(
relationship:
| ExtendedRelation
| {
relationType?: RelationType;
relationName?: string;
baseTableName?: string;
relatedTableName?: string;
relationAuthor?: string;
mappingTableName?: string;
userMappingTable?: UserMappingTable;
relatedTable?: UserRelatedTable;
},
): ExtendedRelation {
if (relationship instanceof ExtendedRelation) {
relationship.relation_name = relationship.relation_name || RelationType.SIMPLE_ATTRIBUTES.name;
} else {
relationship.relationType = RelationType.SIMPLE_ATTRIBUTES;
}
return this.addRelationship(relationship);
}
/**
* Adds a media relationship between the base table and user media related
* table. Creates a default user mapping table and the media table if
* needed.
* @param {module:extension/relatedTables~Relationship|module:extension/relatedTables~ExtendedRelation} relationship relationship to add
* @return {Promise<ExtendedRelation>}
*/
addMediaRelationship(
relationship:
| ExtendedRelation
| {
relationType?: RelationType;
relationName?: string;
baseTableName?: string;
relatedTableName?: string;
relationAuthor?: string;
mappingTableName?: string;
userMappingTable?: UserMappingTable;
relatedTable?: UserRelatedTable;
},
): ExtendedRelation {
if (relationship instanceof ExtendedRelation) {
relationship.relation_name = relationship.relation_name || RelationType.MEDIA.name;
} else {
relationship.relationType = RelationType.MEDIA;
}
return this.addRelationship(relationship);
}
/**
* Remove a specific relationship from the GeoPackage
* @param {module:extension/relatedTables~Relationship|module:extension/relatedTables~ExtendedRelation} relationship relationship to remove
* @return {Number} number of relationships removed
*/
removeRelationship(
relationship:
| ExtendedRelation
| {
relationType?: RelationType;
relationName?: string;
baseTableName?: string;
relatedTableName?: string;
relationAuthor?: string;
mappingTableName?: string;
userMappingTable?: string;
relatedTable?: UserRelatedTable;
},
): number {
let relationName: string;
let relatedTableName: string;
let baseTableName: string;
let userMappingTable: string;
if (relationship instanceof ExtendedRelation) {
relationName = relationship.relation_name;
relatedTableName = relationship.related_table_name;
baseTableName = relationship.base_table_name;
userMappingTable = relationship.mapping_table_name;
} else {
relationName = relationship.relationName;
relatedTableName = relationship.relatedTableName;
baseTableName = relationship.baseTableName;
userMappingTable = relationship.userMappingTable;
if (relationship.relationType) {
relationName = relationship.relationType.name;
}
if (relationship.relationAuthor) {
relationName = this.buildRelationName(relationship.relationAuthor, relationName);
}
}
if (this.extendedRelationDao.isTableExists()) {
const values = new ColumnValues();
values.addColumn(ExtendedRelationDao.COLUMN_BASE_TABLE_NAME, baseTableName);
values.addColumn(ExtendedRelationDao.COLUMN_RELATED_TABLE_NAME, relatedTableName);
values.addColumn(ExtendedRelationDao.COLUMN_RELATION_NAME, relationName);
const iterator = this.extendedRelationDao.queryForFieldValues(values);
const tablesToDelete: string[] = [];
const relationsToDelete: ExtendedRelation[] = [];
for (const extendedRelation of iterator) {
tablesToDelete.push(extendedRelation.mapping_table_name as string);
relationsToDelete.push((extendedRelation as unknown) as ExtendedRelation);
}
tablesToDelete.forEach(table => {
this.geoPackage.deleteTable(table);
});
this.extensionsDao.deleteByExtensionAndTableName(RelatedTablesExtension.EXTENSION_NAME, userMappingTable);
for (const extendedRelation of relationsToDelete) {
this.extendedRelationDao.delete(extendedRelation);
}
return tablesToDelete.length;
}
return 0;
}
/**
* Create a default user mapping table and extension row if either does not
* exist. When not created, there is no guarantee that an existing table has
* the same schema as the provided tabled.
* @param {string | UserMappingTable} userMappingTableOrName user mapping table or name
* @return {Promise<Boolean>}
*/
createUserMappingTable(userMappingTableOrName: UserMappingTable | string): boolean {
let umt;
if (userMappingTableOrName instanceof UserMappingTable) {
umt = userMappingTableOrName;
} else {
umt = UserMappingTable.create(userMappingTableOrName);
}
this.getOrCreateMappingTable(umt.getTableName());
if (!this.geoPackage.isTable(umt.getTableName())) {
return !!this.geoPackage.tableCreator.createUserTable(umt);
}
return true;
}
/**
* Create a user related table if it does not exist. When not created, there
* is no guarantee that an existing table has the same schema as the
* provided tabled.
* @param {module:extension/relatedTables~UserRelatedTable} relatedTable user related table
* @return {Boolean} true if the table now exists
*/
createRelatedTable(relatedTable: UserRelatedTable): boolean {
if (!this.geoPackage.isTable(relatedTable.getTableName())) {
this.geoPackage.tableCreator.createUserTable(relatedTable);
const contents = new Contents();
contents.table_name = relatedTable.getTableName();
contents.data_type = relatedTable.data_type;
contents.identifier = relatedTable.getTableName();
this.geoPackage.contentsDao.create(contents);
const refreshed = this.geoPackage.contentsDao.refresh(contents);
relatedTable.setContents(refreshed);
}
return true;
}
/**
* Validate that the relation name is valid between the base and related tables
* @param {string} baseTableName base table name
* @param {string} relatedTableName related table name
* @param {string} relationName relation name
* @return {Boolean}
*/
validateRelationship(baseTableName: string, relatedTableName: string, relationName: string): boolean {
// Verify the base and related tables exist
if (!this.geoPackage.isTable(baseTableName)) {
console.log('Base relationship table does not exist: ' + baseTableName + ', Relation: ' + relationName);
return false;
}
if (!this.geoPackage.isTable(relatedTableName)) {
console.log('Related relationship table does not exist: ' + relatedTableName + ', Relation: ' + relationName);
return false;
}
// Verify spec defined relation types
const relationType = RelationType.fromName(relationName);
if (relationType) {
if (!this.geoPackage.isTableType(relationType.dataType, relatedTableName)) {
console.log(
'The related table must be a ' +
relationType.dataType +
' table. Related Table: ' +
relatedTableName +
', Type: ' +
this.geoPackage.getTableType(relatedTableName),
);
return false;
}
return true;
}
return true;
}
/**
* Get the related id mappings for the base id
* @param {string} mappingTableName mapping table name
* @param {Number} baseId base id
* @return {Number[]} ids of related items
*/
getMappingsForBase(mappingTableName: string | ExtendedRelation, baseId: number): number[] {
const mappingDao = this.getMappingDao(mappingTableName);
const results = mappingDao.queryByBaseId(baseId);
const relatedIds = [];
for (let i = 0; i < results.length; i++) {
const row = mappingDao.getUserMappingRow(results[i]);
relatedIds.push(row.relatedId);
}
return relatedIds;
}
/**
* Get the related id mapping rows for the base id
* @param {string} mappingTableName mapping table name
* @param {Number} baseId base id
* @return {module:extension/relatedTables~UserMappingRow[]} user mapping rows
*/
getMappingRowsForBase(mappingTableName: string | ExtendedRelation, baseId: number): UserMappingRow[] {
const mappingDao = this.getMappingDao(mappingTableName);
const mappingRows: UserMappingRow[] = [];
const rows = mappingDao.queryByBaseId(baseId);
rows.forEach(row => {
mappingRows.push(mappingDao.getUserMappingRow(row));
});
return mappingRows;
}
/**
* Get the base id mappings for the base id
* @param {string} mappingTableName mapping table name
* @param {Number} relatedId related id
* @return {Number[]} ids of base items
*/
getMappingsForRelated(mappingTableName: string | ExtendedRelation, relatedId: number): number[] {
const mappingDao = this.getMappingDao(mappingTableName);
const results = mappingDao.queryByRelatedId(relatedId);
const baseIds = [];
for (let i = 0; i < results.length; i++) {
const row = mappingDao.getUserMappingRow(results[i]);
baseIds.push(row.baseId);
}
return baseIds;
}
/**
* Returns a {module:extension/relatedTables~MediaDao} from the table specified
* @param {string|MediaTable|ExtendedRelation} tableName either a table name or a MediaTable
* @return {module:extension/relatedTables~MediaDao}
*/
getMediaDao(tableName: string | MediaTable | ExtendedRelation): MediaDao<MediaRow> {
let table;
if (tableName instanceof MediaTable) {
table = tableName.getTableName();
} else if (tableName instanceof ExtendedRelation) {
table = tableName.related_table_name;
} else if (typeof tableName === 'string') {
table = tableName;
}
const reader = new UserCustomTableReader(table);
const userTable = reader.readTable(this.geoPackage.database);
table = new MediaTable(userTable.getTableName(), userTable.getUserColumns().getColumns(), MediaTable.requiredColumns());
table.setContents(this.geoPackage.contentsDao.queryForId(userTable.getTableName()));
return new MediaDao(this.geoPackage, table);
}
/**
* Returns a {module:extension/relatedTables~SimpleAttributesDao} from the table specified
* @param {string|SimpleAttributesTable|ExtendedRelation} tableName either a table name or a SimpleAttributesDao
* @return {module:extension/relatedTables~SimpleAttributesDao}
*/
getSimpleAttributesDao(
tableName: string | ExtendedRelation | SimpleAttributesTable,
): SimpleAttributesDao<SimpleAttributesRow> {
let table;
if (tableName instanceof SimpleAttributesTable && tableName.TABLE_TYPE === 'simple_attributes') {
table = tableName;
} else {
if (tableName instanceof ExtendedRelation) {
table = tableName.related_table_name;
}
const reader = new UserCustomTableReader(table);
const userTable = reader.readTable(this.geoPackage.database);
table = new SimpleAttributesTable(
userTable.getTableName(),
userTable.getUserColumns().getColumns(),
SimpleAttributesTable.requiredColumns(),
);
table.setContents(this.geoPackage.contentsDao.queryForId(table.getTableName()));
}
return new SimpleAttributesDao(this.geoPackage, table);
}
/**
* Builds the custom relation name with the author
* @param {string} author author
* @param {string} name name
* @return {string}
*/
buildRelationName(author: string, name: string): string {
return 'x-' + author + '_' + name;
}
/**
* Remove all traces of the extension
*/
removeExtension(): void {
if (this.extendedRelationDao.isTableExists()) {
const extendedRelations = this.extendedRelationDao.queryForAll();
extendedRelations.forEach(
function(relation: { mapping_table_name: string }): boolean {
return this.geoPackage.deleteTable(relation.mapping_table_name);
}.bind(this),
);
this.geoPackage.deleteTable(ExtendedRelationDao.TABLE_NAME);
}
if (this.extensionsDao.isTableExists()) {
this.extensionsDao.deleteByExtension(RelatedTablesExtension.EXTENSION_NAME);
}
}
/**
* Determine if the GeoPackage has the extension
* @param {String} [mappingTableName] mapping table name to check, if not specified, this checks for any mapping table name
* @return {Boolean}
*/
has(mappingTableName?: string): boolean {
if (mappingTableName) {
return (
this.hasExtension(RelatedTablesExtension.EXTENSION_NAME, ExtendedRelationDao.TABLE_NAME, null) &&
this.hasExtension(RelatedTablesExtension.EXTENSION_NAME, mappingTableName, null)
);
}
return this.hasExtension(RelatedTablesExtension.EXTENSION_NAME, ExtendedRelationDao.TABLE_NAME, null);
}
static RelationshipBuilder(): any {
return OptionBuilder.build([
'baseTableName',
'relatedTableName',
'userMappingTable',
'mappingTableName',
'relationName',
'relationAuthor',
'relationType',
'relatedTable',
]);
}
removeRelationships(table: string) {
try {
if (this.extendedRelationDao.isTableExists()) {
let extendedRelations = this.extendedRelationDao.getTableRelations(table);
extendedRelations.forEach(extendedRelation => {
this.removeRelationship(extendedRelation);
});
}
} catch (e) {
throw new Error("Failed to remove relationships for table: " + table);
}
}
} | the_stack |
import {
AfterContentInit,
ChangeDetectorRef,
ContentChildren,
Directive,
ElementRef,
forwardRef,
inject,
InjectFlags,
Input,
OnDestroy,
Output,
QueryList,
} from '@angular/core';
import {ActiveDescendantKeyManager, Highlightable, ListKeyManagerOption} from '@angular/cdk/a11y';
import {DOWN_ARROW, ENTER, LEFT_ARROW, RIGHT_ARROW, SPACE, UP_ARROW} from '@angular/cdk/keycodes';
import {BooleanInput, coerceArray, coerceBooleanProperty} from '@angular/cdk/coercion';
import {SelectionModel} from '@angular/cdk/collections';
import {BehaviorSubject, combineLatest, defer, merge, Observable, Subject} from 'rxjs';
import {filter, mapTo, startWith, switchMap, take, takeUntil} from 'rxjs/operators';
import {
AbstractControl,
ControlValueAccessor,
NG_VALIDATORS,
NG_VALUE_ACCESSOR,
ValidationErrors,
Validator,
ValidatorFn,
Validators,
} from '@angular/forms';
import {Directionality} from '@angular/cdk/bidi';
import {CdkCombobox} from '@angular/cdk-experimental/combobox';
/** The next id to use for creating unique DOM IDs. */
let nextId = 0;
// TODO(mmalerba):
// - should listbox wrap be configurable?
// - should skipping disabled options be configurable?
/** A selectable option in a listbox. */
@Directive({
selector: '[cdkOption]',
exportAs: 'cdkOption',
host: {
'role': 'option',
'class': 'cdk-option',
'[id]': 'id',
'[attr.aria-selected]': 'isSelected() || null',
'[attr.tabindex]': '_getTabIndex()',
'[attr.aria-disabled]': 'disabled',
'[class.cdk-option-disabled]': 'disabled',
'[class.cdk-option-active]': 'isActive()',
'[class.cdk-option-selected]': 'isSelected()',
'(click)': '_clicked.next()',
'(focus)': '_handleFocus()',
},
})
export class CdkOption<T = unknown> implements ListKeyManagerOption, Highlightable, OnDestroy {
/** The id of the option's host element. */
@Input()
get id() {
return this._id || this._generatedId;
}
set id(value) {
this._id = value;
}
private _id: string;
private _generatedId = `cdk-option-${nextId++}`;
/** The value of this option. */
@Input('cdkOption') value: T;
/**
* The text used to locate this item during listbox typeahead. If not specified,
* the `textContent` of the item will be used.
*/
@Input('cdkOptionTypeaheadLabel') typeaheadLabel: string;
/** Whether this option is disabled. */
@Input('cdkOptionDisabled')
get disabled(): boolean {
return this.listbox.disabled || this._disabled;
}
set disabled(value: BooleanInput) {
this._disabled = coerceBooleanProperty(value);
}
private _disabled: boolean = false;
/** The tabindex of the option when it is enabled. */
@Input('tabindex')
get enabledTabIndex() {
return this._enabledTabIndex === undefined
? this.listbox.enabledTabIndex
: this._enabledTabIndex;
}
set enabledTabIndex(value) {
this._enabledTabIndex = value;
}
private _enabledTabIndex?: number | null;
/** The option's host element */
readonly element: HTMLElement = inject(ElementRef).nativeElement;
/** The parent listbox this option belongs to. */
protected readonly listbox: CdkListbox<T> = inject(CdkListbox);
/** Emits when the option is destroyed. */
protected destroyed = new Subject<void>();
/** Emits when the option is clicked. */
readonly _clicked = new Subject<void>();
/** Whether the option is currently active. */
private _active = false;
ngOnDestroy() {
this.destroyed.next();
this.destroyed.complete();
}
/** Whether this option is selected. */
isSelected() {
return this.listbox.isSelected(this.value);
}
/** Whether this option is active. */
isActive() {
return this._active;
}
/** Toggle the selected state of this option. */
toggle() {
this.listbox.toggle(this);
}
/** Select this option if it is not selected. */
select() {
this.listbox.select(this);
}
/** Deselect this option if it is selected. */
deselect() {
this.listbox.deselect(this);
}
/** Focus this option. */
focus() {
this.element.focus();
}
/** Get the label for this element which is required by the FocusableOption interface. */
getLabel() {
return (this.typeaheadLabel ?? this.element.textContent?.trim()) || '';
}
/**
* Set the option as active.
* @docs-private
*/
setActiveStyles() {
this._active = true;
}
/**
* Set the option as inactive.
* @docs-private
*/
setInactiveStyles() {
this._active = false;
}
/** Handle focus events on the option. */
protected _handleFocus() {
// Options can wind up getting focused in active descendant mode if the user clicks on them.
// In this case, we push focus back to the parent listbox to prevent an extra tab stop when
// the user performs a shift+tab.
if (this.listbox.useActiveDescendant) {
this.listbox._setActiveOption(this);
this.listbox.focus();
}
}
/** Get the tabindex for this option. */
protected _getTabIndex() {
if (this.listbox.useActiveDescendant || this.disabled) {
return -1;
}
return this.isActive() ? this.enabledTabIndex : -1;
}
}
@Directive({
selector: '[cdkListbox]',
exportAs: 'cdkListbox',
host: {
'role': 'listbox',
'class': 'cdk-listbox',
'[id]': 'id',
'[attr.tabindex]': '_getTabIndex()',
'[attr.aria-disabled]': 'disabled',
'[attr.aria-multiselectable]': 'multiple',
'[attr.aria-activedescendant]': '_getAriaActiveDescendant()',
'[attr.aria-orientation]': 'orientation',
'(focus)': '_handleFocus()',
'(keydown)': '_handleKeydown($event)',
'(focusout)': '_handleFocusOut($event)',
},
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CdkListbox),
multi: true,
},
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => CdkListbox),
multi: true,
},
],
})
export class CdkListbox<T = unknown>
implements AfterContentInit, OnDestroy, ControlValueAccessor, Validator
{
/** The id of the option's host element. */
@Input()
get id() {
return this._id || this._generatedId;
}
set id(value) {
this._id = value;
}
private _id: string;
private _generatedId = `cdk-listbox-${nextId++}`;
/** The tabindex to use when the listbox is enabled. */
@Input('tabindex')
get enabledTabIndex() {
return this._enabledTabIndex === undefined ? 0 : this._enabledTabIndex;
}
set enabledTabIndex(value) {
this._enabledTabIndex = value;
}
private _enabledTabIndex?: number | null;
/** The value selected in the listbox, represented as an array of option values. */
@Input('cdkListboxValue')
get value(): readonly T[] {
return this.selectionModel().selected;
}
set value(value: readonly T[]) {
this._setSelection(value);
}
/**
* Whether the listbox allows multiple options to be selected. If the value switches from `true`
* to `false`, and more than one option is selected, all options are deselected.
*/
@Input('cdkListboxMultiple')
get multiple(): boolean {
return this._multiple;
}
set multiple(value: BooleanInput) {
this._multiple = coerceBooleanProperty(value);
this._updateSelectionModel();
this._onValidatorChange();
}
private _multiple: boolean = false;
/** Whether the listbox is disabled. */
@Input('cdkListboxDisabled')
get disabled(): boolean {
return this._disabled;
}
set disabled(value: BooleanInput) {
this._disabled = coerceBooleanProperty(value);
}
private _disabled: boolean = false;
/** Whether the listbox will use active descendant or will move focus onto the options. */
@Input('cdkListboxUseActiveDescendant')
get useActiveDescendant(): boolean {
return this._useActiveDescendant;
}
set useActiveDescendant(shouldUseActiveDescendant: BooleanInput) {
this._useActiveDescendant = coerceBooleanProperty(shouldUseActiveDescendant);
}
private _useActiveDescendant: boolean = false;
/** The orientation of the listbox. Only affects keyboard interaction, not visual layout. */
@Input('cdkListboxOrientation') orientation: 'horizontal' | 'vertical' = 'vertical';
/** The function used to compare option values. */
@Input('cdkListboxCompareWith')
get compareWith(): undefined | ((o1: T, o2: T) => boolean) {
return this._compareWith;
}
set compareWith(fn: undefined | ((o1: T, o2: T) => boolean)) {
this._compareWith = fn;
this._updateSelectionModel();
}
private _compareWith?: (o1: T, o2: T) => boolean;
/** Emits when the selected value(s) in the listbox change. */
@Output('cdkListboxValueChange') readonly valueChange = new Subject<ListboxValueChangeEvent<T>>();
/** The child options in this listbox. */
@ContentChildren(CdkOption, {descendants: true}) protected options: QueryList<CdkOption<T>>;
// TODO(mmalerba): Refactor SelectionModel so that its not necessary to create new instances
/** The selection model used by the listbox. */
protected selectionModelSubject = new BehaviorSubject(
new SelectionModel<T>(this.multiple, [], true, this._compareWith),
);
/** The key manager that manages keyboard navigation for this listbox. */
protected listKeyManager: ActiveDescendantKeyManager<CdkOption<T>>;
/** Emits when the listbox is destroyed. */
protected readonly destroyed = new Subject<void>();
/** The host element of the listbox. */
protected readonly element: HTMLElement = inject(ElementRef).nativeElement;
/** The change detector for this listbox. */
protected readonly changeDetectorRef = inject(ChangeDetectorRef);
/** Callback called when the listbox has been touched */
private _onTouched = () => {};
/** Callback called when the listbox value changes */
private _onChange: (value: readonly T[]) => void = () => {};
/** Callback called when the form validator changes. */
private _onValidatorChange = () => {};
/** Emits when an option has been clicked. */
private _optionClicked = defer(() =>
(this.options.changes as Observable<CdkOption<T>[]>).pipe(
startWith(this.options),
switchMap(options => merge(...options.map(option => option._clicked.pipe(mapTo(option))))),
),
);
/** The directionality of the page. */
private readonly _dir = inject(Directionality, InjectFlags.Optional);
// TODO(mmalerba): Should not depend on combobox
private readonly _combobox = inject(CdkCombobox, InjectFlags.Optional);
/**
* Validator that produces an error if multiple values are selected in a single selection
* listbox.
* @param control The control to validate
* @return A validation error or null
*/
private _validateMultipleValues: ValidatorFn = (control: AbstractControl) => {
const controlValue = this._coerceValue(control.value);
if (!this.multiple && controlValue.length > 1) {
return {'cdkListboxMultipleValues': true};
}
return null;
};
/**
* Validator that produces an error if any selected values are not valid options for this listbox.
* @param control The control to validate
* @return A validation error or null
*/
private _validateInvalidValues: ValidatorFn = (control: AbstractControl) => {
const controlValue = this._coerceValue(control.value);
const invalidValues = this._getValuesWithValidity(controlValue, false);
if (invalidValues.length) {
return {'cdkListboxInvalidValues': {'values': invalidValues}};
}
return null;
};
/** The combined set of validators for this listbox. */
private _validators = Validators.compose([
this._validateMultipleValues,
this._validateInvalidValues,
])!;
constructor() {
this.selectionModelSubject
.pipe(
switchMap(selectionModel => selectionModel.changed),
takeUntil(this.destroyed),
)
.subscribe(() => {
this._updateInternalValue();
});
}
ngAfterContentInit() {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
this._verifyNoOptionValueCollisions();
}
this._initKeyManager();
this._combobox?._registerContent(this.id, 'listbox');
this.options.changes.pipe(takeUntil(this.destroyed)).subscribe(() => {
this._updateInternalValue();
this._onValidatorChange();
});
this._optionClicked
.pipe(
filter(option => !option.disabled),
takeUntil(this.destroyed),
)
.subscribe(option => this._handleOptionClicked(option));
}
ngOnDestroy() {
this.listKeyManager.change.complete();
this.destroyed.next();
this.destroyed.complete();
}
/**
* Toggle the selected state of the given option.
* @param option The option to toggle
*/
toggle(option: CdkOption<T>) {
this.toggleValue(option.value);
}
/**
* Toggle the selected state of the given value.
* @param value The value to toggle
*/
toggleValue(value: T) {
this.selectionModel().toggle(value);
}
/**
* Select the given option.
* @param option The option to select
*/
select(option: CdkOption<T>) {
this.selectValue(option.value);
}
/**
* Select the given value.
* @param value The value to select
*/
selectValue(value: T) {
this.selectionModel().select(value);
}
/**
* Deselect the given option.
* @param option The option to deselect
*/
deselect(option: CdkOption<T>) {
this.deselectValue(option.value);
}
/**
* Deselect the given value.
* @param value The value to deselect
*/
deselectValue(value: T) {
this.selectionModel().deselect(value);
}
/**
* Set the selected state of all options.
* @param isSelected The new selected state to set
*/
setAllSelected(isSelected: boolean) {
if (!isSelected) {
this.selectionModel().clear();
} else {
this.selectionModel().select(...this.options.toArray().map(option => option.value));
}
}
/**
* Get whether the given option is selected.
* @param option The option to get the selected state of
*/
isSelected(option: CdkOption<T> | T) {
return this.selectionModel().isSelected(option instanceof CdkOption ? option.value : option);
}
/**
* Registers a callback to be invoked when the listbox's value changes from user input.
* @param fn The callback to register
* @docs-private
*/
registerOnChange(fn: (value: readonly T[]) => void): void {
this._onChange = fn;
}
/**
* Registers a callback to be invoked when the listbox is blurred by the user.
* @param fn The callback to register
* @docs-private
*/
registerOnTouched(fn: () => {}): void {
this._onTouched = fn;
}
/**
* Sets the listbox's value.
* @param value The new value of the listbox
* @docs-private
*/
writeValue(value: readonly T[]): void {
this._setSelection(value);
}
/**
* Sets the disabled state of the listbox.
* @param isDisabled The new disabled state
* @docs-private
*/
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
/**
* Validate the given control
* @docs-private
*/
validate(control: AbstractControl<any, any>): ValidationErrors | null {
return this._validators(control);
}
/**
* Registers a callback to be called when the form validator changes.
* @param fn The callback to call
* @docs-private
*/
registerOnValidatorChange(fn: () => void) {
this._onValidatorChange = fn;
}
/** Focus the listbox's host element. */
focus() {
this.element.focus();
}
/** The selection model used to track the listbox's value. */
protected selectionModel() {
return this.selectionModelSubject.value;
}
/**
* Triggers the given option in response to user interaction.
* - In single selection mode: selects the option and deselects any other selected option.
* - In multi selection mode: toggles the selected state of the option.
* @param option The option to trigger
*/
protected triggerOption(option: CdkOption<T> | null) {
if (option && !option.disabled) {
let changed = false;
this.selectionModel()
.changed.pipe(take(1), takeUntil(this.destroyed))
.subscribe(() => (changed = true));
if (this.multiple) {
this.toggle(option);
} else {
this.select(option);
}
if (changed) {
this._onChange(this.value);
this.valueChange.next({
value: this.value,
listbox: this,
option: option,
});
}
}
}
/**
* Sets the given option as active.
* @param option The option to make active
*/
_setActiveOption(option: CdkOption<T>) {
this.listKeyManager.setActiveItem(option);
}
/** Called when the listbox receives focus. */
protected _handleFocus() {
if (!this.useActiveDescendant) {
this.listKeyManager.setNextItemActive();
this._focusActiveOption();
}
}
/** Called when the user presses keydown on the listbox. */
protected _handleKeydown(event: KeyboardEvent) {
if (this._disabled) {
return;
}
const {keyCode} = event;
const previousActiveIndex = this.listKeyManager.activeItemIndex;
if (keyCode === SPACE || keyCode === ENTER) {
this.triggerOption(this.listKeyManager.activeItem);
event.preventDefault();
} else {
this.listKeyManager.onKeydown(event);
}
/** Will select an option if shift was pressed while navigating to the option */
const isArrow =
keyCode === UP_ARROW ||
keyCode === DOWN_ARROW ||
keyCode === LEFT_ARROW ||
keyCode === RIGHT_ARROW;
if (isArrow && event.shiftKey && previousActiveIndex !== this.listKeyManager.activeItemIndex) {
this.triggerOption(this.listKeyManager.activeItem);
}
}
/**
* Called when the focus leaves an element in the listbox.
* @param event The focusout event
*/
protected _handleFocusOut(event: FocusEvent) {
const otherElement = event.relatedTarget as Element;
if (this.element !== otherElement && !this.element.contains(otherElement)) {
this._onTouched();
}
}
/** Get the id of the active option if active descendant is being used. */
protected _getAriaActiveDescendant(): string | null | undefined {
return this._useActiveDescendant ? this.listKeyManager?.activeItem?.id : null;
}
/** Get the tabindex for the listbox. */
protected _getTabIndex() {
if (this.disabled) {
return -1;
}
return this.useActiveDescendant || !this.listKeyManager.activeItem ? this.enabledTabIndex : -1;
}
/** Initialize the key manager. */
private _initKeyManager() {
this.listKeyManager = new ActiveDescendantKeyManager(this.options)
.withWrap()
.withTypeAhead()
.withHomeAndEnd()
.withAllowedModifierKeys(['shiftKey']);
if (this.orientation === 'vertical') {
this.listKeyManager.withVerticalOrientation();
} else {
this.listKeyManager.withHorizontalOrientation(this._dir?.value || 'ltr');
}
this.listKeyManager.change
.pipe(takeUntil(this.destroyed))
.subscribe(() => this._focusActiveOption());
}
// TODO(mmalerba): Should not depend on combobox.
private _updatePanelForSelection(option: CdkOption<T>) {
if (this._combobox) {
if (!this.multiple) {
this._combobox.updateAndClose(option.isSelected() ? option.value : []);
} else {
this._combobox.updateAndClose(this.value);
}
}
}
/** Update the selection mode when the 'multiple' property changes. */
private _updateSelectionModel() {
this.selectionModelSubject.next(
new SelectionModel(
this.multiple,
!this.multiple && this.value.length > 1 ? [] : this.value.slice(),
true,
this._compareWith,
),
);
}
/** Focus the active option. */
private _focusActiveOption() {
if (!this.useActiveDescendant) {
this.listKeyManager.activeItem?.focus();
}
this.changeDetectorRef.markForCheck();
}
/**
* Set the selected values.
* @param value The list of new selected values.
*/
private _setSelection(value: readonly T[]) {
const coercedValue = this._coerceValue(value);
this.selectionModel().setSelection(
...(!this.multiple && coercedValue.length > 1
? []
: this._getValuesWithValidity(coercedValue, true)),
);
}
/** Update the internal value of the listbox based on the selection model. */
private _updateInternalValue() {
const indexCache = new Map<T, number>();
// Check if we need to remove any values due to them becoming invalid
// (e.g. if the option was removed from the DOM.)
const selected = this.selectionModel().selected;
const validSelected = this._getValuesWithValidity(selected, true);
if (validSelected.length != selected.length) {
this.selectionModel().setSelection(...validSelected);
}
this.selectionModel().sort((a: T, b: T) => {
const aIndex = this._getIndexForValue(indexCache, a);
const bIndex = this._getIndexForValue(indexCache, b);
return aIndex - bIndex;
});
this.changeDetectorRef.markForCheck();
}
/**
* Gets the index of the given value in the given list of options.
* @param cache The cache of indices found so far
* @param value The value to find
* @return The index of the value in the options list
*/
private _getIndexForValue(cache: Map<T, number>, value: T) {
const isEqual = this.compareWith || Object.is;
if (!cache.has(value)) {
let index = -1;
for (let i = 0; i < this.options.length; i++) {
if (isEqual(value, this.options.get(i)!.value)) {
index = i;
break;
}
}
cache.set(value, index);
}
return cache.get(value)!;
}
/**
* Handle the user clicking an option.
* @param option The option that was clicked.
*/
private _handleOptionClicked(option: CdkOption<T>) {
this.listKeyManager.setActiveItem(option);
this.triggerOption(option);
this._updatePanelForSelection(option);
}
/** Verifies that no two options represent the same value under the compareWith function. */
private _verifyNoOptionValueCollisions() {
combineLatest([
this.selectionModelSubject,
this.options.changes.pipe(startWith(this.options)),
]).subscribe(() => {
const isEqual = this.compareWith ?? Object.is;
for (let i = 0; i < this.options.length; i++) {
const option = this.options.get(i)!;
let duplicate: CdkOption<T> | null = null;
for (let j = i + 1; j < this.options.length; j++) {
const other = this.options.get(j)!;
if (isEqual(option.value, other.value)) {
duplicate = other;
break;
}
}
if (duplicate) {
// TODO(mmalerba): Link to docs about this.
if (this.compareWith) {
console.warn(
`Found multiple CdkOption representing the same value under the given compareWith function`,
{
option1: option.element,
option2: duplicate.element,
compareWith: this.compareWith,
},
);
} else {
console.warn(`Found multiple CdkOption with the same value`, {
option1: option.element,
option2: duplicate.element,
});
}
return;
}
}
});
}
/**
* Coerces a value into an array representing a listbox selection.
* @param value The value to coerce
* @return An array
*/
private _coerceValue(value: readonly T[]) {
return value == null ? [] : coerceArray(value);
}
/**
* Get the sublist of values with the given validity.
* @param values The list of values
* @param valid Whether to get valid values
* @return The sublist of values with the requested validity
*/
private _getValuesWithValidity(values: readonly T[], valid: boolean) {
const isEqual = this.compareWith || Object.is;
const validValues = (this.options || []).map(option => option.value);
return values.filter(
value => valid === validValues.some(validValue => isEqual(value, validValue)),
);
}
}
/** Change event that is fired whenever the value of the listbox changes. */
export interface ListboxValueChangeEvent<T> {
/** The new value of the listbox. */
readonly value: readonly T[];
/** Reference to the listbox that emitted the event. */
readonly listbox: CdkListbox<T>;
/** Reference to the option that was triggered. */
readonly option: CdkOption<T>;
} | the_stack |
import autocomplete from "autocompleter";
import {parseYaml} from "obsidian";
/**
*
* @param input_element
* @param autocomplete_items
* @param call_on_completion A function that will be called when a user has selected a suggestion and performed the autocomplete action. onChange event will not be called, because it would trigger opening the autocomplete menu again, so that's why a separate callback is used.
*/
export function createAutocomplete(input_element: HTMLInputElement, autocomplete_items: IAutocompleteItem[], call_on_completion: (field_value: string) => void) {
autocomplete_items = merge_and_sort_autocomplete_items(autocomplete_items, CustomAutocompleteItems);
autocomplete<IAutocompleteItem>({
input: input_element,
fetch: (input_value_but_not_used: string, update: (items: IAutocompleteItem[]) => void) => {
const max_suggestions = 30;
// Get the so far typed text - exclude everything that is on the right side of the caret.
let caret_position = input_element.selectionStart;
const typed_text = input_element.value.slice(0, caret_position);
const search_query = get_search_query(typed_text);
if ("" === search_query.search_text) {
// No suggestions for empty word.
update([]);
} else {
// The word is not empty, so can suggest something.
let matched_items = autocomplete_items.filter(item => item_match(item, search_query));
matched_items = matched_items.slice(0, max_suggestions); // Limit to a reasonable amount of suggestions.
update(matched_items);
}
},
onSelect: (item) => {
// A user has selected an item to be autocompleted
// Get the item text and already typed text
let supplement = item.value;
let caret_position = input_element.selectionStart;
const typed_text = input_element.value.slice(0, caret_position);
const search_query = get_search_query(typed_text);
const search_text = search_query.search_text;
// Special case: Check if }} happens to appear after the caret
const after_caret = input_element.value.slice(caret_position, caret_position + 2);
if ("}}" === after_caret) {
// The replacing will happen in a {{variable}}.
// Do not accidentally insert another }} pair.
supplement = supplement.replace(/}}$/, ""); // Only removes a trailing }} if there is one.
}
// Try to save part of the beginning, in case it seems like not being part of the search query.
let replace_start = find_starting_position(search_text, supplement); // The length difference of typed_text and search_text will be added here below.
if (false === replace_start) {
// This should never happen, but if it does, do not replace anything, just insert.
replace_start = caret_position;
} else {
// Adjust the position
replace_start += typed_text.length - search_text.length;
}
// Choose a method for doing the inserting
if (undefined !== document.execCommand) {
// execCommand() is deprecated, but available.
// Use it to do the insertion, because this way an undo history can be preserved.
input_element.setSelectionRange(replace_start, caret_position); // First select the part that will be replaced, because execCommand() does not support defining positions. This adds a cumbersome selection step to the undo history, but at least undoing works.
document.execCommand("insertText", false, supplement);
} else {
// execCommand() is not available anymore.
// Use setRangeText() to do the insertion. It will clear undo history, but at least the insertion works.
input_element.setRangeText(supplement, replace_start, caret_position);
}
// Move the caret to a logical continuation point
caret_position = replace_start + supplement.length;
if (supplement.match(/:}}$/)) {
// Place the caret after the colon, instead of after }}.
caret_position -= 2;
}
input_element.setSelectionRange(caret_position, caret_position);
// Call a hook
call_on_completion(input_element.value);
},
render: (item) => {
const div_element = document.createElement("div");
div_element.createSpan({text: item.value, attr: {class: "SC-autocomplete-value"}});
div_element.createSpan({text: ": ", attr: {class: "SC-autocomplete-separator"}});
div_element.createSpan({text: item.help_text, attr: {class: "SC-autocomplete-help-text"}});
return div_element;
},
minLength: 2, // Minimum length when autocomplete menu should pop up.
className: "SC-autocomplete", // The component always has a class 'autocomplete', but add 'SC-autocomplete' so that SC's CSS can target 'SC-autocomplete', so it will not mess up stuff if Obsidian happens to have an element with class 'autocomplete'.
keysToIgnore: [ 38 /* Up */, 13 /* Enter */, 27 /* Esc */, 16 /* Shift */, 17 /* Ctrl */, 18 /* Alt */, 20 /* CapsLock */, 91 /* WindowsKey */, 9 /* Tab */ ] // Defined just to prevent ignoring left and right keys.
});
}
export interface IAutocompleteItem {
help_text: string;
value: string;
group: string;
type: AutocompleteSearchQueryType;
}
function item_match(item: IAutocompleteItem, search_query: IAutocompleteSearchQuery): boolean {
const item_value = item.value.toLocaleLowerCase();
const search_text = search_query.search_text.toLocaleLowerCase();
// Match query type
if (item.type !== search_query.search_type) {
// If the query type is different, do not include this item.
// This can happen e.g. if {{ is typed, and the item is not a variable, or {{! is typed, and the item is not an unescaped variable.
return false;
}
// Match text
let search_character: string;
let search_position = 0;
for (let search_character_index = 0; search_character_index < search_text.length; search_character_index++) {
search_character = search_text[search_character_index];
if (item_value.includes(search_character, search_position)) {
// This character was found in item_value.
search_position = item_value.indexOf(search_character, search_position) + 1;
} else {
// This character was not found.
return false;
}
}
return true;
}
function find_starting_position(typed_text: string, supplement: string) {
typed_text = typed_text.toLocaleLowerCase();
supplement = supplement.toLocaleLowerCase();
for (let supplement_index = supplement.length; supplement_index >= 0; supplement_index--) {
let partial_supplement = supplement.slice(0, supplement_index);
if (typed_text.contains(partial_supplement)) {
return typed_text.indexOf(partial_supplement);
}
}
return false;
}
const CustomAutocompleteItems: IAutocompleteItem[] = [];
export function addCustomAutocompleteItems(custom_autocomplete_yaml: string) {
// Ensure the content is not empty
if (0 === custom_autocomplete_yaml.trim().length) {
return "The content is empty.";
}
// Try to parse YAML syntax
let yaml: any;
try {
yaml = parseYaml(custom_autocomplete_yaml);
} catch (error) {
// A syntax error has appeared.
return error.message;
}
if (null === yaml || typeof yaml !== "object") {
return "Unable to parse the content due to unknown reason."
}
// Iterate autocomplete item groups
const group_names = Object.getOwnPropertyNames(yaml);
group_names.forEach((group_name: string) => {
const group_items = yaml[group_name];
const group_item_values = Object.getOwnPropertyNames(group_items);
// Iterate all autocomplete items in the group
group_item_values.forEach((autocomplete_item_value: string) => {
const autocomplete_item_label = group_items[autocomplete_item_value];
if (typeof autocomplete_item_label !== "string") {
return "Autocomplete item '" + autocomplete_item_value + "' has an incorrect help text type: " + typeof autocomplete_item_label;
}
// Determine a correct type for the item
let type: AutocompleteSearchQueryType = "other";
if (autocomplete_item_value.startsWith("{{")) {
// This is a variable
type = "normal-variable";
}
// The item is ok, add it to the list
CustomAutocompleteItems.push({
value: autocomplete_item_value,
help_text: autocomplete_item_label,
group: group_name,
type: type,
});
if (type === "normal-variable") {
// Add an unescaped version of the variable, too
CustomAutocompleteItems.push({
value: autocomplete_item_value.replace(/^{{/, "{{!"), // Add an exclamation mark to the variable name.
help_text: autocomplete_item_label,
group: group_name,
type: "unescaped-variable",
});
}
});
});
// All ok
return true;
}
function merge_and_sort_autocomplete_items(...autocomplete_item_sets: IAutocompleteItem[][]) {
const merged_autocomplete_items: IAutocompleteItem[] = [].concat(...autocomplete_item_sets);
return merged_autocomplete_items.sort((a, b) => {
// First compare groups
if (a.group < b.group) {
// a's group should come before b's group.
return -1;
} else if (a.group > b.group) {
// a's group should come after b's group.
return 1;
} else {
// The groups are the same.
// Compare values.
if (a.value < b.value) {
// a should come before b.
return -1;
} else if (a.value > b.value) {
// a should come after b.
return 1;
} else {
// The values are the same.
// The order does not matter.
return 0;
}
}
});
}
type AutocompleteSearchQueryType = "other" | "normal-variable" | "unescaped-variable";
interface IAutocompleteSearchQuery {
search_text: string;
search_type: AutocompleteSearchQueryType;
}
/**
* Reduces an input string to the nearest logical word.
* @param typed_text
*/
function get_search_query(typed_text: string): IAutocompleteSearchQuery {
let search_text = typed_text.match(/\S*?$/)[0]; // Reduce the text - limit to a single word (= exclude spaces and everything before them).
let search_type: AutocompleteSearchQueryType = "other"; // May be overwritten.
if (search_text.contains("}}")) {
// The query happens right after a {{variable}}.
// Make the query string to start after the }} pair, i.e. remove }} and everything before it. This improves the search.
search_text = search_text.replace(/.+}}/, "");
}
if (search_text.contains("{{")) {
// A {{variable}} is being queried.
// Make the query string to start from the {{ pair, i.e. remove everything before {{ . This improves the search.
search_text = search_text.replace(/.+{{/, "{{");
if (search_text.contains("{{!")) {
// An _unescaped_ variable is searched for.
search_type = "unescaped-variable";
} else {
// A normal variable is searched for.
search_type = "normal-variable";
}
}
return {
search_text: search_text,
search_type: search_type,
};
} | the_stack |
import * as vscode from "vscode";
import {PluginTreeItem, Resource, CustomResource, ContextValueTypes, Utils} from "../../../runtime";
import {getSkillDetailsFromWorkspace, SkillDetailsType, getHostedSkillMetadata} from "../../../utils/skillHelper";
import {EN_US_LOCALE, SKILL_ACTION_URLS, SKILL_ACTION_ITEMS, SKILL_NOT_DEPLOYED_MSG} from "../../../constants";
import {onWorkspaceOpenEventEmitter} from "../../events";
import {SkillActionsView} from "../skillActionsView";
import {Logger} from "../../../logger";
import {getSkillFolderInWs} from "../../../utils/workspaceHelper";
import {EXTENSION_COMMAND_CONFIG} from "../../../aplContainer/config/configuration";
import {ActionType} from "../../../runtime/lib/telemetry";
function getIModelGeneratorLink(skillId: string, locale?: string): string {
Logger.verbose(`Calling method: ${SkillActionsViewProvider.name}.getIModelGeneratorLink`);
locale = locale ?? EN_US_LOCALE.replace("-", "_");
return SKILL_ACTION_URLS.IMODEL_EDITOR(skillId, locale);
}
export class SkillActionsViewProvider implements vscode.TreeDataProvider<PluginTreeItem<Resource>> {
readonly onDidChangeTreeData = onWorkspaceOpenEventEmitter.event;
readonly treeView: SkillActionsView;
constructor(view: SkillActionsView) {
this.treeView = view;
}
getTreeItem(element: PluginTreeItem<Resource>): vscode.TreeItem | Thenable<vscode.TreeItem> {
Logger.debug(`Calling method: ${SkillActionsViewProvider.name}.getTreeItem`);
return element;
}
async getChildren(element?: PluginTreeItem<Resource>): Promise<Array<PluginTreeItem<Resource>>> {
Logger.debug(`Calling method: ${SkillActionsViewProvider.name}.getChildren`);
const treeItems: Array<PluginTreeItem<Resource>> = [];
const skillFolder = getSkillFolderInWs(this.treeView.extensionContext);
if (skillFolder) {
const skillDetails = getSkillDetailsFromWorkspace(this.treeView.extensionContext);
const skillName: string = skillDetails.skillName;
const skillId: string = skillDetails.skillId;
if (!element) {
if (!Utils.isNonBlankString(skillId)) {
Logger.info(SKILL_NOT_DEPLOYED_MSG);
void vscode.window.showWarningMessage(SKILL_NOT_DEPLOYED_MSG);
}
treeItems.push(
new PluginTreeItem<Resource>(
skillName,
null,
vscode.TreeItemCollapsibleState.Expanded,
undefined,
undefined,
ContextValueTypes.SKILL,
),
);
} else if (element.label === skillName) {
await this.addSkillActionResources(treeItems, skillDetails);
} else if (element.label === SKILL_ACTION_ITEMS.MANIFEST.LABEL) {
this.addManifestResources(treeItems, skillFolder);
} else if (element.label === SKILL_ACTION_ITEMS.IM.LABEL) {
this.addIModelResources(treeItems, skillFolder, skillDetails);
} else if (element.label === SKILL_ACTION_ITEMS.ALEXA_PRESENTATION_LANGUAGE.LABEL) {
this.addAplRendererResources(treeItems, skillFolder, skillDetails);
} else if (element.label === SKILL_ACTION_ITEMS.TEST.LABEL) {
this.addTestResources(treeItems, skillFolder, skillDetails);
}
} else {
Logger.error(`Method: ${SkillActionsViewProvider.name}.getChildren failure`);
// This view should technically be invisible
// But instead of setting the context, adding a view item to select a skill
treeItems.push(
new PluginTreeItem<CustomResource>(
"Select a skill",
null,
vscode.TreeItemCollapsibleState.None,
{
title: "openWorkspace",
command: "ask.container.openWorkspace",
},
undefined,
ContextValueTypes.SKILL,
),
);
}
return treeItems;
}
/**
* Function to add skill actions under skill tree item
*
* @private
* @param {Array<PluginTreeItem<Resource>>} treeItemsArray - tree items
* @param {SkillDetailsType} skillDetails - Skill information
* @returns {Array<PluginTreeItem<Resource>>} - updated tree items
*
* @memberOf SkillActionsViewProvider
*/
private async addSkillActionResources(
treeItemsArray: Array<PluginTreeItem<Resource>>,
skillDetails: SkillDetailsType,
): Promise<Array<PluginTreeItem<Resource>>> {
const skillId: string = skillDetails.skillId;
if (Utils.isNonBlankString(skillId)) {
treeItemsArray.push(
new PluginTreeItem<Resource>(
SKILL_ACTION_ITEMS.MANIFEST.LABEL,
null,
vscode.TreeItemCollapsibleState.Collapsed,
undefined,
undefined,
ContextValueTypes.SKILL,
),
);
treeItemsArray.push(
new PluginTreeItem<Resource>(
SKILL_ACTION_ITEMS.IM.LABEL,
null,
vscode.TreeItemCollapsibleState.Collapsed,
undefined,
undefined,
ContextValueTypes.SKILL,
),
);
}
treeItemsArray.push(
new PluginTreeItem<Resource>(
SKILL_ACTION_ITEMS.ALEXA_PRESENTATION_LANGUAGE.LABEL,
null,
vscode.TreeItemCollapsibleState.Collapsed,
undefined,
undefined,
ContextValueTypes.SKILL,
),
);
if (Utils.isNonBlankString(skillId)) {
const hostedMetadata = await getHostedSkillMetadata(skillId, this.treeView.extensionContext);
if (hostedMetadata !== undefined) {
treeItemsArray.push(
new PluginTreeItem<Resource>(
SKILL_ACTION_ITEMS.DEPLOY.LABEL,
null,
vscode.TreeItemCollapsibleState.None,
{
title: "deployHostedSkill",
command: "askContainer.skillsConsole.deployHostedSkill",
},
undefined,
ContextValueTypes.SKILL,
),
);
} else {
treeItemsArray.push(
new PluginTreeItem<Resource>(
SKILL_ACTION_ITEMS.DEPLOY.LABEL,
null,
vscode.TreeItemCollapsibleState.None,
{
title: "deployNonHostedSkill",
command: "askContainer.skillsConsole.deploySelfHostedSkill",
},
undefined,
ContextValueTypes.SKILL,
),
);
}
treeItemsArray.push(
new PluginTreeItem<Resource>(
SKILL_ACTION_ITEMS.TEST.LABEL,
null,
vscode.TreeItemCollapsibleState.Collapsed,
undefined,
undefined,
ContextValueTypes.SKILL,
),
);
}
return treeItemsArray;
}
/**
* Function to add APL related actions into Skill Actions treeview under 'APL renderer' tree item
*
* @private
* @param {Array<PluginTreeItem<Resource>>} resourceArray - tree items
* @returns {Array<PluginTreeItem<Resource>>} - updated tree items
*
* @memberOf SkillActionsViewProvider
*/
private addAplRendererResources(
resourceArray: Array<PluginTreeItem<Resource>>,
skillFolder: vscode.Uri,
skillDetails: SkillDetailsType,
): Array<PluginTreeItem<Resource>> {
const skillId: string = skillDetails.skillId;
resourceArray.push(
new PluginTreeItem<Resource>(
SKILL_ACTION_ITEMS.ALEXA_PRESENTATION_LANGUAGE.ITEMS.CREATE_APL_DOCUMENT.LABEL,
null,
vscode.TreeItemCollapsibleState.None,
{
title: EXTENSION_COMMAND_CONFIG.CREATE_APL_DOCUMENT_FROM_SAMPLE.TITLE,
command: EXTENSION_COMMAND_CONFIG.CREATE_APL_DOCUMENT_FROM_SAMPLE.NAME,
arguments: [skillFolder],
},
undefined,
ContextValueTypes.SKILL,
),
);
resourceArray.push(
new PluginTreeItem<Resource>(
SKILL_ACTION_ITEMS.ALEXA_PRESENTATION_LANGUAGE.ITEMS.PREVIEW_APL_DOCUMENT.LABEL,
null,
vscode.TreeItemCollapsibleState.None,
{
title: EXTENSION_COMMAND_CONFIG.RENDER_APL_DOCUMENT.TITLE,
command: EXTENSION_COMMAND_CONFIG.RENDER_APL_DOCUMENT.NAME,
arguments: [skillFolder],
},
undefined,
ContextValueTypes.SKILL,
),
);
resourceArray.push(
new PluginTreeItem<Resource>(
SKILL_ACTION_ITEMS.ALEXA_PRESENTATION_LANGUAGE.ITEMS.CHANGE_VIEWPORT_PROFILE.LABEL,
null,
vscode.TreeItemCollapsibleState.None,
{
title: EXTENSION_COMMAND_CONFIG.CHANGE_VIEWPORT_PROFILE.TITLE,
command: EXTENSION_COMMAND_CONFIG.CHANGE_VIEWPORT_PROFILE.NAME,
},
undefined,
ContextValueTypes.SKILL,
),
);
if (Utils.isNonBlankString(skillId)) {
resourceArray.push(
new PluginTreeItem<Resource>(
SKILL_ACTION_ITEMS.ALEXA_PRESENTATION_LANGUAGE.ITEMS.DOWNLOAD_APL_DOCUMENT.LABEL,
null,
vscode.TreeItemCollapsibleState.None,
{
title: EXTENSION_COMMAND_CONFIG.DOWNLOAD_APL_DOCUMENT.TITLE,
command: EXTENSION_COMMAND_CONFIG.DOWNLOAD_APL_DOCUMENT.NAME,
arguments: [skillFolder],
},
undefined,
ContextValueTypes.SKILL,
),
);
}
return resourceArray;
}
/**
* Function to add manifest related actions into Skill Actions treeview under 'Manifest' tree item
*
* @private
* @param {Array<PluginTreeItem<Resource>>} treeItemsArray - tree items
* @param {vscode.Uri} skillFolder - Skill folder URI
* @param {SkillDetailsType} skillDetails - Skill information
* @returns {Array<PluginTreeItem<Resource>>} - updated tree items for manifest dropdown
*
* @memberOf SkillActionsViewProvider
*/
private addManifestResources(treeItemsArray: Array<PluginTreeItem<Resource>>, skillFolder: vscode.Uri): Array<PluginTreeItem<Resource>> {
Logger.verbose(`Calling method: ${SkillActionsViewProvider.name}.addManifestResources`);
treeItemsArray.push(
new PluginTreeItem<Resource>(
SKILL_ACTION_ITEMS.MANIFEST.ITEMS.DOWNLOAD,
null,
vscode.TreeItemCollapsibleState.None,
{
title: "syncManifest",
command: "ask.container.syncManifest",
arguments: [skillFolder],
},
undefined,
ContextValueTypes.SKILL,
),
);
return treeItemsArray;
}
/**
* Function to add IModel related actions into Skill Actions treeview under 'Interaction Model' tree item
*
* @private
* @param {Array<PluginTreeItem<Resource>>} treeItemsArray - tree items
* @param {vscode.Uri} skillFolder - Skill folder URI
* @param {SkillDetailsType} skillDetails - Skill information
* @returns {Array<PluginTreeItem<Resource>>} - updated tree items for IM dropdown
*
* @memberOf SkillActionsViewProvider
*/
private addIModelResources(
treeItemsArray: Array<PluginTreeItem<Resource>>,
skillFolder: vscode.Uri,
skillDetails: SkillDetailsType,
): Array<PluginTreeItem<Resource>> {
Logger.verbose(`Calling method: ${SkillActionsViewProvider.name}.addIModelResources`);
const skillId = skillDetails.skillId;
treeItemsArray.push(
new PluginTreeItem<Resource>(
SKILL_ACTION_ITEMS.IM.ITEMS.EDITOR,
null,
vscode.TreeItemCollapsibleState.None,
{
title: "openUrl",
command: "ask.container.openUrl",
arguments: [getIModelGeneratorLink(skillId, skillDetails.defaultLocale), {CommandType: ActionType.IM_EDITOR}],
},
undefined,
ContextValueTypes.SKILL,
),
);
treeItemsArray.push(
new PluginTreeItem<Resource>(
SKILL_ACTION_ITEMS.IM.ITEMS.DOWNLOAD,
null,
vscode.TreeItemCollapsibleState.None,
{
title: "syncInteractionModel",
command: "ask.container.syncInteractionModel",
arguments: [skillFolder],
},
undefined,
ContextValueTypes.SKILL,
),
);
return treeItemsArray;
}
/**
* Function to add testing related actions into Skill Actions treeview under 'Test skill' tree item
*
* @private
* @param {Array<PluginTreeItem<Resource>>} resourceArray - tree items
* @returns {Array<PluginTreeItem<Resource>>} - updated tree items
*
* @memberOf SkillActionsViewProvider
*/
private addTestResources(
treeItemsArray: Array<PluginTreeItem<Resource>>,
skillFolder: vscode.Uri,
skillDetails: SkillDetailsType,
): Array<PluginTreeItem<Resource>> {
const skillId: string = skillDetails.skillId;
if (Utils.isNonBlankString(skillId)) {
treeItemsArray.push(
new PluginTreeItem<Resource>(
SKILL_ACTION_ITEMS.TEST.ITEMS.OPEN,
null,
vscode.TreeItemCollapsibleState.None,
{
title: "simulateSkill",
command: "askContainer.skillsConsole.simulateSkill",
},
undefined,
ContextValueTypes.SKILL,
),
);
treeItemsArray.push(
new PluginTreeItem<Resource>(
SKILL_ACTION_ITEMS.TEST.ITEMS.REPLAY,
null,
vscode.TreeItemCollapsibleState.None,
{
title: "simulateSkill",
command: "askContainer.skillsConsole.simulateReplay",
},
undefined,
ContextValueTypes.SKILL,
),
);
treeItemsArray.push(
new PluginTreeItem<Resource>(
SKILL_ACTION_ITEMS.TEST.ITEMS.VIEWPORT,
null,
vscode.TreeItemCollapsibleState.None,
{
title: "simulateSkill",
command: "askContainer.skillsConsole.changeSimulatorViewport",
},
undefined,
ContextValueTypes.SKILL,
),
);
}
return treeItemsArray;
}
} | the_stack |
import { browser, by, element, $, $$ } from 'protractor';
import { CONFIGURATIONS } from '../../src/config/configuration';
const fs = require('fs');
const config = CONFIGURATIONS.optional.general.e2e;
export class Jazz {
navigateToJazzGet() {
return browser.driver.get(config.APPLN_URL);
}
getCreateService() {
return element(by.css('div.btn-text'));
}
getPageTitle() {
return element(by.xpath('//div/div[2]/div/services-list/section/navigation-bar/div'));
}
getLambda() {
return element(by.css('div.service-box>div.icon-icon-function'));
}
getWebsite() {
return element(by.css('div.service-box>div.icon-icon-web'));
}
getServiceName() {
return element(by.css('input#serviceName'));
}
getNameSpace() {
return element(by.css('input#domainName'));
}
getServiceDescription() {
return element(by.css('div.input-field-container>div.input-wrapper>textarea'));
}
getEventScheduleFixedRate() {
return element(by.css('div.radio-container>label[for="fixedRate"]'));
}
getAwsServiceName() {
return element(by.xpath('(//table-template//div[@class="table-row pointer"]/div)[1]'));
}
getAPIType(servicename) {
return element(by.xpath('//div/div[@class="table-row pointer"]/div[text()="'+servicename+'"]/parent::div/div[2]'));
}
getFunctionType(servicename) {
return element(by.xpath('//div/div[@class="table-row pointer"]/div[text()="'+servicename+'"]/parent::div/div[2]'));
}
getWebsiteType(servicename) {
return element(by.xpath('//div/div[@class="table-row pointer"]/div[text()="'+servicename+'"]/parent::div/div[2]'));
}
getslsType(servicename) {
return element(by.xpath('//div/div[@class="table-row pointer"]/div[text()="'+servicename+'"]/parent::div/div[2]'));
}
getAPIStatus(servicename) {
return element(by.xpath('//div/div[@class="table-row pointer"]/div[text()="'+servicename+'"]/parent::div/div[5]'));
}
getFunctionStatus(servicename) {
return element(by.xpath('//div/div[@class="table-row pointer"]/div[text()="'+servicename+'"]/parent::div/div[5]'));
}
getWebsiteStatus(servicename) {
return element(by.xpath('//div/div[@class="table-row pointer"]/div[text()="'+servicename+'"]/parent::div/div[5]'));
}
getDummy() {
return element(by.xpath('//*[@id="exampleName"]'));
}
getSubmit() {
return element(by.css('section.submit-form>button.btn'));
}
getDone() {
return element(by.css('section.footer-btn>btn-jazz-primary'));
}
getServiceNameHeader() {
return element(by.xpath('//div[@class="page-title-wrap hide-for-mobile"]/h1[@class="page-hdr bold-title"]'));
}
getProdName() {
return element(by.xpath('//div[1]/span[@title="deployment completed"]'))
// '//div[@class="stage-title stageDisp" and contains(text(),"prod")]'))
}
getProdHeader() {
return element(by.xpath('//div[@class="servie-details-container"]/h1[@class="page-hdr bold-title relative" and contains(text(),"prod")]'));
}
getAsset() {
return element(by.xpath('//li[@class="x caps" and contains(text(),"assets")]'));
}
getAssetHeader() {
return element(by.xpath('//div/div[2]/div/section[1]/div/div[2]/section/env-assets-section/div/div[1]/div[2]/div[1]/div[1]/span[2]'));
}
getRefresh() {
return element(by.xpath('*//div[@class="refresh-button"]'));
}
getServiceHomePage() {
return element(by.xpath('//div[@class="navigation-item"]/span[@class="icon-icon-back hide"]/following-sibling::a[text()="Services"]'));
}
getWebsiteName() {
return element(by.xpath('//div[@class="table-row pointer"]/div[text()="website"]/preceding-sibling::div'));
}
getDeploymentStatus() {
return element(by.xpath('//li[@class="x caps" and contains(text(),"deployments")]'));
}
getDeploymentStatusVerify() {
return element(by.xpath('//div[contains(text(),"successful")]'));
}
getAssetStatusVerify() {
return element(by.css('div.asset-content-row.row ul.section-left.col-md-6.col-sm-12 li:nth-child(1) > div.det-value'));
}
getLamdaName() {
return element(by.xpath('//div[@class="table-row pointer"]/div[text()="function"]/preceding-sibling::div'));
}
getOverviewStatus() {
return element(by.xpath('//li[@class="x caps active" and contains(text(),"overview")]'));
}
getLogs() {
return element(by.xpath('//li[@class="x caps" and contains(text(),"logs")]'));
}
getFilterIcon() {
return element(by.xpath('//div[@class="filter-icon relative"]'));
}
getDay() {
return element(by.xpath('//div[@class="dropdown open"]/ul[@class="dropdown-menu"]/li/a[(text()="Day")]'));
}
getWeek() {
return element(by.xpath('//div[@class="dropdown open"]/ul[@class="dropdown-menu"]/li/a[(text()="Week")]'));
}
getMonth() {
return element(by.xpath('//div[@class="dropdown open"]/ul[@class="dropdown-menu"]/li/a[(text()="Month")]'));
}
getYear() {
return element(by.xpath('//div[@class="dropdown open"]/ul[@class="dropdown-menu"]/li/a[(text()="Year")]'));
}
getDropDown() {
return element(by.xpath('//div[text()="TIME RANGE"]/following-sibling::dropdown[@title="Select range"]/div[@class="dropdown"]/button[@class="btn dropdown-btn dropdown-toggle"]'));
}
getWeekVerify() {
return element(by.xpath('//div[@class="row"]/div[contains(text(),"Time Range")]/b[text()="Week"]'));
}
getMonthVerify() {
return element(by.xpath('//div[@class="row"]/div[contains(text(),"Time Range")]/b[text()="Month"]'));
}
getYearVerify() {
return element(by.xpath('//div[@class="row"]/div[contains(text(),"Time Range")]/b[text()="Year"]'));
}
homePageRefresh() {
return element(by.xpath('//span[@title="Refresh"]'));
}
serviceStatus(servicename) {
return element(by.xpath('//div/div[@class="table-row pointer"]/div[text()="'+servicename+'"]/parent::div/div[contains(text(), "active")]'));
}
getMetrices() {
return element(by.xpath('//li[contains(text(),"metrics")]'));
}
getTestAPI() {
return element(by.xpath('//button[text()="TEST API"]'));
}
getAPIGET() {
return element(by.xpath('//span[@class="opblock-summary-method"][contains(text(),"GET")]'));
}
getAPIPOST() {
return element(by.xpath('//span[@class="opblock-summary-method"][contains(text(),"POST")]'));
}
getTryOut() {
return element(by.xpath('//button[@class="btn try-out__btn"]'));
}
getStringA() {
return element(by.xpath('//input[@placeholder="a"]'));
}
getStringB() {
return element(by.xpath('//input[@placeholder="b"]'));
}
getExecute() {
return element(by.css('div.execute-wrapper>button'));
}
getMetricesCount() {
return element(by.xpath('//div[@class="metrics-footer"][contains(text(),"Count")]/preceding-sibling::div[@class="metrics-card-content"]'));
}
getXXError() {
return element(by.css('div.metrics-carousel-scroller>div.metrics-card:nth-child(1)'));
}
getXXErrorFive() {
return element(by.css('div.metrics-carousel-scroller>div.metrics-card:nth-child(2)'));
}
getCacheHitCount() {
return element(by.css('div.metrics-carousel-scroller>div.metrics-card:nth-child(3)'));
}
getCacheMissCount() {
return element(by.css('div.metrics-carousel-scroller>div.metrics-card:nth-child(4)'));
}
getCount() {
return element(by.css('div.metrics-carousel-scroller>div.metrics-card:nth-child(5)'));
}
getIntegrationLatency() {
return element(by.css('div.metrics-carousel-scroller>div.metrics-card:nth-child(6)'));
}
getLatency() {
return element(by.css('div.metrics-carousel-scroller>div.metrics-card:nth-child(7)'));
}
getTestFunction() {
return element(by.xpath('//btn-jazz-secondary[@class="testApiBtn"]/button[text()="TEST FUNCTION"]'));
}
getTestArea() {
return element(by.xpath('//textarea[contains(@class,"input-textarea")]'));
}
getTestButton() {
return element(by.xpath('//div/button[@class="btn-round primary start-button"]'));
}
getClose() {
return element(by.xpath('//div[@class="sidebar-frame"]//div[@class="icon-icon-close pointer"]'));
}
getInvocations() {
return element(by.css('div.metrics-carousel-scroller>div.metrics-card:nth-child(1)'));
}
getWebsiteLink() {
return element(by.xpath('//btn-jazz-secondary[@class="testApiBtn"]/button[text()="GO TO WEBSITE"]'));
}
getMetricsChildOne() {
return element(by.css('div.metrics-carousel-scroller>div.metrics-card:nth-child(1)'));
}
getMetricsChildTwo() {
return element(by.css('div.metrics-carousel-scroller>div.metrics-card:nth-child(2)'));
}
getMetricsChildThree() {
return element(by.css('div.metrics-carousel-scroller>div.metrics-card:nth-child(3)'));
}
getMetricsChildFour() {
return element(by.css('div.metrics-carousel-scroller>div.metrics-card:nth-child(4)'));
}
getMetricsChildFive() {
return element(by.css('div.metrics-carousel-scroller>div.metrics-card:nth-child(5)'));
}
getMetricsChildSix() {
return element(by.css('div.metrics-carousel-scroller>div.metrics-card:nth-child(6)'));
}
getMetricsChildSeven() {
return element(by.css('div.metrics-carousel-scroller>div.metrics-card:nth-child(7)'));
}
serverResponse() {
return element(by.xpath('//td[@class="col response-col_status"][contains(text(),"200")]'));
}
goToFunction() {
return element(by.xpath('//button[@class="btnT-radial-in"]'));
}
testSuccessMessage() {
return element(by.css('div.column-heading.success > span:nth-child(2)'));
}
websiteTemplete() {
return element(by.xpath('//p[contains(text(),"Jazz Serverless Platform Website Template")]'));
}
getMetricesRequestCount() {
return element(by.xpath('//div[contains(text(),"10")]'));
}
// Environment Locators
getRepository() {
return element(by.xpath('//div[contains(@class,"det-value repository-link link PlaceHolder")]'));
}
// bitbucket locators
getEnvironmentBit() {
return element(by.xpath('//span[contains(text(), "Bitbucket")]'));
}
getEnvironmentGit() {
return element(by.xpath('//div/div[2]/div[1]/h1[contains(text(),"GitLab Community Edition")]'));
}
bitbucketLogo() {
return element(by.xpath('//span[@class="aui-header-logo-device"]'));
}
createBranch() {
return element(by.xpath('//span[@class="aui-icon icon-create-branch"]'));
}
drp_BranchType() {
return element(by.xpath('//a[@id="branch-type"]'));
}
select_BranchType() {
return element(by.xpath('//a[contains(text(),"Feature")]'));
}
branchName() {
return element(by.xpath('//input[@id="branch-name"]'));
}
btn_CreateBranch() {
return element(by.xpath('//input[@id="create-branch-submit"]'));
}
bitUsername() {
return element(by.xpath('//*[@id="j_username"]'));
}
bitPassword() {
return element(by.xpath('//*[@id="j_password"]'));
}
bitLogin() {
return element(by.xpath('//*[@id="submit"]'));
}
testBranch() {
return element(by.xpath('//div[@class="eachBranch col-md-2 col-sm-5"]//div//div[@class="overview-value"]'));
}
activeTestBranch() {
return element(by.xpath('//div[2]/span[@title="deployment completed"]'));
}
getTestBranch() {
return element(by.xpath('//div[@class="eachBranch col-md-2 col-sm-5"]//div//div[@class="overview-value"]'));
}
bitbucketGetServiceName() {
return element(by.css('li:nth-child(2).aui-nav-selected>a'));
}
createBranchLabel() {
return element(by.xpath('//h2[contains(text(),"Create branch")]'));
}
testBranchStatus() {
return element(by.xpath('//div[@class="eachBranch col-md-2 col-sm-5"]//div//span[@title="deployment completed"]'));
}
drpBitTestBranch() {
return element(by.xpath('//button[@id="repository-layout-revision-selector"]'));
}
selectBitTestBranch() {
return element(by.xpath('//a/span[@title="feature/test"]'));
}
indexFile() {
return element(by.xpath('//a[contains(text(),"index.js")]'));
}
btnEditIndexFile() {
return element(by.xpath('//button[@class="aui-button in-browser-edit-button"]'));
}
editIndexFile() {
return element(by.xpath('//div[@class="CodeMirror-code"]'));
}
getBranchFileCommit() {
return element(by.xpath('//button[@title="Commit your changes"]'));
}
getDialogCommit() {
return element(by.xpath('//button[@class=aui-button aui-button-primary commit-button"]'));
}
//gitlab locators
gitUsername() {
return element(by.xpath('//*[@id="user_login"]'));
}
gitPassword() {
return element(by.xpath('//*[@id="user_password"]'));
}
gitLogin() {
return element(by.xpath('//input[@value="Sign in"]'));
}
drpGitBranchType() {
return element(by.xpath('//a[@class="btn dropdown-toggle has-tooltip"]//i[@class="fa fa-caret-down"]'));
}
selectGitBranchType() {
return element(by.xpath('//a[text()="New branch"]'));
}
gitBranchName() {
return element(by.xpath('//input[@id="branch_name"]'));
}
btnGitCreateBranch() {
return element(by.xpath('//button[contains(text(),"Create branch")]'));
}
gitIndexFile() {
return element(by.xpath('//span[contains(text(),"index.js")]'));
}
gitEditIndexFile() {
return element(by.xpath('//a[contains(text(),"Edit")]'));
}
removeLineFirst() {
return element(by.xpath('//*[@id="editor"]/div[2]/div'));
}
gitComitChanges() {
return element(by.xpath('//button[contains(text(),"Commit changes:)]'));
}
getRepo() {
return element(by.xpath('//div[contains(text(),"Repository")]'));
}
getTestBranchName() {
return element(by.xpath('//div[@class="stage-title2 stageDisp"]'));
}
getLoginSpinner()
{
return element(by.css('div.loader'));
}
getSpinner() {
return element(by.css('div.loading-circle'));
}
getMetricsSpinner() {
return element(by.css('div.jz-spinner'));
}
getBitLogoutIcon() {
return element(by.xpath('//span[@id="current-user"]//span[@class="aui-avatar-inner"]'));
}
getBitLogout() {
return element(by.xpath('//a[@class="logout-link"]'));
}
getGitLogoutIcon() {
return element(by.xpath('//a[@class="header-user-dropdown-toggle"]//*[contains(@class,"caret-down")]'));
}
getGitLogout() {
return element(by.xpath('//a[@class="sign-out-link"]'));
}
getService(servicename) {
return element(by.xpath('(//table-template//div[@class="table-row pointer"]/div)[contains(text(),"'+servicename+'")]'));
}
SwaggerFailed(){
return element(by.xpath('//*[@class="errors__title"]'));
}
logoutIcon() {
return element(by.xpath('//jazz-header/header/div[2]/div[2]/ul/li[2]/div/div/div[1]'));
}
logout() {
return element(by.xpath('//div[contains(text(),"Logout")]'));
}
testError() {
return element(by.xpath('//*[@id="main-message"]/h1/span'));
}
getBuildCustom() {
return element(by.xpath('//div[@class="icon-icon-sls-app"]//img'));
}
accountSelect() {
return element(by.xpath('//div[contains(@class,"each-section-accReg")]//button[contains(@class,"btn dropdown-btn dropdown-toggle")]'));
}
regionSelect() {
return element(by.xpath('//*[@id="typeform"]/section[4]/div/div[2]/section/div/div[2]/div[2]/dropdown/div/button'));
}
firstAccount() {
return element(by.xpath('//section[4]/div/div[2]/section/div/div[1]/div[2]/dropdown/div/ul/li[1]/a'));
}
secountAccount() {
return element(by.xpath('//section[4]/div[1]/div[2]/section[1]/div[1]/div[1]/div[2]/dropdown[1]/div[1]/ul[1]/li[2]/a[1]'));
}
eastRegion() {
return element(by.xpath('//a[contains(text(),"us-east-1")]'));
}
westRegion() {
return element(by.xpath('//a[contains(text(),"us-west-2")]'));
}
deployDesciptor() {
return element(by.xpath('//section[@id="deployment-descriptor"]//label'));
}
eastRegionVerify() {
return element(by.xpath('//div[contains(text(),"us-east-1")]'));
}
westRegionVerify() {
return element(by.xpath('//div[contains(text(),"us-west-2")]'));
}
getJavaRuntime() {
return element(by.xpath('//p[contains(text(),"java8")]'));
//label[contains(@for,"java")]//span[contains(@class,"background")]
}
getPython27() {
return element(by.xpath('//p[contains(text(),"python2.7")]'));
//label[contains(@for,"python")]//span[contains(@class,"background")]
}
getPython36() {
return element(by.xpath('//p[contains(text(),"python3.6")]'));
}
} | the_stack |
import fs from 'fs';
import os from 'os';
import path from 'path';
import fg from 'fast-glob';
import mkdirp from 'mkdirp';
import rimrafSync from 'rimraf';
import { jsonc } from 'jsonc';
import fxp from 'fast-xml-parser';
import filesize from 'filesize';
import { promisify } from 'util';
import { inject, injectable } from "inversify";
import { FsAtomicWriter } from './fs-atomic-writer';
import { FsJsonFileMapping, FsJsonFileMappingOptions } from './fs-json-file-mapping';
import { TaskReporterService } from 'backend/task/task-reporter-service';
import { LogService } from 'backend/logger/log-service';
import { NotificationService } from 'backend/notification/notification-service';
import { concurrently } from 'utils/concurrently';
import { fastRandomId } from 'utils/random';
import { FsThrottledWriterOptions, FsThrottledWriter } from './fs-throttled-writer';
import { awaitableTimeout } from 'fxdk/base/async';
const rimraf = promisify(rimrafSync);
export interface CopyOptions {
onProgress?: (progress: number) => void,
}
/**
* Yes, stupid-ass abstraction
*/
@injectable()
export class FsService {
static readonly separator = path.sep;
@inject(LogService)
protected readonly logService: LogService;
@inject(NotificationService)
protected readonly notificationService: NotificationService;
@inject(TaskReporterService)
protected readonly taskReporterService: TaskReporterService;
tmpdir() {
return os.tmpdir();
}
basename(entryPath: string, ext?: string) {
return path.basename(entryPath, ext);
}
dirname(entryPath: string) {
return path.dirname(entryPath);
}
filesizeToHumanReadable(size: number): string {
return filesize(size);
}
isAbsolutePath(entryPath: string) {
return path.isAbsolute(entryPath);
}
relativePath(from: string, to: string) {
return path.relative(from, to);
}
splitPath(entryPath: string): string[] {
return entryPath.split(path.sep);
}
joinPath(...args: string[]) {
return path.join(...args);
}
resolvePath(entryPath: string) {
return path.resolve(entryPath);
}
async statSafe(entryPath: string): Promise<fs.Stats | null> {
try {
return await this.stat(entryPath);
} catch (e) {
return null;
}
}
async statSafeRetries(entryPath: string, retries = 3, waitTimeout = 25): Promise<fs.Stats | null> {
let retriesLeft = retries;
do {
const stat = await this.statSafe(entryPath);
if (stat) {
return stat;
}
await awaitableTimeout(waitTimeout);
} while (retriesLeft--);
return null;
}
stat(entryPath: string) {
return fs.promises.stat(entryPath);
}
statSync(entryPath: string) {
return fs.statSync(entryPath);
}
rimraf(entryPath: string) {
return rimraf(entryPath);
}
async ensureDeleted(entryPath: string) {
const stat = await this.statSafe(entryPath);
if (stat) {
if (stat.isDirectory()) {
await this.rimraf(entryPath);
} else {
await this.unlink(entryPath);
}
}
}
readdir(entryPath: string): Promise<string[]> {
return fs.promises.readdir(entryPath);
}
mkdirp(entryPath: string) {
return mkdirp(entryPath);
}
mkdirpSync(entryPath: string) {
return mkdirp.sync(entryPath);
}
async ensureDir(entryPath: string) {
const stat = await this.statSafe(entryPath);
if (!stat) {
return this.mkdirp(entryPath);
}
if (!stat.isDirectory()) {
throw new Error(`${entryPath} exist but is not a directory`);
}
}
unlink(entryPath: string) {
return fs.promises.unlink(entryPath);
}
rename(entryPath: string, newEntryPath: string) {
return fs.promises.rename(entryPath, newEntryPath);
}
createReadStream(entryPath: string) {
return fs.createReadStream(entryPath);
}
createWriteStream(entryPath: string) {
return fs.createWriteStream(entryPath);
}
readFile(entryPath: string) {
return fs.promises.readFile(entryPath);
}
async readFileFirstBytes(entryPath: string, bytes: number): Promise<string> {
const fd = await fs.promises.open(entryPath, 'r');
const buffer = Buffer.allocUnsafe(bytes);
await fd.read(buffer, 0, bytes, 0);
await fd.close();
return buffer.toString();
}
async readFileString(entryPath: string): Promise<string> {
return (await this.readFile(entryPath)).toString();
}
async readFileJson<T>(entryPath: string): Promise<T> {
const content = await this.readFileString(entryPath);
return JSON.parse(content);
}
async readFileJsonc<T>(entryPath: string): Promise<T> {
const content = await this.readFileString(entryPath);
return jsonc.parse(content);
}
async readFileXML<T>(entryPath: string, options?: fxp.X2jOptionsOptional): Promise<T> {
const content = await this.readFileString(entryPath);
return fxp.parse(content, options);
}
writeFile(entryPath: string, content: string | Buffer) {
return fs.promises.writeFile(entryPath, content);
}
writeFileJson<T>(entryPath: string, content: T, pretty = true) {
return this.writeFile(entryPath, JSON.stringify(content, undefined, pretty ? 2 : undefined));
}
writeFileJsonc<T>(entryPath: string, content: T, pretty = true) {
return this.writeFile(entryPath, jsonc.stringify(content, undefined, pretty ? 2 : undefined));
}
createAtomicWriter(entryPath: string) {
return new FsAtomicWriter(entryPath, this.writeFile.bind(this));
}
async createJsonFileMapping<T extends object>(
entryPath: string,
options?: FsJsonFileMappingOptions<T>,
): Promise<FsJsonFileMapping<T>> {
const writer = this.createAtomicWriter(entryPath);
const reader = async () => {
const content = await this.readFile(entryPath);
try {
return {
...(options?.defaults || null),
...JSON.parse(content.toString()),
};
} catch (e) {
return options?.defaults || {};
}
};
const snapshot = await reader();
return new FsJsonFileMapping(snapshot, writer, reader, options);
}
createThrottledFileWriter<T>(entryPath: string, options: FsThrottledWriterOptions<T>): FsThrottledWriter<T> {
return new FsThrottledWriter(
(content) => this.writeFile(entryPath, content),
options,
);
}
/**
* If sourcePath is /a/b/entry
* And target is /a/c
* It will copy content of /a/b/entry to /a/c/entry
*
* @param sourcePath
* @param target
*/
async copy(sourcePath: string, target: string, options: CopyOptions = {}) {
const sourceName = this.basename(sourcePath);
const targetPath = this.joinPath(target, sourceName);
const sourceStat = await this.statSafe(sourcePath);
if (!sourceStat) {
throw new Error(`Can't copy ${sourcePath} -> ${target} as ${sourcePath} does not exist`);
}
const {
onProgress = () => {},
} = options;
// Handle file first
if (!sourceStat.isDirectory()) {
const sourceSize = sourceStat.size;
let doneSize = 0;
if (onProgress) {
return this.doCopyFile(sourcePath, targetPath, onProgress);
}
return this.taskReporterService.wrap(`Copying ${sourcePath} to ${target}`, (task) => {
return this.doCopyFile(sourcePath, targetPath, (bytesRead) => {
doneSize += bytesRead;
task.setProgress(doneSize / sourceSize);
});
});
}
// Now directories
if (onProgress) {
return this.doCopyDir(sourcePath, targetPath, onProgress);
}
return this.taskReporterService.wrap(`Copying ${sourcePath} to ${target}`, async (task) => {
return this.doCopyDir(sourcePath, targetPath, (progress: number) => task.setProgress(progress));
});
}
async copyFileContent(sourcePath: string, targetPath: string, options: CopyOptions = {}): Promise<void> {
const sourcePathStats = await this.statSafe(sourcePath);
if (!sourcePathStats) {
throw new Error('No source path: '+ sourcePath);
}
return new Promise((resolve, reject) => {
const reader = this.createReadStream(sourcePath);
const writer = this.createWriteStream(targetPath);
let finished = false;
const finish = (error?: Error) => {
if (!finished) {
finished = true;
if (error) {
return reject(error);
}
return resolve();
}
};
reader.once('error', finish);
writer.once('error', finish);
writer.once('close', () => finish());
if (options.onProgress) {
const totalSize = sourcePathStats.size;
let doneSize = 0;
reader.on('data', (chunk) => {
doneSize += chunk.length;
options.onProgress?.(doneSize / totalSize);
});
}
reader.pipe(writer);
});
}
/**
* Copies /a/b/* to /a/c/*
*/
async copyDirContent(sourcePath: string, targetPath: string, options: CopyOptions = {}) {
const {
onProgress = () => {},
} = options;
return this.doCopyDir(sourcePath, targetPath, onProgress);
}
private async doCopyDir(
sourcePath: string,
targetPath: string,
reportProgress: (bytesRead: number) => void = () => {},
): Promise<void> {
type SourcePath = string;
type TargetPath = string;
const sourceDirPaths = new Set<SourcePath>([sourcePath]);
const filesToCopy = new Map<SourcePath, TargetPath>();
const ignoredFiles = new Set();
let totalSize = 0;
let doneSize = 0;
for (const sourceDirPath of sourceDirPaths) {
const targetDirPath = this.joinPath(targetPath, this.relativePath(sourcePath, sourceDirPath));
const [dirEntryNames] = await concurrently(
this.readdir(sourceDirPath),
this.mkdirp(targetDirPath),
);
await Promise.all(dirEntryNames.map(async (dirEntryName) => {
const dirEntrySourcePath = this.joinPath(sourceDirPath, dirEntryName);
const dirEntryTargetPath = this.joinPath(targetDirPath, dirEntryName);
const dirEntrySourceStat = await this.statSafe(dirEntrySourcePath);
if (dirEntrySourceStat) {
if (dirEntrySourceStat.isDirectory()) {
return sourceDirPaths.add(dirEntrySourcePath);
}
// TODO: Support file overwrites
if (await this.statSafe(dirEntryTargetPath)) {
return ignoredFiles.add(dirEntrySourcePath);
}
filesToCopy.set(dirEntrySourcePath, dirEntryTargetPath);
totalSize += dirEntrySourceStat.size;
}
}));
}
if (ignoredFiles.size) {
this.notificationService.warning(`Following files won't be copied as they will overwrite existing files: ${[...ignoredFiles.values()].join(', ')}`);
}
for (const [fileSourcePath, fileTargetPath] of filesToCopy.entries()) {
await this.doCopyFile(fileSourcePath, fileTargetPath, (bytesRead) => {
doneSize += bytesRead;
reportProgress(doneSize / totalSize);
});
}
}
private doCopyFile(sourcePath: string, targetPath: string, reportProgress: (bytesRead: number) => void = () => {}): Promise<void> {
return new Promise((resolve, reject) => {
const reader = this.createReadStream(sourcePath);
const writer = this.createWriteStream(targetPath);
let finished = false;
const finish = (error?: Error) => {
if (!finished) {
finished = true;
if (error) {
return reject(error);
}
return resolve();
}
};
reader.once('error', finish);
writer.once('error', finish);
writer.once('close', () => finish());
reader.on('data', (chunk) => reportProgress(chunk.length));
reader.pipe(writer);
});
}
async glob(patterns: string | string[], options: fg.Options): Promise<string[]> {
return fg(patterns, options);
}
async readIgnorePatterns(basePath: string, fileName: string = '.fxdkignore'): Promise<string[]> {
try {
const filePath = this.joinPath(basePath, fileName);
const fileContent = await this.readFileString(filePath);
return fileContent.trim().split('\n').map((line) => line.trim()).filter(Boolean);
} catch (e) {
return [];
}
}
async moveToTrashBin(...entryPaths: string[]): Promise<void> {
await new Promise<void>((resolve, reject) => {
const msgId = fastRandomId();
emit('sdk:recycleShellItems', msgId, entryPaths);
const handler = (rmsgId: string, error: string) => {
if (msgId !== rmsgId) {
return;
}
RemoveEventHandler('sdk:recycleShellItemsResponse', handler);
if (error) {
return reject(new Error(error));
}
return resolve();
}
on('sdk:recycleShellItemsResponse', handler);
});
}
async ensureFile(entryPath: string, content = '') {
if (!(await this.statSafe(entryPath))) {
await this.writeFile(entryPath, content);
}
}
} | the_stack |
export type ValueTypes = {
/** expression to compare columns of type Boolean. All fields are combined with logical 'AND'. */
["Boolean_comparison_exp"]: {
_eq?:boolean,
_gt?:boolean,
_gte?:boolean,
_in?:boolean[],
_is_null?:boolean,
_lt?:boolean,
_lte?:boolean,
_neq?:boolean,
_nin?:boolean[]
};
["CacheControlScope"]:CacheControlScope;
/** conflict action */
["conflict_action"]:conflict_action;
/** expression to compare columns of type Int. All fields are combined with logical 'AND'. */
["Int_comparison_exp"]: {
_eq?:number,
_gt?:number,
_gte?:number,
_in?:number[],
_is_null?:boolean,
_lt?:number,
_lte?:number,
_neq?:number,
_nin?:number[]
};
/** mutation root */
["mutation_root"]: AliasType<{
delete_todos?: [{ /** filter the rows which have to be deleted */
where:ValueTypes["todos_bool_exp"]},ValueTypes["todos_mutation_response"]],
delete_users?: [{ /** filter the rows which have to be deleted */
where:ValueTypes["users_bool_exp"]},ValueTypes["users_mutation_response"]],
insert_todos?: [{ /** the rows to be inserted */
objects:ValueTypes["todos_insert_input"][], /** on conflict condition */
on_conflict?:ValueTypes["todos_on_conflict"]},ValueTypes["todos_mutation_response"]],
insert_users?: [{ /** the rows to be inserted */
objects:ValueTypes["users_insert_input"][], /** on conflict condition */
on_conflict?:ValueTypes["users_on_conflict"]},ValueTypes["users_mutation_response"]],
update_todos?: [{ /** increments the integer columns with given value of the filtered values */
_inc?:ValueTypes["todos_inc_input"], /** sets the columns of the filtered rows to the given values */
_set?:ValueTypes["todos_set_input"], /** filter the rows which have to be updated */
where:ValueTypes["todos_bool_exp"]},ValueTypes["todos_mutation_response"]],
update_users?: [{ /** increments the integer columns with given value of the filtered values */
_inc?:ValueTypes["users_inc_input"], /** sets the columns of the filtered rows to the given values */
_set?:ValueTypes["users_set_input"], /** filter the rows which have to be updated */
where:ValueTypes["users_bool_exp"]},ValueTypes["users_mutation_response"]]
__typename?: true
}>;
/** column ordering options */
["order_by"]:order_by;
["Query"]: AliasType<{
hello?:true
__typename?: true
}>;
/** query root */
["query_root"]: AliasType<{
hello?:true,
todos?: [{ /** distinct select on columns */
distinct_on?:ValueTypes["todos_select_column"][], /** limit the nuber of rows returned */
limit?:number, /** skip the first n rows. Use only with order_by */
offset?:number, /** sort the rows by one or more columns */
order_by?:ValueTypes["todos_order_by"][], /** filter the rows returned */
where?:ValueTypes["todos_bool_exp"]},ValueTypes["todos"]],
todos_aggregate?: [{ /** distinct select on columns */
distinct_on?:ValueTypes["todos_select_column"][], /** limit the nuber of rows returned */
limit?:number, /** skip the first n rows. Use only with order_by */
offset?:number, /** sort the rows by one or more columns */
order_by?:ValueTypes["todos_order_by"][], /** filter the rows returned */
where?:ValueTypes["todos_bool_exp"]},ValueTypes["todos_aggregate"]],
todos_by_pk?: [{ id:number},ValueTypes["todos"]],
users?: [{ /** distinct select on columns */
distinct_on?:ValueTypes["users_select_column"][], /** limit the nuber of rows returned */
limit?:number, /** skip the first n rows. Use only with order_by */
offset?:number, /** sort the rows by one or more columns */
order_by?:ValueTypes["users_order_by"][], /** filter the rows returned */
where?:ValueTypes["users_bool_exp"]},ValueTypes["users"]],
users_aggregate?: [{ /** distinct select on columns */
distinct_on?:ValueTypes["users_select_column"][], /** limit the nuber of rows returned */
limit?:number, /** skip the first n rows. Use only with order_by */
offset?:number, /** sort the rows by one or more columns */
order_by?:ValueTypes["users_order_by"][], /** filter the rows returned */
where?:ValueTypes["users_bool_exp"]},ValueTypes["users_aggregate"]],
users_by_pk?: [{ id:number},ValueTypes["users"]]
__typename?: true
}>;
/** expression to compare columns of type String. All fields are combined with logical 'AND'. */
["String_comparison_exp"]: {
_eq?:string,
_gt?:string,
_gte?:string,
_ilike?:string,
_in?:string[],
_is_null?:boolean,
_like?:string,
_lt?:string,
_lte?:string,
_neq?:string,
_nilike?:string,
_nin?:string[],
_nlike?:string,
_nsimilar?:string,
_similar?:string
};
/** subscription root */
["subscription_root"]: AliasType<{
todos?: [{ /** distinct select on columns */
distinct_on?:ValueTypes["todos_select_column"][], /** limit the nuber of rows returned */
limit?:number, /** skip the first n rows. Use only with order_by */
offset?:number, /** sort the rows by one or more columns */
order_by?:ValueTypes["todos_order_by"][], /** filter the rows returned */
where?:ValueTypes["todos_bool_exp"]},ValueTypes["todos"]],
todos_aggregate?: [{ /** distinct select on columns */
distinct_on?:ValueTypes["todos_select_column"][], /** limit the nuber of rows returned */
limit?:number, /** skip the first n rows. Use only with order_by */
offset?:number, /** sort the rows by one or more columns */
order_by?:ValueTypes["todos_order_by"][], /** filter the rows returned */
where?:ValueTypes["todos_bool_exp"]},ValueTypes["todos_aggregate"]],
todos_by_pk?: [{ id:number},ValueTypes["todos"]],
users?: [{ /** distinct select on columns */
distinct_on?:ValueTypes["users_select_column"][], /** limit the nuber of rows returned */
limit?:number, /** skip the first n rows. Use only with order_by */
offset?:number, /** sort the rows by one or more columns */
order_by?:ValueTypes["users_order_by"][], /** filter the rows returned */
where?:ValueTypes["users_bool_exp"]},ValueTypes["users"]],
users_aggregate?: [{ /** distinct select on columns */
distinct_on?:ValueTypes["users_select_column"][], /** limit the nuber of rows returned */
limit?:number, /** skip the first n rows. Use only with order_by */
offset?:number, /** sort the rows by one or more columns */
order_by?:ValueTypes["users_order_by"][], /** filter the rows returned */
where?:ValueTypes["users_bool_exp"]},ValueTypes["users_aggregate"]],
users_by_pk?: [{ id:number},ValueTypes["users"]]
__typename?: true
}>;
/** columns and relationships of "todos" */
["todos"]: AliasType<{
id?:true,
is_completed?:true,
text?:true,
/** An object relationship */
user?:ValueTypes["users"],
user_authID?:true
__typename?: true
}>;
/** aggregated selection of "todos" */
["todos_aggregate"]: AliasType<{
aggregate?:ValueTypes["todos_aggregate_fields"],
nodes?:ValueTypes["todos"]
__typename?: true
}>;
/** aggregate fields of "todos" */
["todos_aggregate_fields"]: AliasType<{
avg?:ValueTypes["todos_avg_fields"],
count?: [{ columns?:ValueTypes["todos_select_column"][], distinct?:boolean},true],
max?:ValueTypes["todos_max_fields"],
min?:ValueTypes["todos_min_fields"],
stddev?:ValueTypes["todos_stddev_fields"],
stddev_pop?:ValueTypes["todos_stddev_pop_fields"],
stddev_samp?:ValueTypes["todos_stddev_samp_fields"],
sum?:ValueTypes["todos_sum_fields"],
var_pop?:ValueTypes["todos_var_pop_fields"],
var_samp?:ValueTypes["todos_var_samp_fields"],
variance?:ValueTypes["todos_variance_fields"]
__typename?: true
}>;
/** order by aggregate values of table "todos" */
["todos_aggregate_order_by"]: {
avg?:ValueTypes["todos_avg_order_by"],
count?:ValueTypes["order_by"],
max?:ValueTypes["todos_max_order_by"],
min?:ValueTypes["todos_min_order_by"],
stddev?:ValueTypes["todos_stddev_order_by"],
stddev_pop?:ValueTypes["todos_stddev_pop_order_by"],
stddev_samp?:ValueTypes["todos_stddev_samp_order_by"],
sum?:ValueTypes["todos_sum_order_by"],
var_pop?:ValueTypes["todos_var_pop_order_by"],
var_samp?:ValueTypes["todos_var_samp_order_by"],
variance?:ValueTypes["todos_variance_order_by"]
};
/** input type for inserting array relation for remote table "todos" */
["todos_arr_rel_insert_input"]: {
data:ValueTypes["todos_insert_input"][],
on_conflict?:ValueTypes["todos_on_conflict"]
};
/** aggregate avg on columns */
["todos_avg_fields"]: AliasType<{
id?:true
__typename?: true
}>;
/** order by avg() on columns of table "todos" */
["todos_avg_order_by"]: {
id?:ValueTypes["order_by"]
};
/** Boolean expression to filter rows from the table "todos". All fields are combined with a logical 'AND'. */
["todos_bool_exp"]: {
_and?:(ValueTypes["todos_bool_exp"] | undefined)[],
_not?:ValueTypes["todos_bool_exp"],
_or?:(ValueTypes["todos_bool_exp"] | undefined)[],
id?:ValueTypes["Int_comparison_exp"],
is_completed?:ValueTypes["Boolean_comparison_exp"],
text?:ValueTypes["String_comparison_exp"],
user?:ValueTypes["users_bool_exp"],
user_authID?:ValueTypes["String_comparison_exp"]
};
/** unique or primary key constraints on table "todos" */
["todos_constraint"]:todos_constraint;
/** input type for incrementing integer columne in table "todos" */
["todos_inc_input"]: {
id?:number
};
/** input type for inserting data into table "todos" */
["todos_insert_input"]: {
id?:number,
is_completed?:boolean,
text?:string,
user?:ValueTypes["users_obj_rel_insert_input"],
user_authID?:string
};
/** aggregate max on columns */
["todos_max_fields"]: AliasType<{
id?:true,
text?:true,
user_authID?:true
__typename?: true
}>;
/** order by max() on columns of table "todos" */
["todos_max_order_by"]: {
id?:ValueTypes["order_by"],
text?:ValueTypes["order_by"],
user_authID?:ValueTypes["order_by"]
};
/** aggregate min on columns */
["todos_min_fields"]: AliasType<{
id?:true,
text?:true,
user_authID?:true
__typename?: true
}>;
/** order by min() on columns of table "todos" */
["todos_min_order_by"]: {
id?:ValueTypes["order_by"],
text?:ValueTypes["order_by"],
user_authID?:ValueTypes["order_by"]
};
/** response of any mutation on the table "todos" */
["todos_mutation_response"]: AliasType<{
/** number of affected rows by the mutation */
affected_rows?:true,
/** data of the affected rows by the mutation */
returning?:ValueTypes["todos"]
__typename?: true
}>;
/** input type for inserting object relation for remote table "todos" */
["todos_obj_rel_insert_input"]: {
data:ValueTypes["todos_insert_input"],
on_conflict?:ValueTypes["todos_on_conflict"]
};
/** on conflict condition type for table "todos" */
["todos_on_conflict"]: {
constraint:ValueTypes["todos_constraint"],
update_columns:ValueTypes["todos_update_column"][]
};
/** ordering options when selecting data from "todos" */
["todos_order_by"]: {
id?:ValueTypes["order_by"],
is_completed?:ValueTypes["order_by"],
text?:ValueTypes["order_by"],
user?:ValueTypes["users_order_by"],
user_authID?:ValueTypes["order_by"]
};
/** select columns of table "todos" */
["todos_select_column"]:todos_select_column;
/** input type for updating data in table "todos" */
["todos_set_input"]: {
id?:number,
is_completed?:boolean,
text?:string,
user_authID?:string
};
/** aggregate stddev on columns */
["todos_stddev_fields"]: AliasType<{
id?:true
__typename?: true
}>;
/** order by stddev() on columns of table "todos" */
["todos_stddev_order_by"]: {
id?:ValueTypes["order_by"]
};
/** aggregate stddev_pop on columns */
["todos_stddev_pop_fields"]: AliasType<{
id?:true
__typename?: true
}>;
/** order by stddev_pop() on columns of table "todos" */
["todos_stddev_pop_order_by"]: {
id?:ValueTypes["order_by"]
};
/** aggregate stddev_samp on columns */
["todos_stddev_samp_fields"]: AliasType<{
id?:true
__typename?: true
}>;
/** order by stddev_samp() on columns of table "todos" */
["todos_stddev_samp_order_by"]: {
id?:ValueTypes["order_by"]
};
/** aggregate sum on columns */
["todos_sum_fields"]: AliasType<{
id?:true
__typename?: true
}>;
/** order by sum() on columns of table "todos" */
["todos_sum_order_by"]: {
id?:ValueTypes["order_by"]
};
/** update columns of table "todos" */
["todos_update_column"]:todos_update_column;
/** aggregate var_pop on columns */
["todos_var_pop_fields"]: AliasType<{
id?:true
__typename?: true
}>;
/** order by var_pop() on columns of table "todos" */
["todos_var_pop_order_by"]: {
id?:ValueTypes["order_by"]
};
/** aggregate var_samp on columns */
["todos_var_samp_fields"]: AliasType<{
id?:true
__typename?: true
}>;
/** order by var_samp() on columns of table "todos" */
["todos_var_samp_order_by"]: {
id?:ValueTypes["order_by"]
};
/** aggregate variance on columns */
["todos_variance_fields"]: AliasType<{
id?:true
__typename?: true
}>;
/** order by variance() on columns of table "todos" */
["todos_variance_order_by"]: {
id?:ValueTypes["order_by"]
};
/** The `Upload` scalar type represents a file upload. */
["Upload"]:unknown;
/** columns and relationships of "users" */
["users"]: AliasType<{
authID?:true,
id?:true,
name?:true,
todos?: [{ /** distinct select on columns */
distinct_on?:ValueTypes["todos_select_column"][], /** limit the nuber of rows returned */
limit?:number, /** skip the first n rows. Use only with order_by */
offset?:number, /** sort the rows by one or more columns */
order_by?:ValueTypes["todos_order_by"][], /** filter the rows returned */
where?:ValueTypes["todos_bool_exp"]},ValueTypes["todos"]],
todos_aggregate?: [{ /** distinct select on columns */
distinct_on?:ValueTypes["todos_select_column"][], /** limit the nuber of rows returned */
limit?:number, /** skip the first n rows. Use only with order_by */
offset?:number, /** sort the rows by one or more columns */
order_by?:ValueTypes["todos_order_by"][], /** filter the rows returned */
where?:ValueTypes["todos_bool_exp"]},ValueTypes["todos_aggregate"]]
__typename?: true
}>;
/** aggregated selection of "users" */
["users_aggregate"]: AliasType<{
aggregate?:ValueTypes["users_aggregate_fields"],
nodes?:ValueTypes["users"]
__typename?: true
}>;
/** aggregate fields of "users" */
["users_aggregate_fields"]: AliasType<{
avg?:ValueTypes["users_avg_fields"],
count?: [{ columns?:ValueTypes["users_select_column"][], distinct?:boolean},true],
max?:ValueTypes["users_max_fields"],
min?:ValueTypes["users_min_fields"],
stddev?:ValueTypes["users_stddev_fields"],
stddev_pop?:ValueTypes["users_stddev_pop_fields"],
stddev_samp?:ValueTypes["users_stddev_samp_fields"],
sum?:ValueTypes["users_sum_fields"],
var_pop?:ValueTypes["users_var_pop_fields"],
var_samp?:ValueTypes["users_var_samp_fields"],
variance?:ValueTypes["users_variance_fields"]
__typename?: true
}>;
/** order by aggregate values of table "users" */
["users_aggregate_order_by"]: {
avg?:ValueTypes["users_avg_order_by"],
count?:ValueTypes["order_by"],
max?:ValueTypes["users_max_order_by"],
min?:ValueTypes["users_min_order_by"],
stddev?:ValueTypes["users_stddev_order_by"],
stddev_pop?:ValueTypes["users_stddev_pop_order_by"],
stddev_samp?:ValueTypes["users_stddev_samp_order_by"],
sum?:ValueTypes["users_sum_order_by"],
var_pop?:ValueTypes["users_var_pop_order_by"],
var_samp?:ValueTypes["users_var_samp_order_by"],
variance?:ValueTypes["users_variance_order_by"]
};
/** input type for inserting array relation for remote table "users" */
["users_arr_rel_insert_input"]: {
data:ValueTypes["users_insert_input"][],
on_conflict?:ValueTypes["users_on_conflict"]
};
/** aggregate avg on columns */
["users_avg_fields"]: AliasType<{
id?:true
__typename?: true
}>;
/** order by avg() on columns of table "users" */
["users_avg_order_by"]: {
id?:ValueTypes["order_by"]
};
/** Boolean expression to filter rows from the table "users". All fields are combined with a logical 'AND'. */
["users_bool_exp"]: {
_and?:(ValueTypes["users_bool_exp"] | undefined)[],
_not?:ValueTypes["users_bool_exp"],
_or?:(ValueTypes["users_bool_exp"] | undefined)[],
authID?:ValueTypes["String_comparison_exp"],
id?:ValueTypes["Int_comparison_exp"],
name?:ValueTypes["String_comparison_exp"],
todos?:ValueTypes["todos_bool_exp"]
};
/** unique or primary key constraints on table "users" */
["users_constraint"]:users_constraint;
/** input type for incrementing integer columne in table "users" */
["users_inc_input"]: {
id?:number
};
/** input type for inserting data into table "users" */
["users_insert_input"]: {
authID?:string,
id?:number,
name?:string,
todos?:ValueTypes["todos_arr_rel_insert_input"]
};
/** aggregate max on columns */
["users_max_fields"]: AliasType<{
authID?:true,
id?:true,
name?:true
__typename?: true
}>;
/** order by max() on columns of table "users" */
["users_max_order_by"]: {
authID?:ValueTypes["order_by"],
id?:ValueTypes["order_by"],
name?:ValueTypes["order_by"]
};
/** aggregate min on columns */
["users_min_fields"]: AliasType<{
authID?:true,
id?:true,
name?:true
__typename?: true
}>;
/** order by min() on columns of table "users" */
["users_min_order_by"]: {
authID?:ValueTypes["order_by"],
id?:ValueTypes["order_by"],
name?:ValueTypes["order_by"]
};
/** response of any mutation on the table "users" */
["users_mutation_response"]: AliasType<{
/** number of affected rows by the mutation */
affected_rows?:true,
/** data of the affected rows by the mutation */
returning?:ValueTypes["users"]
__typename?: true
}>;
/** input type for inserting object relation for remote table "users" */
["users_obj_rel_insert_input"]: {
data:ValueTypes["users_insert_input"],
on_conflict?:ValueTypes["users_on_conflict"]
};
/** on conflict condition type for table "users" */
["users_on_conflict"]: {
constraint:ValueTypes["users_constraint"],
update_columns:ValueTypes["users_update_column"][]
};
/** ordering options when selecting data from "users" */
["users_order_by"]: {
authID?:ValueTypes["order_by"],
id?:ValueTypes["order_by"],
name?:ValueTypes["order_by"],
todos_aggregate?:ValueTypes["todos_aggregate_order_by"]
};
/** select columns of table "users" */
["users_select_column"]:users_select_column;
/** input type for updating data in table "users" */
["users_set_input"]: {
authID?:string,
id?:number,
name?:string
};
/** aggregate stddev on columns */
["users_stddev_fields"]: AliasType<{
id?:true
__typename?: true
}>;
/** order by stddev() on columns of table "users" */
["users_stddev_order_by"]: {
id?:ValueTypes["order_by"]
};
/** aggregate stddev_pop on columns */
["users_stddev_pop_fields"]: AliasType<{
id?:true
__typename?: true
}>;
/** order by stddev_pop() on columns of table "users" */
["users_stddev_pop_order_by"]: {
id?:ValueTypes["order_by"]
};
/** aggregate stddev_samp on columns */
["users_stddev_samp_fields"]: AliasType<{
id?:true
__typename?: true
}>;
/** order by stddev_samp() on columns of table "users" */
["users_stddev_samp_order_by"]: {
id?:ValueTypes["order_by"]
};
/** aggregate sum on columns */
["users_sum_fields"]: AliasType<{
id?:true
__typename?: true
}>;
/** order by sum() on columns of table "users" */
["users_sum_order_by"]: {
id?:ValueTypes["order_by"]
};
/** update columns of table "users" */
["users_update_column"]:users_update_column;
/** aggregate var_pop on columns */
["users_var_pop_fields"]: AliasType<{
id?:true
__typename?: true
}>;
/** order by var_pop() on columns of table "users" */
["users_var_pop_order_by"]: {
id?:ValueTypes["order_by"]
};
/** aggregate var_samp on columns */
["users_var_samp_fields"]: AliasType<{
id?:true
__typename?: true
}>;
/** order by var_samp() on columns of table "users" */
["users_var_samp_order_by"]: {
id?:ValueTypes["order_by"]
};
/** aggregate variance on columns */
["users_variance_fields"]: AliasType<{
id?:true
__typename?: true
}>;
/** order by variance() on columns of table "users" */
["users_variance_order_by"]: {
id?:ValueTypes["order_by"]
}
}
export type PartialObjects = {
/** expression to compare columns of type Boolean. All fields are combined with logical 'AND'. */
["Boolean_comparison_exp"]: {
_eq?:boolean,
_gt?:boolean,
_gte?:boolean,
_in?:boolean[],
_is_null?:boolean,
_lt?:boolean,
_lte?:boolean,
_neq?:boolean,
_nin?:boolean[]
},
["CacheControlScope"]:CacheControlScope,
/** conflict action */
["conflict_action"]:conflict_action,
/** expression to compare columns of type Int. All fields are combined with logical 'AND'. */
["Int_comparison_exp"]: {
_eq?:number,
_gt?:number,
_gte?:number,
_in?:number[],
_is_null?:boolean,
_lt?:number,
_lte?:number,
_neq?:number,
_nin?:number[]
},
/** mutation root */
["mutation_root"]: {
__typename?: "mutation_root";
/** delete data from the table: "todos" */
delete_todos?:PartialObjects["todos_mutation_response"],
/** delete data from the table: "users" */
delete_users?:PartialObjects["users_mutation_response"],
/** insert data into the table: "todos" */
insert_todos?:PartialObjects["todos_mutation_response"],
/** insert data into the table: "users" */
insert_users?:PartialObjects["users_mutation_response"],
/** update data of the table: "todos" */
update_todos?:PartialObjects["todos_mutation_response"],
/** update data of the table: "users" */
update_users?:PartialObjects["users_mutation_response"]
},
/** column ordering options */
["order_by"]:order_by,
["Query"]: {
__typename?: "Query";
hello?:string
},
/** query root */
["query_root"]: {
__typename?: "query_root";
hello?:string,
/** fetch data from the table: "todos" */
todos?:PartialObjects["todos"][],
/** fetch aggregated fields from the table: "todos" */
todos_aggregate?:PartialObjects["todos_aggregate"],
/** fetch data from the table: "todos" using primary key columns */
todos_by_pk?:PartialObjects["todos"],
/** fetch data from the table: "users" */
users?:PartialObjects["users"][],
/** fetch aggregated fields from the table: "users" */
users_aggregate?:PartialObjects["users_aggregate"],
/** fetch data from the table: "users" using primary key columns */
users_by_pk?:PartialObjects["users"]
},
/** expression to compare columns of type String. All fields are combined with logical 'AND'. */
["String_comparison_exp"]: {
_eq?:string,
_gt?:string,
_gte?:string,
_ilike?:string,
_in?:string[],
_is_null?:boolean,
_like?:string,
_lt?:string,
_lte?:string,
_neq?:string,
_nilike?:string,
_nin?:string[],
_nlike?:string,
_nsimilar?:string,
_similar?:string
},
/** subscription root */
["subscription_root"]: {
__typename?: "subscription_root";
/** fetch data from the table: "todos" */
todos?:PartialObjects["todos"][],
/** fetch aggregated fields from the table: "todos" */
todos_aggregate?:PartialObjects["todos_aggregate"],
/** fetch data from the table: "todos" using primary key columns */
todos_by_pk?:PartialObjects["todos"],
/** fetch data from the table: "users" */
users?:PartialObjects["users"][],
/** fetch aggregated fields from the table: "users" */
users_aggregate?:PartialObjects["users_aggregate"],
/** fetch data from the table: "users" using primary key columns */
users_by_pk?:PartialObjects["users"]
},
/** columns and relationships of "todos" */
["todos"]: {
__typename?: "todos";
id?:number,
is_completed?:boolean,
text?:string,
/** An object relationship */
user?:PartialObjects["users"],
user_authID?:string
},
/** aggregated selection of "todos" */
["todos_aggregate"]: {
__typename?: "todos_aggregate";
aggregate?:PartialObjects["todos_aggregate_fields"],
nodes?:PartialObjects["todos"][]
},
/** aggregate fields of "todos" */
["todos_aggregate_fields"]: {
__typename?: "todos_aggregate_fields";
avg?:PartialObjects["todos_avg_fields"],
count?:number,
max?:PartialObjects["todos_max_fields"],
min?:PartialObjects["todos_min_fields"],
stddev?:PartialObjects["todos_stddev_fields"],
stddev_pop?:PartialObjects["todos_stddev_pop_fields"],
stddev_samp?:PartialObjects["todos_stddev_samp_fields"],
sum?:PartialObjects["todos_sum_fields"],
var_pop?:PartialObjects["todos_var_pop_fields"],
var_samp?:PartialObjects["todos_var_samp_fields"],
variance?:PartialObjects["todos_variance_fields"]
},
/** order by aggregate values of table "todos" */
["todos_aggregate_order_by"]: {
avg?:PartialObjects["todos_avg_order_by"],
count?:PartialObjects["order_by"],
max?:PartialObjects["todos_max_order_by"],
min?:PartialObjects["todos_min_order_by"],
stddev?:PartialObjects["todos_stddev_order_by"],
stddev_pop?:PartialObjects["todos_stddev_pop_order_by"],
stddev_samp?:PartialObjects["todos_stddev_samp_order_by"],
sum?:PartialObjects["todos_sum_order_by"],
var_pop?:PartialObjects["todos_var_pop_order_by"],
var_samp?:PartialObjects["todos_var_samp_order_by"],
variance?:PartialObjects["todos_variance_order_by"]
},
/** input type for inserting array relation for remote table "todos" */
["todos_arr_rel_insert_input"]: {
data:PartialObjects["todos_insert_input"][],
on_conflict?:PartialObjects["todos_on_conflict"]
},
/** aggregate avg on columns */
["todos_avg_fields"]: {
__typename?: "todos_avg_fields";
id?:number
},
/** order by avg() on columns of table "todos" */
["todos_avg_order_by"]: {
id?:PartialObjects["order_by"]
},
/** Boolean expression to filter rows from the table "todos". All fields are combined with a logical 'AND'. */
["todos_bool_exp"]: {
_and?:(PartialObjects["todos_bool_exp"] | undefined)[],
_not?:PartialObjects["todos_bool_exp"],
_or?:(PartialObjects["todos_bool_exp"] | undefined)[],
id?:PartialObjects["Int_comparison_exp"],
is_completed?:PartialObjects["Boolean_comparison_exp"],
text?:PartialObjects["String_comparison_exp"],
user?:PartialObjects["users_bool_exp"],
user_authID?:PartialObjects["String_comparison_exp"]
},
/** unique or primary key constraints on table "todos" */
["todos_constraint"]:todos_constraint,
/** input type for incrementing integer columne in table "todos" */
["todos_inc_input"]: {
id?:number
},
/** input type for inserting data into table "todos" */
["todos_insert_input"]: {
id?:number,
is_completed?:boolean,
text?:string,
user?:PartialObjects["users_obj_rel_insert_input"],
user_authID?:string
},
/** aggregate max on columns */
["todos_max_fields"]: {
__typename?: "todos_max_fields";
id?:number,
text?:string,
user_authID?:string
},
/** order by max() on columns of table "todos" */
["todos_max_order_by"]: {
id?:PartialObjects["order_by"],
text?:PartialObjects["order_by"],
user_authID?:PartialObjects["order_by"]
},
/** aggregate min on columns */
["todos_min_fields"]: {
__typename?: "todos_min_fields";
id?:number,
text?:string,
user_authID?:string
},
/** order by min() on columns of table "todos" */
["todos_min_order_by"]: {
id?:PartialObjects["order_by"],
text?:PartialObjects["order_by"],
user_authID?:PartialObjects["order_by"]
},
/** response of any mutation on the table "todos" */
["todos_mutation_response"]: {
__typename?: "todos_mutation_response";
/** number of affected rows by the mutation */
affected_rows?:number,
/** data of the affected rows by the mutation */
returning?:PartialObjects["todos"][]
},
/** input type for inserting object relation for remote table "todos" */
["todos_obj_rel_insert_input"]: {
data:PartialObjects["todos_insert_input"],
on_conflict?:PartialObjects["todos_on_conflict"]
},
/** on conflict condition type for table "todos" */
["todos_on_conflict"]: {
constraint:PartialObjects["todos_constraint"],
update_columns:PartialObjects["todos_update_column"][]
},
/** ordering options when selecting data from "todos" */
["todos_order_by"]: {
id?:PartialObjects["order_by"],
is_completed?:PartialObjects["order_by"],
text?:PartialObjects["order_by"],
user?:PartialObjects["users_order_by"],
user_authID?:PartialObjects["order_by"]
},
/** select columns of table "todos" */
["todos_select_column"]:todos_select_column,
/** input type for updating data in table "todos" */
["todos_set_input"]: {
id?:number,
is_completed?:boolean,
text?:string,
user_authID?:string
},
/** aggregate stddev on columns */
["todos_stddev_fields"]: {
__typename?: "todos_stddev_fields";
id?:number
},
/** order by stddev() on columns of table "todos" */
["todos_stddev_order_by"]: {
id?:PartialObjects["order_by"]
},
/** aggregate stddev_pop on columns */
["todos_stddev_pop_fields"]: {
__typename?: "todos_stddev_pop_fields";
id?:number
},
/** order by stddev_pop() on columns of table "todos" */
["todos_stddev_pop_order_by"]: {
id?:PartialObjects["order_by"]
},
/** aggregate stddev_samp on columns */
["todos_stddev_samp_fields"]: {
__typename?: "todos_stddev_samp_fields";
id?:number
},
/** order by stddev_samp() on columns of table "todos" */
["todos_stddev_samp_order_by"]: {
id?:PartialObjects["order_by"]
},
/** aggregate sum on columns */
["todos_sum_fields"]: {
__typename?: "todos_sum_fields";
id?:number
},
/** order by sum() on columns of table "todos" */
["todos_sum_order_by"]: {
id?:PartialObjects["order_by"]
},
/** update columns of table "todos" */
["todos_update_column"]:todos_update_column,
/** aggregate var_pop on columns */
["todos_var_pop_fields"]: {
__typename?: "todos_var_pop_fields";
id?:number
},
/** order by var_pop() on columns of table "todos" */
["todos_var_pop_order_by"]: {
id?:PartialObjects["order_by"]
},
/** aggregate var_samp on columns */
["todos_var_samp_fields"]: {
__typename?: "todos_var_samp_fields";
id?:number
},
/** order by var_samp() on columns of table "todos" */
["todos_var_samp_order_by"]: {
id?:PartialObjects["order_by"]
},
/** aggregate variance on columns */
["todos_variance_fields"]: {
__typename?: "todos_variance_fields";
id?:number
},
/** order by variance() on columns of table "todos" */
["todos_variance_order_by"]: {
id?:PartialObjects["order_by"]
},
/** The `Upload` scalar type represents a file upload. */
["Upload"]:any,
/** columns and relationships of "users" */
["users"]: {
__typename?: "users";
authID?:string,
id?:number,
name?:string,
/** An array relationship */
todos?:PartialObjects["todos"][],
/** An aggregated array relationship */
todos_aggregate?:PartialObjects["todos_aggregate"]
},
/** aggregated selection of "users" */
["users_aggregate"]: {
__typename?: "users_aggregate";
aggregate?:PartialObjects["users_aggregate_fields"],
nodes?:PartialObjects["users"][]
},
/** aggregate fields of "users" */
["users_aggregate_fields"]: {
__typename?: "users_aggregate_fields";
avg?:PartialObjects["users_avg_fields"],
count?:number,
max?:PartialObjects["users_max_fields"],
min?:PartialObjects["users_min_fields"],
stddev?:PartialObjects["users_stddev_fields"],
stddev_pop?:PartialObjects["users_stddev_pop_fields"],
stddev_samp?:PartialObjects["users_stddev_samp_fields"],
sum?:PartialObjects["users_sum_fields"],
var_pop?:PartialObjects["users_var_pop_fields"],
var_samp?:PartialObjects["users_var_samp_fields"],
variance?:PartialObjects["users_variance_fields"]
},
/** order by aggregate values of table "users" */
["users_aggregate_order_by"]: {
avg?:PartialObjects["users_avg_order_by"],
count?:PartialObjects["order_by"],
max?:PartialObjects["users_max_order_by"],
min?:PartialObjects["users_min_order_by"],
stddev?:PartialObjects["users_stddev_order_by"],
stddev_pop?:PartialObjects["users_stddev_pop_order_by"],
stddev_samp?:PartialObjects["users_stddev_samp_order_by"],
sum?:PartialObjects["users_sum_order_by"],
var_pop?:PartialObjects["users_var_pop_order_by"],
var_samp?:PartialObjects["users_var_samp_order_by"],
variance?:PartialObjects["users_variance_order_by"]
},
/** input type for inserting array relation for remote table "users" */
["users_arr_rel_insert_input"]: {
data:PartialObjects["users_insert_input"][],
on_conflict?:PartialObjects["users_on_conflict"]
},
/** aggregate avg on columns */
["users_avg_fields"]: {
__typename?: "users_avg_fields";
id?:number
},
/** order by avg() on columns of table "users" */
["users_avg_order_by"]: {
id?:PartialObjects["order_by"]
},
/** Boolean expression to filter rows from the table "users". All fields are combined with a logical 'AND'. */
["users_bool_exp"]: {
_and?:(PartialObjects["users_bool_exp"] | undefined)[],
_not?:PartialObjects["users_bool_exp"],
_or?:(PartialObjects["users_bool_exp"] | undefined)[],
authID?:PartialObjects["String_comparison_exp"],
id?:PartialObjects["Int_comparison_exp"],
name?:PartialObjects["String_comparison_exp"],
todos?:PartialObjects["todos_bool_exp"]
},
/** unique or primary key constraints on table "users" */
["users_constraint"]:users_constraint,
/** input type for incrementing integer columne in table "users" */
["users_inc_input"]: {
id?:number
},
/** input type for inserting data into table "users" */
["users_insert_input"]: {
authID?:string,
id?:number,
name?:string,
todos?:PartialObjects["todos_arr_rel_insert_input"]
},
/** aggregate max on columns */
["users_max_fields"]: {
__typename?: "users_max_fields";
authID?:string,
id?:number,
name?:string
},
/** order by max() on columns of table "users" */
["users_max_order_by"]: {
authID?:PartialObjects["order_by"],
id?:PartialObjects["order_by"],
name?:PartialObjects["order_by"]
},
/** aggregate min on columns */
["users_min_fields"]: {
__typename?: "users_min_fields";
authID?:string,
id?:number,
name?:string
},
/** order by min() on columns of table "users" */
["users_min_order_by"]: {
authID?:PartialObjects["order_by"],
id?:PartialObjects["order_by"],
name?:PartialObjects["order_by"]
},
/** response of any mutation on the table "users" */
["users_mutation_response"]: {
__typename?: "users_mutation_response";
/** number of affected rows by the mutation */
affected_rows?:number,
/** data of the affected rows by the mutation */
returning?:PartialObjects["users"][]
},
/** input type for inserting object relation for remote table "users" */
["users_obj_rel_insert_input"]: {
data:PartialObjects["users_insert_input"],
on_conflict?:PartialObjects["users_on_conflict"]
},
/** on conflict condition type for table "users" */
["users_on_conflict"]: {
constraint:PartialObjects["users_constraint"],
update_columns:PartialObjects["users_update_column"][]
},
/** ordering options when selecting data from "users" */
["users_order_by"]: {
authID?:PartialObjects["order_by"],
id?:PartialObjects["order_by"],
name?:PartialObjects["order_by"],
todos_aggregate?:PartialObjects["todos_aggregate_order_by"]
},
/** select columns of table "users" */
["users_select_column"]:users_select_column,
/** input type for updating data in table "users" */
["users_set_input"]: {
authID?:string,
id?:number,
name?:string
},
/** aggregate stddev on columns */
["users_stddev_fields"]: {
__typename?: "users_stddev_fields";
id?:number
},
/** order by stddev() on columns of table "users" */
["users_stddev_order_by"]: {
id?:PartialObjects["order_by"]
},
/** aggregate stddev_pop on columns */
["users_stddev_pop_fields"]: {
__typename?: "users_stddev_pop_fields";
id?:number
},
/** order by stddev_pop() on columns of table "users" */
["users_stddev_pop_order_by"]: {
id?:PartialObjects["order_by"]
},
/** aggregate stddev_samp on columns */
["users_stddev_samp_fields"]: {
__typename?: "users_stddev_samp_fields";
id?:number
},
/** order by stddev_samp() on columns of table "users" */
["users_stddev_samp_order_by"]: {
id?:PartialObjects["order_by"]
},
/** aggregate sum on columns */
["users_sum_fields"]: {
__typename?: "users_sum_fields";
id?:number
},
/** order by sum() on columns of table "users" */
["users_sum_order_by"]: {
id?:PartialObjects["order_by"]
},
/** update columns of table "users" */
["users_update_column"]:users_update_column,
/** aggregate var_pop on columns */
["users_var_pop_fields"]: {
__typename?: "users_var_pop_fields";
id?:number
},
/** order by var_pop() on columns of table "users" */
["users_var_pop_order_by"]: {
id?:PartialObjects["order_by"]
},
/** aggregate var_samp on columns */
["users_var_samp_fields"]: {
__typename?: "users_var_samp_fields";
id?:number
},
/** order by var_samp() on columns of table "users" */
["users_var_samp_order_by"]: {
id?:PartialObjects["order_by"]
},
/** aggregate variance on columns */
["users_variance_fields"]: {
__typename?: "users_variance_fields";
id?:number
},
/** order by variance() on columns of table "users" */
["users_variance_order_by"]: {
id?:PartialObjects["order_by"]
}
}
/** expression to compare columns of type Boolean. All fields are combined with logical 'AND'. */
export type Boolean_comparison_exp = {
_eq?:boolean,
_gt?:boolean,
_gte?:boolean,
_in?:boolean[],
_is_null?:boolean,
_lt?:boolean,
_lte?:boolean,
_neq?:boolean,
_nin?:boolean[]
}
export enum CacheControlScope {
PRIVATE = "PRIVATE",
PUBLIC = "PUBLIC"
}
/** conflict action */
export enum conflict_action {
ignore = "ignore",
update = "update"
}
/** expression to compare columns of type Int. All fields are combined with logical 'AND'. */
export type Int_comparison_exp = {
_eq?:number,
_gt?:number,
_gte?:number,
_in?:number[],
_is_null?:boolean,
_lt?:number,
_lte?:number,
_neq?:number,
_nin?:number[]
}
/** mutation root */
export type mutation_root = {
__typename?: "mutation_root",
/** delete data from the table: "todos" */
delete_todos?:todos_mutation_response,
/** delete data from the table: "users" */
delete_users?:users_mutation_response,
/** insert data into the table: "todos" */
insert_todos?:todos_mutation_response,
/** insert data into the table: "users" */
insert_users?:users_mutation_response,
/** update data of the table: "todos" */
update_todos?:todos_mutation_response,
/** update data of the table: "users" */
update_users?:users_mutation_response
}
/** column ordering options */
export enum order_by {
asc = "asc",
asc_nulls_first = "asc_nulls_first",
asc_nulls_last = "asc_nulls_last",
desc = "desc",
desc_nulls_first = "desc_nulls_first",
desc_nulls_last = "desc_nulls_last"
}
export type Query = {
__typename?: "Query",
hello?:string
}
/** query root */
export type query_root = {
__typename?: "query_root",
hello?:string,
/** fetch data from the table: "todos" */
todos:todos[],
/** fetch aggregated fields from the table: "todos" */
todos_aggregate:todos_aggregate,
/** fetch data from the table: "todos" using primary key columns */
todos_by_pk?:todos,
/** fetch data from the table: "users" */
users:users[],
/** fetch aggregated fields from the table: "users" */
users_aggregate:users_aggregate,
/** fetch data from the table: "users" using primary key columns */
users_by_pk?:users
}
/** expression to compare columns of type String. All fields are combined with logical 'AND'. */
export type String_comparison_exp = {
_eq?:string,
_gt?:string,
_gte?:string,
_ilike?:string,
_in?:string[],
_is_null?:boolean,
_like?:string,
_lt?:string,
_lte?:string,
_neq?:string,
_nilike?:string,
_nin?:string[],
_nlike?:string,
_nsimilar?:string,
_similar?:string
}
/** subscription root */
export type subscription_root = {
__typename?: "subscription_root",
/** fetch data from the table: "todos" */
todos:todos[],
/** fetch aggregated fields from the table: "todos" */
todos_aggregate:todos_aggregate,
/** fetch data from the table: "todos" using primary key columns */
todos_by_pk?:todos,
/** fetch data from the table: "users" */
users:users[],
/** fetch aggregated fields from the table: "users" */
users_aggregate:users_aggregate,
/** fetch data from the table: "users" using primary key columns */
users_by_pk?:users
}
/** columns and relationships of "todos" */
export type todos = {
__typename?: "todos",
id:number,
is_completed:boolean,
text:string,
/** An object relationship */
user:users,
user_authID:string
}
/** aggregated selection of "todos" */
export type todos_aggregate = {
__typename?: "todos_aggregate",
aggregate?:todos_aggregate_fields,
nodes:todos[]
}
/** aggregate fields of "todos" */
export type todos_aggregate_fields = {
__typename?: "todos_aggregate_fields",
avg?:todos_avg_fields,
count?:number,
max?:todos_max_fields,
min?:todos_min_fields,
stddev?:todos_stddev_fields,
stddev_pop?:todos_stddev_pop_fields,
stddev_samp?:todos_stddev_samp_fields,
sum?:todos_sum_fields,
var_pop?:todos_var_pop_fields,
var_samp?:todos_var_samp_fields,
variance?:todos_variance_fields
}
/** order by aggregate values of table "todos" */
export type todos_aggregate_order_by = {
avg?:todos_avg_order_by,
count?:order_by,
max?:todos_max_order_by,
min?:todos_min_order_by,
stddev?:todos_stddev_order_by,
stddev_pop?:todos_stddev_pop_order_by,
stddev_samp?:todos_stddev_samp_order_by,
sum?:todos_sum_order_by,
var_pop?:todos_var_pop_order_by,
var_samp?:todos_var_samp_order_by,
variance?:todos_variance_order_by
}
/** input type for inserting array relation for remote table "todos" */
export type todos_arr_rel_insert_input = {
data:todos_insert_input[],
on_conflict?:todos_on_conflict
}
/** aggregate avg on columns */
export type todos_avg_fields = {
__typename?: "todos_avg_fields",
id?:number
}
/** order by avg() on columns of table "todos" */
export type todos_avg_order_by = {
id?:order_by
}
/** Boolean expression to filter rows from the table "todos". All fields are combined with a logical 'AND'. */
export type todos_bool_exp = {
_and?:(todos_bool_exp | undefined)[],
_not?:todos_bool_exp,
_or?:(todos_bool_exp | undefined)[],
id?:Int_comparison_exp,
is_completed?:Boolean_comparison_exp,
text?:String_comparison_exp,
user?:users_bool_exp,
user_authID?:String_comparison_exp
}
/** unique or primary key constraints on table "todos" */
export enum todos_constraint {
todos_pkey = "todos_pkey"
}
/** input type for incrementing integer columne in table "todos" */
export type todos_inc_input = {
id?:number
}
/** input type for inserting data into table "todos" */
export type todos_insert_input = {
id?:number,
is_completed?:boolean,
text?:string,
user?:users_obj_rel_insert_input,
user_authID?:string
}
/** aggregate max on columns */
export type todos_max_fields = {
__typename?: "todos_max_fields",
id?:number,
text?:string,
user_authID?:string
}
/** order by max() on columns of table "todos" */
export type todos_max_order_by = {
id?:order_by,
text?:order_by,
user_authID?:order_by
}
/** aggregate min on columns */
export type todos_min_fields = {
__typename?: "todos_min_fields",
id?:number,
text?:string,
user_authID?:string
}
/** order by min() on columns of table "todos" */
export type todos_min_order_by = {
id?:order_by,
text?:order_by,
user_authID?:order_by
}
/** response of any mutation on the table "todos" */
export type todos_mutation_response = {
__typename?: "todos_mutation_response",
/** number of affected rows by the mutation */
affected_rows:number,
/** data of the affected rows by the mutation */
returning:todos[]
}
/** input type for inserting object relation for remote table "todos" */
export type todos_obj_rel_insert_input = {
data:todos_insert_input,
on_conflict?:todos_on_conflict
}
/** on conflict condition type for table "todos" */
export type todos_on_conflict = {
constraint:todos_constraint,
update_columns:todos_update_column[]
}
/** ordering options when selecting data from "todos" */
export type todos_order_by = {
id?:order_by,
is_completed?:order_by,
text?:order_by,
user?:users_order_by,
user_authID?:order_by
}
/** select columns of table "todos" */
export enum todos_select_column {
id = "id",
is_completed = "is_completed",
text = "text",
user_authID = "user_authID"
}
/** input type for updating data in table "todos" */
export type todos_set_input = {
id?:number,
is_completed?:boolean,
text?:string,
user_authID?:string
}
/** aggregate stddev on columns */
export type todos_stddev_fields = {
__typename?: "todos_stddev_fields",
id?:number
}
/** order by stddev() on columns of table "todos" */
export type todos_stddev_order_by = {
id?:order_by
}
/** aggregate stddev_pop on columns */
export type todos_stddev_pop_fields = {
__typename?: "todos_stddev_pop_fields",
id?:number
}
/** order by stddev_pop() on columns of table "todos" */
export type todos_stddev_pop_order_by = {
id?:order_by
}
/** aggregate stddev_samp on columns */
export type todos_stddev_samp_fields = {
__typename?: "todos_stddev_samp_fields",
id?:number
}
/** order by stddev_samp() on columns of table "todos" */
export type todos_stddev_samp_order_by = {
id?:order_by
}
/** aggregate sum on columns */
export type todos_sum_fields = {
__typename?: "todos_sum_fields",
id?:number
}
/** order by sum() on columns of table "todos" */
export type todos_sum_order_by = {
id?:order_by
}
/** update columns of table "todos" */
export enum todos_update_column {
id = "id",
is_completed = "is_completed",
text = "text",
user_authID = "user_authID"
}
/** aggregate var_pop on columns */
export type todos_var_pop_fields = {
__typename?: "todos_var_pop_fields",
id?:number
}
/** order by var_pop() on columns of table "todos" */
export type todos_var_pop_order_by = {
id?:order_by
}
/** aggregate var_samp on columns */
export type todos_var_samp_fields = {
__typename?: "todos_var_samp_fields",
id?:number
}
/** order by var_samp() on columns of table "todos" */
export type todos_var_samp_order_by = {
id?:order_by
}
/** aggregate variance on columns */
export type todos_variance_fields = {
__typename?: "todos_variance_fields",
id?:number
}
/** order by variance() on columns of table "todos" */
export type todos_variance_order_by = {
id?:order_by
}
/** The `Upload` scalar type represents a file upload. */
export type Upload = any
/** columns and relationships of "users" */
export type users = {
__typename?: "users",
authID:string,
id:number,
name:string,
/** An array relationship */
todos:todos[],
/** An aggregated array relationship */
todos_aggregate:todos_aggregate
}
/** aggregated selection of "users" */
export type users_aggregate = {
__typename?: "users_aggregate",
aggregate?:users_aggregate_fields,
nodes:users[]
}
/** aggregate fields of "users" */
export type users_aggregate_fields = {
__typename?: "users_aggregate_fields",
avg?:users_avg_fields,
count?:number,
max?:users_max_fields,
min?:users_min_fields,
stddev?:users_stddev_fields,
stddev_pop?:users_stddev_pop_fields,
stddev_samp?:users_stddev_samp_fields,
sum?:users_sum_fields,
var_pop?:users_var_pop_fields,
var_samp?:users_var_samp_fields,
variance?:users_variance_fields
}
/** order by aggregate values of table "users" */
export type users_aggregate_order_by = {
avg?:users_avg_order_by,
count?:order_by,
max?:users_max_order_by,
min?:users_min_order_by,
stddev?:users_stddev_order_by,
stddev_pop?:users_stddev_pop_order_by,
stddev_samp?:users_stddev_samp_order_by,
sum?:users_sum_order_by,
var_pop?:users_var_pop_order_by,
var_samp?:users_var_samp_order_by,
variance?:users_variance_order_by
}
/** input type for inserting array relation for remote table "users" */
export type users_arr_rel_insert_input = {
data:users_insert_input[],
on_conflict?:users_on_conflict
}
/** aggregate avg on columns */
export type users_avg_fields = {
__typename?: "users_avg_fields",
id?:number
}
/** order by avg() on columns of table "users" */
export type users_avg_order_by = {
id?:order_by
}
/** Boolean expression to filter rows from the table "users". All fields are combined with a logical 'AND'. */
export type users_bool_exp = {
_and?:(users_bool_exp | undefined)[],
_not?:users_bool_exp,
_or?:(users_bool_exp | undefined)[],
authID?:String_comparison_exp,
id?:Int_comparison_exp,
name?:String_comparison_exp,
todos?:todos_bool_exp
}
/** unique or primary key constraints on table "users" */
export enum users_constraint {
users_authID_key = "users_authID_key",
users_pkey = "users_pkey"
}
/** input type for incrementing integer columne in table "users" */
export type users_inc_input = {
id?:number
}
/** input type for inserting data into table "users" */
export type users_insert_input = {
authID?:string,
id?:number,
name?:string,
todos?:todos_arr_rel_insert_input
}
/** aggregate max on columns */
export type users_max_fields = {
__typename?: "users_max_fields",
authID?:string,
id?:number,
name?:string
}
/** order by max() on columns of table "users" */
export type users_max_order_by = {
authID?:order_by,
id?:order_by,
name?:order_by
}
/** aggregate min on columns */
export type users_min_fields = {
__typename?: "users_min_fields",
authID?:string,
id?:number,
name?:string
}
/** order by min() on columns of table "users" */
export type users_min_order_by = {
authID?:order_by,
id?:order_by,
name?:order_by
}
/** response of any mutation on the table "users" */
export type users_mutation_response = {
__typename?: "users_mutation_response",
/** number of affected rows by the mutation */
affected_rows:number,
/** data of the affected rows by the mutation */
returning:users[]
}
/** input type for inserting object relation for remote table "users" */
export type users_obj_rel_insert_input = {
data:users_insert_input,
on_conflict?:users_on_conflict
}
/** on conflict condition type for table "users" */
export type users_on_conflict = {
constraint:users_constraint,
update_columns:users_update_column[]
}
/** ordering options when selecting data from "users" */
export type users_order_by = {
authID?:order_by,
id?:order_by,
name?:order_by,
todos_aggregate?:todos_aggregate_order_by
}
/** select columns of table "users" */
export enum users_select_column {
authID = "authID",
id = "id",
name = "name"
}
/** input type for updating data in table "users" */
export type users_set_input = {
authID?:string,
id?:number,
name?:string
}
/** aggregate stddev on columns */
export type users_stddev_fields = {
__typename?: "users_stddev_fields",
id?:number
}
/** order by stddev() on columns of table "users" */
export type users_stddev_order_by = {
id?:order_by
}
/** aggregate stddev_pop on columns */
export type users_stddev_pop_fields = {
__typename?: "users_stddev_pop_fields",
id?:number
}
/** order by stddev_pop() on columns of table "users" */
export type users_stddev_pop_order_by = {
id?:order_by
}
/** aggregate stddev_samp on columns */
export type users_stddev_samp_fields = {
__typename?: "users_stddev_samp_fields",
id?:number
}
/** order by stddev_samp() on columns of table "users" */
export type users_stddev_samp_order_by = {
id?:order_by
}
/** aggregate sum on columns */
export type users_sum_fields = {
__typename?: "users_sum_fields",
id?:number
}
/** order by sum() on columns of table "users" */
export type users_sum_order_by = {
id?:order_by
}
/** update columns of table "users" */
export enum users_update_column {
authID = "authID",
id = "id",
name = "name"
}
/** aggregate var_pop on columns */
export type users_var_pop_fields = {
__typename?: "users_var_pop_fields",
id?:number
}
/** order by var_pop() on columns of table "users" */
export type users_var_pop_order_by = {
id?:order_by
}
/** aggregate var_samp on columns */
export type users_var_samp_fields = {
__typename?: "users_var_samp_fields",
id?:number
}
/** order by var_samp() on columns of table "users" */
export type users_var_samp_order_by = {
id?:order_by
}
/** aggregate variance on columns */
export type users_variance_fields = {
__typename?: "users_variance_fields",
id?:number
}
/** order by variance() on columns of table "users" */
export type users_variance_order_by = {
id?:order_by
}
type Func<P extends any[], R> = (...args: P) => R;
type AnyFunc = Func<any, any>;
type WithTypeNameValue<T> = T & {
__typename?: true;
};
type AliasType<T> = WithTypeNameValue<T> & {
__alias?: Record<string, WithTypeNameValue<T>>;
};
type NotUndefined<T> = T extends undefined ? never : T;
export type ResolverType<F> = NotUndefined<F extends [infer ARGS, any] ? ARGS : undefined>;
export type ArgsType<F extends AnyFunc> = F extends Func<infer P, any> ? P : never;
interface GraphQLResponse {
data?: Record<string, any>;
errors?: Array<{
message: string;
}>;
}
export type MapInterface<SRC, DST> = SRC extends {
__interface: infer INTERFACE;
__resolve: infer IMPLEMENTORS;
}
? ObjectToUnion<
Omit<
{
[Key in keyof Omit<DST, keyof INTERFACE | '__typename'>]: Key extends keyof IMPLEMENTORS
? MapType<IMPLEMENTORS[Key], DST[Key]> &
Omit<
{
[Key in keyof Omit<
DST,
keyof IMPLEMENTORS | '__typename'
>]: Key extends keyof INTERFACE
? LastMapTypeSRCResolver<INTERFACE[Key], DST[Key]>
: never;
},
keyof IMPLEMENTORS
> &
(DST extends { __typename: any }
? MapType<IMPLEMENTORS[Key], { __typename: true }>
: {})
: never;
},
keyof INTERFACE | '__typename'
>
>
: never;
export type ValueToUnion<T> = T extends {
__typename: infer R;
}
? {
[P in keyof Omit<T, '__typename'>]: T[P] & {
__typename: R;
};
}
: T;
export type ObjectToUnion<T> = {
[P in keyof T]: T[P];
}[keyof T];
type Anify<T> = { [P in keyof T]?: any };
type LastMapTypeSRCResolver<SRC, DST> = SRC extends undefined
? undefined
: SRC extends Array<infer AR>
? LastMapTypeSRCResolver<AR, DST>[]
: SRC extends { __interface: any; __resolve: any }
? MapInterface<SRC, DST>
: SRC extends { __union: any; __resolve: infer RESOLVE }
? ObjectToUnion<MapType<RESOLVE, ValueToUnion<DST>>>
: DST extends boolean
? SRC
: MapType<SRC, DST>;
type MapType<SRC extends Anify<DST>, DST> = DST extends boolean
? SRC
: DST extends {
__alias: any;
}
? {
[A in keyof DST["__alias"]]: Required<SRC> extends Anify<
DST["__alias"][A]
>
? MapType<Required<SRC>, DST["__alias"][A]>
: never;
} &
{
[Key in keyof Omit<DST, "__alias">]: DST[Key] extends [
any,
infer PAYLOAD
]
? LastMapTypeSRCResolver<SRC[Key], PAYLOAD>
: LastMapTypeSRCResolver<SRC[Key], DST[Key]>;
}
: {
[Key in keyof DST]: DST[Key] extends [any, infer PAYLOAD]
? LastMapTypeSRCResolver<SRC[Key], PAYLOAD>
: LastMapTypeSRCResolver<SRC[Key], DST[Key]>;
};
type OperationToGraphQL<V, T> = <Z>(o: Z | V) => Promise<MapType<T, Z>>;
type CastToGraphQL<V, T> = (
resultOfYourQuery: any
) => <Z>(o: Z | V) => MapType<T, Z>;
type fetchOptions = ArgsType<typeof fetch>;
export type SelectionFunction<V> = <T>(t: T | V) => T;
export declare function Chain(
...options: fetchOptions
):{
query: OperationToGraphQL<ValueTypes["query_root"],query_root>,mutation: OperationToGraphQL<ValueTypes["mutation_root"],mutation_root>,subscription: OperationToGraphQL<ValueTypes["subscription_root"],subscription_root>
}
export declare const Zeus: {
query: (o: ValueTypes["query_root"]) => string,mutation: (o: ValueTypes["mutation_root"]) => string,subscription: (o: ValueTypes["subscription_root"]) => string
}
export declare const Cast: {
query: CastToGraphQL<
ValueTypes["query_root"],
query_root
>,mutation: CastToGraphQL<
ValueTypes["mutation_root"],
mutation_root
>,subscription: CastToGraphQL<
ValueTypes["subscription_root"],
subscription_root
>
}
export declare const Gql: ReturnType<typeof Chain> | the_stack |
import initTrace from "debug";
import { LIST_SIZE_MASK, MAX_DEPTH, POINTER_DOUBLE_FAR_MASK, POINTER_TYPE_MASK } from "../../constants";
import { bufferToHex, format, padToWord } from "../../util";
import { ListElementSize } from "../list-element-size";
import {
ObjectSize,
getByteLength,
padToWord as padObjectToWord,
getWordLength,
getDataWordLength,
} from "../object-size";
import { Segment } from "../segment";
import { Orphan } from "./orphan";
import { PointerAllocationResult } from "./pointer-allocation-result";
import { PointerType } from "./pointer-type";
import { Message } from "../message";
import {
PTR_TRAVERSAL_LIMIT_EXCEEDED,
PTR_DEPTH_LIMIT_EXCEEDED,
PTR_OFFSET_OUT_OF_BOUNDS,
PTR_INVALID_LIST_SIZE,
PTR_INVALID_POINTER_TYPE,
PTR_INVALID_FAR_TARGET,
TYPE_COMPOSITE_SIZE_UNDEFINED,
PTR_WRONG_POINTER_TYPE,
PTR_WRONG_LIST_TYPE,
INVARIANT_UNREACHABLE_CODE,
} from "../../errors";
const trace = initTrace("capnp:pointer");
trace("load");
export interface _PointerCtor {
readonly displayName: string;
}
export interface PointerCtor<T extends Pointer> {
readonly _capnp: _PointerCtor;
new (segment: Segment, byteOffset: number, depthLimit?: number): T;
}
export interface _Pointer {
compositeIndex?: number;
compositeList: boolean;
/**
* A number that is decremented as nested pointers are traversed. When this hits zero errors will be thrown.
*/
depthLimit: number;
}
/**
* A pointer referencing a single byte location in a segment. This is typically used for Cap'n Proto pointers, but is
* also sometimes used to reference an offset to a pointer's content or tag words.
*
* @export
* @class Pointer
*/
export class Pointer {
static readonly adopt = adopt;
static readonly copyFrom = copyFrom;
static readonly disown = disown;
static readonly dump = dump;
static readonly isNull = isNull;
static readonly _capnp: _PointerCtor = {
displayName: "Pointer" as string,
};
readonly _capnp: _Pointer;
/** Offset, in bytes, from the start of the segment to the beginning of this pointer. */
byteOffset: number;
/**
* The starting segment for this pointer's data. In the case of a far pointer, the actual content this pointer is
* referencing will be in another segment within the same message.
*/
segment: Segment;
constructor(segment: Segment, byteOffset: number, depthLimit = MAX_DEPTH) {
this._capnp = { compositeList: false, depthLimit };
this.segment = segment;
this.byteOffset = byteOffset;
if (depthLimit === 0) {
throw new Error(format(PTR_DEPTH_LIMIT_EXCEEDED, this));
}
// Make sure we keep track of all pointer allocations; there's a limit per message (prevent DoS).
trackPointerAllocation(segment.message, this);
// NOTE: It's okay to have a pointer to the end of the segment; you'll see this when creating pointers to the
// beginning of the content of a newly-allocated composite list with zero elements. Unlike other language
// implementations buffer over/underflows are not a big issue since all buffer access is bounds checked in native
// code anyway.
if (byteOffset < 0 || byteOffset > segment.byteLength) {
throw new Error(format(PTR_OFFSET_OUT_OF_BOUNDS, byteOffset));
}
trace("new %s", this);
}
toString(): string {
return format("Pointer_%d@%a,%s,limit:%x", this.segment.id, this.byteOffset, dump(this), this._capnp.depthLimit);
}
}
/**
* Adopt an orphaned pointer, making the pointer point to the orphaned content without copying it.
*
* @param {Orphan<Pointer>} src The orphan to adopt.
* @param {Pointer} p The the pointer to adopt into.
* @returns {void}
*/
export function adopt<T extends Pointer>(src: Orphan<T>, p: T): void {
src._moveTo(p);
}
/**
* Convert a pointer to an Orphan, zeroing out the pointer and leaving its content untouched. If the content is no
* longer needed, call `disown()` on the orphaned pointer to erase the contents as well.
*
* Call `adopt()` on the orphan with the new target pointer location to move it back into the message; the orphan
* object is then invalidated after adoption (can only adopt once!).
*
* @param {T} p The pointer to turn into an Orphan.
* @returns {Orphan<T>} An orphaned pointer.
*/
export function disown<T extends Pointer>(p: T): Orphan<T> {
return new Orphan(p);
}
export function dump(p: Pointer): string {
return bufferToHex(p.segment.buffer.slice(p.byteOffset, p.byteOffset + 8));
}
/**
* Get the total number of bytes required to hold a list of the provided size with the given length, rounded up to the
* nearest word.
*
* @param {ListElementSize} elementSize A number describing the size of the list elements.
* @param {number} length The length of the list.
* @param {ObjectSize} [compositeSize] The size of each element in a composite list; required if
* `elementSize === ListElementSize.COMPOSITE`.
* @returns {number} The number of bytes required to hold an element of that size, or `NaN` if that is undefined.
*/
export function getListByteLength(elementSize: ListElementSize, length: number, compositeSize?: ObjectSize): number {
switch (elementSize) {
case ListElementSize.BIT:
return padToWord((length + 7) >>> 3);
case ListElementSize.BYTE:
case ListElementSize.BYTE_2:
case ListElementSize.BYTE_4:
case ListElementSize.BYTE_8:
case ListElementSize.POINTER:
case ListElementSize.VOID:
return padToWord(getListElementByteLength(elementSize) * length);
/* istanbul ignore next */
case ListElementSize.COMPOSITE:
if (compositeSize === undefined) {
throw new Error(format(PTR_INVALID_LIST_SIZE, NaN));
}
return length * padToWord(getByteLength(compositeSize));
/* istanbul ignore next */
default:
throw new Error(PTR_INVALID_LIST_SIZE);
}
}
/**
* Get the number of bytes required to hold a list element of the provided size. `COMPOSITE` elements do not have a
* fixed size, and `BIT` elements are packed into exactly a single bit, so these both return `NaN`.
*
* @param {ListElementSize} elementSize A number describing the size of the list elements.
* @returns {number} The number of bytes required to hold an element of that size, or `NaN` if that is undefined.
*/
export function getListElementByteLength(elementSize: ListElementSize): number {
switch (elementSize) {
/* istanbul ignore next */
case ListElementSize.BIT:
return NaN;
case ListElementSize.BYTE:
return 1;
case ListElementSize.BYTE_2:
return 2;
case ListElementSize.BYTE_4:
return 4;
case ListElementSize.BYTE_8:
case ListElementSize.POINTER:
return 8;
/* istanbul ignore next */
case ListElementSize.COMPOSITE:
// Caller has to figure it out based on the tag word.
return NaN;
/* istanbul ignore next */
case ListElementSize.VOID:
return 0;
/* istanbul ignore next */
default:
throw new Error(format(PTR_INVALID_LIST_SIZE, elementSize));
}
}
/**
* Add an offset to the pointer's offset and return a new Pointer for that address.
*
* @param {number} offset The number of bytes to add to the offset.
* @param {Pointer} p The pointer to add from.
* @returns {Pointer} A new pointer to the address.
*/
export function add(offset: number, p: Pointer): Pointer {
return new Pointer(p.segment, p.byteOffset + offset, p._capnp.depthLimit);
}
/**
* Replace a pointer with a deep copy of the pointer at `src` and all of its contents.
*
* @param {Pointer} src The pointer to copy.
* @param {Pointer} p The pointer to copy into.
* @returns {void}
*/
export function copyFrom(src: Pointer, p: Pointer): void {
// If the pointer is the same then this is a noop.
if (p.segment === src.segment && p.byteOffset === src.byteOffset) {
trace("ignoring copy operation from identical pointer %s", src);
return;
}
// Make sure we erase this pointer's contents before moving on. If src is null, that's all we do.
erase(p); // noop if null
if (isNull(src)) return;
switch (getTargetPointerType(src)) {
case PointerType.STRUCT:
copyFromStruct(src, p);
break;
case PointerType.LIST:
copyFromList(src, p);
break;
/* istanbul ignore next */
default:
throw new Error(format(PTR_INVALID_POINTER_TYPE, getTargetPointerType(p)));
}
}
/**
* Recursively erase a pointer, any far pointers/landing pads/tag words, and the content it points to.
*
* Note that this will leave "holes" of zeroes in the message, since the space cannot be reclaimed. With packing this
* will have a negligible effect on the final message size.
*
* FIXME: This may need protection against infinite recursion...
*
* @param {Pointer} p The pointer to erase.
* @returns {void}
*/
export function erase(p: Pointer): void {
if (isNull(p)) return;
// First deal with the contents.
let c: Pointer;
switch (getTargetPointerType(p)) {
case PointerType.STRUCT: {
const size = getTargetStructSize(p);
c = getContent(p);
// Wipe the data section.
c.segment.fillZeroWords(c.byteOffset, size.dataByteLength / 8);
// Iterate over all the pointers and nuke them.
for (let i = 0; i < size.pointerLength; i++) {
erase(add(i * 8, c));
}
break;
}
case PointerType.LIST: {
const elementSize = getTargetListElementSize(p);
const length = getTargetListLength(p);
let contentWords = padToWord(length * getListElementByteLength(elementSize));
c = getContent(p);
if (elementSize === ListElementSize.POINTER) {
for (let i = 0; i < length; i++) {
erase(new Pointer(c.segment, c.byteOffset + i * 8, p._capnp.depthLimit - 1));
}
// Calling erase on each pointer takes care of the content, nothing left to do here.
break;
} else if (elementSize === ListElementSize.COMPOSITE) {
// Read some stuff from the tag word.
const tag = add(-8, c);
const compositeSize = getStructSize(tag);
const compositeByteLength = getByteLength(compositeSize);
contentWords = getOffsetWords(tag);
// Kill the tag word.
c.segment.setWordZero(c.byteOffset - 8);
// Recursively erase each pointer.
for (let i = 0; i < length; i++) {
for (let j = 0; j < compositeSize.pointerLength; j++) {
erase(new Pointer(c.segment, c.byteOffset + i * compositeByteLength + j * 8, p._capnp.depthLimit - 1));
}
}
}
c.segment.fillZeroWords(c.byteOffset, contentWords);
break;
}
case PointerType.OTHER:
// No content.
break;
default:
throw new Error(format(PTR_INVALID_POINTER_TYPE, getTargetPointerType(p)));
}
erasePointer(p);
}
/**
* Set the pointer (and far pointer landing pads, if applicable) to zero. Does not touch the pointer's content.
*
* @param {Pointer} p The pointer to erase.
* @returns {void}
*/
export function erasePointer(p: Pointer): void {
if (getPointerType(p) === PointerType.FAR) {
const landingPad = followFar(p);
if (isDoubleFar(p)) {
// Kill the double-far tag word.
landingPad.segment.setWordZero(landingPad.byteOffset + 8);
}
// Kill the landing pad.
landingPad.segment.setWordZero(landingPad.byteOffset);
}
// Finally! Kill the pointer itself...
p.segment.setWordZero(p.byteOffset);
}
/**
* Interpret the pointer as a far pointer, returning its target segment and offset.
*
* @param {Pointer} p The pointer to read from.
* @returns {Pointer} A pointer to the far target.
*/
export function followFar(p: Pointer): Pointer {
const targetSegment = p.segment.message.getSegment(p.segment.getUint32(p.byteOffset + 4));
const targetWordOffset = p.segment.getUint32(p.byteOffset) >>> 3;
return new Pointer(targetSegment, targetWordOffset * 8, p._capnp.depthLimit - 1);
}
/**
* If the pointer address references a far pointer, follow it to the location where the actual pointer data is written.
* Otherwise, returns the pointer unmodified.
*
* @param {Pointer} p The pointer to read from.
* @returns {Pointer} A new pointer representing the target location, or `p` if it is not a far pointer.
*/
export function followFars(p: Pointer): Pointer {
if (getPointerType(p) === PointerType.FAR) {
const landingPad = followFar(p);
if (isDoubleFar(p)) landingPad.byteOffset += 8;
return landingPad;
}
return p;
}
export function getCapabilityId(p: Pointer): number {
return p.segment.getUint32(p.byteOffset + 4);
}
function isCompositeList(p: Pointer): boolean {
return getTargetPointerType(p) === PointerType.LIST && getTargetListElementSize(p) === ListElementSize.COMPOSITE;
}
/**
* Obtain the location of the pointer's content, following far pointers as needed.
* If the pointer is a struct pointer and `compositeIndex` is set, it will be offset by a multiple of the struct's size.
*
* @param {Pointer} p The pointer to read from.
* @param {boolean} [ignoreCompositeIndex] If true, will not follow the composite struct pointer's composite index and
* instead return a pointer to the parent list's contents (also the beginning of the first struct).
* @returns {Pointer} A pointer to the beginning of the pointer's content.
*/
export function getContent(p: Pointer, ignoreCompositeIndex?: boolean): Pointer {
let c: Pointer;
if (isDoubleFar(p)) {
const landingPad = followFar(p);
c = new Pointer(p.segment.message.getSegment(getFarSegmentId(landingPad)), getOffsetWords(landingPad) * 8);
} else {
const target = followFars(p);
c = new Pointer(target.segment, target.byteOffset + 8 + getOffsetWords(target) * 8);
}
if (isCompositeList(p)) c.byteOffset += 8;
if (!ignoreCompositeIndex && p._capnp.compositeIndex !== undefined) {
// Seek backwards by one word so we can read the struct size off the tag word.
c.byteOffset -= 8;
// Seek ahead by `compositeIndex` multiples of the struct's total size.
c.byteOffset += 8 + p._capnp.compositeIndex * getByteLength(padObjectToWord(getStructSize(c)));
}
return c;
}
/**
* Read the target segment ID from a far pointer.
*
* @param {Pointer} p The pointer to read from.
* @returns {number} The target segment ID.
*/
export function getFarSegmentId(p: Pointer): number {
return p.segment.getUint32(p.byteOffset + 4);
}
/**
* Get a number indicating the size of the list's elements.
*
* @param {Pointer} p The pointer to read from.
* @returns {ListElementSize} The size of the list's elements.
*/
export function getListElementSize(p: Pointer): ListElementSize {
return p.segment.getUint32(p.byteOffset + 4) & LIST_SIZE_MASK;
}
/**
* Get the number of elements in a list pointer. For composite lists, it instead represents the total number of words in
* the list (not counting the tag word).
*
* This method does **not** attempt to distinguish between composite and non-composite lists. To get the correct
* length for composite lists use `getTargetListLength()` instead.
*
* @param {Pointer} p The pointer to read from.
* @returns {number} The length of the list, or total number of words for composite lists.
*/
export function getListLength(p: Pointer): number {
return p.segment.getUint32(p.byteOffset + 4) >>> 3;
}
/**
* Get the offset (in words) from the end of a pointer to the start of its content. For struct pointers, this is the
* beginning of the data section, and for list pointers it is the location of the first element. The value should
* always be zero for interface pointers.
*
* @param {Pointer} p The pointer to read from.
* @returns {number} The offset, in words, from the end of the pointer to the start of the data section.
*/
export function getOffsetWords(p: Pointer): number {
const o = p.segment.getInt32(p.byteOffset);
// Far pointers only have 29 offset bits.
return o & 2 ? o >> 3 : o >> 2;
}
/**
* Look up the pointer's type.
*
* @param {Pointer} p The pointer to read from.
* @returns {PointerType} The type of pointer.
*/
export function getPointerType(p: Pointer): PointerType {
return p.segment.getUint32(p.byteOffset) & POINTER_TYPE_MASK;
}
/**
* Read the number of data words from this struct pointer.
*
* @param {Pointer} p The pointer to read from.
* @returns {number} The number of data words in the struct.
*/
export function getStructDataWords(p: Pointer): number {
return p.segment.getUint16(p.byteOffset + 4);
}
/**
* Read the number of pointers contained in this struct pointer.
*
* @param {Pointer} p The pointer to read from.
* @returns {number} The number of pointers in this struct.
*/
export function getStructPointerLength(p: Pointer): number {
return p.segment.getUint16(p.byteOffset + 6);
}
/**
* Get an object describing this struct pointer's size.
*
* @param {Pointer} p The pointer to read from.
* @returns {ObjectSize} The size of the struct.
*/
export function getStructSize(p: Pointer): ObjectSize {
return new ObjectSize(getStructDataWords(p) * 8, getStructPointerLength(p));
}
/**
* Get a pointer to this pointer's composite list tag word, following far pointers as needed.
*
* @param {Pointer} p The pointer to read from.
* @returns {Pointer} A pointer to the list's composite tag word.
*/
export function getTargetCompositeListTag(p: Pointer): Pointer {
const c = getContent(p);
// The composite list tag is always one word before the content.
c.byteOffset -= 8;
return c;
}
/**
* Get the object size for the target composite list, following far pointers as needed.
*
* @param {Pointer} p The pointer to read from.
* @returns {ObjectSize} An object describing the size of each struct in the list.
*/
export function getTargetCompositeListSize(p: Pointer): ObjectSize {
return getStructSize(getTargetCompositeListTag(p));
}
/**
* Get the size of the list elements referenced by this pointer, following far pointers if necessary.
*
* @param {Pointer} p The pointer to read from.
* @returns {ListElementSize} The size of the elements in the list.
*/
export function getTargetListElementSize(p: Pointer): ListElementSize {
return getListElementSize(followFars(p));
}
/**
* Get the length of the list referenced by this pointer, following far pointers if necessary. If the list is a
* composite list, it will look up the tag word and read the length from there.
*
* @param {Pointer} p The pointer to read from.
* @returns {number} The number of elements in the list.
*/
export function getTargetListLength(p: Pointer): number {
const t = followFars(p);
if (getListElementSize(t) === ListElementSize.COMPOSITE) {
// The content is prefixed by a tag word; it's a struct pointer whose offset contains the list's length.
return getOffsetWords(getTargetCompositeListTag(p));
}
return getListLength(t);
}
/**
* Get the type of a pointer, following far pointers if necessary. For non-far pointers this is equivalent to calling
* `getPointerType()`.
*
* The target of a far pointer can never be another far pointer, and this method will throw if such a situation is
* encountered.
*
* @param {Pointer} p The pointer to read from.
* @returns {PointerType} The type of pointer referenced by this pointer.
*/
export function getTargetPointerType(p: Pointer): PointerType {
const t = getPointerType(followFars(p));
if (t === PointerType.FAR) throw new Error(format(PTR_INVALID_FAR_TARGET, p));
return t;
}
/**
* Get the size of the struct referenced by a pointer, following far pointers if necessary.
*
* @param {Pointer} p The poiner to read from.
* @returns {ObjectSize} The size of the struct referenced by this pointer.
*/
export function getTargetStructSize(p: Pointer): ObjectSize {
return getStructSize(followFars(p));
}
/**
* Initialize a pointer to point at the data in the content segment. If the content segment is not the same as the
* pointer's segment, this will allocate and write far pointers as needed. Nothing is written otherwise.
*
* The return value includes a pointer to write the pointer's actual data to (the eventual far target), and the offset
* value (in words) to use for that pointer. In the case of double-far pointers this offset will always be zero.
*
* @param {Segment} contentSegment The segment containing this pointer's content.
* @param {number} contentOffset The offset within the content segment for the beginning of this pointer's content.
* @param {Pointer} p The pointer to initialize.
* @returns {PointerAllocationResult} An object containing a pointer (where the pointer data should be written), and
* the value to use as the offset for that pointer.
*/
export function initPointer(contentSegment: Segment, contentOffset: number, p: Pointer): PointerAllocationResult {
if (p.segment !== contentSegment) {
// Need a far pointer.
trace("Initializing far pointer %s -> %s.", p, contentSegment);
if (!contentSegment.hasCapacity(8)) {
// GAH! Not enough space in the content segment for a landing pad so we need a double far pointer.
const landingPad = p.segment.allocate(16);
trace("GAH! Initializing double-far pointer in %s from %s -> %s.", p, contentSegment, landingPad);
setFarPointer(true, landingPad.byteOffset / 8, landingPad.segment.id, p);
setFarPointer(false, contentOffset / 8, contentSegment.id, landingPad);
landingPad.byteOffset += 8;
return new PointerAllocationResult(landingPad, 0);
}
// Allocate a far pointer landing pad in the target segment.
const landingPad = contentSegment.allocate(8);
if (landingPad.segment.id !== contentSegment.id) {
throw new Error(INVARIANT_UNREACHABLE_CODE);
}
setFarPointer(false, landingPad.byteOffset / 8, landingPad.segment.id, p);
return new PointerAllocationResult(landingPad, (contentOffset - landingPad.byteOffset - 8) / 8);
}
trace("Initializing intra-segment pointer %s -> %a.", p, contentOffset);
return new PointerAllocationResult(p, (contentOffset - p.byteOffset - 8) / 8);
}
/**
* Check if the pointer is a double-far pointer.
*
* @param {Pointer} p The pointer to read from.
* @returns {boolean} `true` if it is a double-far pointer, `false` otherwise.
*/
export function isDoubleFar(p: Pointer): boolean {
return getPointerType(p) === PointerType.FAR && (p.segment.getUint32(p.byteOffset) & POINTER_DOUBLE_FAR_MASK) !== 0;
}
/**
* Quickly check to see if the pointer is "null". A "null" pointer is a zero word, equivalent to an empty struct
* pointer.
*
* @param {Pointer} p The pointer to read from.
* @returns {boolean} `true` if the pointer is "null".
*/
export function isNull(p: Pointer): boolean {
return p.segment.isWordZero(p.byteOffset);
}
/**
* Relocate a pointer to the given destination, ensuring that it points to the same content. This will create far
* pointers as needed if the content is in a different segment than the destination. After the relocation the source
* pointer will be erased and is no longer valid.
*
* @param {Pointer} dst The desired location for the `src` pointer. Any existing contents will be erased before
* relocating!
* @param {Pointer} src The pointer to relocate.
* @returns {void}
*/
export function relocateTo(dst: Pointer, src: Pointer): void {
const t = followFars(src);
const lo = t.segment.getUint8(t.byteOffset) & 0x03; // discard the offset
const hi = t.segment.getUint32(t.byteOffset + 4);
// Make sure anything dst was pointing to is wiped out.
erase(dst);
const res = initPointer(t.segment, t.byteOffset + 8 + getOffsetWords(t) * 8, dst);
// Keep the low 2 bits and write the new offset.
res.pointer.segment.setUint32(res.pointer.byteOffset, lo | (res.offsetWords << 2));
// Keep the high 32 bits intact.
res.pointer.segment.setUint32(res.pointer.byteOffset + 4, hi);
erasePointer(src);
}
/**
* Write a far pointer.
*
* @param {boolean} doubleFar Set to `true` if this is a double far pointer.
* @param {number} offsetWords The offset, in words, to the target pointer.
* @param {number} segmentId The segment the target pointer is located in.
* @param {Pointer} p The pointer to write to.
* @returns {void}
*/
export function setFarPointer(doubleFar: boolean, offsetWords: number, segmentId: number, p: Pointer): void {
const A = PointerType.FAR;
const B = doubleFar ? 1 : 0;
const C = offsetWords;
const D = segmentId;
p.segment.setUint32(p.byteOffset, A | (B << 2) | (C << 3));
p.segment.setUint32(p.byteOffset + 4, D);
}
/**
* Write a raw interface pointer.
*
* @param {number} capId The capability ID.
* @param {Pointer} p The pointer to write to.
* @returns {void}
*/
export function setInterfacePointer(capId: number, p: Pointer): void {
p.segment.setUint32(p.byteOffset, PointerType.OTHER);
p.segment.setUint32(p.byteOffset + 4, capId);
}
/**
* Write a raw list pointer.
*
* @param {number} offsetWords The number of words from the end of this pointer to the beginning of the list content.
* @param {ListElementSize} size The size of each element in the list.
* @param {number} length The number of elements in the list.
* @param {Pointer} p The pointer to write to.
* @param {ObjectSize} [compositeSize] For composite lists this describes the size of each element in this list. This
* is required for composite lists.
* @returns {void}
*/
export function setListPointer(
offsetWords: number,
size: ListElementSize,
length: number,
p: Pointer,
compositeSize?: ObjectSize
): void {
const A = PointerType.LIST;
const B = offsetWords;
const C = size;
let D = length;
if (size === ListElementSize.COMPOSITE) {
if (compositeSize === undefined) {
throw new TypeError(TYPE_COMPOSITE_SIZE_UNDEFINED);
}
D *= getWordLength(compositeSize);
}
p.segment.setUint32(p.byteOffset, A | (B << 2));
p.segment.setUint32(p.byteOffset + 4, C | (D << 3));
}
/**
* Write a raw struct pointer.
*
* @param {number} offsetWords The number of words from the end of this pointer to the beginning of the struct's data
* section.
* @param {ObjectSize} size An object describing the size of the struct.
* @param {Pointer} p The pointer to write to.
* @returns {void}
*/
export function setStructPointer(offsetWords: number, size: ObjectSize, p: Pointer): void {
const A = PointerType.STRUCT;
const B = offsetWords;
const C = getDataWordLength(size);
const D = size.pointerLength;
p.segment.setUint32(p.byteOffset, A | (B << 2));
p.segment.setUint16(p.byteOffset + 4, C);
p.segment.setUint16(p.byteOffset + 6, D);
}
/**
* Read some bits off a pointer to make sure it has the right pointer data.
*
* @param {PointerType} pointerType The expected pointer type.
* @param {Pointer} p The pointer to validate.
* @param {ListElementSize} [elementSize] For list pointers, the expected element size. Leave this
* undefined for struct pointers.
* @returns {void}
*/
export function validate(pointerType: PointerType, p: Pointer, elementSize?: ListElementSize): void {
if (isNull(p)) return;
const t = followFars(p);
// Check the pointer type.
const A = t.segment.getUint32(t.byteOffset) & POINTER_TYPE_MASK;
if (A !== pointerType) {
throw new Error(format(PTR_WRONG_POINTER_TYPE, p, pointerType));
}
// Check the list element size, if provided.
if (elementSize !== undefined) {
const C = t.segment.getUint32(t.byteOffset + 4) & LIST_SIZE_MASK;
if (C !== elementSize) {
throw new Error(format(PTR_WRONG_LIST_TYPE, p, ListElementSize[elementSize]));
}
}
}
export function copyFromList(src: Pointer, dst: Pointer): void {
if (dst._capnp.depthLimit <= 0) throw new Error(PTR_DEPTH_LIMIT_EXCEEDED);
const srcContent = getContent(src);
const srcElementSize = getTargetListElementSize(src);
const srcLength = getTargetListLength(src);
let srcCompositeSize;
let srcStructByteLength;
let dstContent;
if (srcElementSize === ListElementSize.POINTER) {
dstContent = dst.segment.allocate(srcLength << 3);
// Recursively copy each pointer in the list.
for (let i = 0; i < srcLength; i++) {
const srcPtr = new Pointer(srcContent.segment, srcContent.byteOffset + (i << 3), src._capnp.depthLimit - 1);
const dstPtr = new Pointer(dstContent.segment, dstContent.byteOffset + (i << 3), dst._capnp.depthLimit - 1);
copyFrom(srcPtr, dstPtr);
}
} else if (srcElementSize === ListElementSize.COMPOSITE) {
srcCompositeSize = padObjectToWord(getTargetCompositeListSize(src));
srcStructByteLength = getByteLength(srcCompositeSize);
dstContent = dst.segment.allocate(getByteLength(srcCompositeSize) * srcLength + 8);
// Copy the tag word.
dstContent.segment.copyWord(dstContent.byteOffset, srcContent.segment, srcContent.byteOffset - 8);
// Copy the entire contents, including all pointers. This should be more efficient than making `srcLength`
// copies to skip the pointer sections, and we're about to rewrite all those pointers anyway.
// PERF: Skip this step if the composite struct only contains pointers.
if (srcCompositeSize.dataByteLength > 0) {
const wordLength = getWordLength(srcCompositeSize) * srcLength;
dstContent.segment.copyWords(dstContent.byteOffset + 8, srcContent.segment, srcContent.byteOffset, wordLength);
}
// Recursively copy all the pointers in each struct.
for (let i = 0; i < srcLength; i++) {
for (let j = 0; j < srcCompositeSize.pointerLength; j++) {
const offset = i * srcStructByteLength + srcCompositeSize.dataByteLength + (j << 3);
const srcPtr = new Pointer(srcContent.segment, srcContent.byteOffset + offset, src._capnp.depthLimit - 1);
const dstPtr = new Pointer(dstContent.segment, dstContent.byteOffset + offset + 8, dst._capnp.depthLimit - 1);
copyFrom(srcPtr, dstPtr);
}
}
} else {
const byteLength = padToWord(
srcElementSize === ListElementSize.BIT
? (srcLength + 7) >>> 3
: getListElementByteLength(srcElementSize) * srcLength
);
const wordLength = byteLength >>> 3;
dstContent = dst.segment.allocate(byteLength);
// Copy all of the list contents word-by-word.
dstContent.segment.copyWords(dstContent.byteOffset, srcContent.segment, srcContent.byteOffset, wordLength);
}
// Initialize the list pointer.
const res = initPointer(dstContent.segment, dstContent.byteOffset, dst);
setListPointer(res.offsetWords, srcElementSize, srcLength, res.pointer, srcCompositeSize);
}
export function copyFromStruct(src: Pointer, dst: Pointer): void {
if (dst._capnp.depthLimit <= 0) throw new Error(PTR_DEPTH_LIMIT_EXCEEDED);
const srcContent = getContent(src);
const srcSize = getTargetStructSize(src);
const srcDataWordLength = getDataWordLength(srcSize);
// Allocate space for the destination content.
const dstContent = dst.segment.allocate(getByteLength(srcSize));
// Copy the data section.
dstContent.segment.copyWords(dstContent.byteOffset, srcContent.segment, srcContent.byteOffset, srcDataWordLength);
// Copy the pointer section.
for (let i = 0; i < srcSize.pointerLength; i++) {
const offset = srcSize.dataByteLength + i * 8;
const srcPtr = new Pointer(srcContent.segment, srcContent.byteOffset + offset, src._capnp.depthLimit - 1);
const dstPtr = new Pointer(dstContent.segment, dstContent.byteOffset + offset, dst._capnp.depthLimit - 1);
copyFrom(srcPtr, dstPtr);
}
// Don't touch dst if it's already initialized as a composite list pointer. With composite struct pointers there's
// no pointer to copy here and we've already copied the contents.
if (dst._capnp.compositeList) return;
// Initialize the struct pointer.
const res = initPointer(dstContent.segment, dstContent.byteOffset, dst);
setStructPointer(res.offsetWords, srcSize, res.pointer);
}
/**
* Track the allocation of a new Pointer object.
*
* This will decrement an internal counter tracking how many bytes have been traversed in the message so far. After
* a certain limit, this method will throw an error in order to prevent a certain class of DoS attacks.
*
* @param {Message} message The message the pointer belongs to.
* @param {Pointer} p The pointer being allocated.
* @returns {void}
*/
export function trackPointerAllocation(message: Message, p: Pointer): void {
message._capnp.traversalLimit -= 8;
if (message._capnp.traversalLimit <= 0) {
throw new Error(format(PTR_TRAVERSAL_LIMIT_EXCEEDED, p));
}
} | the_stack |
import { TypeKind, Type, ClassType, EnumType, UnionType, ClassProperty } from "../Type";
import { matchType, nullableFromUnion, removeNullFromUnion } from "../TypeUtils";
import { Name, DependencyName, Namer, funPrefixNamer } from "../Naming";
import {
legalizeCharacters,
isLetterOrUnderscore,
isLetterOrUnderscoreOrDigit,
stringEscape,
splitIntoWords,
combineWords,
firstUpperWordStyle,
allUpperWordStyle,
camelCase,
} from "../support/Strings";
import { assert, defined } from "../support/Support";
import { StringOption, BooleanOption, Option, OptionValues, getOptionValues } from "../RendererOptions";
import { Sourcelike, maybeAnnotated, modifySource } from "../Source";
import { anyTypeIssueAnnotation, nullTypeIssueAnnotation } from "../Annotation";
import { TargetLanguage } from "../TargetLanguage";
import { ConvenienceRenderer } from "../ConvenienceRenderer";
import { RenderContext } from "../Renderer";
export const goOptions = {
justTypes: new BooleanOption("just-types", "Plain types only", false),
justTypesAndPackage: new BooleanOption("just-types-and-package", "Plain types with package only", false),
packageName: new StringOption("package", "Generated package name", "NAME", "main"),
multiFileOutput: new BooleanOption("multi-file-output", "Renders each top-level object in its own Go file", false),
};
export class GoTargetLanguage extends TargetLanguage {
constructor() {
super("Go", ["go", "golang"], "go");
}
protected getOptions(): Option<any>[] {
return [goOptions.justTypes, goOptions.packageName, goOptions.multiFileOutput, goOptions.justTypesAndPackage];
}
get supportsUnionsWithBothNumberTypes(): boolean {
return true;
}
get supportsOptionalClassProperties(): boolean {
return true;
}
protected makeRenderer(renderContext: RenderContext, untypedOptionValues: { [name: string]: any }): GoRenderer {
return new GoRenderer(this, renderContext, getOptionValues(goOptions, untypedOptionValues));
}
protected get defaultIndentation(): string {
return "\t";
}
}
const namingFunction = funPrefixNamer("namer", goNameStyle);
const legalizeName = legalizeCharacters(isLetterOrUnderscoreOrDigit);
function goNameStyle(original: string): string {
const words = splitIntoWords(original);
return combineWords(
words,
legalizeName,
firstUpperWordStyle,
firstUpperWordStyle,
allUpperWordStyle,
allUpperWordStyle,
"",
isLetterOrUnderscore
);
}
const primitiveValueTypeKinds: TypeKind[] = ["integer", "double", "bool", "string"];
const compoundTypeKinds: TypeKind[] = ["array", "class", "map", "enum"];
function isValueType(t: Type): boolean {
const kind = t.kind;
return primitiveValueTypeKinds.indexOf(kind) >= 0 || kind === "class" || kind === "enum";
}
function singleDescriptionComment(description: string[] | undefined): string {
if (description === undefined) return "";
return "// " + description.join("; ");
}
function canOmitEmpty(cp: ClassProperty): boolean {
if (!cp.isOptional) return false;
const t = cp.type;
return ["union", "null", "any"].indexOf(t.kind) < 0;
}
export class GoRenderer extends ConvenienceRenderer {
private readonly _topLevelUnmarshalNames = new Map<Name, Name>();
private _currentFilename: string | undefined;
constructor(
targetLanguage: TargetLanguage,
renderContext: RenderContext,
private readonly _options: OptionValues<typeof goOptions>
) {
super(targetLanguage, renderContext);
}
protected makeNamedTypeNamer(): Namer {
return namingFunction;
}
protected namerForObjectProperty(): Namer {
return namingFunction;
}
protected makeUnionMemberNamer(): Namer {
return namingFunction;
}
protected makeEnumCaseNamer(): Namer {
return namingFunction;
}
protected get enumCasesInGlobalNamespace(): boolean {
return true;
}
protected makeTopLevelDependencyNames(_: Type, topLevelName: Name): DependencyName[] {
const unmarshalName = new DependencyName(
namingFunction,
topLevelName.order,
(lookup) => `unmarshal_${lookup(topLevelName)}`
);
this._topLevelUnmarshalNames.set(topLevelName, unmarshalName);
return [unmarshalName];
}
/// startFile takes a file name, lowercases it, appends ".go" to it, and sets it as the current filename.
protected startFile(basename: Sourcelike): void {
if (this._options.multiFileOutput === false) {
return;
}
assert(this._currentFilename === undefined, "Previous file wasn't finished: " + this._currentFilename);
// FIXME: The filenames should actually be Sourcelikes, too
this._currentFilename = `${this.sourcelikeToString(basename)}.go`.toLowerCase();
this.initializeEmitContextForFilename(this._currentFilename);
}
/// endFile pushes the current file name onto the collection of finished files and then resets the current file name. These finished files are used in index.ts to write the output.
protected endFile(): void {
if (this._options.multiFileOutput === false) {
return;
}
this.finishFile(defined(this._currentFilename));
this._currentFilename = undefined;
}
private emitBlock(line: Sourcelike, f: () => void): void {
this.emitLine(line, " {");
this.indent(f);
this.emitLine("}");
}
private emitFunc(decl: Sourcelike, f: () => void): void {
this.emitBlock(["func ", decl], f);
}
private emitStruct(name: Name, table: Sourcelike[][]): void {
this.emitBlock(["type ", name, " struct"], () => this.emitTable(table));
}
private nullableGoType(t: Type, withIssues: boolean): Sourcelike {
const goType = this.goType(t, withIssues);
if (isValueType(t)) {
return ["*", goType];
} else {
return goType;
}
}
private propertyGoType(cp: ClassProperty): Sourcelike {
const t = cp.type;
if (t instanceof UnionType && nullableFromUnion(t) === null) {
return ["*", this.goType(t, true)];
}
if (cp.isOptional) {
return this.nullableGoType(t, true);
}
return this.goType(t, true);
}
private goType(t: Type, withIssues: boolean = false): Sourcelike {
return matchType<Sourcelike>(
t,
(_anyType) => maybeAnnotated(withIssues, anyTypeIssueAnnotation, "interface{}"),
(_nullType) => maybeAnnotated(withIssues, nullTypeIssueAnnotation, "interface{}"),
(_boolType) => "bool",
(_integerType) => "int64",
(_doubleType) => "float64",
(_stringType) => "string",
(arrayType) => ["[]", this.goType(arrayType.items, withIssues)],
(classType) => this.nameForNamedType(classType),
(mapType) => {
let valueSource: Sourcelike;
const v = mapType.values;
if (v instanceof UnionType && nullableFromUnion(v) === null) {
valueSource = ["*", this.nameForNamedType(v)];
} else {
valueSource = this.goType(v, withIssues);
}
return ["map[string]", valueSource];
},
(enumType) => this.nameForNamedType(enumType),
(unionType) => {
const nullable = nullableFromUnion(unionType);
if (nullable !== null) return this.nullableGoType(nullable, withIssues);
return this.nameForNamedType(unionType);
}
);
}
private emitTopLevel(t: Type, name: Name): void {
this.startFile(name);
if (
this._options.multiFileOutput &&
this._options.justTypes === false &&
this._options.justTypesAndPackage === false &&
this.leadingComments === undefined
) {
this.emitLineOnce(
"// This file was generated from JSON Schema using quicktype, do not modify it directly."
);
this.emitLineOnce("// To parse and unparse this JSON data, add this code to your project and do:");
this.emitLineOnce("//");
const ref = modifySource(camelCase, name);
this.emitLineOnce("// ", ref, ", err := ", defined(this._topLevelUnmarshalNames.get(name)), "(bytes)");
this.emitLineOnce("// bytes, err = ", ref, ".Marshal()");
}
this.emitPackageDefinitons(true);
const unmarshalName = defined(this._topLevelUnmarshalNames.get(name));
if (this.namedTypeToNameForTopLevel(t) === undefined) {
this.emitLine("type ", name, " ", this.goType(t));
}
if (this._options.justTypes || this._options.justTypesAndPackage) return;
this.ensureBlankLine();
this.emitFunc([unmarshalName, "(data []byte) (", name, ", error)"], () => {
this.emitLine("var r ", name);
this.emitLine("err := json.Unmarshal(data, &r)");
this.emitLine("return r, err");
});
this.ensureBlankLine();
this.emitFunc(["(r *", name, ") Marshal() ([]byte, error)"], () => {
this.emitLine("return json.Marshal(r)");
});
this.endFile();
}
private emitClass(c: ClassType, className: Name): void {
this.startFile(className);
this.emitPackageDefinitons(false);
let columns: Sourcelike[][] = [];
this.forEachClassProperty(c, "none", (name, jsonName, p) => {
const goType = this.propertyGoType(p);
const comment = singleDescriptionComment(this.descriptionForClassProperty(c, jsonName));
const omitEmpty = canOmitEmpty(p) ? ",omitempty" : [];
columns.push([[name, " "], [goType, " "], ['`json:"', stringEscape(jsonName), omitEmpty, '"`'], comment]);
});
this.emitDescription(this.descriptionForType(c));
this.emitStruct(className, columns);
this.endFile();
}
private emitEnum(e: EnumType, enumName: Name): void {
this.startFile(enumName);
this.emitPackageDefinitons(false);
this.emitDescription(this.descriptionForType(e));
this.emitLine("type ", enumName, " string");
this.emitLine("const (");
this.indent(() =>
this.forEachEnumCase(e, "none", (name, jsonName) => {
this.emitLine(name, " ", enumName, ' = "', stringEscape(jsonName), '"');
})
);
this.emitLine(")");
this.endFile();
}
private emitUnion(u: UnionType, unionName: Name): void {
this.startFile(unionName);
this.emitPackageDefinitons(false);
const [hasNull, nonNulls] = removeNullFromUnion(u);
const isNullableArg = hasNull !== null ? "true" : "false";
const ifMember: <T, U>(
kind: TypeKind,
ifNotMember: U,
f: (t: Type, fieldName: Name, goType: Sourcelike) => T
) => T | U = (kind, ifNotMember, f) => {
const maybeType = u.findMember(kind);
if (maybeType === undefined) return ifNotMember;
return f(maybeType, this.nameForUnionMember(u, maybeType), this.goType(maybeType));
};
const maybeAssignNil = (kind: TypeKind): void => {
ifMember(kind, undefined, (_1, fieldName, _2) => {
this.emitLine("x.", fieldName, " = nil");
});
};
const makeArgs = (
primitiveArg: (fieldName: Sourcelike) => Sourcelike,
compoundArg: (isClass: boolean, fieldName: Sourcelike) => Sourcelike
): Sourcelike => {
const args: Sourcelike = [];
for (const kind of primitiveValueTypeKinds) {
args.push(
ifMember(kind, "nil", (_1, fieldName, _2) => primitiveArg(fieldName)),
", "
);
}
for (const kind of compoundTypeKinds) {
args.push(
ifMember(kind, "false, nil", (t, fieldName, _) => compoundArg(t.kind === "class", fieldName)),
", "
);
}
args.push(isNullableArg);
return args;
};
let columns: Sourcelike[][] = [];
this.forEachUnionMember(u, nonNulls, "none", null, (fieldName, t) => {
const goType = this.nullableGoType(t, true);
columns.push([[fieldName, " "], goType]);
});
this.emitDescription(this.descriptionForType(u));
this.emitStruct(unionName, columns);
if (this._options.justTypes || this._options.justTypesAndPackage) return;
this.ensureBlankLine();
this.emitFunc(["(x *", unionName, ") UnmarshalJSON(data []byte) error"], () => {
for (const kind of compoundTypeKinds) {
maybeAssignNil(kind);
}
ifMember("class", undefined, (_1, _2, goType) => {
this.emitLine("var c ", goType);
});
const args = makeArgs(
(fn) => ["&x.", fn],
(isClass, fn) => {
if (isClass) {
return "true, &c";
} else {
return ["true, &x.", fn];
}
}
);
this.emitLine("object, err := unmarshalUnion(data, ", args, ")");
this.emitBlock("if err != nil", () => {
this.emitLine("return err");
});
this.emitBlock("if object", () => {
ifMember("class", undefined, (_1, fieldName, _2) => {
this.emitLine("x.", fieldName, " = &c");
});
});
this.emitLine("return nil");
});
this.ensureBlankLine();
this.emitFunc(["(x *", unionName, ") MarshalJSON() ([]byte, error)"], () => {
const args = makeArgs(
(fn) => ["x.", fn],
(_, fn) => ["x.", fn, " != nil, x.", fn]
);
this.emitLine("return marshalUnion(", args, ")");
});
this.endFile();
}
private emitSingleFileHeaderComments(): void {
this.emitLineOnce("// This file was generated from JSON Schema using quicktype, do not modify it directly.");
this.emitLineOnce("// To parse and unparse this JSON data, add this code to your project and do:");
this.forEachTopLevel("none", (_: Type, name: Name) => {
this.emitLine("//");
const ref = modifySource(camelCase, name);
this.emitLine("// ", ref, ", err := ", defined(this._topLevelUnmarshalNames.get(name)), "(bytes)");
this.emitLine("// bytes, err = ", ref, ".Marshal()");
});
}
private emitPackageDefinitons(includeJSONEncodingImport: boolean): void {
if (!this._options.justTypes || this._options.justTypesAndPackage) {
this.ensureBlankLine();
const packageDeclaration = "package " + this._options.packageName;
this.emitLineOnce(packageDeclaration);
this.ensureBlankLine();
}
if (!this._options.justTypes && !this._options.justTypesAndPackage) {
this.ensureBlankLine();
if (this.haveNamedUnions && this._options.multiFileOutput === false) {
this.emitLineOnce('import "bytes"');
this.emitLineOnce('import "errors"');
}
if (includeJSONEncodingImport) {
this.emitLineOnce('import "encoding/json"');
}
this.ensureBlankLine();
}
}
private emitHelperFunctions(): void {
if (this.haveNamedUnions) {
this.startFile("JSONSchemaSupport");
this.emitPackageDefinitons(true);
if (this._options.multiFileOutput) {
this.emitLineOnce('import "bytes"');
this.emitLineOnce('import "errors"');
}
this.ensureBlankLine();
this
.emitMultiline(`func unmarshalUnion(data []byte, pi **int64, pf **float64, pb **bool, ps **string, haveArray bool, pa interface{}, haveObject bool, pc interface{}, haveMap bool, pm interface{}, haveEnum bool, pe interface{}, nullable bool) (bool, error) {
if pi != nil {
*pi = nil
}
if pf != nil {
*pf = nil
}
if pb != nil {
*pb = nil
}
if ps != nil {
*ps = nil
}
dec := json.NewDecoder(bytes.NewReader(data))
dec.UseNumber()
tok, err := dec.Token()
if err != nil {
return false, err
}
switch v := tok.(type) {
case json.Number:
if pi != nil {
i, err := v.Int64()
if err == nil {
*pi = &i
return false, nil
}
}
if pf != nil {
f, err := v.Float64()
if err == nil {
*pf = &f
return false, nil
}
return false, errors.New("Unparsable number")
}
return false, errors.New("Union does not contain number")
case float64:
return false, errors.New("Decoder should not return float64")
case bool:
if pb != nil {
*pb = &v
return false, nil
}
return false, errors.New("Union does not contain bool")
case string:
if haveEnum {
return false, json.Unmarshal(data, pe)
}
if ps != nil {
*ps = &v
return false, nil
}
return false, errors.New("Union does not contain string")
case nil:
if nullable {
return false, nil
}
return false, errors.New("Union does not contain null")
case json.Delim:
if v == '{' {
if haveObject {
return true, json.Unmarshal(data, pc)
}
if haveMap {
return false, json.Unmarshal(data, pm)
}
return false, errors.New("Union does not contain object")
}
if v == '[' {
if haveArray {
return false, json.Unmarshal(data, pa)
}
return false, errors.New("Union does not contain array")
}
return false, errors.New("Cannot handle delimiter")
}
return false, errors.New("Cannot unmarshal union")
}
func marshalUnion(pi *int64, pf *float64, pb *bool, ps *string, haveArray bool, pa interface{}, haveObject bool, pc interface{}, haveMap bool, pm interface{}, haveEnum bool, pe interface{}, nullable bool) ([]byte, error) {
if pi != nil {
return json.Marshal(*pi)
}
if pf != nil {
return json.Marshal(*pf)
}
if pb != nil {
return json.Marshal(*pb)
}
if ps != nil {
return json.Marshal(*ps)
}
if haveArray {
return json.Marshal(pa)
}
if haveObject {
return json.Marshal(pc)
}
if haveMap {
return json.Marshal(pm)
}
if haveEnum {
return json.Marshal(pe)
}
if nullable {
return json.Marshal(nil)
}
return nil, errors.New("Union must not be null")
}`);
this.endFile();
}
}
protected emitSourceStructure(): void {
if (
this._options.multiFileOutput === false &&
this._options.justTypes === false &&
this._options.justTypesAndPackage === false &&
this.leadingComments === undefined
) {
this.emitSingleFileHeaderComments();
}
this.forEachTopLevel(
"leading-and-interposing",
(t, name) => this.emitTopLevel(t, name),
(t) =>
!(this._options.justTypes || this._options.justTypesAndPackage) ||
this.namedTypeToNameForTopLevel(t) === undefined
);
this.forEachObject("leading-and-interposing", (c: ClassType, className: Name) => this.emitClass(c, className));
this.forEachEnum("leading-and-interposing", (u: EnumType, enumName: Name) => this.emitEnum(u, enumName));
this.forEachUnion("leading-and-interposing", (u: UnionType, unionName: Name) => this.emitUnion(u, unionName));
if (this._options.justTypes || this._options.justTypesAndPackage) {
return;
}
this.emitHelperFunctions();
}
} | the_stack |
import * as loggingTypes from '../lib/loggingprovider/loggingprovider.types';
import * as net from '../lib/net/net.types';
import * as social from './social';
import * as ui from './ui';
// --- Core <--> UI Interfaces ---
export interface UserFeedback {
email :string;
error :string;
feedback :string;
logs :string;
browserInfo ?:string;
proxyingId ?:string;
feedbackType ?:UserFeedbackType;
}
export enum UserFeedbackType {
USER_INITIATED = 0,
PROXYING_FAILURE = 1,
CLOUD_CONNECTIONS_DISCONNECTED = 2,
CLOUD_SERVER_NO_CONNECT = 3,
CLOUD_SERVER_NO_START = 4,
TROUBLE_SIGNING_IN = 5,
NO_FRIENDS = 6,
TROUBLE_STARTING_CONNECTION = 7,
DISCONNECTED_FROM_FRIEND = 8,
OTHER_FEEDBACK = 9
}
// Object containing an update to apply to another object
export interface UpdateGlobalSettingArgs {
name: string; // field being updated
value: Object; // anything that's getting updated
}
// Object containing description so it can be saved to storage.
export interface GlobalSettings {
version :number;
description :string;
stunServers :freedom.RTCPeerConnection.RTCIceServer[];
hasSeenSharingEnabledScreen :boolean;
hasSeenWelcome :boolean;
hasSeenMetrics :boolean;
allowNonUnicast :boolean;
mode :ui.Mode;
statsReportingEnabled :boolean;
consoleFilter :loggingTypes.Level;
language :string;
force_message_version :number;
quiverUserName :string;
proxyBypass: string[];
enforceProxyServerValidity :boolean;
validProxyServers :ValidProxyServerIdentities;
activePromoId: string;
shouldHijackDO: boolean;
crypto: boolean;
reproxy: reproxySettings;
// A list of strings, each represented as a constant below, with
// prefix 'FEATURE_'.
enabledExperiments :string[];
}
export const FEATURE_VERIFY = 'verify';
export interface InitialState {
networkNames :string[];
cloudProviderNames :string[];
globalSettings :GlobalSettings;
onlineNetworks :social.NetworkState[];
availableVersion :string;
portControlSupport :PortControlSupport;
}
export interface ValidProxyServerIdentities {
[key: string]: string;
}
export interface ManagedPolicyUpdate {
enforceProxyServerValidity :boolean;
validProxyServers :ValidProxyServerIdentities;
}
export interface ConnectionState {
localGettingFromRemote :social.GettingState;
localSharingWithRemote :social.SharingState;
bytesSent :number;
bytesReceived :number;
activeEndpoint :net.Endpoint;
proxyingId ?:string;
}
// Contains settings directing rtc-to-net server to go directly to net or
// reproxy through a socks proxy server (such as local Tor proxy).
export interface reproxySettings {
enabled :boolean; // Reproxy through socks is enabled
socksEndpoint :net.Endpoint; // Endpoint through which to reproxy
}
// --- Communications ---
// Commands are sent from the UI to the Core due to a user interaction.
// This fully describes the set of commands that Core must respond to.
//
// Enum value names should be verb phrases that clearly describe the action
// being requested.
//
// TODO: Finalize which of these can be removed, then clean up accordingly.
export enum Command {
GET_INITIAL_STATE_DEPRECATED_0_8_10 = 1000,
RESTART = 1001,
LOGIN = 1002,
LOGOUT = 1003,
SEND_INSTANCE_HANDSHAKE_MESSAGE = 1004,
START_PROXYING = 1005,
STOP_PROXYING = 1006,
MODIFY_CONSENT = 1007, // TODO: make this work with the consent piece.
SEND_CREDENTIALS = 1014,
UPDATE_GLOBAL_SETTINGS = 1015, // Fully replaces the uProxy global settings
GET_LOGS = 1016,
GET_NAT_TYPE = 1017,
PING_UNTIL_ONLINE = 1018,
GET_FULL_STATE = 1019,
GET_VERSION = 1020,
HANDLE_CORE_UPDATE = 1021,
REFRESH_PORT_CONTROL = 1022,
CREDENTIALS_ERROR = 1023,
GET_INVITE_URL = 1025,
SEND_EMAIL = 1026,
ACCEPT_INVITATION = 1027,
INVITE_GITHUB_USER = 1028,
CLOUD_UPDATE = 1029,
UPDATE_ORG_POLICY = 1030,
REMOVE_CONTACT = 1031,
POST_REPORT = 1032,
VERIFY_USER = 1033,
VERIFY_USER_SAS = 1034,
GET_PORT_CONTROL_SUPPORT = 1035,
UPDATE_GLOBAL_SETTING = 1036, // Updates a single global setting
CHECK_REPROXY = 1037
}
// Updates are sent from the Core to the UI, to update state that the UI must
// expose to the user.
export enum Update {
INITIAL_STATE_DEPRECATED_0_8_10 = 2000,
NETWORK = 2001, // One particular network.
USER_SELF = 2002, // Local / myself on the network.
USER_FRIEND = 2003, // Remote friend on the roster.
COMMAND_FULFILLED = 2005,
COMMAND_REJECTED = 2006,
START_GIVING_TO_FRIEND = 2009,
STOP_GIVING_TO_FRIEND = 2010,
// TODO: "Get credentials" is a command, not an "update". Consider
// renaming the "Update" enum.
GET_CREDENTIALS = 2012,
LAUNCH_UPROXY = 2013,
SIGNALLING_MESSAGE = 2014, /* copypaste messages */
START_GETTING = 2015,
START_GIVING = 2017,
STOP_GIVING = 2018,
STATE = 2019,
FAILED_TO_GIVE = 2020,
CORE_UPDATE_AVAILABLE = 2024,
PORT_CONTROL_STATUS = 2025,
// Payload is a string, obtained from the SignalBatcher in uproxy-lib.
ONETIME_MESSAGE = 2026,
// Deprecated: CLOUD_INSTALL_STATUS = 2027,
REMOVE_FRIEND = 2028, // Removed friend from roster.
// Deprecated: CLOUD_INSTALL_PROGRESS = 2029,
REFRESH_GLOBAL_SETTINGS = 2030, // Sends UI new canonical version of global settings
REPROXY_ERROR = 2031, // Controls reproxy error bar notification to sharer
REPROXY_WORKING = 2032
}
// Action taken by the user. These values are not on the wire. They are passed
// in messages from the UI to the core. They correspond to the different
// buttons that the user may be clicking on.
export enum ConsentUserAction {
// Actions made by user w.r.t. remote as a proxy
REQUEST = 5000, CANCEL_REQUEST, IGNORE_OFFER, UNIGNORE_OFFER,
// Actions made by user w.r.t. remote as a client
OFFER = 5100, CANCEL_OFFER, IGNORE_REQUEST, UNIGNORE_REQUEST,
}
// Payload of FAILED_TO_GET and FAILED_TO_GIVE messages.
export interface FailedToGetOrGive {
name: string;
proxyingId: string;
}
/**
* ConsentCommands are sent from the UI to the Core, to modify the consent of
* a :RemoteInstance in the local client. (This is not sent on the wire to
* the peer). This should only be passed along with a `Command.MODIFY_CONSENT`
* command.
*/
export interface ConsentCommand {
path :social.UserPath;
action :ConsentUserAction;
}
export interface CloudfrontPostData {
payload :Object;
cloudfrontPath :string;
}
export enum LoginType {
INITIAL = 0,
RECONNECT,
TEST
}
export interface LoginArgs {
network :string;
loginType :LoginType;
userName ?:string;
}
export interface LoginResult {
userId :string;
instanceId :string;
}
export interface NetworkInfo {
natType ?:string;
pmpSupport :boolean;
pcpSupport :boolean;
upnpSupport :boolean;
errorMsg ?:string;
};
export interface EmailData {
networkInfo: social.SocialNetworkInfo;
to :string;
subject :string;
body :string;
};
// Data needed to accept user invites.
export interface AcceptInvitationData {
network :social.SocialNetworkInfo;
tokenObj ?:any;
userId ?:string;
};
// Data needed to generate an invite URL.
export interface CreateInviteArgs {
network :social.SocialNetworkInfo;
isRequesting :boolean;
isOffering :boolean;
userId ?:string; // for GitHub only
};
export enum PortControlSupport {PENDING, TRUE, FALSE};
export enum ReproxyCheck {PENDING, TRUE, FALSE, UNCHECKED};
export enum CloudOperationType {
CLOUD_INSTALL = 0
}
// Arguments to cloudUpdate
export interface CloudOperationArgs {
operation: CloudOperationType;
// Use this cloud computing provider to access a server.
providerName :string;
// Provider-specific region in which to locate a new server.
region ?:string;
};
// Argument to removeContact
export interface RemoveContactArgs {
// Name of the network the contact is a part of
networkName :string,
// userId of the contact you want to remove
userId :string
};
export interface PostReportArgs {
payload: Object;
path: string;
};
export interface FinishVerifyArgs {
inst: social.InstancePath,
sameSAS: boolean
};
/**
* The primary interface to the uProxy Core.
*
* This will be enforced for both the actual core implementation, as well as
* abstraction layers such as the Chrome Extension, so that all components
* which speak to the core benefit from this consistency.
*/
// TODO: Rename CoreApi.
export interface CoreApi {
// Send your own instanceId to target clientId.
getFullState() :Promise<InitialState>;
modifyConsent(command :ConsentCommand) :void;
getLogs() :Promise<string>;
// Using peer as a proxy.
start(instancePath :social.InstancePath) : Promise<net.Endpoint>;
stop (path :social.InstancePath) : Promise<void>;
updateGlobalSettings(newSettings :GlobalSettings) :void;
updateGlobalSetting(change: UpdateGlobalSettingArgs): void;
login(loginArgs :LoginArgs) : Promise<LoginResult>;
logout(networkInfo :social.SocialNetworkInfo) : Promise<void>;
// TODO: use Event instead of attaching manual handler. This allows event
// removal, etc.
onUpdate(update :Update, handler :Function) :void;
pingUntilOnline(pingUrl :string) : Promise<void>;
getVersion() :Promise<{ version :string }>;
getInviteUrl(data :CreateInviteArgs): Promise<string>;
// Installs or destroys uProxy on a server. Generally a long-running operation, so
// callers should expose CLOUD_INSTALL_STATUS updates to the user.
// This may also invoke an OAuth flow, in order to perform operations
// with the cloud computing provider on the user's behalf.
cloudUpdate(args :CloudOperationArgs): Promise<void>;
// Removes contact from roster, storage, and friend list
removeContact(args :RemoveContactArgs) : Promise<void>;
// Make a domain-fronted POST request to the uProxy logs/stats server.
postReport(args:PostReportArgs) : Promise<void>;
// Start a ZRTP key-verification session.
verifyUser(inst :social.InstancePath) :void;
// Confirm or reject the SAS in a ZRTP key-verification session.
finishVerifyUser(args:FinishVerifyArgs) :void;
inviteGitHubUser(data :CreateInviteArgs) : Promise<void>;
getPortControlSupport(): Promise<PortControlSupport>;
// Check if socks reproxy exists at input port
checkReproxy(port :number): Promise<ReproxyCheck>;
} | the_stack |
import * as mocha from "mocha";
import * as should from "should";
import { BinaryStream } from "node-opcua-binary-stream";
import { ExtensionObject, OpaqueStructure } from "node-opcua-extension-object";
import { nodesets } from "node-opcua-nodesets";
import { DataType, Variant } from "node-opcua-variant";
import { checkDebugFlag, make_debugLog } from "node-opcua-debug";
import { AttributeIds } from "node-opcua-data-model";
import { StatusCodes } from "node-opcua-status-code";
import { CallMethodResult, DataTypeDefinition, StructureDefinition } from "node-opcua-types";
import { getExtraDataTypeManager, promoteOpaqueStructure } from "node-opcua-client-dynamic-extension-object";
import { AddressSpace, adjustNamespaceArray, ensureDatatypeExtracted, PseudoSession, resolveOpaqueOnAddressSpace } from "..";
import { generateAddressSpace } from "../nodeJS";
const debugLog = make_debugLog("TEST");
const doDebug = checkDebugFlag("TEST");
describe("Testing AutoID custom types", async function (this: any) {
this.timeout(200000); // could be slow on appveyor !
let addressSpace: AddressSpace;
before(async () => {
addressSpace = AddressSpace.create();
const namespace0 = addressSpace.getDefaultNamespace();
await generateAddressSpace(addressSpace, [nodesets.standard, nodesets.di, nodesets.autoId]);
await ensureDatatypeExtracted(addressSpace);
});
after(() => {
addressSpace.dispose();
});
it("should construct a ScanSettings", () => {
enum LocationTypeEnumeration {
NMEA = 0, // An NMEA string representing a coordinate as defined in 9.1.2.
LOCAL = 2, // A local coordinate as defined in 9.3.4
WGS84 = 4, // A lat / lon / alt coordinate as defined in 9.3.16
NAME = 5 // A name for a location as defined in 9.1.1
}
interface ScanSettings extends ExtensionObject {
duration: number;
cycles: number;
dataAvailable: boolean;
locationType?: LocationTypeEnumeration;
}
const nsAutoId = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/AutoID/");
nsAutoId.should.eql(2);
const scanSettingsDataTypeNode = addressSpace.findDataType("ScanSettings", nsAutoId)!;
should.exist(scanSettingsDataTypeNode);
const settings = addressSpace.constructExtensionObject(scanSettingsDataTypeNode, {}) as ScanSettings;
});
function encode_decode(obj: Variant): Variant {
const size = obj.binaryStoreSize();
const stream = new BinaryStream(Buffer.alloc(size));
obj.encode(stream);
stream.rewind();
// reconstruct a object ( some object may not have a default Binary and should be recreated
const objReloaded = new Variant();
objReloaded.decode(stream);
debugLog("Reloaded = ", objReloaded.toString());
return objReloaded;
}
it("should construct a ScanResult ", async () => {
interface ScanResult extends ExtensionObject {}
const nsAutoId = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/AutoID/");
nsAutoId.should.eql(2);
const rfidScanResultDataTypeNode = addressSpace.findDataType("RfidScanResult", nsAutoId)!;
should.exist(rfidScanResultDataTypeNode);
const scanResult = addressSpace.constructExtensionObject(rfidScanResultDataTypeNode, {
// ScanResult
codeType: "Hello",
scanData: {
epc: {
pC: 12,
uId: Buffer.from("Hello"),
xpC_W1: 10,
xpC_W2: 12
}
},
timestamp: new Date(2018, 11, 23),
location: {
local: {
x: 100,
y: 200,
z: 300,
timestamp: new Date(),
dilutionOfPrecision: 0.01,
usefulPrecicision: 2 // <<!!!! Note the TYPO HERE ! Bug in AutoID.XML !
}
}
}) as ScanResult;
debugLog("scanResult = ", scanResult.toString());
//xx debugLog(scanResult.schema);
const v = new Variant({
dataType: DataType.ExtensionObject,
value: scanResult
});
const reload_v = encode_decode(v);
await resolveOpaqueOnAddressSpace(addressSpace, reload_v);
debugLog(reload_v.toString());
debugLog(scanResult.toString());
});
it("should create a opcua variable with a scan result", () => {
const namespace = addressSpace.getOwnNamespace();
const nsAutoId = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/AutoID/");
nsAutoId.should.eql(2);
const rfidScanResultDataTypeNode = addressSpace.findDataType("RfidScanResult", nsAutoId)!;
should.exist(rfidScanResultDataTypeNode);
const scanResult = addressSpace.constructExtensionObject(rfidScanResultDataTypeNode, {
codeType: "Code",
scanData: { string: "Hello" },
sighting: [{}, {}]
});
const scanResultNode = namespace.addVariable({
browseName: "ScanResult",
dataType: rfidScanResultDataTypeNode,
value: { dataType: DataType.ExtensionObject, value: scanResult }
});
// debugLog(scanResultNode.toString());
});
it("test RfidScanResult", async () => {
const nsAutoId = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/AutoID/");
const rfidScanResultDataTypeNode = addressSpace.findDataType("RfidScanResult", nsAutoId)!;
if (!rfidScanResultDataTypeNode) {
throw new Error("cannot find RfidScanResult");
}
const namespace = addressSpace.getOwnNamespace();
const scanResult = addressSpace.constructExtensionObject(rfidScanResultDataTypeNode, {
// ScanResult
scanData: {
epc: {
pC: 12,
uId: Buffer.from("Hello"),
xpC_W1: 10,
xpC_W2: 12
}
},
timestamp: new Date(2018, 11, 23),
location: {
local: {
x: 100,
y: 200,
z: 300,
dilutionOfPrecision: 0.01,
timestamp: new Date(),
usefulPrecicision: 2 // <<!!!! Note the TYPO HERE ! Bug in AutoID.XML !
}
}
});
debugLog(scanResult.toString());
const v = new Variant({
dataType: DataType.ExtensionObject,
value: scanResult
});
const reload_v = encode_decode(v);
await resolveOpaqueOnAddressSpace(addressSpace, reload_v);
debugLog(reload_v.toString());
// re-encode reload_vso that we keep the Opaque structure
const reload_v2 = encode_decode(reload_v);
reload_v2.value.should.be.instanceOf(OpaqueStructure);
// now let's encode the variant that contains the Opaque Strucgture
const bs2 = new BinaryStream(10000);
reload_v2.encode(bs2);
// and verify that it could be decoded well
const v2 = new Variant();
bs2.length = 0;
v2.decode(bs2);
await resolveOpaqueOnAddressSpace(addressSpace, v2);
debugLog(v2.toString());
});
it("KX The dataTypeDefinition of RfidScanResult shall contain base dataTypeDefinition ", () => {
const nsAutoId = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/AutoID/");
const scanResultDataTypeNode = addressSpace.findDataType("ScanResult", nsAutoId);
{
const dataValue = scanResultDataTypeNode.readAttribute(null, AttributeIds.DataTypeDefinition);
dataValue.statusCode.should.eql(StatusCodes.Good);
const dataTypeDefinition = dataValue.value.value as DataTypeDefinition;
dataTypeDefinition.should.be.instanceOf(StructureDefinition);
//Xx console.log(dataTypeDefinition.toString());
const structureDefinition = dataTypeDefinition as StructureDefinition;
structureDefinition.fields.length.should.eql(4);
}
const rfidScanResultDataTypeNode = addressSpace.findDataType("RfidScanResult", nsAutoId)!;
{
const dataValue = rfidScanResultDataTypeNode.readAttribute(null, AttributeIds.DataTypeDefinition);
dataValue.statusCode.should.eql(StatusCodes.Good);
const dataTypeDefinition = dataValue.value.value as DataTypeDefinition;
dataTypeDefinition.should.be.instanceOf(StructureDefinition);
//Xx console.log(dataTypeDefinition.toString());
const structureDefinition = dataTypeDefinition as StructureDefinition;
structureDefinition.fields.length.should.eql(5);
}
});
it("GHU - should promote the OpaqueStructure of an array of variant containing Extension Object", async () => {
const nsAutoId = addressSpace.getNamespaceIndex("http://opcfoundation.org/UA/AutoID/");
const rfidScanResultDataTypeNode = addressSpace.findDataType("RfidScanResult", nsAutoId)!;
const extObj1 = addressSpace.constructExtensionObject(rfidScanResultDataTypeNode, {});
const extObj2 = addressSpace.constructExtensionObject(rfidScanResultDataTypeNode, {});
const callResult = new CallMethodResult({
statusCode: StatusCodes.Good,
outputArguments: [
new Variant({
dataType: DataType.ExtensionObject,
value: [extObj1, extObj2]
})
]
});
const v = new Variant({
dataType: DataType.ExtensionObject,
value: callResult
});
// re-encode reload_vso that we keep the Opaque structure
const reload_v2 = encode_decode(v);
reload_v2.value.should.be.instanceOf(CallMethodResult);
const callbackResult2 = reload_v2.value as CallMethodResult;
callbackResult2.outputArguments.length.should.eql(1);
callbackResult2.outputArguments[0].dataType.should.eql(DataType.ExtensionObject);
callbackResult2.outputArguments[0].value.length.should.eql(2);
callbackResult2.outputArguments[0].value[0].should.be.instanceOf(OpaqueStructure);
callbackResult2.outputArguments[0].value[1].should.be.instanceOf(OpaqueStructure);
const session = new PseudoSession(addressSpace);
const extraDataTypeManager = await getExtraDataTypeManager(session);
await promoteOpaqueStructure(
session,
callbackResult2.outputArguments.map((a) => ({ value: a }))
);
callbackResult2.outputArguments[0].value[0].should.not.be.instanceOf(OpaqueStructure);
callbackResult2.outputArguments[0].value[1].should.not.be.instanceOf(OpaqueStructure);
debugLog(reload_v2.toString());
});
}); | the_stack |
import { useCallback, useContext, useEffect, useState, useRef } from 'react';
import { UserAttributes, OptimizelyDecideOption } from '@optimizely/optimizely-sdk';
import { getLogger, LoggerFacade } from '@optimizely/js-sdk-logging';
import { setupAutoUpdateListeners } from './autoUpdate';
import { ReactSDKClient, VariableValuesObject, OnReadyResult } from './client';
import { OptimizelyContext } from './Context';
import { areAttributesEqual, OptimizelyDecision, createFailedDecision } from './utils';
const hooksLogger: LoggerFacade = getLogger('ReactSDK');
enum HookType {
EXPERIMENT = 'Experiment',
FEATURE = 'Feature',
}
type HookOptions = {
autoUpdate?: boolean;
timeout?: number;
};
type DecideHooksOptions = HookOptions & { decideOptions?: OptimizelyDecideOption[] };
type HookOverrides = {
overrideUserId?: string;
overrideAttributes?: UserAttributes;
};
type ClientReady = boolean;
type DidTimeout = boolean;
interface InitializationState {
clientReady: ClientReady;
didTimeout: DidTimeout;
}
// TODO - Get these from the core SDK once it's typed
interface ExperimentDecisionValues {
variation: string | null;
}
// TODO - Get these from the core SDK once it's typed
interface FeatureDecisionValues {
isEnabled: boolean;
variables: VariableValuesObject;
}
interface UseExperiment {
(experimentKey: string, options?: HookOptions, overrides?: HookOverrides): [
ExperimentDecisionValues['variation'],
ClientReady,
DidTimeout
];
}
interface UseFeature {
(featureKey: string, options?: HookOptions, overrides?: HookOverrides): [
FeatureDecisionValues['isEnabled'],
FeatureDecisionValues['variables'],
ClientReady,
DidTimeout
];
}
interface UseDecision {
(featureKey: string, options?: DecideHooksOptions, overrides?: HookOverrides): [
OptimizelyDecision,
ClientReady,
DidTimeout
];
}
interface DecisionInputs {
entityKey: string;
overrideUserId?: string;
overrideAttributes?: UserAttributes;
}
/**
* Equality check applied to decision inputs passed into hooks (experiment/feature keys, override user IDs, and override user attributes).
* Used to determine when we need to recompute a decision because different inputs were passed into a hook.
* @param {DecisionInputs} oldDecisionInputs
* @param {DecisionInput} newDecisionInputs
* @returns boolean
*/
function areDecisionInputsEqual(oldDecisionInputs: DecisionInputs, newDecisionInputs: DecisionInputs): boolean {
return (
oldDecisionInputs.entityKey === newDecisionInputs.entityKey &&
oldDecisionInputs.overrideUserId === newDecisionInputs.overrideUserId &&
areAttributesEqual(oldDecisionInputs.overrideAttributes, newDecisionInputs.overrideAttributes)
);
}
/**
* Subscribe to changes in initialization state of the argument client. onInitStateChange callback
* is called on the following events:
* - optimizely successfully becomes ready
* - timeout is reached prior to optimizely becoming ready
* - optimizely becomes ready after the timeout has already passed
* @param {ReactSDKClient} optimizely
* @param {number|undefined} timeout
* @param {Function} onInitStateChange
*/
function subscribeToInitialization(
optimizely: ReactSDKClient,
timeout: number | undefined,
onInitStateChange: (initState: InitializationState) => void
): void {
optimizely
.onReady({ timeout })
.then((res: OnReadyResult) => {
if (res.success) {
hooksLogger.info('Client became ready');
onInitStateChange({
clientReady: true,
didTimeout: false,
});
return;
}
hooksLogger.info(`Client did not become ready before timeout of ${timeout}ms, reason="${res.reason || ''}"`);
onInitStateChange({
clientReady: false,
didTimeout: true,
});
res.dataReadyPromise!.then(() => {
hooksLogger.info('Client became ready after timeout already elapsed');
onInitStateChange({
clientReady: true,
didTimeout: true,
});
});
})
.catch(() => {
hooksLogger.error(`Error initializing client. The core client or user promise(s) rejected.`);
});
}
function useCompareAttrsMemoize(value: UserAttributes | undefined): UserAttributes | undefined {
const ref = useRef<UserAttributes | undefined>();
if (!areAttributesEqual(value, ref.current)) {
ref.current = value;
}
return ref.current;
}
/**
* A React Hook that retrieves the variation for an experiment, optionally
* auto updating that value based on underlying user or datafile changes.
*
* Note: The react client can become ready AFTER the timeout period.
* ClientReady and DidTimeout provide signals to handle this scenario.
*/
export const useExperiment: UseExperiment = (experimentKey, options = {}, overrides = {}) => {
const { optimizely, isServerSide, timeout } = useContext(OptimizelyContext);
if (!optimizely) {
throw new Error('optimizely prop must be supplied via a parent <OptimizelyProvider>');
}
const overrideAttrs = useCompareAttrsMemoize(overrides.overrideAttributes);
const getCurrentDecision: () => ExperimentDecisionValues = useCallback(
() => ({
variation: optimizely.activate(experimentKey, overrides.overrideUserId, overrideAttrs),
}),
[optimizely, experimentKey, overrides.overrideUserId, overrideAttrs]
);
const isClientReady = isServerSide || optimizely.isReady();
const [state, setState] = useState<ExperimentDecisionValues & InitializationState>(() => {
const decisionState = isClientReady ? getCurrentDecision() : { variation: null };
return {
...decisionState,
clientReady: isClientReady,
didTimeout: false,
};
});
// Decision state is derived from entityKey and overrides arguments.
// Track the previous value of those arguments, and update state when they change.
// This is an instance of the derived state pattern recommended here:
// https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-getderivedstatefromprops
const currentDecisionInputs: DecisionInputs = {
entityKey: experimentKey,
overrideUserId: overrides.overrideUserId,
overrideAttributes: overrideAttrs,
};
const [prevDecisionInputs, setPrevDecisionInputs] = useState<DecisionInputs>(currentDecisionInputs);
if (!areDecisionInputsEqual(prevDecisionInputs, currentDecisionInputs)) {
setPrevDecisionInputs(currentDecisionInputs);
setState(prevState => ({
...prevState,
...getCurrentDecision(),
}));
}
const finalReadyTimeout = options.timeout !== undefined ? options.timeout : timeout;
useEffect(() => {
// Subscribe to initialzation promise only
// 1. When client is using Sdk Key, which means the initialization will be asynchronous
// and we need to wait for the promise and update decision.
// 2. When client is using datafile only but client is not ready yet which means user
// was provided as a promise and we need to subscribe and wait for user to become available.
if (optimizely.getIsUsingSdkKey() || !isClientReady) {
subscribeToInitialization(optimizely, finalReadyTimeout, initState => {
setState({
...getCurrentDecision(),
...initState,
});
});
}
}, []);
useEffect(() => {
// Subscribe to update after first datafile is fetched and readyPromise is resolved to avoid redundant rendering.
if (optimizely.getIsReadyPromiseFulfilled() && options.autoUpdate) {
return setupAutoUpdateListeners(optimizely, HookType.EXPERIMENT, experimentKey, hooksLogger, () => {
setState(prevState => ({
...prevState,
...getCurrentDecision(),
}));
});
}
return (): void => {};
}, [optimizely.getIsReadyPromiseFulfilled(), options.autoUpdate, optimizely, experimentKey, getCurrentDecision]);
useEffect(
() =>
optimizely.onForcedVariationsUpdate(() => {
setState(prevState => ({
...prevState,
...getCurrentDecision(),
}));
}),
[getCurrentDecision, optimizely]
);
return [state.variation, state.clientReady, state.didTimeout];
};
/**
* A React Hook that retrieves the status of a feature flag and its variables, optionally
* auto updating those values based on underlying user or datafile changes.
*
* Note: The react client can become ready AFTER the timeout period.
* ClientReady and DidTimeout provide signals to handle this scenario.
*/
export const useFeature: UseFeature = (featureKey, options = {}, overrides = {}) => {
const { optimizely, isServerSide, timeout } = useContext(OptimizelyContext);
if (!optimizely) {
throw new Error('optimizely prop must be supplied via a parent <OptimizelyProvider>');
}
const overrideAttrs = useCompareAttrsMemoize(overrides.overrideAttributes);
const getCurrentDecision: () => FeatureDecisionValues = useCallback(
() => ({
isEnabled: optimizely.isFeatureEnabled(featureKey, overrides.overrideUserId, overrideAttrs),
variables: optimizely.getFeatureVariables(featureKey, overrides.overrideUserId, overrideAttrs),
}),
[optimizely, featureKey, overrides.overrideUserId, overrideAttrs]
);
const isClientReady = isServerSide || optimizely.isReady();
const [state, setState] = useState<FeatureDecisionValues & InitializationState>(() => {
const decisionState = isClientReady ? getCurrentDecision() : { isEnabled: false, variables: {} };
return {
...decisionState,
clientReady: isClientReady,
didTimeout: false,
};
});
// Decision state is derived from entityKey and overrides arguments.
// Track the previous value of those arguments, and update state when they change.
// This is an instance of the derived state pattern recommended here:
// https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-getderivedstatefromprops
const currentDecisionInputs: DecisionInputs = {
entityKey: featureKey,
overrideUserId: overrides.overrideUserId,
overrideAttributes: overrides.overrideAttributes,
};
const [prevDecisionInputs, setPrevDecisionInputs] = useState<DecisionInputs>(currentDecisionInputs);
if (!areDecisionInputsEqual(prevDecisionInputs, currentDecisionInputs)) {
setPrevDecisionInputs(currentDecisionInputs);
setState(prevState => ({
...prevState,
...getCurrentDecision(),
}));
}
const finalReadyTimeout = options.timeout !== undefined ? options.timeout : timeout;
useEffect(() => {
// Subscribe to initialzation promise only
// 1. When client is using Sdk Key, which means the initialization will be asynchronous
// and we need to wait for the promise and update decision.
// 2. When client is using datafile only but client is not ready yet which means user
// was provided as a promise and we need to subscribe and wait for user to become available.
if (optimizely.getIsUsingSdkKey() || !isClientReady) {
subscribeToInitialization(optimizely, finalReadyTimeout, initState => {
setState({
...getCurrentDecision(),
...initState,
});
});
}
}, []);
useEffect(() => {
// Subscribe to update after first datafile is fetched and readyPromise is resolved to avoid redundant rendering.
if (optimizely.getIsReadyPromiseFulfilled() && options.autoUpdate) {
return setupAutoUpdateListeners(optimizely, HookType.FEATURE, featureKey, hooksLogger, () => {
setState(prevState => ({
...prevState,
...getCurrentDecision(),
}));
});
}
return (): void => {};
}, [optimizely.getIsReadyPromiseFulfilled(), options.autoUpdate, optimizely, featureKey, getCurrentDecision]);
return [state.isEnabled, state.variables, state.clientReady, state.didTimeout];
};
/**
* A React Hook that retrieves the flag decision, optionally
* auto updating those values based on underlying user or datafile changes.
*
* Note: The react client can become ready AFTER the timeout period.
* ClientReady and DidTimeout provide signals to handle this scenario.
*/
export const useDecision: UseDecision = (flagKey, options = {}, overrides = {}) => {
const { optimizely, isServerSide, timeout } = useContext(OptimizelyContext);
if (!optimizely) {
throw new Error('optimizely prop must be supplied via a parent <OptimizelyProvider>');
}
const overrideAttrs = useCompareAttrsMemoize(overrides.overrideAttributes);
const getCurrentDecision: () => { decision: OptimizelyDecision } = useCallback(
() => ({
decision: optimizely.decide(flagKey, options.decideOptions, overrides.overrideUserId, overrideAttrs)
}),
[optimizely, flagKey, overrides.overrideUserId, overrideAttrs, options.decideOptions]
);
const isClientReady = isServerSide || optimizely.isReady();
const [state, setState] = useState<{ decision: OptimizelyDecision } & InitializationState>(() => {
const decisionState = isClientReady? getCurrentDecision()
: { decision: createFailedDecision(flagKey, 'Optimizely SDK not configured properly yet.', { id: overrides.overrideUserId || null, attributes: overrideAttrs}) };
return {
...decisionState,
clientReady: isClientReady,
didTimeout: false,
};
});
// Decision state is derived from entityKey and overrides arguments.
// Track the previous value of those arguments, and update state when they change.
// This is an instance of the derived state pattern recommended here:
// https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-getderivedstatefromprops
const currentDecisionInputs: DecisionInputs = {
entityKey: flagKey,
overrideUserId: overrides.overrideUserId,
overrideAttributes: overrides.overrideAttributes,
};
const [prevDecisionInputs, setPrevDecisionInputs] = useState<DecisionInputs>(currentDecisionInputs);
if (!areDecisionInputsEqual(prevDecisionInputs, currentDecisionInputs)) {
setPrevDecisionInputs(currentDecisionInputs);
setState(prevState => ({
...prevState,
...getCurrentDecision(),
}));
}
const finalReadyTimeout = options.timeout !== undefined ? options.timeout : timeout;
useEffect(() => {
// Subscribe to initialzation promise only
// 1. When client is using Sdk Key, which means the initialization will be asynchronous
// and we need to wait for the promise and update decision.
// 2. When client is using datafile only but client is not ready yet which means user
// was provided as a promise and we need to subscribe and wait for user to become available.
if (optimizely.getIsUsingSdkKey() || !isClientReady) {
subscribeToInitialization(optimizely, finalReadyTimeout, initState => {
setState({
...getCurrentDecision(),
...initState,
});
});
}
}, []);
useEffect(() => {
// Subscribe to update after first datafile is fetched and readyPromise is resolved to avoid redundant rendering.
if (optimizely.getIsReadyPromiseFulfilled() && options.autoUpdate) {
return setupAutoUpdateListeners(optimizely, HookType.FEATURE, flagKey, hooksLogger, () => {
setState(prevState => ({
...prevState,
...getCurrentDecision(),
}));
});
}
return (): void => {};
}, [optimizely.getIsReadyPromiseFulfilled(), options.autoUpdate, optimizely, flagKey, getCurrentDecision]);
return [state.decision, state.clientReady, state.didTimeout];
}; | the_stack |
import Page = require('../../../base/Page');
import Response = require('../../../http/response');
import V1 = require('../V1');
import { SerializableClass } from '../../../interfaces';
type CallSummariesCallDirection = 'outbound_api'|'outbound_dial'|'inbound'|'trunking_originating'|'trunking_terminating';
type CallSummariesCallState = 'ringing'|'completed'|'busy'|'fail'|'noanswer'|'canceled'|'answered'|'undialed';
type CallSummariesCallType = 'carrier'|'sip'|'trunking'|'client';
type CallSummariesProcessingState = 'complete'|'partial';
type CallSummariesProcessingStateRequest = 'completed'|'started'|'partial'|'all';
type CallSummariesSortBy = 'start_time'|'end_time';
/**
* Initialize the CallSummariesList
*
* @param version - Version of the resource
*/
declare function CallSummariesList(version: V1): CallSummariesListInstance;
interface CallSummariesListInstance {
/**
* Streams CallSummariesInstance records from the API.
*
* This operation lazily loads records as efficiently as possible until the limit
* is reached.
*
* The results are passed into the callback function, so this operation is memory
* efficient.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param callback - Function to process each record
*/
each(callback?: (item: CallSummariesInstance, done: (err?: Error) => void) => void): void;
/**
* Streams CallSummariesInstance records from the API.
*
* This operation lazily loads records as efficiently as possible until the limit
* is reached.
*
* The results are passed into the callback function, so this operation is memory
* efficient.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param opts - Options for request
* @param callback - Function to process each record
*/
each(opts?: CallSummariesListInstanceEachOptions, callback?: (item: CallSummariesInstance, done: (err?: Error) => void) => void): void;
/**
* Retrieve a single target page of CallSummariesInstance records from the API.
*
* The request is executed immediately.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param callback - Callback to handle list of records
*/
getPage(callback?: (error: Error | null, items: CallSummariesPage) => any): Promise<CallSummariesPage>;
/**
* Retrieve a single target page of CallSummariesInstance records from the API.
*
* The request is executed immediately.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param targetUrl - API-generated URL for the requested results page
* @param callback - Callback to handle list of records
*/
getPage(targetUrl?: string, callback?: (error: Error | null, items: CallSummariesPage) => any): Promise<CallSummariesPage>;
/**
* Lists CallSummariesInstance records from the API as a list.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param callback - Callback to handle list of records
*/
list(callback?: (error: Error | null, items: CallSummariesInstance[]) => any): Promise<CallSummariesInstance[]>;
/**
* Lists CallSummariesInstance records from the API as a list.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param opts - Options for request
* @param callback - Callback to handle list of records
*/
list(opts?: CallSummariesListInstanceOptions, callback?: (error: Error | null, items: CallSummariesInstance[]) => any): Promise<CallSummariesInstance[]>;
/**
* Retrieve a single page of CallSummariesInstance records from the API.
*
* The request is executed immediately.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param callback - Callback to handle list of records
*/
page(callback?: (error: Error | null, items: CallSummariesPage) => any): Promise<CallSummariesPage>;
/**
* Retrieve a single page of CallSummariesInstance records from the API.
*
* The request is executed immediately.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param opts - Options for request
* @param callback - Callback to handle list of records
*/
page(opts?: CallSummariesListInstancePageOptions, callback?: (error: Error | null, items: CallSummariesPage) => any): Promise<CallSummariesPage>;
/**
* Provide a user-friendly representation
*/
toJSON(): any;
}
/**
* Options to pass to each
*
* @property abnormalSession - The abnormal_session
* @property branded - The branded
* @property callState - The call_state
* @property callType - The call_type
* @property callback -
* Function to process each record. If this and a positional
* callback are passed, this one will be used
* @property direction - The direction
* @property done - Function to be called upon completion of streaming
* @property endTime - The end_time
* @property from - The from
* @property fromCarrier - The from_carrier
* @property fromCountryCode - The from_country_code
* @property hasTag - The has_tag
* @property limit -
* Upper limit for the number of records to return.
* each() guarantees never to return more than limit.
* Default is no limit
* @property pageSize -
* Number of records to fetch per request,
* when not set will use the default value of 50 records.
* If no pageSize is defined but a limit is defined,
* each() will attempt to read the limit with the most efficient
* page size, i.e. min(limit, 1000)
* @property processingState - The processing_state
* @property sortBy - The sort_by
* @property startTime - The start_time
* @property subaccount - The subaccount
* @property to - The to
* @property toCarrier - The to_carrier
* @property toCountryCode - The to_country_code
* @property verifiedCaller - The verified_caller
*/
interface CallSummariesListInstanceEachOptions {
abnormalSession?: boolean;
branded?: boolean;
callState?: string;
callType?: string;
callback?: (item: CallSummariesInstance, done: (err?: Error) => void) => void;
direction?: string;
done?: Function;
endTime?: string;
from?: string;
fromCarrier?: string;
fromCountryCode?: string;
hasTag?: boolean;
limit?: number;
pageSize?: number;
processingState?: CallSummariesProcessingStateRequest;
sortBy?: CallSummariesSortBy;
startTime?: string;
subaccount?: string;
to?: string;
toCarrier?: string;
toCountryCode?: string;
verifiedCaller?: boolean;
}
/**
* Options to pass to list
*
* @property abnormalSession - The abnormal_session
* @property branded - The branded
* @property callState - The call_state
* @property callType - The call_type
* @property direction - The direction
* @property endTime - The end_time
* @property from - The from
* @property fromCarrier - The from_carrier
* @property fromCountryCode - The from_country_code
* @property hasTag - The has_tag
* @property limit -
* Upper limit for the number of records to return.
* list() guarantees never to return more than limit.
* Default is no limit
* @property pageSize -
* Number of records to fetch per request,
* when not set will use the default value of 50 records.
* If no page_size is defined but a limit is defined,
* list() will attempt to read the limit with the most
* efficient page size, i.e. min(limit, 1000)
* @property processingState - The processing_state
* @property sortBy - The sort_by
* @property startTime - The start_time
* @property subaccount - The subaccount
* @property to - The to
* @property toCarrier - The to_carrier
* @property toCountryCode - The to_country_code
* @property verifiedCaller - The verified_caller
*/
interface CallSummariesListInstanceOptions {
abnormalSession?: boolean;
branded?: boolean;
callState?: string;
callType?: string;
direction?: string;
endTime?: string;
from?: string;
fromCarrier?: string;
fromCountryCode?: string;
hasTag?: boolean;
limit?: number;
pageSize?: number;
processingState?: CallSummariesProcessingStateRequest;
sortBy?: CallSummariesSortBy;
startTime?: string;
subaccount?: string;
to?: string;
toCarrier?: string;
toCountryCode?: string;
verifiedCaller?: boolean;
}
/**
* Options to pass to page
*
* @property abnormalSession - The abnormal_session
* @property branded - The branded
* @property callState - The call_state
* @property callType - The call_type
* @property direction - The direction
* @property endTime - The end_time
* @property from - The from
* @property fromCarrier - The from_carrier
* @property fromCountryCode - The from_country_code
* @property hasTag - The has_tag
* @property pageNumber - Page Number, this value is simply for client state
* @property pageSize - Number of records to return, defaults to 50
* @property pageToken - PageToken provided by the API
* @property processingState - The processing_state
* @property sortBy - The sort_by
* @property startTime - The start_time
* @property subaccount - The subaccount
* @property to - The to
* @property toCarrier - The to_carrier
* @property toCountryCode - The to_country_code
* @property verifiedCaller - The verified_caller
*/
interface CallSummariesListInstancePageOptions {
abnormalSession?: boolean;
branded?: boolean;
callState?: string;
callType?: string;
direction?: string;
endTime?: string;
from?: string;
fromCarrier?: string;
fromCountryCode?: string;
hasTag?: boolean;
pageNumber?: number;
pageSize?: number;
pageToken?: string;
processingState?: CallSummariesProcessingStateRequest;
sortBy?: CallSummariesSortBy;
startTime?: string;
subaccount?: string;
to?: string;
toCarrier?: string;
toCountryCode?: string;
verifiedCaller?: boolean;
}
interface CallSummariesPayload extends CallSummariesResource, Page.TwilioResponsePayload {
}
interface CallSummariesResource {
account_sid: string;
attributes: object;
call_sid: string;
call_state: CallSummariesCallState;
call_type: CallSummariesCallType;
carrier_edge: object;
client_edge: object;
connect_duration: number;
created_time: Date;
duration: number;
end_time: Date;
from: object;
processing_state: CallSummariesProcessingState;
properties: object;
sdk_edge: object;
sip_edge: object;
start_time: Date;
tags: string[];
to: object;
trust: object;
url: string;
}
interface CallSummariesSolution {
}
declare class CallSummariesInstance extends SerializableClass {
/**
* Initialize the CallSummariesContext
*
* @param version - Version of the resource
* @param payload - The instance payload
*/
constructor(version: V1, payload: CallSummariesPayload);
accountSid: string;
attributes: any;
callSid: string;
callState: CallSummariesCallState;
callType: CallSummariesCallType;
carrierEdge: any;
clientEdge: any;
connectDuration: number;
createdTime: Date;
duration: number;
endTime: Date;
from: any;
processingState: CallSummariesProcessingState;
properties: any;
sdkEdge: any;
sipEdge: any;
startTime: Date;
tags: string[];
to: any;
/**
* Provide a user-friendly representation
*/
toJSON(): any;
trust: any;
url: string;
}
declare class CallSummariesPage extends Page<V1, CallSummariesPayload, CallSummariesResource, CallSummariesInstance> {
/**
* Initialize the CallSummariesPage
*
* @param version - Version of the resource
* @param response - Response from the API
* @param solution - Path solution
*/
constructor(version: V1, response: Response<string>, solution: CallSummariesSolution);
/**
* Build an instance of CallSummariesInstance
*
* @param payload - Payload response from the API
*/
getInstance(payload: CallSummariesPayload): CallSummariesInstance;
/**
* Provide a user-friendly representation
*/
toJSON(): any;
}
export { CallSummariesCallDirection, CallSummariesCallState, CallSummariesCallType, CallSummariesInstance, CallSummariesList, CallSummariesListInstance, CallSummariesListInstanceEachOptions, CallSummariesListInstanceOptions, CallSummariesListInstancePageOptions, CallSummariesPage, CallSummariesPayload, CallSummariesProcessingState, CallSummariesProcessingStateRequest, CallSummariesResource, CallSummariesSolution, CallSummariesSortBy } | the_stack |
import { getUintArray } from '../utils'
function getEdgeTable () {
return new Uint32Array([
0x0, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c,
0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00,
0x190, 0x99, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c,
0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90,
0x230, 0x339, 0x33, 0x13a, 0x636, 0x73f, 0x435, 0x53c,
0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30,
0x3a0, 0x2a9, 0x1a3, 0xaa, 0x7a6, 0x6af, 0x5a5, 0x4ac,
0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0,
0x460, 0x569, 0x663, 0x76a, 0x66, 0x16f, 0x265, 0x36c,
0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60,
0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff, 0x3f5, 0x2fc,
0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0,
0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55, 0x15c,
0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950,
0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc,
0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0,
0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc,
0xcc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0,
0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c,
0x15c, 0x55, 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650,
0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc,
0x2fc, 0x3f5, 0xff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0,
0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c,
0x36c, 0x265, 0x16f, 0x66, 0x76a, 0x663, 0x569, 0x460,
0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac,
0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa, 0x1a3, 0x2a9, 0x3a0,
0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c,
0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33, 0x339, 0x230,
0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c,
0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99, 0x190,
0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c,
0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x0
])
}
function getTriTable (): Int32Array {
return new Int32Array([
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1,
3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1,
3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1,
3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1,
9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1,
1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1,
9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1,
2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1,
8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1,
9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1,
4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1,
3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1,
1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1,
4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1,
4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1,
9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1,
1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1,
5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1,
2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1,
9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1,
0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1,
2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1,
10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1,
4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1,
5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1,
5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1,
9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1,
0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1,
1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1,
10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1,
8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1,
2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1,
7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1,
9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1,
2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1,
11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1,
9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1,
5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1,
11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1,
11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1,
1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1,
9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1,
5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1,
2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1,
0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1,
5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1,
6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1,
0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1,
3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1,
6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1,
5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1,
1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1,
10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1,
6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1,
1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1,
8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1,
7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1,
3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1,
5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1,
0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1,
9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1,
8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1,
5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1,
0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1,
6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1,
10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1,
10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1,
8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1,
1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1,
3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1,
0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1,
10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1,
0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1,
3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1,
6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1,
9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1,
8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1,
3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1,
6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1,
0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1,
10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1,
10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1,
1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1,
2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1,
7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1,
7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1,
2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1,
1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1,
11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1,
8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1,
0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1,
7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1,
10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1,
2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1,
6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1,
7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1,
2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1,
1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1,
10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1,
10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1,
0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1,
7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1,
6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1,
8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1,
9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1,
6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1,
1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1,
4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1,
10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1,
8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1,
0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1,
1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1,
8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1,
10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1,
4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1,
10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1,
5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1,
11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1,
9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1,
6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1,
7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1,
3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1,
7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1,
9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1,
3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1,
6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1,
9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1,
1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1,
4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1,
7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1,
6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1,
3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1,
0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1,
6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1,
1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1,
0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1,
11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1,
6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1,
5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1,
9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1,
1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1,
1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1,
10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1,
0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1,
5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1,
10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1,
11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1,
0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1,
9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1,
7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1,
2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1,
8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1,
9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1,
9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1,
1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1,
9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1,
9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1,
5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1,
0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1,
10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1,
2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1,
0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1,
0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1,
9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1,
5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1,
3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1,
5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1,
8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1,
0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1,
9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1,
0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1,
1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1,
3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1,
4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1,
9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1,
11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1,
11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1,
2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1,
9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1,
3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1,
1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1,
4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1,
4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1,
0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1,
3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1,
3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1,
0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1,
9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1,
1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
])
}
// Triangles are constructed between points on cube edges.
// allowedContours[edge1][edge1] indicates which lines from a given
// triangle should be shown in line mode.
// Values are bitmasks:
// In loop over cubes we keep another bitmask indicating whether our current
// cell is the first x-value (1),
// first y-value (2) or first z-value (4) of the current loop.
// We draw all lines on leading faces but only draw trailing face lines the first
// time through the loop
// A value of 8 below means the edge is always drawn (leading face)
// E.g. the first row, lines between edge0 and other edges in the bottom
// x-y plane are only drawn for the first value of z, edges in the
// x-z plane are only drawn for the first value of y. No other lines
// are drawn as they're redundant
// The line between edge 1 and 5 is always drawn as it's on the leading edge
function getAllowedContours () {
return [
[ 0, 4, 4, 4, 2, 0, 0, 0, 2, 2, 0, 0 ], // 1 2 3 4 8 9
[ 4, 0, 4, 4, 0, 8, 0, 0, 0, 8, 8, 0 ], // 0 2 3 5 9 10
[ 4, 4, 0, 4, 0, 0, 8, 0, 0, 0, 8, 8 ], // 0 1 3 6 10 11
[ 4, 4, 4, 0, 0, 0, 0, 1, 1, 0, 0, 1 ], // 0 1 2 7 8 11
[ 2, 0, 0, 0, 0, 8, 8, 8, 2, 2, 0, 0 ], // 0 5 6 7 8 9
[ 0, 8, 0, 0, 8, 0, 8, 8, 0, 8, 8, 0 ], // And rotate it
[ 0, 0, 8, 0, 8, 8, 0, 8, 0, 0, 8, 8 ],
[ 0, 0, 0, 1, 8, 8, 8, 0, 1, 0, 0, 1 ],
[ 2, 0, 0, 1, 2, 0, 0, 1, 0, 2, 0, 1 ], // 0 3 4 7 9 11
[ 2, 8, 0, 0, 2, 8, 0, 0, 2, 0, 8, 0 ], // And rotate some more
[ 0, 8, 8, 0, 0, 8, 8, 0, 0, 8, 0, 8 ],
[ 0, 0, 8, 1, 0, 0, 8, 1, 1, 0, 8, 0 ]
]
}
interface MarchingCubes {
new (field: number[], nx: number, ny: number, nz: number, atomindex: number[]): void
triangulate: (_isolevel: number, _noNormals: boolean, _box: number[][]|undefined, _contour: boolean, _wrap: boolean) => {
position: Float32Array
normal: undefined|Float32Array
index: Uint32Array|Uint16Array
atomindex: Int32Array|undefined
contour: boolean
}
}
function MarchingCubes (this: MarchingCubes, field: number[], nx: number, ny: number, nz: number, atomindex: number[]) {
// Based on alteredq / http://alteredqualia.com/
// port of greggman's ThreeD version of marching cubes to Three.js
// http://webglsamples.googlecode.com/hg/blob/blob.html
//
// Adapted for NGL by Alexander Rose
var isolevel = 0
var noNormals = false
var contour = false
var wrap = false
var isNegativeIso = false
var normalFactor = -1
var n = nx * ny * nz
// deltas
var yd = nx
var zd = nx * ny
var normalCache: Float32Array, vertexIndex: Int32Array
var count: number, icount: number
var ilist = new Int32Array(12)
var positionArray: number[] = []
var normalArray: number[] = []
var indexArray: number[] = []
var atomindexArray: number[] = []
var edgeTable = getEdgeTable()
var triTable = getTriTable()
var allowedContours = getAllowedContours()
var mx: number, my: number, mz: number
//
this.triangulate = function (_isolevel: number, _noNormals: boolean, _box: number[][]|undefined, _contour: boolean, _wrap: boolean) {
isolevel = _isolevel
isNegativeIso = isolevel < 0.0
contour = _contour
wrap = _wrap
// Normals currently disabled in contour mode for performance (unused)
noNormals = _noNormals || contour
if (!noNormals) {
normalFactor = isolevel > 0 ? -1.0 : 1.0
if (!normalCache) {
normalCache = new Float32Array(n * 3)
}
}
var vIndexLength = n * 3
if (!vertexIndex || vertexIndex.length !== vIndexLength) {
vertexIndex = new Int32Array(vIndexLength)
}
count = 0
icount = 0
if (_box !== undefined) {
var min = _box[ 0 ].map(Math.round)
var max = _box[ 1 ].map(Math.round)
mx = nx * Math.ceil(Math.abs(min[ 0 ]) / nx)
my = ny * Math.ceil(Math.abs(min[ 1 ]) / ny)
mz = nz * Math.ceil(Math.abs(min[ 2 ]) / nz)
triangulate(
min[ 0 ], min[ 1 ], min[ 2 ],
max[ 0 ], max[ 1 ], max[ 2 ]
)
} else {
mx = my = mz = 0
triangulate()
}
positionArray.length = count * 3
if (!noNormals) normalArray.length = count * 3
indexArray.length = icount
if (atomindex) atomindexArray.length = count
return {
position: new Float32Array(positionArray),
normal: noNormals ? undefined : new Float32Array(normalArray),
index: getUintArray(indexArray, positionArray.length / 3),
atomindex: atomindex ? new Int32Array(atomindexArray) : undefined,
contour: contour
}
}
// polygonization
function lerp (a: number, b: number, t: number) { return a + (b - a) * t }
function index (x: number, y: number, z: number) {
x = (x + mx) % nx
y = (y + my) % ny
z = (z + mz) % nz
return ((zd * z) + yd * y) + x
}
function VIntX (q: number, offset: number, x: number, y: number, z: number, valp1: number, valp2: number) {
var _q = 3 * q
if (vertexIndex[ _q ] < 0) {
var mu = (isolevel - valp1) / (valp2 - valp1)
var nc = normalCache
var c = count * 3
positionArray[ c + 0 ] = x + mu
positionArray[ c + 1 ] = y
positionArray[ c + 2 ] = z
if (!noNormals) {
var q3 = q * 3
normalArray[ c ] = normalFactor * lerp(nc[ q3 ], nc[ q3 + 3 ], mu)
normalArray[ c + 1 ] = normalFactor * lerp(nc[ q3 + 1 ], nc[ q3 + 4 ], mu)
normalArray[ c + 2 ] = normalFactor * lerp(nc[ q3 + 2 ], nc[ q3 + 5 ], mu)
}
if (atomindex) atomindexArray[ count ] = atomindex[ q + Math.round(mu) ]
vertexIndex[ _q ] = count
ilist[ offset ] = count
count += 1
} else {
ilist[ offset ] = vertexIndex[ _q ]
}
}
function VIntY (q: number, offset: number, x: number, y: number, z: number, valp1: number, valp2: number) {
var _q = 3 * q + 1
if (vertexIndex[ _q ] < 0) {
var mu = (isolevel - valp1) / (valp2 - valp1)
var nc = normalCache
var c = count * 3
positionArray[ c ] = x
positionArray[ c + 1 ] = y + mu
positionArray[ c + 2 ] = z
if (!noNormals) {
var q3 = q * 3
var q6 = q3 + yd * 3
normalArray[ c ] = normalFactor * lerp(nc[ q3 ], nc[ q6 ], mu)
normalArray[ c + 1 ] = normalFactor * lerp(nc[ q3 + 1 ], nc[ q6 + 1 ], mu)
normalArray[ c + 2 ] = normalFactor * lerp(nc[ q3 + 2 ], nc[ q6 + 2 ], mu)
}
if (atomindex) atomindexArray[ count ] = atomindex[ q + Math.round(mu) * yd ]
vertexIndex[ _q ] = count
ilist[ offset ] = count
count += 1
} else {
ilist[ offset ] = vertexIndex[ _q ]
}
}
function VIntZ (q: number, offset: number, x: number, y: number, z: number, valp1: number, valp2: number) {
var _q = 3 * q + 2
if (vertexIndex[ _q ] < 0) {
var mu = (isolevel - valp1) / (valp2 - valp1)
var nc = normalCache
var c = count * 3
positionArray[ c ] = x
positionArray[ c + 1 ] = y
positionArray[ c + 2 ] = z + mu
if (!noNormals) {
var q3 = q * 3
var q6 = q3 + zd * 3
normalArray[ c ] = normalFactor * lerp(nc[ q3 ], nc[ q6 ], mu)
normalArray[ c + 1 ] = normalFactor * lerp(nc[ q3 + 1 ], nc[ q6 + 1 ], mu)
normalArray[ c + 2 ] = normalFactor * lerp(nc[ q3 + 2 ], nc[ q6 + 2 ], mu)
}
if (atomindex) atomindexArray[ count ] = atomindex[ q + Math.round(mu) * zd ]
vertexIndex[ _q ] = count
ilist[ offset ] = count
count += 1
} else {
ilist[ offset ] = vertexIndex[ _q ]
}
}
function compNorm (q: number) {
var q3 = q * 3
if (normalCache[ q3 ] === 0.0) {
normalCache[ q3 ] = field[ (q - 1 + n) % n ] - field[ (q + 1) % n ]
normalCache[ q3 + 1 ] = field[ (q - yd + n) % n ] - field[ (q + yd) % n ]
normalCache[ q3 + 2 ] = field[ (q - zd + n) % n ] - field[ (q + zd) % n ]
}
}
function polygonize (fx: number, fy: number, fz: number, q: number, edgeFilter: number) {
// cache indices
var q1
var qy
var qz
var q1y
var q1z
var qyz
var q1yz
if (wrap) {
q = index(fx, fy, fz)
q1 = index(fx + 1, fy, fz)
qy = index(fx, fy + 1, fz)
qz = index(fx, fy, fz + 1)
q1y = index(fx + 1, fy + 1, fz)
q1z = index(fx + 1, fy, fz + 1)
qyz = index(fx, fy + 1, fz + 1)
q1yz = index(fx + 1, fy + 1, fz + 1)
} else {
q1 = q + 1
qy = q + yd
qz = q + zd
q1y = qy + 1
q1z = qz + 1
qyz = qy + zd
q1yz = qyz + 1
}
var cubeindex = 0
var field0 = field[ q ]
var field1 = field[ q1 ]
var field2 = field[ qy ]
var field3 = field[ q1y ]
var field4 = field[ qz ]
var field5 = field[ q1z ]
var field6 = field[ qyz ]
var field7 = field[ q1yz ]
if (field0 < isolevel) cubeindex |= 1
if (field1 < isolevel) cubeindex |= 2
if (field2 < isolevel) cubeindex |= 8
if (field3 < isolevel) cubeindex |= 4
if (field4 < isolevel) cubeindex |= 16
if (field5 < isolevel) cubeindex |= 32
if (field6 < isolevel) cubeindex |= 128
if (field7 < isolevel) cubeindex |= 64
// if cube is entirely in/out of the surface - bail, nothing to draw
var bits = edgeTable[ cubeindex ]
if (bits === 0) return 0
var fx2 = fx + 1
var fy2 = fy + 1
var fz2 = fz + 1
// top of the cube
if (bits & 1) {
if (!noNormals) {
compNorm(q)
compNorm(q1)
}
VIntX(q, 0, fx, fy, fz, field0, field1)
}
if (bits & 2) {
if (!noNormals) {
compNorm(q1)
compNorm(q1y)
}
VIntY(q1, 1, fx2, fy, fz, field1, field3)
}
if (bits & 4) {
if (!noNormals) {
compNorm(qy)
compNorm(q1y)
}
VIntX(qy, 2, fx, fy2, fz, field2, field3)
}
if (bits & 8) {
if (!noNormals) {
compNorm(q)
compNorm(qy)
}
VIntY(q, 3, fx, fy, fz, field0, field2)
}
// bottom of the cube
if (bits & 16) {
if (!noNormals) {
compNorm(qz)
compNorm(q1z)
}
VIntX(qz, 4, fx, fy, fz2, field4, field5)
}
if (bits & 32) {
if (!noNormals) {
compNorm(q1z)
compNorm(q1yz)
}
VIntY(q1z, 5, fx2, fy, fz2, field5, field7)
}
if (bits & 64) {
if (!noNormals) {
compNorm(qyz)
compNorm(q1yz)
}
VIntX(qyz, 6, fx, fy2, fz2, field6, field7)
}
if (bits & 128) {
if (!noNormals) {
compNorm(qz)
compNorm(qyz)
}
VIntY(qz, 7, fx, fy, fz2, field4, field6)
}
// vertical lines of the cube
if (bits & 256) {
if (!noNormals) {
compNorm(q)
compNorm(qz)
}
VIntZ(q, 8, fx, fy, fz, field0, field4)
}
if (bits & 512) {
if (!noNormals) {
compNorm(q1)
compNorm(q1z)
}
VIntZ(q1, 9, fx2, fy, fz, field1, field5)
}
if (bits & 1024) {
if (!noNormals) {
compNorm(q1y)
compNorm(q1yz)
}
VIntZ(q1y, 10, fx2, fy2, fz, field3, field7)
}
if (bits & 2048) {
if (!noNormals) {
compNorm(qy)
compNorm(qyz)
}
VIntZ(qy, 11, fx, fy2, fz, field2, field6)
}
var triIndex = cubeindex << 4 // re-purpose cubeindex into an offset into triTable
var e1
var e2
var e3
var i = 0
// here is where triangles are created
while (triTable[ triIndex + i ] !== -1) {
e1 = triTable[ triIndex + i ]
e2 = triTable[ triIndex + i + 1 ]
e3 = triTable[ triIndex + i + 2 ]
if (contour) {
if (allowedContours[ e1 ][ e2 ] & edgeFilter) {
indexArray[ icount++ ] = ilist[ e1 ]
indexArray[ icount++ ] = ilist[ e2 ]
}
if (allowedContours[ e2 ][ e3 ] & edgeFilter) {
indexArray[ icount++ ] = ilist[ e2 ]
indexArray[ icount++ ] = ilist[ e3 ]
}
if (allowedContours[ e1 ][ e3 ] & edgeFilter) {
indexArray[ icount++ ] = ilist[ e1 ]
indexArray[ icount++ ] = ilist[ e3 ]
}
} else {
indexArray[ icount++ ] = ilist[ isNegativeIso ? e1 : e2 ]
indexArray[ icount++ ] = ilist[ isNegativeIso ? e2 : e1 ]
indexArray[ icount++ ] = ilist[ e3 ]
}
i += 3
}
}
function triangulate (xBeg?: number, yBeg?: number, zBeg?: number, xEnd?: number, yEnd?: number, zEnd?: number) {
let q
let q3
let x
let y
let z
let yOffset
let zOffset
xBeg = xBeg !== undefined ? xBeg : 0
yBeg = yBeg !== undefined ? yBeg : 0
zBeg = zBeg !== undefined ? zBeg : 0
xEnd = xEnd !== undefined ? xEnd : nx - 1
yEnd = yEnd !== undefined ? yEnd : ny - 1
zEnd = zEnd !== undefined ? zEnd : nz - 1
if (!wrap) {
if (noNormals) {
xBeg = Math.max(0, xBeg)
yBeg = Math.max(0, yBeg)
zBeg = Math.max(0, zBeg)
xEnd = Math.min(nx - 1, xEnd)
yEnd = Math.min(ny - 1, yEnd)
zEnd = Math.min(nz - 1, zEnd)
} else {
xBeg = Math.max(1, xBeg)
yBeg = Math.max(1, yBeg)
zBeg = Math.max(1, zBeg)
xEnd = Math.min(nx - 2, xEnd)
yEnd = Math.min(ny - 2, yEnd)
zEnd = Math.min(nz - 2, zEnd)
}
}
let xBeg2, yBeg2, zBeg2, xEnd2, yEnd2, zEnd2
if (!wrap) {
// init part of the vertexIndex
// (takes a significant amount of time to do for all)
xBeg2 = Math.max(0, xBeg - 2)
yBeg2 = Math.max(0, yBeg - 2)
zBeg2 = Math.max(0, zBeg - 2)
xEnd2 = Math.min(nx, xEnd + 2)
yEnd2 = Math.min(ny, yEnd + 2)
zEnd2 = Math.min(nz, zEnd + 2)
for (z = zBeg2; z < zEnd2; ++z) {
zOffset = zd * z
for (y = yBeg2; y < yEnd2; ++y) {
yOffset = zOffset + yd * y
for (x = xBeg2; x < xEnd2; ++x) {
q = 3 * (yOffset + x)
vertexIndex[ q ] = -1
vertexIndex[ q + 1 ] = -1
vertexIndex[ q + 2 ] = -1
}
}
}
} else {
xBeg2 = xBeg - 2
yBeg2 = yBeg - 2
zBeg2 = zBeg - 2
xEnd2 = xEnd + 2
yEnd2 = yEnd + 2
zEnd2 = zEnd + 2
for (z = zBeg2; z < zEnd2; ++z) {
for (y = yBeg2; y < yEnd2; ++y) {
for (x = xBeg2; x < xEnd2; ++x) {
q3 = index(x, y, z) * 3
vertexIndex[ q3 ] = -1
vertexIndex[ q3 + 1 ] = -1
vertexIndex[ q3 + 2 ] = -1
}
}
}
}
if (!wrap) {
// clip space where the isovalue is too low
var __break
var __xBeg = xBeg; var __yBeg = yBeg; var __zBeg = zBeg
var __xEnd = xEnd; var __yEnd = yEnd; var __zEnd = zEnd
__break = false
for (z = zBeg; z < zEnd; ++z) {
for (y = yBeg; y < yEnd; ++y) {
for (x = xBeg; x < xEnd; ++x) {
q = ((nx * ny) * z) + (nx * y) + x
if (field[ q ] >= isolevel) {
__zBeg = z
__break = true
break
}
}
if (__break) break
}
if (__break) break
}
__break = false
for (y = yBeg; y < yEnd; ++y) {
for (z = __zBeg; z < zEnd; ++z) {
for (x = xBeg; x < xEnd; ++x) {
q = ((nx * ny) * z) + (nx * y) + x
if (field[ q ] >= isolevel) {
__yBeg = y
__break = true
break
}
}
if (__break) break
}
if (__break) break
}
__break = false
for (x = xBeg; x < xEnd; ++x) {
for (y = __yBeg; y < yEnd; ++y) {
for (z = __zBeg; z < zEnd; ++z) {
q = ((nx * ny) * z) + (nx * y) + x
if (field[ q ] >= isolevel) {
__xBeg = x
__break = true
break
}
}
if (__break) break
}
if (__break) break
}
__break = false
for (z = zEnd; z >= zBeg; --z) {
for (y = yEnd; y >= yBeg; --y) {
for (x = xEnd; x >= xBeg; --x) {
q = ((nx * ny) * z) + (nx * y) + x
if (field[ q ] >= isolevel) {
__zEnd = z
__break = true
break
}
}
if (__break) break
}
if (__break) break
}
__break = false
for (y = yEnd; y >= yBeg; --y) {
for (z = __zEnd; z >= zBeg; --z) {
for (x = xEnd; x >= xBeg; --x) {
q = ((nx * ny) * z) + (nx * y) + x
if (field[ q ] >= isolevel) {
__yEnd = y
__break = true
break
}
}
if (__break) break
}
if (__break) break
}
__break = false
for (x = xEnd; x >= xBeg; --x) {
for (y = __yEnd; y >= yBeg; --y) {
for (z = __zEnd; z >= zBeg; --z) {
q = ((nx * ny) * z) + (nx * y) + x
if (field[ q ] >= isolevel) {
__xEnd = x
__break = true
break
}
}
if (__break) break
}
if (__break) break
}
//
if (noNormals) {
xBeg = Math.max(0, __xBeg - 1)
yBeg = Math.max(0, __yBeg - 1)
zBeg = Math.max(0, __zBeg - 1)
xEnd = Math.min(nx - 1, __xEnd + 1)
yEnd = Math.min(ny - 1, __yEnd + 1)
zEnd = Math.min(nz - 1, __zEnd + 1)
} else {
xBeg = Math.max(1, __xBeg - 1)
yBeg = Math.max(1, __yBeg - 1)
zBeg = Math.max(1, __zBeg - 1)
xEnd = Math.min(nx - 2, __xEnd + 1)
yEnd = Math.min(ny - 2, __yEnd + 1)
zEnd = Math.min(nz - 2, __zEnd + 1)
}
}
// polygonize part of the grid
var edgeFilter = 15
for (z = zBeg; z < zEnd; ++z, edgeFilter &= ~4) {
zOffset = zd * z
edgeFilter |= 2
for (y = yBeg; y < yEnd; ++y, edgeFilter &= ~2) {
yOffset = zOffset + yd * y
edgeFilter |= 1
for (x = xBeg; x < xEnd; ++x, edgeFilter &= ~1) {
q = yOffset + x
polygonize(x, y, z, q, edgeFilter)
}
}
}
}
}
Object.assign(MarchingCubes, {__deps: [ getEdgeTable, getTriTable, getAllowedContours, getUintArray ]})
export default MarchingCubes | the_stack |
interface String {
match< RE extends RegExp >( regexp: RE ): ReturnType<
RE[ typeof Symbol.match ]
>
matchAll< RE extends RegExp >( regexp: RE ): ReturnType<
RE[ typeof Symbol.matchAll ]
>
}
namespace $ {
type Groups_to_params<T> = {
[P in keyof T]?: T[P] | boolean | undefined;
};
export type $mol_regexp_source =
| number
| string
| RegExp
| { [ key in string ] : $mol_regexp_source }
| readonly[ $mol_regexp_source , ... $mol_regexp_source[] ]
export type $mol_regexp_groups< Source extends $mol_regexp_source >
= Source extends number
? {}
: Source extends string
? {}
: Source extends $mol_regexp_source[]
? $mol_type_merge< $mol_type_intersect< {
[ key in Extract< keyof Source , number > ] : $mol_regexp_groups< Source[ key ] >
}[ Extract< keyof Source , number > ] > >
: Source extends RegExp
? Record< string, string > extends NonNullable< NonNullable< ReturnType< Source['exec'] > >[ 'groups' ] >
? {}
: NonNullable< NonNullable< ReturnType< Source['exec'] > >[ 'groups' ] >
: Source extends { readonly [ key in string ] : $mol_regexp_source }
? $mol_type_merge< $mol_type_intersect< {
[ key in keyof Source ] :
$mol_type_merge<
& $mol_type_override<
{
readonly [ k in Extract< keyof Source , string > ]: string
},
{
readonly [ k in key ]:
Source[ key ] extends string
? Source[ key ]
: string
}
>
& $mol_regexp_groups< Source[ key ] >
>
}[ keyof Source ] > >
: never
/** Type safe reguar expression builder */
export class $mol_regexp< Groups extends Record< string , string > > extends RegExp {
/** Prefer to use $mol_regexp.from */
constructor( source : string , flags : string = 'gsu' , readonly groups : ( Extract< keyof Groups , string > )[] = [] ) {
super( source , flags )
}
*[Symbol.matchAll] (str:string): IterableIterator< $mol_type_override< RegExpExecArray, { groups?: { [ key in keyof Groups ] : string } } > > {
const index = this.lastIndex
this.lastIndex = 0
try {
while ( this.lastIndex < str.length ) {
const found = this.exec(str)
if( !found ) break
yield found
}
} finally {
this.lastIndex = index
}
}
/** Parses input and returns found capture groups or null */
[ Symbol.match ]( str : string ): null | string[] {
const res = [ ... this[Symbol.matchAll]( str ) ].filter( r => r.groups ).map( r => r[0] )
if( !res.length ) return null
return res
}
/** Splits string by regexp edges */
[ Symbol.split ]( str : string ): string[] {
const res = [] as string[]
let token_last = null
for( let token of this[Symbol.matchAll]( str ) ) {
if( token.groups && ( token_last ? token_last.groups : true ) ) res.push( '' )
res.push( token[0] )
token_last = token
}
if( !res.length ) res.push( '' )
return res
}
test( str : string ): boolean {
return Boolean( str.match( this) )
}
exec( str : string ): $mol_type_override< RegExpExecArray , { groups?: { [ key in keyof Groups ] : string } } > | null {
const from = this.lastIndex
if( from >= str.length ) return null
const res = super.exec( str )
if( res === null ) {
this.lastIndex = str.length
if( !str ) return null
return Object.assign( [ str.slice( from ) ], {
index: from,
input: str,
} )
}
if( from === this.lastIndex ) {
$mol_fail( new Error( 'Captured empty substring' ) )
}
type Token = { [ key in keyof Groups ] : string } & { [ key : number ] : string }
const groups = {} as Token
const skipped = str.slice( from , this.lastIndex - res[0].length )
if( skipped ) {
this.lastIndex = this.lastIndex - res[0].length
return Object.assign( [ skipped ], {
index: from,
input: res.input,
} )
}
for( let i = 0 ; i < this.groups.length ; ++i ) {
const group = this.groups[ i ]
groups[ group ] = groups[ group ] || res[ i + 1 ] || '' as any
}
return Object.assign( res, { groups } )
}
generate(
params: Groups_to_params< Groups >
): string | null {
return null
}
/** Makes regexp that non-greedy repeats this pattern from min to max count */
static repeat<
Source extends $mol_regexp_source
>(
source : Source ,
min = 0 ,
max = Number.POSITIVE_INFINITY ,
) : $mol_regexp< $mol_regexp_groups< Source > > {
const regexp = $mol_regexp.from( source )
const upper = Number.isFinite( max ) ? max : ''
const str = `(?:${ regexp.source }){${ min },${ upper }}?`
const regexp2 = new $mol_regexp( str , regexp.flags , regexp.groups )
regexp2.generate = params => {
const res = regexp.generate( params )
if( res ) return res
if( min > 0 ) return res
return ''
}
return regexp2
}
/** Makes regexp that greedy repeats this pattern from min to max count */
static repeat_greedy<
Source extends $mol_regexp_source
>(
source : Source ,
min = 0 ,
max = Number.POSITIVE_INFINITY ,
) : $mol_regexp< $mol_regexp_groups< Source > > {
const regexp = $mol_regexp.from( source )
const upper = Number.isFinite( max ) ? max : ''
const str = `(?:${ regexp.source }){${ min },${ upper }}`
const regexp2 = new $mol_regexp( str , regexp.flags , regexp.groups )
regexp2.generate = params => {
const res = regexp.generate( params )
if( res ) return res
if( min > 0 ) return res
return ''
}
return regexp2
}
/** Makes regexp that allow absent of this pattern */
static optional<
Source extends $mol_regexp_source
>( source : Source ) {
return $mol_regexp.repeat_greedy( source , 0 , 1 )
}
/** Makes regexp that look ahead for pattern */
static force_after( source : $mol_regexp_source ) {
const regexp = $mol_regexp.from( source )
return new $mol_regexp(
`(?=${ regexp.source })` ,
regexp.flags ,
regexp.groups ,
)
}
/** Makes regexp that look ahead for pattern */
static forbid_after( source : $mol_regexp_source ) {
const regexp = $mol_regexp.from( source )
return new $mol_regexp(
`(?!${ regexp.source })` ,
regexp.flags ,
regexp.groups ,
)
}
/** Converts some js values to regexp */
static from<
Source extends $mol_regexp_source
>(
source : Source ,
{ ignoreCase , multiline } : Partial< Pick< RegExp , 'ignoreCase' | 'multiline' > > = {
ignoreCase : false ,
multiline : false ,
} ,
) : $mol_regexp< $mol_regexp_groups< Source > > {
let flags = 'gsu'
if( multiline ) flags += 'm'
if( ignoreCase ) flags += 'i'
if( typeof source === 'number' ) {
const src = `\\u{${ source.toString(16) }}`
const regexp = new $mol_regexp< $mol_regexp_groups< Source > >( src , flags )
regexp.generate = ()=> src
return regexp
} if( typeof source === 'string' ) {
const src = source.replace( /[.*+?^${}()|[\]\\]/g , '\\$&' )
const regexp = new $mol_regexp< $mol_regexp_groups< Source > >( src , flags )
regexp.generate = ()=> source
return regexp
} else if( source instanceof $mol_regexp ) {
const regexp = new $mol_regexp<any>( source.source, flags, source.groups )
regexp.generate = params => source.generate( params )
return regexp
} if( source instanceof RegExp ) {
const test = new RegExp( '|' + source.source )
const groups = Array.from(
{ length : test.exec('')!.length - 1 } ,
( _ , i )=> String( i + 1 ) ,
)
const regexp = new $mol_regexp< $mol_regexp_groups< Source > >(
source.source ,
source.flags ,
groups as any ,
)
regexp.generate = ()=> ''
return regexp
} if( Array.isArray( source ) ) {
const patterns = source.map( src => Array.isArray( src )
? $mol_regexp.optional( src as any )
: $mol_regexp.from( src )
)
const chunks = patterns.map( pattern => pattern.source )
const groups = [] as ( Extract< keyof $mol_regexp_groups< Source > , string > )[]
let index = 0
for( const pattern of patterns ) {
for( let group of pattern.groups ) {
if( Number( group ) >= 0 ) {
groups.push( String( index ++ ) as any )
} else {
groups.push( group )
}
}
}
const regexp = new $mol_regexp( chunks.join( '' ) , flags , groups )
regexp.generate = params => {
let res = ''
for( const pattern of patterns ) {
let sub = pattern.generate( params )
if( sub === null ) return ''
res += sub
}
return res
}
return regexp
} else {
const groups = [] as string[]
const chunks = Object.keys( source ).map( name => {
groups.push( name )
const regexp = $mol_regexp.from( source[ name ] )
groups.push( ... regexp.groups )
return `(${regexp.source})`
} ) as any as readonly[ $mol_regexp_source , ... $mol_regexp_source[] ]
const regexp = new $mol_regexp< $mol_regexp_groups< Source > >(
`(?:${ chunks.join('|') })` ,
flags ,
groups as any[] ,
)
const validator = new RegExp( '^' + regexp.source + '$', flags )
regexp.generate = params => {
for( let option in source ) {
if( option in params ) {
if( typeof params[ option as any ] === 'boolean' ) {
if( !params[ option as any ] ) continue
} else {
const str = String( params[ option as any ] )
if( str.match( validator ) ) return str
$mol_fail( new Error( `Wrong param: ${option}=${str}` ) )
}
} else {
if( typeof source[ option as any ] !== 'object' ) continue
}
const res = $mol_regexp.from( source[ option as any ] ).generate( params )
if( res ) return res
}
return null
}
return regexp
}
}
/** Makes regexp which includes only unicode category */
static unicode_only( ... category: $mol_unicode_category ) {
return new $mol_regexp(
`\\p{${ category.join( '=' ) }}`
)
}
/** Makes regexp which excludes unicode category */
static unicode_except( ... category: $mol_unicode_category ) {
return new $mol_regexp(
`\\P{${ category.join( '=' ) }}`
)
}
static char_range(
from: number,
to: number,
): $mol_regexp<{}> {
return new $mol_regexp(
`${ $mol_regexp.from( from ).source }-${ $mol_regexp.from( to ).source }`
)
}
static char_only(
... allowed: readonly [ $mol_regexp_source, ... $mol_regexp_source[] ]
): $mol_regexp<{}> {
const regexp = allowed.map( f => $mol_regexp.from( f ).source ).join('')
return new $mol_regexp( `[${ regexp }]` )
}
static char_except(
... forbidden: readonly [ $mol_regexp_source, ... $mol_regexp_source[] ]
): $mol_regexp<{}> {
const regexp = forbidden.map( f => $mol_regexp.from( f ).source ).join('')
return new $mol_regexp( `[^${ regexp }]` )
}
static decimal_only = $mol_regexp.from( /\d/gsu )
static decimal_except = $mol_regexp.from( /\D/gsu )
static latin_only = $mol_regexp.from( /\w/gsu )
static latin_except = $mol_regexp.from( /\W/gsu )
static space_only = $mol_regexp.from( /\s/gsu )
static space_except = $mol_regexp.from( /\S/gsu )
static word_break_only = $mol_regexp.from( /\b/gsu )
static word_break_except = $mol_regexp.from( /\B/gsu )
static tab = $mol_regexp.from( /\t/gsu )
static slash_back = $mol_regexp.from( /\\/gsu )
static nul = $mol_regexp.from( /\0/gsu )
static char_any = $mol_regexp.from( /./gsu )
static begin = $mol_regexp.from( /^/gsu )
static end = $mol_regexp.from( /$/gsu )
static or = $mol_regexp.from( /|/gsu )
static line_end = $mol_regexp.from({
win_end: [ [ '\r' ], '\n' ],
mac_end: '\r',
})
}
} | the_stack |
import { Logger } from "../log";
import {
Body,
C,
getBody,
IncomingRequestMessage,
IncomingResponseMessage,
isBody,
NameAddrHeader,
OutgoingAckRequest,
OutgoingByeRequest,
OutgoingInfoRequest,
OutgoingInviteRequest,
OutgoingInviteRequestDelegate,
OutgoingMessageRequest,
OutgoingNotifyRequest,
OutgoingPrackRequest,
OutgoingReferRequest,
OutgoingRequestDelegate,
OutgoingRequestMessage,
RequestOptions
} from "../messages";
import { Session, SessionDelegate, SessionState, SignalingState } from "../session";
import { Timers } from "../timers";
import { InviteClientTransaction, InviteServerTransaction, TransactionState } from "../transactions";
import { UserAgentCore } from "../user-agent-core";
import { ByeUserAgentClient } from "../user-agents/bye-user-agent-client";
import { ByeUserAgentServer } from "../user-agents/bye-user-agent-server";
import { InfoUserAgentClient } from "../user-agents/info-user-agent-client";
import { InfoUserAgentServer } from "../user-agents/info-user-agent-server";
import { MessageUserAgentClient } from "../user-agents/message-user-agent-client";
import { MessageUserAgentServer } from "../user-agents/message-user-agent-server";
import { NotifyUserAgentClient } from "../user-agents/notify-user-agent-client";
import { NotifyUserAgentServer } from "../user-agents/notify-user-agent-server";
import { PrackUserAgentClient } from "../user-agents/prack-user-agent-client";
import { PrackUserAgentServer } from "../user-agents/prack-user-agent-server";
import { ReInviteUserAgentClient } from "../user-agents/re-invite-user-agent-client";
import { ReInviteUserAgentServer } from "../user-agents/re-invite-user-agent-server";
import { ReferUserAgentClient } from "../user-agents/refer-user-agent-client";
import { ReferUserAgentServer } from "../user-agents/refer-user-agent-server";
import { Dialog } from "./dialog";
import { DialogState } from "./dialog-state";
/**
* Session Dialog.
* @public
*/
export class SessionDialog extends Dialog implements Session {
public delegate: SessionDelegate | undefined;
public reinviteUserAgentClient: ReInviteUserAgentClient | undefined;
public reinviteUserAgentServer: ReInviteUserAgentServer | undefined;
/** The state of the offer/answer exchange. */
private _signalingState: SignalingState = SignalingState.Initial;
/** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, or Stable. */
private _offer: Body | undefined;
/** The current answer. Undefined unless signaling state Stable. */
private _answer: Body | undefined;
/** The rollback offer. Undefined unless signaling state HaveLocalOffer or HaveRemoteOffer. */
private _rollbackOffer: Body | undefined;
/** The rollback answer. Undefined unless signaling state HaveLocalOffer or HaveRemoteOffer. */
private _rollbackAnswer: Body | undefined;
/** True if waiting for an ACK to the initial transaction 2xx (UAS only). */
private ackWait = false;
/** True if processing an ACK to the initial transaction 2xx (UAS only). */
private ackProcessing = false;
/** Retransmission timer for 2xx response which confirmed the dialog. */
private invite2xxTimer: number | undefined;
/** The rseq of the last reliable response. */
private rseq: number | undefined;
private logger: Logger;
constructor(
private initialTransaction: InviteClientTransaction | InviteServerTransaction,
core: UserAgentCore,
state: DialogState,
delegate?: SessionDelegate
) {
super(core, state);
this.delegate = delegate;
if (initialTransaction instanceof InviteServerTransaction) {
// If we're created by an invite server transaction, we're
// going to be waiting for an ACK if are to be confirmed.
this.ackWait = true;
}
// If we're confirmed upon creation start the retransmitting whatever
// the 2xx final response was that confirmed us into existence.
if (!this.early) {
this.start2xxRetransmissionTimer();
}
this.signalingStateTransition(initialTransaction.request);
this.logger = core.loggerFactory.getLogger("sip.invite-dialog");
this.logger.log(`INVITE dialog ${this.id} constructed`);
}
public dispose(): void {
super.dispose();
this._signalingState = SignalingState.Closed;
this._offer = undefined;
this._answer = undefined;
if (this.invite2xxTimer) {
clearTimeout(this.invite2xxTimer);
this.invite2xxTimer = undefined;
}
// The UAS MUST still respond to any pending requests received for that
// dialog. It is RECOMMENDED that a 487 (Request Terminated) response
// be generated to those pending requests.
// https://tools.ietf.org/html/rfc3261#section-15.1.2
// TODO:
// this.userAgentServers.forEach((uas) => uas.reply(487));
this.logger.log(`INVITE dialog ${this.id} destroyed`);
}
// FIXME: Need real state machine
get sessionState(): SessionState {
if (this.early) {
return SessionState.Early;
} else if (this.ackWait) {
return SessionState.AckWait;
} else if (this._signalingState === SignalingState.Closed) {
return SessionState.Terminated;
} else {
return SessionState.Confirmed;
}
}
/** The state of the offer/answer exchange. */
get signalingState(): SignalingState {
return this._signalingState;
}
/** The current offer. Undefined unless signaling state HaveLocalOffer, HaveRemoteOffer, of Stable. */
get offer(): Body | undefined {
return this._offer;
}
/** The current answer. Undefined unless signaling state Stable. */
get answer(): Body | undefined {
return this._answer;
}
/** Confirm the dialog. Only matters if dialog is currently early. */
public confirm(): void {
// When we're confirmed start the retransmitting whatever
// the 2xx final response that may have confirmed us.
if (this.early) {
this.start2xxRetransmissionTimer();
}
super.confirm();
}
/** Re-confirm the dialog. Only matters if handling re-INVITE request. */
public reConfirm(): void {
// When we're confirmed start the retransmitting whatever
// the 2xx final response that may have confirmed us.
if (this.reinviteUserAgentServer) {
this.startReInvite2xxRetransmissionTimer();
}
}
/**
* The UAC core MUST generate an ACK request for each 2xx received from
* the transaction layer. The header fields of the ACK are constructed
* in the same way as for any request sent within a dialog (see Section
* 12) with the exception of the CSeq and the header fields related to
* authentication. The sequence number of the CSeq header field MUST be
* the same as the INVITE being acknowledged, but the CSeq method MUST
* be ACK. The ACK MUST contain the same credentials as the INVITE. If
* the 2xx contains an offer (based on the rules above), the ACK MUST
* carry an answer in its body. If the offer in the 2xx response is not
* acceptable, the UAC core MUST generate a valid answer in the ACK and
* then send a BYE immediately.
* https://tools.ietf.org/html/rfc3261#section-13.2.2.4
* @param options - ACK options bucket.
*/
public ack(options: RequestOptions = {}): OutgoingAckRequest {
this.logger.log(`INVITE dialog ${this.id} sending ACK request`);
let transaction: InviteClientTransaction;
if (this.reinviteUserAgentClient) {
// We're sending ACK for a re-INVITE
if (!(this.reinviteUserAgentClient.transaction instanceof InviteClientTransaction)) {
throw new Error("Transaction not instance of InviteClientTransaction.");
}
transaction = this.reinviteUserAgentClient.transaction;
this.reinviteUserAgentClient = undefined;
} else {
// We're sending ACK for the initial INVITE
if (!(this.initialTransaction instanceof InviteClientTransaction)) {
throw new Error("Initial transaction not instance of InviteClientTransaction.");
}
transaction = this.initialTransaction;
}
const message = this.createOutgoingRequestMessage(C.ACK, {
cseq: transaction.request.cseq, // ACK cseq is INVITE cseq
extraHeaders: options.extraHeaders,
body: options.body
});
transaction.ackResponse(message); // See InviteClientTransaction for details.
this.signalingStateTransition(message);
return { message };
}
/**
* Terminating a Session
*
* This section describes the procedures for terminating a session
* established by SIP. The state of the session and the state of the
* dialog are very closely related. When a session is initiated with an
* INVITE, each 1xx or 2xx response from a distinct UAS creates a
* dialog, and if that response completes the offer/answer exchange, it
* also creates a session. As a result, each session is "associated"
* with a single dialog - the one which resulted in its creation. If an
* initial INVITE generates a non-2xx final response, that terminates
* all sessions (if any) and all dialogs (if any) that were created
* through responses to the request. By virtue of completing the
* transaction, a non-2xx final response also prevents further sessions
* from being created as a result of the INVITE. The BYE request is
* used to terminate a specific session or attempted session. In this
* case, the specific session is the one with the peer UA on the other
* side of the dialog. When a BYE is received on a dialog, any session
* associated with that dialog SHOULD terminate. A UA MUST NOT send a
* BYE outside of a dialog. The caller's UA MAY send a BYE for either
* confirmed or early dialogs, and the callee's UA MAY send a BYE on
* confirmed dialogs, but MUST NOT send a BYE on early dialogs.
*
* However, the callee's UA MUST NOT send a BYE on a confirmed dialog
* until it has received an ACK for its 2xx response or until the server
* transaction times out. If no SIP extensions have defined other
* application layer states associated with the dialog, the BYE also
* terminates the dialog.
*
* https://tools.ietf.org/html/rfc3261#section-15
* FIXME: Make these proper Exceptions...
* @param options - BYE options bucket.
* @returns
* Throws `Error` if callee's UA attempts a BYE on an early dialog.
* Throws `Error` if callee's UA attempts a BYE on a confirmed dialog
* while it's waiting on the ACK for its 2xx response.
*/
public bye(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingByeRequest {
this.logger.log(`INVITE dialog ${this.id} sending BYE request`);
// The caller's UA MAY send a BYE for either
// confirmed or early dialogs, and the callee's UA MAY send a BYE on
// confirmed dialogs, but MUST NOT send a BYE on early dialogs.
//
// However, the callee's UA MUST NOT send a BYE on a confirmed dialog
// until it has received an ACK for its 2xx response or until the server
// transaction times out.
// https://tools.ietf.org/html/rfc3261#section-15
if (this.initialTransaction instanceof InviteServerTransaction) {
if (this.early) {
// FIXME: TODO: This should throw a proper exception.
throw new Error("UAS MUST NOT send a BYE on early dialogs.");
}
if (this.ackWait && this.initialTransaction.state !== TransactionState.Terminated) {
// FIXME: TODO: This should throw a proper exception.
throw new Error(
"UAS MUST NOT send a BYE on a confirmed dialog " +
"until it has received an ACK for its 2xx response " +
"or until the server transaction times out."
);
}
}
// A BYE request is constructed as would any other request within a
// dialog, as described in Section 12.
//
// Once the BYE is constructed, the UAC core creates a new non-INVITE
// client transaction, and passes it the BYE request. The UAC MUST
// consider the session terminated (and therefore stop sending or
// listening for media) as soon as the BYE request is passed to the
// client transaction. If the response for the BYE is a 481
// (Call/Transaction Does Not Exist) or a 408 (Request Timeout) or no
// response at all is received for the BYE (that is, a timeout is
// returned by the client transaction), the UAC MUST consider the
// session and the dialog terminated.
// https://tools.ietf.org/html/rfc3261#section-15.1.1
return new ByeUserAgentClient(this, delegate, options);
}
/**
* An INFO request can be associated with an Info Package (see
* Section 5), or associated with a legacy INFO usage (see Section 2).
*
* The construction of the INFO request is the same as any other
* non-target refresh request within an existing invite dialog usage as
* described in Section 12.2 of RFC 3261.
* https://tools.ietf.org/html/rfc6086#section-4.2.1
* @param options - Options bucket.
*/
public info(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingInfoRequest {
this.logger.log(`INVITE dialog ${this.id} sending INFO request`);
if (this.early) {
// FIXME: TODO: This should throw a proper exception.
throw new Error("Dialog not confirmed.");
}
return new InfoUserAgentClient(this, delegate, options);
}
/**
* Modifying an Existing Session
*
* A successful INVITE request (see Section 13) establishes both a
* dialog between two user agents and a session using the offer-answer
* model. Section 12 explains how to modify an existing dialog using a
* target refresh request (for example, changing the remote target URI
* of the dialog). This section describes how to modify the actual
* session. This modification can involve changing addresses or ports,
* adding a media stream, deleting a media stream, and so on. This is
* accomplished by sending a new INVITE request within the same dialog
* that established the session. An INVITE request sent within an
* existing dialog is known as a re-INVITE.
*
* Note that a single re-INVITE can modify the dialog and the
* parameters of the session at the same time.
*
* Either the caller or callee can modify an existing session.
* https://tools.ietf.org/html/rfc3261#section-14
* @param options - Options bucket
*/
public invite(delegate?: OutgoingInviteRequestDelegate, options?: RequestOptions): OutgoingInviteRequest {
this.logger.log(`INVITE dialog ${this.id} sending INVITE request`);
if (this.early) {
// FIXME: TODO: This should throw a proper exception.
throw new Error("Dialog not confirmed.");
}
// Note that a UAC MUST NOT initiate a new INVITE transaction within a
// dialog while another INVITE transaction is in progress in either
// direction.
//
// 1. If there is an ongoing INVITE client transaction, the TU MUST
// wait until the transaction reaches the completed or terminated
// state before initiating the new INVITE.
//
// 2. If there is an ongoing INVITE server transaction, the TU MUST
// wait until the transaction reaches the confirmed or terminated
// state before initiating the new INVITE.
//
// However, a UA MAY initiate a regular transaction while an INVITE
// transaction is in progress. A UA MAY also initiate an INVITE
// transaction while a regular transaction is in progress.
// https://tools.ietf.org/html/rfc3261#section-14.1
if (this.reinviteUserAgentClient) {
// FIXME: TODO: This should throw a proper exception.
throw new Error("There is an ongoing re-INVITE client transaction.");
}
if (this.reinviteUserAgentServer) {
// FIXME: TODO: This should throw a proper exception.
throw new Error("There is an ongoing re-INVITE server transaction.");
}
return new ReInviteUserAgentClient(this, delegate, options);
}
/**
* A UAC MAY associate a MESSAGE request with an existing dialog. If a
* MESSAGE request is sent within a dialog, it is "associated" with any
* media session or sessions associated with that dialog.
* https://tools.ietf.org/html/rfc3428#section-4
* @param options - Options bucket.
*/
public message(delegate: OutgoingRequestDelegate, options?: RequestOptions): OutgoingMessageRequest {
this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`);
if (this.early) {
// FIXME: TODO: This should throw a proper exception.
throw new Error("Dialog not confirmed.");
}
const message = this.createOutgoingRequestMessage(C.MESSAGE, options);
return new MessageUserAgentClient(this.core, message, delegate);
}
/**
* The NOTIFY mechanism defined in [2] MUST be used to inform the agent
* sending the REFER of the status of the reference.
* https://tools.ietf.org/html/rfc3515#section-2.4.4
* @param options - Options bucket.
*/
public notify(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingNotifyRequest {
this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`);
if (this.early) {
// FIXME: TODO: This should throw a proper exception.
throw new Error("Dialog not confirmed.");
}
return new NotifyUserAgentClient(this, delegate, options);
}
/**
* Assuming the response is to be transmitted reliably, the UAC MUST
* create a new request with method PRACK. This request is sent within
* the dialog associated with the provisional response (indeed, the
* provisional response may have created the dialog). PRACK requests
* MAY contain bodies, which are interpreted according to their type and
* disposition.
* https://tools.ietf.org/html/rfc3262#section-4
* @param options - Options bucket.
*/
public prack(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingPrackRequest {
this.logger.log(`INVITE dialog ${this.id} sending PRACK request`);
return new PrackUserAgentClient(this, delegate, options);
}
/**
* REFER is a SIP request and is constructed as defined in [1]. A REFER
* request MUST contain exactly one Refer-To header field value.
* https://tools.ietf.org/html/rfc3515#section-2.4.1
* @param options - Options bucket.
*/
public refer(delegate?: OutgoingRequestDelegate, options?: RequestOptions): OutgoingReferRequest {
this.logger.log(`INVITE dialog ${this.id} sending REFER request`);
if (this.early) {
// FIXME: TODO: This should throw a proper exception.
throw new Error("Dialog not confirmed.");
}
// FIXME: TODO: Validate Refer-To header field value.
return new ReferUserAgentClient(this, delegate, options);
}
/**
* Requests sent within a dialog, as any other requests, are atomic. If
* a particular request is accepted by the UAS, all the state changes
* associated with it are performed. If the request is rejected, none
* of the state changes are performed.
* https://tools.ietf.org/html/rfc3261#section-12.2.2
* @param message - Incoming request message within this dialog.
*/
public receiveRequest(message: IncomingRequestMessage): void {
this.logger.log(`INVITE dialog ${this.id} received ${message.method} request`);
// Response retransmissions cease when an ACK request for the
// response is received. This is independent of whatever transport
// protocols are used to send the response.
// https://tools.ietf.org/html/rfc6026#section-8.1
if (message.method === C.ACK) {
// If ackWait is true, then this is the ACK to the initial INVITE,
// otherwise this is an ACK to an in dialog INVITE. In either case,
// guard to make sure the sequence number of the ACK matches the INVITE.
if (this.ackWait) {
if (this.initialTransaction instanceof InviteClientTransaction) {
this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`);
return;
}
if (this.initialTransaction.request.cseq !== message.cseq) {
this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`);
return;
}
// Update before the delegate has a chance to handle the
// message as delegate may callback into this dialog.
this.ackWait = false;
} else {
if (!this.reinviteUserAgentServer) {
this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`);
return;
}
if (this.reinviteUserAgentServer.transaction.request.cseq !== message.cseq) {
this.logger.warn(`INVITE dialog ${this.id} received unexpected ${message.method} request, dropping.`);
return;
}
this.reinviteUserAgentServer = undefined;
}
this.signalingStateTransition(message);
if (this.delegate && this.delegate.onAck) {
const promiseOrVoid = this.delegate.onAck({ message });
if (promiseOrVoid instanceof Promise) {
this.ackProcessing = true; // make sure this is always reset to false
promiseOrVoid.then(() => (this.ackProcessing = false)).catch(() => (this.ackProcessing = false));
}
}
return;
}
// Request within a dialog out of sequence guard.
// https://tools.ietf.org/html/rfc3261#section-12.2.2
if (!this.sequenceGuard(message)) {
this.logger.log(`INVITE dialog ${this.id} rejected out of order ${message.method} request.`);
return;
}
// Request within a dialog common processing.
// https://tools.ietf.org/html/rfc3261#section-12.2.2
super.receiveRequest(message);
// Handle various INVITE related cross-over, glare and race conditions
if (message.method === C.INVITE) {
// Hopefully this message is helpful...
const warning = (): void => {
const reason = this.ackWait ? "waiting for initial ACK" : "processing initial ACK";
this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${reason}`);
let msg = "RFC 5407 suggests the following to avoid this race condition... ";
msg += " Note: Implementation issues are outside the scope of this document,";
msg += " but the following tip is provided for avoiding race conditions of";
msg += " this type. The caller can delay sending re-INVITE F6 for some period";
msg += " of time (2 seconds, perhaps), after which the caller can reasonably";
msg += " assume that its ACK has been received. Implementors can decouple the";
msg += " actions of the user (e.g., pressing the hold button) from the actions";
msg += " of the protocol (the sending of re-INVITE F6), so that the UA can";
msg += " behave like this. In this case, it is the implementor's choice as to";
msg += " how long to wait. In most cases, such an implementation may be";
msg += " useful to prevent the type of race condition shown in this section.";
msg += " This document expresses no preference about whether or not they";
msg += " should wait for an ACK to be delivered. After considering the impact";
msg += " on user experience, implementors should decide whether or not to wait";
msg += " for a while, because the user experience depends on the";
msg += " implementation and has no direct bearing on protocol behavior.";
this.logger.warn(msg);
return; // drop re-INVITE request message
};
// A UAS that receives a second INVITE before it sends the final
// response to a first INVITE with a lower CSeq sequence number on the
// same dialog MUST return a 500 (Server Internal Error) response to the
// second INVITE and MUST include a Retry-After header field with a
// randomly chosen value of between 0 and 10 seconds.
// https://tools.ietf.org/html/rfc3261#section-14.2
const retryAfter = Math.floor(Math.random() * 10) + 1;
const extraHeaders = [`Retry-After: ${retryAfter}`];
// There may be ONLY ONE offer/answer negotiation in progress for a
// single dialog at any point in time. Section 4 explains how to ensure
// this.
// https://tools.ietf.org/html/rfc6337#section-2.2
if (this.ackProcessing) {
// UAS-IsI: While an INVITE server transaction is incomplete or ACK
// transaction associated with an offer/answer is incomplete,
// a UA must reject another INVITE request with a 500
// response.
// https://tools.ietf.org/html/rfc6337#section-4.3
this.core.replyStateless(message, { statusCode: 500, extraHeaders });
warning();
return;
}
// 3.1.4. Callee Receives re-INVITE (Established State) While in the
// Moratorium State (Case 1)
// https://tools.ietf.org/html/rfc5407#section-3.1.4
// 3.1.5. Callee Receives re-INVITE (Established State) While in the
// Moratorium State (Case 2)
// https://tools.ietf.org/html/rfc5407#section-3.1.5
if (this.ackWait && this.signalingState !== SignalingState.Stable) {
// This scenario is basically the same as that of Section 3.1.4, but
// differs in sending an offer in the 200 and an answer in the ACK. In
// contrast to the previous case, the offer in the 200 (F3) and the
// offer in the re-INVITE (F6) collide with each other.
//
// Bob sends a 491 to the re-INVITE (F6) since he is not able to
// properly handle a new request until he receives an answer. (Note:
// 500 with a Retry-After header may be returned if the 491 response is
// understood to indicate request collision. However, 491 is
// recommended here because 500 applies to so many cases that it is
// difficult to determine what the real problem was.)
// https://tools.ietf.org/html/rfc5407#section-3.1.5
// UAS-IsI: While an INVITE server transaction is incomplete or ACK
// transaction associated with an offer/answer is incomplete,
// a UA must reject another INVITE request with a 500
// response.
// https://tools.ietf.org/html/rfc6337#section-4.3
this.core.replyStateless(message, { statusCode: 500, extraHeaders });
warning();
return;
}
// A UAS that receives a second INVITE before it sends the final
// response to a first INVITE with a lower CSeq sequence number on the
// same dialog MUST return a 500 (Server Internal Error) response to the
// second INVITE and MUST include a Retry-After header field with a
// randomly chosen value of between 0 and 10 seconds.
// https://tools.ietf.org/html/rfc3261#section-14.2
if (this.reinviteUserAgentServer) {
this.core.replyStateless(message, { statusCode: 500, extraHeaders });
return;
}
// A UAS that receives an INVITE on a dialog while an INVITE it had sent
// on that dialog is in progress MUST return a 491 (Request Pending)
// response to the received INVITE.
// https://tools.ietf.org/html/rfc3261#section-14.2
if (this.reinviteUserAgentClient) {
this.core.replyStateless(message, { statusCode: 491 });
return;
}
}
// Requests within a dialog MAY contain Record-Route and Contact header
// fields. However, these requests do not cause the dialog's route set
// to be modified, although they may modify the remote target URI.
// Specifically, requests that are not target refresh requests do not
// modify the dialog's remote target URI, and requests that are target
// refresh requests do. For dialogs that have been established with an
// INVITE, the only target refresh request defined is re-INVITE (see
// Section 14). Other extensions may define different target refresh
// requests for dialogs established in other ways.
//
// Note that an ACK is NOT a target refresh request.
//
// Target refresh requests only update the dialog's remote target URI,
// and not the route set formed from the Record-Route. Updating the
// latter would introduce severe backwards compatibility problems with
// RFC 2543-compliant systems.
// https://tools.ietf.org/html/rfc3261#section-15
if (message.method === C.INVITE) {
// FIXME: parser needs to be typed...
const contact = message.parseHeader("contact");
if (!contact) {
// TODO: Review to make sure this will never happen
throw new Error("Contact undefined.");
}
if (!(contact instanceof NameAddrHeader)) {
throw new Error("Contact not instance of NameAddrHeader.");
}
this.dialogState.remoteTarget = contact.uri;
}
// Switch on method and then delegate.
switch (message.method) {
case C.BYE:
// A UAS core receiving a BYE request for an existing dialog MUST follow
// the procedures of Section 12.2.2 to process the request. Once done,
// the UAS SHOULD terminate the session (and therefore stop sending and
// listening for media). The only case where it can elect not to are
// multicast sessions, where participation is possible even if the other
// participant in the dialog has terminated its involvement in the
// session. Whether or not it ends its participation on the session,
// the UAS core MUST generate a 2xx response to the BYE, and MUST pass
// that to the server transaction for transmission.
//
// The UAS MUST still respond to any pending requests received for that
// dialog. It is RECOMMENDED that a 487 (Request Terminated) response
// be generated to those pending requests.
// https://tools.ietf.org/html/rfc3261#section-15.1.2
{
const uas = new ByeUserAgentServer(this, message);
this.delegate && this.delegate.onBye ? this.delegate.onBye(uas) : uas.accept();
this.dispose();
}
break;
case C.INFO:
// If a UA receives an INFO request associated with an Info Package that
// the UA has not indicated willingness to receive, the UA MUST send a
// 469 (Bad Info Package) response (see Section 11.6), which contains a
// Recv-Info header field with Info Packages for which the UA is willing
// to receive INFO requests.
{
const uas = new InfoUserAgentServer(this, message);
this.delegate && this.delegate.onInfo
? this.delegate.onInfo(uas)
: uas.reject({
statusCode: 469,
extraHeaders: ["Recv-Info:"]
});
}
break;
case C.INVITE:
// If the new session description is not acceptable, the UAS can reject
// it by returning a 488 (Not Acceptable Here) response for the re-
// INVITE. This response SHOULD include a Warning header field.
// https://tools.ietf.org/html/rfc3261#section-14.2
{
const uas = new ReInviteUserAgentServer(this, message);
this.signalingStateTransition(message);
this.delegate && this.delegate.onInvite ? this.delegate.onInvite(uas) : uas.reject({ statusCode: 488 }); // TODO: Warning header field.
}
break;
case C.MESSAGE:
{
const uas = new MessageUserAgentServer(this.core, message);
this.delegate && this.delegate.onMessage ? this.delegate.onMessage(uas) : uas.accept();
}
break;
case C.NOTIFY:
// https://tools.ietf.org/html/rfc3515#section-2.4.4
{
const uas = new NotifyUserAgentServer(this, message);
this.delegate && this.delegate.onNotify ? this.delegate.onNotify(uas) : uas.accept();
}
break;
case C.PRACK:
// https://tools.ietf.org/html/rfc3262#section-4
{
const uas = new PrackUserAgentServer(this, message);
this.delegate && this.delegate.onPrack ? this.delegate.onPrack(uas) : uas.accept();
}
break;
case C.REFER:
// https://tools.ietf.org/html/rfc3515#section-2.4.2
{
const uas = new ReferUserAgentServer(this, message);
this.delegate && this.delegate.onRefer ? this.delegate.onRefer(uas) : uas.reject();
}
break;
default:
{
this.logger.log(`INVITE dialog ${this.id} received unimplemented ${message.method} request`);
this.core.replyStateless(message, { statusCode: 501 });
}
break;
}
}
/**
* Guard against out of order reliable provisional responses and retransmissions.
* Returns false if the response should be discarded, otherwise true.
* @param message - Incoming response message within this dialog.
*/
public reliableSequenceGuard(message: IncomingResponseMessage): boolean {
const statusCode = message.statusCode;
if (!statusCode) {
throw new Error("Status code undefined");
}
if (statusCode > 100 && statusCode < 200) {
// If a provisional response is received for an initial request, and
// that response contains a Require header field containing the option
// tag 100rel, the response is to be sent reliably. If the response is
// a 100 (Trying) (as opposed to 101 to 199), this option tag MUST be
// ignored, and the procedures below MUST NOT be used.
// https://tools.ietf.org/html/rfc3262#section-4
const requireHeader = message.getHeader("require");
const rseqHeader = message.getHeader("rseq");
const rseq = requireHeader && requireHeader.includes("100rel") && rseqHeader ? Number(rseqHeader) : undefined;
if (rseq) {
// Handling of subsequent reliable provisional responses for the same
// initial request follows the same rules as above, with the following
// difference: reliable provisional responses are guaranteed to be in
// order. As a result, if the UAC receives another reliable provisional
// response to the same request, and its RSeq value is not one higher
// than the value of the sequence number, that response MUST NOT be
// acknowledged with a PRACK, and MUST NOT be processed further by the
// UAC. An implementation MAY discard the response, or MAY cache the
// response in the hopes of receiving the missing responses.
// https://tools.ietf.org/html/rfc3262#section-4
if (this.rseq && this.rseq + 1 !== rseq) {
return false;
}
// Once a reliable provisional response is received, retransmissions of
// that response MUST be discarded. A response is a retransmission when
// its dialog ID, CSeq, and RSeq match the original response. The UAC
// MUST maintain a sequence number that indicates the most recently
// received in-order reliable provisional response for the initial
// request. This sequence number MUST be maintained until a final
// response is received for the initial request. Its value MUST be
// initialized to the RSeq header field in the first reliable
// provisional response received for the initial request.
// https://tools.ietf.org/html/rfc3262#section-4
this.rseq = this.rseq ? this.rseq + 1 : rseq;
}
}
return true;
}
/**
* If not in a stable signaling state, rollback to prior stable signaling state.
*/
public signalingStateRollback(): void {
if (
this._signalingState === SignalingState.HaveLocalOffer ||
this.signalingState === SignalingState.HaveRemoteOffer
) {
if (this._rollbackOffer && this._rollbackAnswer) {
this._signalingState = SignalingState.Stable;
this._offer = this._rollbackOffer;
this._answer = this._rollbackAnswer;
}
}
}
/**
* Update the signaling state of the dialog.
* @param message - The message to base the update off of.
*/
public signalingStateTransition(
message: IncomingRequestMessage | IncomingResponseMessage | OutgoingRequestMessage | Body
): void {
const body = getBody(message);
// No body, no session. No, woman, no cry.
if (!body || body.contentDisposition !== "session") {
return;
}
// We've got an existing offer and answer which we may wish to rollback to
if (this._signalingState === SignalingState.Stable) {
this._rollbackOffer = this._offer;
this._rollbackAnswer = this._answer;
}
// We're in UAS role, receiving incoming request with session description
if (message instanceof IncomingRequestMessage) {
switch (this._signalingState) {
case SignalingState.Initial:
case SignalingState.Stable:
this._signalingState = SignalingState.HaveRemoteOffer;
this._offer = body;
this._answer = undefined;
break;
case SignalingState.HaveLocalOffer:
this._signalingState = SignalingState.Stable;
this._answer = body;
break;
case SignalingState.HaveRemoteOffer:
// You cannot make a new offer while one is in progress.
// https://tools.ietf.org/html/rfc3261#section-13.2.1
// FIXME: What to do here?
break;
case SignalingState.Closed:
break;
default:
throw new Error("Unexpected signaling state.");
}
}
// We're in UAC role, receiving incoming response with session description
if (message instanceof IncomingResponseMessage) {
switch (this._signalingState) {
case SignalingState.Initial:
case SignalingState.Stable:
this._signalingState = SignalingState.HaveRemoteOffer;
this._offer = body;
this._answer = undefined;
break;
case SignalingState.HaveLocalOffer:
this._signalingState = SignalingState.Stable;
this._answer = body;
break;
case SignalingState.HaveRemoteOffer:
// You cannot make a new offer while one is in progress.
// https://tools.ietf.org/html/rfc3261#section-13.2.1
// FIXME: What to do here?
break;
case SignalingState.Closed:
break;
default:
throw new Error("Unexpected signaling state.");
}
}
// We're in UAC role, sending outgoing request with session description
if (message instanceof OutgoingRequestMessage) {
switch (this._signalingState) {
case SignalingState.Initial:
case SignalingState.Stable:
this._signalingState = SignalingState.HaveLocalOffer;
this._offer = body;
this._answer = undefined;
break;
case SignalingState.HaveLocalOffer:
// You cannot make a new offer while one is in progress.
// https://tools.ietf.org/html/rfc3261#section-13.2.1
// FIXME: What to do here?
break;
case SignalingState.HaveRemoteOffer:
this._signalingState = SignalingState.Stable;
this._answer = body;
break;
case SignalingState.Closed:
break;
default:
throw new Error("Unexpected signaling state.");
}
}
// We're in UAS role, sending outgoing response with session description
if (isBody(message)) {
switch (this._signalingState) {
case SignalingState.Initial:
case SignalingState.Stable:
this._signalingState = SignalingState.HaveLocalOffer;
this._offer = body;
this._answer = undefined;
break;
case SignalingState.HaveLocalOffer:
// You cannot make a new offer while one is in progress.
// https://tools.ietf.org/html/rfc3261#section-13.2.1
// FIXME: What to do here?
break;
case SignalingState.HaveRemoteOffer:
this._signalingState = SignalingState.Stable;
this._answer = body;
break;
case SignalingState.Closed:
break;
default:
throw new Error("Unexpected signaling state.");
}
}
}
private start2xxRetransmissionTimer(): void {
if (this.initialTransaction instanceof InviteServerTransaction) {
const transaction = this.initialTransaction;
// Once the response has been constructed, it is passed to the INVITE
// server transaction. In order to ensure reliable end-to-end
// transport of the response, it is necessary to periodically pass
// the response directly to the transport until the ACK arrives. The
// 2xx response is passed to the transport with an interval that
// starts at T1 seconds and doubles for each retransmission until it
// reaches T2 seconds (T1 and T2 are defined in Section 17).
// Response retransmissions cease when an ACK request for the
// response is received. This is independent of whatever transport
// protocols are used to send the response.
// https://tools.ietf.org/html/rfc6026#section-8.1
let timeout = Timers.T1;
const retransmission = (): void => {
if (!this.ackWait) {
this.invite2xxTimer = undefined;
return;
}
this.logger.log("No ACK for 2xx response received, attempting retransmission");
transaction.retransmitAcceptedResponse();
timeout = Math.min(timeout * 2, Timers.T2);
this.invite2xxTimer = setTimeout(retransmission, timeout);
};
this.invite2xxTimer = setTimeout(retransmission, timeout);
// If the server retransmits the 2xx response for 64*T1 seconds without
// receiving an ACK, the dialog is confirmed, but the session SHOULD be
// terminated. This is accomplished with a BYE, as described in Section 15.
// https://tools.ietf.org/html/rfc3261#section-13.3.1.4
const stateChanged = (): void => {
if (transaction.state === TransactionState.Terminated) {
transaction.removeStateChangeListener(stateChanged);
if (this.invite2xxTimer) {
clearTimeout(this.invite2xxTimer);
this.invite2xxTimer = undefined;
}
if (this.ackWait) {
if (this.delegate && this.delegate.onAckTimeout) {
this.delegate.onAckTimeout();
} else {
this.bye();
}
}
}
};
transaction.addStateChangeListener(stateChanged);
}
}
// FIXME: Refactor
private startReInvite2xxRetransmissionTimer(): void {
if (this.reinviteUserAgentServer && this.reinviteUserAgentServer.transaction instanceof InviteServerTransaction) {
const transaction = this.reinviteUserAgentServer.transaction;
// Once the response has been constructed, it is passed to the INVITE
// server transaction. In order to ensure reliable end-to-end
// transport of the response, it is necessary to periodically pass
// the response directly to the transport until the ACK arrives. The
// 2xx response is passed to the transport with an interval that
// starts at T1 seconds and doubles for each retransmission until it
// reaches T2 seconds (T1 and T2 are defined in Section 17).
// Response retransmissions cease when an ACK request for the
// response is received. This is independent of whatever transport
// protocols are used to send the response.
// https://tools.ietf.org/html/rfc6026#section-8.1
let timeout = Timers.T1;
const retransmission = (): void => {
if (!this.reinviteUserAgentServer) {
this.invite2xxTimer = undefined;
return;
}
this.logger.log("No ACK for 2xx response received, attempting retransmission");
transaction.retransmitAcceptedResponse();
timeout = Math.min(timeout * 2, Timers.T2);
this.invite2xxTimer = setTimeout(retransmission, timeout);
};
this.invite2xxTimer = setTimeout(retransmission, timeout);
// If the server retransmits the 2xx response for 64*T1 seconds without
// receiving an ACK, the dialog is confirmed, but the session SHOULD be
// terminated. This is accomplished with a BYE, as described in Section 15.
// https://tools.ietf.org/html/rfc3261#section-13.3.1.4
const stateChanged = (): void => {
if (transaction.state === TransactionState.Terminated) {
transaction.removeStateChangeListener(stateChanged);
if (this.invite2xxTimer) {
clearTimeout(this.invite2xxTimer);
this.invite2xxTimer = undefined;
}
if (this.reinviteUserAgentServer) {
// FIXME: TODO: What to do here
}
}
};
transaction.addStateChangeListener(stateChanged);
}
}
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormQuoteDetail_Field_Service_Information {
interface tab_address_Sections {
address_section_2: DevKit.Controls.Section;
ship_to_address: DevKit.Controls.Section;
}
interface tab_general_Sections {
pricing: DevKit.Controls.Section;
quote_detail_information: DevKit.Controls.Section;
}
interface tab_quote_booking_setup_tab_Sections {
tab_4_section_1: DevKit.Controls.Section;
}
interface tab_tab_3_Sections {
tab_3_section_1: DevKit.Controls.Section;
}
interface tab_address extends DevKit.Controls.ITab {
Section: tab_address_Sections;
}
interface tab_general extends DevKit.Controls.ITab {
Section: tab_general_Sections;
}
interface tab_quote_booking_setup_tab extends DevKit.Controls.ITab {
Section: tab_quote_booking_setup_tab_Sections;
}
interface tab_tab_3 extends DevKit.Controls.ITab {
Section: tab_tab_3_Sections;
}
interface Tabs {
address: tab_address;
general: tab_general;
quote_booking_setup_tab: tab_quote_booking_setup_tab;
tab_3: tab_tab_3;
}
interface Body {
Tab: Tabs;
/** Shows the total price of the quote product, based on the price per unit, volume discount, and quantity. */
BaseAmount: DevKit.Controls.Money;
/** Date and time when the record was created. */
CreatedOn: DevKit.Controls.DateTime;
/** Select whether the price per unit is fixed at the value in the specified price list or can be overridden by users who have edit rights to the quote product. */
IsPriceOverridden: DevKit.Controls.Boolean;
/** Select whether the price per unit is fixed at the value in the specified price list or can be overridden by users who have edit rights to the quote product. */
IsPriceOverridden_1: DevKit.Controls.Boolean;
/** Select whether the product exists in the Microsoft Dynamics 365 product catalog or is a write-in product specific to the quote. */
IsProductOverridden: DevKit.Controls.Boolean;
/** Select whether the product exists in the Microsoft Dynamics 365 product catalog or is a write-in product specific to the quote. */
IsProductOverridden_1: DevKit.Controls.Boolean;
/** Type the manual discount amount for the quote product to deduct any negotiated or other savings from the product total on the quote. */
ManualDiscountAmount: DevKit.Controls.Money;
/** The agreement that will be connected to this quote */
msdyn_Agreement: DevKit.Controls.Lookup;
/** Duration of the service associated with the quote line */
msdyn_Duration: DevKit.Controls.Integer;
/** End date of the service associated with the quote line */
msdyn_EndDate: DevKit.Controls.Date;
/** The estimated cost of this quote line */
msdyn_EstimatedCost: DevKit.Controls.Money;
/** The estimated margin of this quote line */
msdyn_EstimatedMargin: DevKit.Controls.Decimal;
msdyn_ImportDetailsFromAgreement: DevKit.Controls.Boolean;
/** The field to distinguish the quote lines to be of project service or field service */
msdyn_LineType: DevKit.Controls.OptionSet;
/** The price list associated for the service account on this quote line */
msdyn_PriceList: DevKit.Controls.Lookup;
/** The sales tax code */
msdyn_SalesTaxCode: DevKit.Controls.Lookup;
/** The service account for this quote line */
msdyn_ServiceAccount: DevKit.Controls.Lookup;
/** Service territory of this service */
msdyn_ServiceTerritory: DevKit.Controls.Lookup;
/** Start Date of the service associated with the quote Line */
msdyn_StartDate: DevKit.Controls.Date;
/** States whether this is taxable */
msdyn_Taxable: DevKit.Controls.Boolean;
/** Type the price per unit of the quote product. The default is to the value in the price list specified on the quote for existing products. */
PricePerUnit: DevKit.Controls.Money;
/** Type a name or description to identify the type of write-in product included in the quote. */
ProductDescription: DevKit.Controls.String;
/** Choose the product to include on the quote to link the product's pricing and other information to the quote. */
ProductId: DevKit.Controls.Lookup;
/** Product Type */
ProductTypeCode: DevKit.Controls.OptionSet;
/** Type the amount or quantity of the product requested by the customer. */
Quantity: DevKit.Controls.Decimal;
/** Type the amount or quantity of the product requested by the customer. */
Quantity_1: DevKit.Controls.Decimal;
/** Unique identifier of the quote for the quote product. */
QuoteId: DevKit.Controls.Lookup;
/** Type the city for the customer's shipping address. */
ShipTo_City: DevKit.Controls.String;
/** Type the primary contact name at the customer's shipping address. */
ShipTo_ContactName: DevKit.Controls.String;
/** Type the country or region for the customer's shipping address. */
ShipTo_Country: DevKit.Controls.String;
/** Type the fax number for the customer's shipping address. */
ShipTo_Fax: DevKit.Controls.String;
/** Select the freight terms to make sure shipping orders are processed correctly. */
ShipTo_FreightTermsCode: DevKit.Controls.OptionSet;
/** Type the first line of the customer's shipping address. */
ShipTo_Line1: DevKit.Controls.String;
/** Type the second line of the customer's shipping address. */
ShipTo_Line2: DevKit.Controls.String;
/** Type the third line of the shipping address. */
ShipTo_Line3: DevKit.Controls.String;
/** Type a name for the customer's shipping address, such as "Headquarters" or "Field office", to identify the address. */
ShipTo_Name: DevKit.Controls.String;
/** Type the ZIP Code or postal code for the shipping address. */
ShipTo_PostalCode: DevKit.Controls.String;
/** Type the state or province for the shipping address. */
ShipTo_StateOrProvince: DevKit.Controls.String;
/** Type the phone number for the customer's shipping address. */
ShipTo_Telephone: DevKit.Controls.String;
/** Type the tax amount for the quote product. */
Tax: DevKit.Controls.Money;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.Controls.Lookup;
/** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */
UoMId: DevKit.Controls.Lookup;
/** Shows the discount amount per unit if a specified volume is purchased. Configure volume discounts in the Product Catalog in the Settings area. */
VolumeDiscountAmount: DevKit.Controls.Money;
/** Select whether the quote product should be shipped to the specified address or held until the customer calls with further pick up or delivery instructions. */
WillCall: DevKit.Controls.Boolean;
}
interface Grid {
QuoteBookingSetups: DevKit.Controls.Grid;
}
}
class FormQuoteDetail_Field_Service_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form QuoteDetail_Field_Service_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form QuoteDetail_Field_Service_Information */
Body: DevKit.FormQuoteDetail_Field_Service_Information.Body;
/** The Grid of form QuoteDetail_Field_Service_Information */
Grid: DevKit.FormQuoteDetail_Field_Service_Information.Grid;
}
namespace FormQuoteDetail_Information {
interface tab_address_Sections {
ship_to_address: DevKit.Controls.Section;
}
interface tab_delivery_Sections {
delivery_information: DevKit.Controls.Section;
}
interface tab_editproductpropertiesinlinetab_Sections {
productpropertiessection: DevKit.Controls.Section;
}
interface tab_general_Sections {
pricing: DevKit.Controls.Section;
quote_detail_information: DevKit.Controls.Section;
}
interface tab_address extends DevKit.Controls.ITab {
Section: tab_address_Sections;
}
interface tab_delivery extends DevKit.Controls.ITab {
Section: tab_delivery_Sections;
}
interface tab_editproductpropertiesinlinetab extends DevKit.Controls.ITab {
Section: tab_editproductpropertiesinlinetab_Sections;
}
interface tab_general extends DevKit.Controls.ITab {
Section: tab_general_Sections;
}
interface Tabs {
address: tab_address;
delivery: tab_delivery;
editproductpropertiesinlinetab: tab_editproductpropertiesinlinetab;
general: tab_general;
}
interface Body {
Tab: Tabs;
/** Shows the total price of the quote product, based on the price per unit, volume discount, and quantity. */
BaseAmount: DevKit.Controls.Money;
/** Shows the total amount due for the quote product, based on the sum of the unit price, quantity, discounts ,and tax. */
ExtendedAmount: DevKit.Controls.Money;
/** Select whether the price per unit is fixed at the value in the specified price list or can be overridden by users who have edit rights to the quote product. */
IsPriceOverridden: DevKit.Controls.Boolean;
/** Select whether the product exists in the Microsoft Dynamics 365 product catalog or is a write-in product specific to the quote. */
IsProductOverridden: DevKit.Controls.Boolean;
/** Type the manual discount amount for the quote product to deduct any negotiated or other savings from the product total on the quote. */
ManualDiscountAmount: DevKit.Controls.Money;
/** The field to distinguish the quote lines to be of project service or field service */
msdyn_LineType: DevKit.Controls.OptionSet;
/** Type the price per unit of the quote product. The default is to the value in the price list specified on the quote for existing products. */
PricePerUnit: DevKit.Controls.Money;
/** Type a name or description to identify the type of write-in product included in the quote. */
ProductDescription: DevKit.Controls.String;
/** Choose the product to include on the quote to link the product's pricing and other information to the quote. */
ProductId: DevKit.Controls.Lookup;
editpropertiescontrol: DevKit.Controls.ActionCards;
/** Type the amount or quantity of the product requested by the customer. */
Quantity: DevKit.Controls.Decimal;
/** Unique identifier of the quote for the quote product. */
QuoteId: DevKit.Controls.Lookup;
/** Unique identifier of the quote for the quote product. */
QuoteId_1: DevKit.Controls.Lookup;
/** Enter the delivery date requested by the customer for the quote product. */
RequestDeliveryBy: DevKit.Controls.Date;
/** Choose the user responsible for the sale of the quote product. */
SalesRepId: DevKit.Controls.Lookup;
/** Type the city for the customer's shipping address. */
ShipTo_City: DevKit.Controls.String;
/** Type the primary contact name at the customer's shipping address. */
ShipTo_ContactName: DevKit.Controls.String;
/** Type the country or region for the customer's shipping address. */
ShipTo_Country: DevKit.Controls.String;
/** Type the fax number for the customer's shipping address. */
ShipTo_Fax: DevKit.Controls.String;
/** Select the freight terms to make sure shipping orders are processed correctly. */
ShipTo_FreightTermsCode: DevKit.Controls.OptionSet;
/** Type the first line of the customer's shipping address. */
ShipTo_Line1: DevKit.Controls.String;
/** Type the second line of the customer's shipping address. */
ShipTo_Line2: DevKit.Controls.String;
/** Type the third line of the shipping address. */
ShipTo_Line3: DevKit.Controls.String;
/** Type a name for the customer's shipping address, such as "Headquarters" or "Field office", to identify the address. */
ShipTo_Name: DevKit.Controls.String;
/** Type the ZIP Code or postal code for the shipping address. */
ShipTo_PostalCode: DevKit.Controls.String;
/** Type the state or province for the shipping address. */
ShipTo_StateOrProvince: DevKit.Controls.String;
/** Type the phone number for the customer's shipping address. */
ShipTo_Telephone: DevKit.Controls.String;
/** Type the tax amount for the quote product. */
Tax: DevKit.Controls.Money;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.Controls.Lookup;
/** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */
UoMId: DevKit.Controls.Lookup;
/** Shows the discount amount per unit if a specified volume is purchased. Configure volume discounts in the Product Catalog in the Settings area. */
VolumeDiscountAmount: DevKit.Controls.Money;
/** Select whether the quote product should be shipped to the specified address or held until the customer calls with further pick up or delivery instructions. */
WillCall: DevKit.Controls.Boolean;
}
}
class FormQuoteDetail_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form QuoteDetail_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form QuoteDetail_Information */
Body: DevKit.FormQuoteDetail_Information.Body;
}
namespace FormQuoteDetail_Project_Information {
interface tab_address_Sections {
ship_to_address: DevKit.Controls.Section;
}
interface tab_ChargeableCategoriesTab_Sections {
ChargeableCategories: DevKit.Controls.Section;
}
interface tab_ChargeableRolesTab_Sections {
ChargeableRoles: DevKit.Controls.Section;
}
interface tab_delivery_Sections {
delivery_information: DevKit.Controls.Section;
}
interface tab_general_Sections {
pricing: DevKit.Controls.Section;
quote_detail_information: DevKit.Controls.Section;
}
interface tab_GeneralProductTab_Sections {
GeneralCostSection: DevKit.Controls.Section;
GeneralProductSection: DevKit.Controls.Section;
GeneralSalesSection: DevKit.Controls.Section;
}
interface tab_GeneralProjectTab_Sections {
AmountsSection: DevKit.Controls.Section;
ProjectSection: DevKit.Controls.Section;
TransactionTypesSection: DevKit.Controls.Section;
}
interface tab_InvoiceScheduleTab_Sections {
InvoiceScheduleSection: DevKit.Controls.Section;
InvoiceScheduleTab_Header: DevKit.Controls.Section;
MilestoneSection: DevKit.Controls.Section;
}
interface tab_ProductTypeTab_Sections {
tab_8_section_1: DevKit.Controls.Section;
}
interface tab_TransactionsTab_Sections {
TransactionSection: DevKit.Controls.Section;
}
interface tab_address extends DevKit.Controls.ITab {
Section: tab_address_Sections;
}
interface tab_ChargeableCategoriesTab extends DevKit.Controls.ITab {
Section: tab_ChargeableCategoriesTab_Sections;
}
interface tab_ChargeableRolesTab extends DevKit.Controls.ITab {
Section: tab_ChargeableRolesTab_Sections;
}
interface tab_delivery extends DevKit.Controls.ITab {
Section: tab_delivery_Sections;
}
interface tab_general extends DevKit.Controls.ITab {
Section: tab_general_Sections;
}
interface tab_GeneralProductTab extends DevKit.Controls.ITab {
Section: tab_GeneralProductTab_Sections;
}
interface tab_GeneralProjectTab extends DevKit.Controls.ITab {
Section: tab_GeneralProjectTab_Sections;
}
interface tab_InvoiceScheduleTab extends DevKit.Controls.ITab {
Section: tab_InvoiceScheduleTab_Sections;
}
interface tab_ProductTypeTab extends DevKit.Controls.ITab {
Section: tab_ProductTypeTab_Sections;
}
interface tab_TransactionsTab extends DevKit.Controls.ITab {
Section: tab_TransactionsTab_Sections;
}
interface Tabs {
address: tab_address;
ChargeableCategoriesTab: tab_ChargeableCategoriesTab;
ChargeableRolesTab: tab_ChargeableRolesTab;
delivery: tab_delivery;
general: tab_general;
GeneralProductTab: tab_GeneralProductTab;
GeneralProjectTab: tab_GeneralProjectTab;
InvoiceScheduleTab: tab_InvoiceScheduleTab;
ProductTypeTab: tab_ProductTypeTab;
TransactionsTab: tab_TransactionsTab;
}
interface Body {
Tab: Tabs;
/** Shows the total price of the quote product, based on the price per unit, volume discount, and quantity. */
BaseAmount: DevKit.Controls.Money;
/** Shows the total amount due for the quote product, based on the sum of the unit price, quantity, discounts ,and tax. */
ExtendedAmount: DevKit.Controls.Money;
/** Shows the total amount due for the quote product, based on the sum of the unit price, quantity, discounts ,and tax. */
ExtendedAmount_1: DevKit.Controls.Money;
/** Shows the total amount due for the quote product, based on the sum of the unit price, quantity, discounts ,and tax. */
ExtendedAmount_2: DevKit.Controls.Money;
/** Select whether the price per unit is fixed at the value in the specified price list or can be overridden by users who have edit rights to the quote product. */
IsPriceOverridden: DevKit.Controls.Boolean;
/** Select whether the product exists in the Microsoft Dynamics 365 product catalog or is a write-in product specific to the quote. */
IsProductOverridden: DevKit.Controls.Boolean;
/** Select whether the product exists in the Microsoft Dynamics 365 product catalog or is a write-in product specific to the quote. */
IsProductOverridden_1: DevKit.Controls.Boolean;
/** Type the manual discount amount for the quote product to deduct any negotiated or other savings from the product total on the quote. */
ManualDiscountAmount: DevKit.Controls.Money;
/** Billing method for the project quote line. Valid values are Time and Material and Fixed Price */
msdyn_BillingMethod: DevKit.Controls.OptionSet;
/** Enter the estimated start date for the billing frequency on the project. */
msdyn_BillingStartDate: DevKit.Controls.Date;
/** Enter the amount the customer has set aside or is willing to pay for the quote component. */
msdyn_BudgetAmount: DevKit.Controls.Money;
/** Enter the amount the customer has set aside or is willing to pay for the quote component. */
msdyn_BudgetAmount_1: DevKit.Controls.Money;
/** Shows the total cost price of the product based on the cost price per unit and quantity. */
msdyn_CostAmount: DevKit.Controls.Money;
/** Cost per unit of the product. The default is the cost price of the product. */
msdyn_CostPricePerUnit: DevKit.Controls.Money;
/** Select whether to include expenses in the quote line. */
msdyn_IncludeExpense: DevKit.Controls.Boolean;
/** Select whether to include fees in the quote line. */
msdyn_IncludeFee: DevKit.Controls.Boolean;
/** Select whether to include time transactions in the quote line. */
msdyn_IncludeTime: DevKit.Controls.Boolean;
/** Select the frequency for the automatic invoice creation job to create the invoice. */
msdyn_invoicefrequency: DevKit.Controls.Lookup;
/** The field to distinguish the quote lines to be of project service or field service */
msdyn_LineType: DevKit.Controls.OptionSet;
/** Select the project related to this quote line. */
msdyn_Project: DevKit.Controls.Lookup;
/** Type the price per unit of the quote product. The default is to the value in the price list specified on the quote for existing products. */
PricePerUnit: DevKit.Controls.Money;
/** Type the price per unit of the quote product. The default is to the value in the price list specified on the quote for existing products. */
PricePerUnit_1: DevKit.Controls.Money;
/** Type the price per unit of the quote product. The default is to the value in the price list specified on the quote for existing products. */
PricePerUnit_2: DevKit.Controls.Money;
/** Type a name or description to identify the type of write-in product included in the quote. */
ProductDescription: DevKit.Controls.String;
/** Type a name or description to identify the type of write-in product included in the quote. */
ProductDescription_1: DevKit.Controls.String;
/** Type a name or description to identify the type of write-in product included in the quote. */
ProductDescription_2: DevKit.Controls.String;
/** Choose the product to include on the quote to link the product's pricing and other information to the quote. */
ProductId: DevKit.Controls.Lookup;
/** Choose the product to include on the quote to link the product's pricing and other information to the quote. */
ProductId_1: DevKit.Controls.Lookup;
/** Product Type */
ProductTypeCode: DevKit.Controls.OptionSet;
/** Product Type */
ProductTypeCode_1: DevKit.Controls.OptionSet;
/** Type the amount or quantity of the product requested by the customer. */
Quantity: DevKit.Controls.Decimal;
/** Type the amount or quantity of the product requested by the customer. */
Quantity_1: DevKit.Controls.Decimal;
/** Unique identifier of the quote for the quote product. */
QuoteId: DevKit.Controls.Lookup;
/** Unique identifier of the quote for the quote product. */
QuoteId_1: DevKit.Controls.Lookup;
/** Unique identifier of the quote for the quote product. */
QuoteId_2: DevKit.Controls.Lookup;
/** Unique identifier of the quote for the quote product. */
QuoteId_3: DevKit.Controls.Lookup;
/** Enter the delivery date requested by the customer for the quote product. */
RequestDeliveryBy: DevKit.Controls.Date;
/** Enter the delivery date requested by the customer for the quote product. */
RequestDeliveryBy_1: DevKit.Controls.Date;
/** Choose the user responsible for the sale of the quote product. */
SalesRepId: DevKit.Controls.Lookup;
/** Type the city for the customer's shipping address. */
ShipTo_City: DevKit.Controls.String;
/** Type the primary contact name at the customer's shipping address. */
ShipTo_ContactName: DevKit.Controls.String;
/** Type the country or region for the customer's shipping address. */
ShipTo_Country: DevKit.Controls.String;
/** Type the fax number for the customer's shipping address. */
ShipTo_Fax: DevKit.Controls.String;
/** Select the freight terms to make sure shipping orders are processed correctly. */
ShipTo_FreightTermsCode: DevKit.Controls.OptionSet;
/** Type the first line of the customer's shipping address. */
ShipTo_Line1: DevKit.Controls.String;
/** Type the second line of the customer's shipping address. */
ShipTo_Line2: DevKit.Controls.String;
/** Type the third line of the shipping address. */
ShipTo_Line3: DevKit.Controls.String;
/** Type a name for the customer's shipping address, such as "Headquarters" or "Field office", to identify the address. */
ShipTo_Name: DevKit.Controls.String;
/** Type the ZIP Code or postal code for the shipping address. */
ShipTo_PostalCode: DevKit.Controls.String;
/** Type the state or province for the shipping address. */
ShipTo_StateOrProvince: DevKit.Controls.String;
/** Type the phone number for the customer's shipping address. */
ShipTo_Telephone: DevKit.Controls.String;
/** Type the tax amount for the quote product. */
Tax: DevKit.Controls.Money;
/** Type the tax amount for the quote product. */
Tax_1: DevKit.Controls.Money;
/** Type the tax amount for the quote product. */
Tax_2: DevKit.Controls.Money;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.Controls.Lookup;
/** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */
UoMId: DevKit.Controls.Lookup;
/** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */
UoMId_1: DevKit.Controls.Lookup;
/** Shows the discount amount per unit if a specified volume is purchased. Configure volume discounts in the Product Catalog in the Settings area. */
VolumeDiscountAmount: DevKit.Controls.Money;
/** Select whether the quote product should be shipped to the specified address or held until the customer calls with further pick up or delivery instructions. */
WillCall: DevKit.Controls.Boolean;
}
interface Grid {
ChargeableRolesGrid: DevKit.Controls.Grid;
ChargeableCategoriesGrid: DevKit.Controls.Grid;
EstimationLines: DevKit.Controls.Grid;
InvoiceScheduleGrid: DevKit.Controls.Grid;
MilestonesGrid: DevKit.Controls.Grid;
}
}
class FormQuoteDetail_Project_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form QuoteDetail_Project_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form QuoteDetail_Project_Information */
Body: DevKit.FormQuoteDetail_Project_Information.Body;
/** The Grid of form QuoteDetail_Project_Information */
Grid: DevKit.FormQuoteDetail_Project_Information.Grid;
}
namespace FormQuoteDetail {
interface tab_general_Sections {
delivery_information: DevKit.Controls.Section;
pricing: DevKit.Controls.Section;
quote_detail_information: DevKit.Controls.Section;
}
interface tab_general extends DevKit.Controls.ITab {
Section: tab_general_Sections;
}
interface Tabs {
general: tab_general;
}
interface Body {
Tab: Tabs;
/** Select whether the price per unit is fixed at the value in the specified price list or can be overridden by users who have edit rights to the quote product. */
IsPriceOverridden: DevKit.Controls.Boolean;
/** Select whether the product exists in the Microsoft Dynamics 365 product catalog or is a write-in product specific to the quote. */
IsProductOverridden: DevKit.Controls.Boolean;
/** Type the manual discount amount for the quote product to deduct any negotiated or other savings from the product total on the quote. */
ManualDiscountAmount: DevKit.Controls.Money;
/** Type the price per unit of the quote product. The default is to the value in the price list specified on the quote for existing products. */
PricePerUnit: DevKit.Controls.Money;
/** Type a name or description to identify the type of write-in product included in the quote. */
ProductDescription: DevKit.Controls.String;
/** Choose the product to include on the quote to link the product's pricing and other information to the quote. */
ProductId: DevKit.Controls.Lookup;
/** Type the amount or quantity of the product requested by the customer. */
Quantity: DevKit.Controls.Decimal;
/** Unique identifier of the quote for the quote product. */
QuoteId: DevKit.Controls.Lookup;
/** Enter the delivery date requested by the customer for the quote product. */
RequestDeliveryBy: DevKit.Controls.Date;
/** Choose the user responsible for the sale of the quote product. */
SalesRepId: DevKit.Controls.Lookup;
/** Type the city for the customer's shipping address. */
ShipTo_City: DevKit.Controls.String;
/** Type the primary contact name at the customer's shipping address. */
ShipTo_ContactName: DevKit.Controls.String;
/** Type the country or region for the customer's shipping address. */
ShipTo_Country: DevKit.Controls.String;
/** Type the fax number for the customer's shipping address. */
ShipTo_Fax: DevKit.Controls.String;
/** Select the freight terms to make sure shipping orders are processed correctly. */
ShipTo_FreightTermsCode: DevKit.Controls.OptionSet;
/** Type the first line of the customer's shipping address. */
ShipTo_Line1: DevKit.Controls.String;
/** Type a name for the customer's shipping address, such as "Headquarters" or "Field office", to identify the address. */
ShipTo_Name: DevKit.Controls.String;
/** Type the ZIP Code or postal code for the shipping address. */
ShipTo_PostalCode: DevKit.Controls.String;
/** Type the state or province for the shipping address. */
ShipTo_StateOrProvince: DevKit.Controls.String;
/** Type the phone number for the customer's shipping address. */
ShipTo_Telephone: DevKit.Controls.String;
/** Type the tax amount for the quote product. */
Tax: DevKit.Controls.Money;
/** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */
UoMId: DevKit.Controls.Lookup;
/** Select whether the quote product should be shipped to the specified address or held until the customer calls with further pick up or delivery instructions. */
WillCall: DevKit.Controls.Boolean;
}
}
class FormQuoteDetail extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form QuoteDetail
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form QuoteDetail */
Body: DevKit.FormQuoteDetail.Body;
}
class QuoteDetailApi {
/**
* DynamicsCrm.DevKit QuoteDetailApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Shows the total price of the quote product, based on the price per unit, volume discount, and quantity. */
BaseAmount: DevKit.WebApi.MoneyValue;
/** Value of the Amount in base currency. */
BaseAmount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who created the record on behalf of another user. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Type additional information to describe the quote product, such as manufacturing details or acceptable substitutions. */
Description: DevKit.WebApi.StringValue;
/** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Shows the total amount due for the quote product, based on the sum of the unit price, quantity, discounts ,and tax. */
ExtendedAmount: DevKit.WebApi.MoneyValue;
/** Value of the Extended Amount in base currency. */
ExtendedAmount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Select whether the price per unit is fixed at the value in the specified price list or can be overridden by users who have edit rights to the quote product. */
IsPriceOverridden: DevKit.WebApi.BooleanValue;
/** Select whether the product exists in the Microsoft Dynamics 365 product catalog or is a write-in product specific to the quote. */
IsProductOverridden: DevKit.WebApi.BooleanValue;
/** Type the line item number for the quote product to easily identify the product in the quote and make sure it's listed in the correct order. */
LineItemNumber: DevKit.WebApi.IntegerValue;
/** Type the manual discount amount for the quote product to deduct any negotiated or other savings from the product total on the quote. */
ManualDiscountAmount: DevKit.WebApi.MoneyValue;
/** Value of the Manual Discount in base currency. */
ManualDiscountAmount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows who last updated the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who last updated the record on behalf of another user. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** The agreement that will be connected to this quote */
msdyn_Agreement: DevKit.WebApi.LookupValue;
/** Billing method for the project quote line. Valid values are Time and Material and Fixed Price */
msdyn_BillingMethod: DevKit.WebApi.OptionSetValue;
/** Enter the estimated start date for the billing frequency on the project. */
msdyn_BillingStartDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the amount the customer has set aside or is willing to pay for the quote component. */
msdyn_BudgetAmount: DevKit.WebApi.MoneyValue;
/** Value of the Budget Amount in base currency. */
msdyn_budgetamount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the total cost price of the product based on the cost price per unit and quantity. */
msdyn_CostAmount: DevKit.WebApi.MoneyValue;
/** Value of the CostAmount in base currency. */
msdyn_costamount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Cost per unit of the product. The default is the cost price of the product. */
msdyn_CostPricePerUnit: DevKit.WebApi.MoneyValue;
/** Value of the Cost Price Per Unit in base currency. */
msdyn_costpriceperunit_Base: DevKit.WebApi.MoneyValueReadonly;
/** Duration of the service associated with the quote line */
msdyn_Duration: DevKit.WebApi.IntegerValue;
/** End date of the service associated with the quote line */
msdyn_EndDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** The estimated cost of this quote line */
msdyn_EstimatedCost: DevKit.WebApi.MoneyValue;
/** Value of the EstimatedCost in base currency. */
msdyn_estimatedcost_Base: DevKit.WebApi.MoneyValueReadonly;
/** The estimated margin of this quote line */
msdyn_EstimatedMargin: DevKit.WebApi.DecimalValue;
/** The estimated revenue of this quote line */
msdyn_EstimatedRevenue: DevKit.WebApi.MoneyValue;
/** Value of the EstimatedRevenue in base currency. */
msdyn_estimatedrevenue_Base: DevKit.WebApi.MoneyValueReadonly;
msdyn_ImportDetailsFromAgreement: DevKit.WebApi.BooleanValue;
/** Select whether to include expenses in the quote line. */
msdyn_IncludeExpense: DevKit.WebApi.BooleanValue;
/** Select whether to include fees in the quote line. */
msdyn_IncludeFee: DevKit.WebApi.BooleanValue;
/** Select whether to include materials in the quote line. */
msdyn_IncludeMaterial: DevKit.WebApi.BooleanValue;
/** Select whether to include time transactions in the quote line. */
msdyn_IncludeTime: DevKit.WebApi.BooleanValue;
/** Select the frequency for the automatic invoice creation job to create the invoice. */
msdyn_invoicefrequency: DevKit.WebApi.LookupValue;
/** abstracts description for product based lines vs write-in products or project based lines */
msdyn_linedescription: DevKit.WebApi.StringValueReadonly;
/** The field to distinguish the quote lines to be of project service or field service */
msdyn_LineType: DevKit.WebApi.OptionSetValue;
/** Shows the opportunity line related to this quote line. */
msdyn_OpportunityLine: DevKit.WebApi.StringValue;
/** The price list associated for the service account on this quote line */
msdyn_PriceList: DevKit.WebApi.LookupValue;
/** Select the project related to this quote line. */
msdyn_Project: DevKit.WebApi.LookupValue;
/** The sales tax code */
msdyn_SalesTaxCode: DevKit.WebApi.LookupValue;
/** The service account for this quote line */
msdyn_ServiceAccount: DevKit.WebApi.LookupValue;
/** Service territory of this service */
msdyn_ServiceTerritory: DevKit.WebApi.LookupValue;
/** Start Date of the service associated with the quote Line */
msdyn_StartDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** States whether this is taxable */
msdyn_Taxable: DevKit.WebApi.BooleanValue;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValueReadonly;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Choose the parent bundle associated with this product */
ParentBundleId: DevKit.WebApi.GuidValue;
/** Choose the parent bundle associated with this product */
ParentBundleIdRef: DevKit.WebApi.LookupValue;
/** Type the price per unit of the quote product. The default is to the value in the price list specified on the quote for existing products. */
PricePerUnit: DevKit.WebApi.MoneyValue;
/** Value of the Price Per Unit in base currency. */
PricePerUnit_Base: DevKit.WebApi.MoneyValueReadonly;
/** Select the type of pricing error, such as a missing or invalid product, or missing quantity. */
PricingErrorCode: DevKit.WebApi.OptionSetValue;
/** Unique identifier of the product line item association with bundle in the quote */
ProductAssociationId: DevKit.WebApi.GuidValue;
/** Type a name or description to identify the type of write-in product included in the quote. */
ProductDescription: DevKit.WebApi.StringValue;
/** Choose the product to include on the quote to link the product's pricing and other information to the quote. */
ProductId: DevKit.WebApi.LookupValue;
/** Calculated field that will be populated by name and description of the product. */
ProductName: DevKit.WebApi.StringValue;
/** User-defined product ID. */
ProductNumber: DevKit.WebApi.StringValueReadonly;
/** Product Type */
ProductTypeCode: DevKit.WebApi.OptionSetValue;
/** Status of the property configuration. */
PropertyConfigurationStatus: DevKit.WebApi.OptionSetValue;
/** Type the amount or quantity of the product requested by the customer. */
Quantity: DevKit.WebApi.DecimalValue;
/** Unique identifier of the product line item in the quote. */
QuoteDetailId: DevKit.WebApi.GuidValue;
/** Quote Detail Name. Added for 1:n referential relationship (internal purposes only) */
QuoteDetailName: DevKit.WebApi.StringValue;
/** Unique identifier of the quote for the quote product. */
QuoteId: DevKit.WebApi.LookupValue;
/** Status of the quote product. */
QuoteStateCode: DevKit.WebApi.OptionSetValueReadonly;
/** Enter the delivery date requested by the customer for the quote product. */
RequestDeliveryBy_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Choose the user responsible for the sale of the quote product. */
SalesRepId: DevKit.WebApi.LookupValue;
/** Unique identifier of the data that maintains the sequence. */
SequenceNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the shipping address. */
ShipTo_AddressId: DevKit.WebApi.GuidValue;
/** Type the city for the customer's shipping address. */
ShipTo_City: DevKit.WebApi.StringValue;
/** Type the primary contact name at the customer's shipping address. */
ShipTo_ContactName: DevKit.WebApi.StringValue;
/** Type the country or region for the customer's shipping address. */
ShipTo_Country: DevKit.WebApi.StringValue;
/** Type the fax number for the customer's shipping address. */
ShipTo_Fax: DevKit.WebApi.StringValue;
/** Select the freight terms to make sure shipping orders are processed correctly. */
ShipTo_FreightTermsCode: DevKit.WebApi.OptionSetValue;
/** Type the first line of the customer's shipping address. */
ShipTo_Line1: DevKit.WebApi.StringValue;
/** Type the second line of the customer's shipping address. */
ShipTo_Line2: DevKit.WebApi.StringValue;
/** Type the third line of the shipping address. */
ShipTo_Line3: DevKit.WebApi.StringValue;
/** Type a name for the customer's shipping address, such as "Headquarters" or "Field office", to identify the address. */
ShipTo_Name: DevKit.WebApi.StringValue;
/** Type the ZIP Code or postal code for the shipping address. */
ShipTo_PostalCode: DevKit.WebApi.StringValue;
/** Type the state or province for the shipping address. */
ShipTo_StateOrProvince: DevKit.WebApi.StringValue;
/** Type the phone number for the customer's shipping address. */
ShipTo_Telephone: DevKit.WebApi.StringValue;
/** Skip the price */
SkipPriceCalculation: DevKit.WebApi.OptionSetValue;
/** Type the tax amount for the quote product. */
Tax: DevKit.WebApi.MoneyValue;
/** Value of the Tax in base currency. */
Tax_Base: DevKit.WebApi.MoneyValueReadonly;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */
UoMId: DevKit.WebApi.LookupValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
/** Shows the discount amount per unit if a specified volume is purchased. Configure volume discounts in the Product Catalog in the Settings area. */
VolumeDiscountAmount: DevKit.WebApi.MoneyValueReadonly;
/** Value of the Volume Discount in base currency. */
VolumeDiscountAmount_Base: DevKit.WebApi.MoneyValueReadonly;
/** Select whether the quote product should be shipped to the specified address or held until the customer calls with further pick up or delivery instructions. */
WillCall: DevKit.WebApi.BooleanValue;
}
}
declare namespace OptionSet {
namespace QuoteDetail {
enum msdyn_BillingMethod {
/** 192350001 */
Fixed_Price,
/** 192350000 */
Time_and_Material
}
enum msdyn_LineType {
/** 690970001 */
Field_Service_Line,
/** 690970000 */
Project_Service_Line
}
enum PricingErrorCode {
/** 36 */
Base_Currency_Attribute_Overflow,
/** 37 */
Base_Currency_Attribute_Underflow,
/** 1 */
Detail_Error,
/** 27 */
Discount_Type_Invalid_State,
/** 33 */
Inactive_Discount_Type,
/** 3 */
Inactive_Price_Level,
/** 20 */
Invalid_Current_Cost,
/** 28 */
Invalid_Discount,
/** 26 */
Invalid_Discount_Type,
/** 19 */
Invalid_Price,
/** 17 */
Invalid_Price_Level_Amount,
/** 34 */
Invalid_Price_Level_Currency,
/** 18 */
Invalid_Price_Level_Percentage,
/** 9 */
Invalid_Pricing_Code,
/** 30 */
Invalid_Pricing_Precision,
/** 7 */
Invalid_Product,
/** 29 */
Invalid_Quantity,
/** 24 */
Invalid_Rounding_Amount,
/** 23 */
Invalid_Rounding_Option,
/** 22 */
Invalid_Rounding_Policy,
/** 21 */
Invalid_Standard_Cost,
/** 15 */
Missing_Current_Cost,
/** 14 */
Missing_Price,
/** 2 */
Missing_Price_Level,
/** 12 */
Missing_Price_Level_Amount,
/** 13 */
Missing_Price_Level_Percentage,
/** 8 */
Missing_Pricing_Code,
/** 6 */
Missing_Product,
/** 31 */
Missing_Product_Default_UOM,
/** 32 */
Missing_Product_UOM_Schedule_,
/** 4 */
Missing_Quantity,
/** 16 */
Missing_Standard_Cost,
/** 5 */
Missing_Unit_Price,
/** 10 */
Missing_UOM,
/** 0 */
None,
/** 35 */
Price_Attribute_Out_Of_Range,
/** 25 */
Price_Calculation_Error,
/** 11 */
Product_Not_In_Price_Level,
/** 38 */
Transaction_currency_is_not_set_for_the_product_price_list_item
}
enum ProductTypeCode {
/** 2 */
Bundle,
/** 4 */
Optional_Bundle_Product,
/** 1 */
Product,
/** 5 */
Project_based_Service,
/** 3 */
Required_Bundle_Product
}
enum PropertyConfigurationStatus {
/** 0 */
Edit,
/** 2 */
Not_Configured,
/** 1 */
Rectify
}
enum QuoteStateCode {
}
enum ShipTo_FreightTermsCode {
/** 1 */
FOB,
/** 2 */
No_Charge
}
enum SkipPriceCalculation {
/** 0 */
DoPriceCalcAlways,
/** 1 */
SkipPriceCalcOnCreate,
/** 2 */
SkipPriceCalcOnUpdate,
/** 3 */
SkipPriceCalcOnUpSert
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Field Service Information','Information','Project Information','QuoteDetail'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import { InvalidArgumentError, InvalidArgumentReason } from '../errors/InvalidArgumentError';
import SdkEnvironment from '../managers/SdkEnvironment';
import { WindowEnvironmentKind } from '../models/WindowEnvironmentKind';
import { Serializable } from '../models/Serializable';
import Environment from '../Environment';
import Log from './Log';
import { ContextSWInterface } from '../models/ContextSW';
import ServiceWorkerUtilHelper from '../helpers/page/ServiceWorkerUtilHelper';
/**
* NOTE: This file contains a mix of code that runs in ServiceWorker and Page contexts
*/
export enum WorkerMessengerCommand {
WorkerVersion = "GetWorkerVersion",
Subscribe = "Subscribe",
SubscribeNew = "SubscribeNew",
AmpSubscriptionState = "amp-web-push-subscription-state",
AmpSubscribe = "amp-web-push-subscribe",
AmpUnsubscribe = "amp-web-push-unsubscribe",
NotificationDisplayed = 'notification.displayed',
NotificationClicked = 'notification.clicked',
NotificationDismissed = 'notification.dismissed',
RedirectPage = 'command.redirect',
SessionUpsert = 'os.session.upsert',
SessionDeactivate = 'os.session.deactivate',
AreYouVisible = "os.page_focused_request",
AreYouVisibleResponse = "os.page_focused_response",
SetLogging = "os.set_sw_logging",
}
export interface WorkerMessengerMessage {
command: WorkerMessengerCommand;
payload: WorkerMessengerPayload;
}
export interface WorkerMessengerReplyBufferRecord {
callback: Function;
onceListenerOnly: boolean;
}
export class WorkerMessengerReplyBuffer {
private replies: { [index: string]: WorkerMessengerReplyBufferRecord[] | null };
constructor() {
this.replies = {};
}
public addListener(command: WorkerMessengerCommand, callback: Function, onceListenerOnly: boolean) {
const record: WorkerMessengerReplyBufferRecord = { callback, onceListenerOnly };
const replies = this.replies[command.toString()];
if (replies)
replies.push(record);
else
this.replies[command.toString()] = [record];
}
public findListenersForMessage(command: WorkerMessengerCommand): WorkerMessengerReplyBufferRecord[] {
return this.replies[command.toString()] || [];
}
public deleteListenerRecords(command: WorkerMessengerCommand) {
this.replies[command.toString()] = null;
}
public deleteAllListenerRecords() {
this.replies = {};
}
public deleteListenerRecord(command: WorkerMessengerCommand, targetRecord: object) {
const listenersForCommand = this.replies[command.toString()];
if (listenersForCommand == null)
return;
for (let listenerRecordIndex = listenersForCommand.length - 1; listenerRecordIndex >= 0; listenerRecordIndex--) {
const listenerRecord = listenersForCommand[listenerRecordIndex];
if (listenerRecord === targetRecord) {
listenersForCommand.splice(listenerRecordIndex, 1);
}
}
}
}
export type WorkerMessengerPayload = Serializable | number | string | object | boolean;
/**
* A Promise-based PostMessage helper to ease back-and-forth replies between
* service workers and window frames.
*/
export class WorkerMessenger {
private context: ContextSWInterface;
private replies: WorkerMessengerReplyBuffer;
constructor(context: ContextSWInterface,
replies: WorkerMessengerReplyBuffer = new WorkerMessengerReplyBuffer()) {
this.context = context;
this.replies = replies;
}
/**
* Broadcasts a message from a service worker to all clients, including uncontrolled clients.
*/
async broadcast(command: WorkerMessengerCommand, payload: WorkerMessengerPayload) {
if (SdkEnvironment.getWindowEnv() !== WindowEnvironmentKind.ServiceWorker)
return;
const clients = await (<ServiceWorkerGlobalScope><any>self).clients.matchAll({ type: 'window', includeUncontrolled: true });
for (const client of clients) {
Log.debug(`[Worker Messenger] [SW -> Page] Broadcasting '${command.toString()}' to window client ${client.url}.`);
client.postMessage({
command: command,
payload: payload
});
}
}
/*
If running on a page context:
Sends a postMessage() to OneSignal's Serviceworker
If running in a ServiceWorker context:
Sends a postMessage() to the supplied windowClient
*/
async unicast(command: WorkerMessengerCommand, payload?: WorkerMessengerPayload, windowClient?: Client) {
const env = SdkEnvironment.getWindowEnv();
if (env === WindowEnvironmentKind.ServiceWorker) {
if (!windowClient) {
throw new InvalidArgumentError('windowClient', InvalidArgumentReason.Empty);
} else {
Log.debug(`[Worker Messenger] [SW -> Page] Unicasting '${command.toString()}' to window client ${windowClient.url}.`);
windowClient.postMessage({
command: command,
payload: payload
} as any);
}
} else {
Log.debug(`[Worker Messenger] [Page -> SW] Unicasting '${command.toString()}' to service worker.`);
this.directPostMessageToSW(command, payload);
}
}
public async directPostMessageToSW(command: WorkerMessengerCommand, payload?: WorkerMessengerPayload): Promise<void> {
Log.debug(`[Worker Messenger] [Page -> SW] Direct command '${command.toString()}' to service worker.`);
const workerRegistration = await this.context.serviceWorkerManager.getRegistration();
if (!workerRegistration) {
Log.error("`[Worker Messenger] [Page -> SW] Could not get ServiceWorkerRegistration to postMessage!");
return;
}
const availableWorker = ServiceWorkerUtilHelper.getAvailableServiceWorker(workerRegistration);
if (!availableWorker) {
Log.error("`[Worker Messenger] [Page -> SW] Could not get ServiceWorker to postMessage!");
return;
}
// The postMessage payload will still arrive at the SW even if it isn't active yet.
availableWorker.postMessage({
command: command,
payload: payload
});
}
/**
* Due to https://github.com/w3c/ServiceWorker/issues/1156, listen() must
* synchronously add self.addEventListener('message') if we are running in the
* service worker.
*/
public async listen() {
if (!Environment.supportsServiceWorkers())
return;
const env = SdkEnvironment.getWindowEnv();
if (env === WindowEnvironmentKind.ServiceWorker) {
self.addEventListener('message', this.onWorkerMessageReceivedFromPage.bind(this));
Log.debug('[Worker Messenger] Service worker is now listening for messages.');
}
else
await this.listenForPage();
}
/**
* Listens for messages for the service worker.
*/
private async listenForPage() {
navigator.serviceWorker.addEventListener('message', this.onPageMessageReceivedFromServiceWorker.bind(this));
Log.debug(`(${location.origin}) [Worker Messenger] Page is now listening for messages.`);
}
onWorkerMessageReceivedFromPage(event: ServiceWorkerMessageEvent) {
const data: WorkerMessengerMessage = event.data;
/* If this message doesn't contain our expected fields, discard the message */
/* The payload may be null. AMP web push sends commands to our service worker in the format:
{ command: "amp-web-push-subscription-state", payload: null }
{ command: "amp-web-push-unsubscribe", payload: null }
{ command: "amp-web-push-subscribe", payload: null }
*/
if (!data || !data.command) {
return;
}
const listenerRecords = this.replies.findListenersForMessage(data.command);
const listenersToRemove = [];
const listenersToCall = [];
Log.debug(`[Worker Messenger] Service worker received message:`, event.data);
for (const listenerRecord of listenerRecords) {
if (listenerRecord.onceListenerOnly) {
listenersToRemove.push(listenerRecord);
}
listenersToCall.push(listenerRecord);
}
for (let i = listenersToRemove.length - 1; i >= 0; i--) {
const listenerRecord = listenersToRemove[i];
this.replies.deleteListenerRecord(data.command, listenerRecord);
}
for (const listenerRecord of listenersToCall) {
listenerRecord.callback.apply(null, [data.payload]);
}
}
/*
Occurs when the page receives a message from the service worker.
A map of callbacks is checked to see if anyone is listening to the specific
message topic. If no one is listening to the message, it is discarded;
otherwise, the listener callback is executed.
*/
onPageMessageReceivedFromServiceWorker(event: ServiceWorkerMessageEvent) {
const data: WorkerMessengerMessage = event.data;
/* If this message doesn't contain our expected fields, discard the message */
if (!data || !data.command) {
return;
}
const listenerRecords = this.replies.findListenersForMessage(data.command);
const listenersToRemove = [];
const listenersToCall = [];
Log.debug(`[Worker Messenger] Page received message:`, event.data);
for (const listenerRecord of listenerRecords) {
if (listenerRecord.onceListenerOnly) {
listenersToRemove.push(listenerRecord);
}
listenersToCall.push(listenerRecord);
}
for (let i = listenersToRemove.length - 1; i >= 0; i--) {
const listenerRecord = listenersToRemove[i];
this.replies.deleteListenerRecord(data.command, listenerRecord);
}
for (const listenerRecord of listenersToCall) {
listenerRecord.callback.apply(null, [data.payload]);
}
}
/*
Subscribes a callback to be notified every time a service worker sends a
message to the window frame with the specific command.
*/
on(command: WorkerMessengerCommand, callback: (WorkerMessengerPayload: any) => void): void {
this.replies.addListener(command, callback, false);
}
/*
Subscribes a callback to be notified the next time a service worker sends a
message to the window frame with the specific command.
The callback is executed once at most.
*/
once(command: WorkerMessengerCommand, callback: (WorkerMessengerPayload: any) => void): void {
this.replies.addListener(command, callback, true);
}
/**
Unsubscribe a callback from being notified about service worker messages
with the specified command.
*/
off(command?: WorkerMessengerCommand): void {
if (command) {
this.replies.deleteListenerRecords(command);
} else {
this.replies.deleteAllListenerRecords();
}
}
} | the_stack |
import * as path from 'path';
import { SwaggerSailsModel, HTTPMethodVerb, MiddlewareType, SwaggerRouteInfo, NameKeyMap, SwaggerActionAttribute, SwaggerModelAttribute, ActionType, SwaggerSailsControllers, AnnotatedFunction, SwaggerControllerAttribute, BluePrintAction, SwaggerModelSchemaAttribute } from './interfaces';
import { loadSwaggerDocComments, blueprintActions } from './utils';
import { map, pickBy, mapValues, forEach, isObject, isArray, isFunction, isString, isUndefined, omit } from 'lodash';
import includeAll from 'include-all';
/**
* Parses Sails route path of the form `/path/:id` to extract list of variables
* and optional variables.
*
* Optional variables are annotated with a `?` as `/path/:id?`.
*
* @note The `variables` elements contains all variables (including optional).
*/
const parsePath = (path: string): { path: string; variables: string[]; optionalVariables: string[] } => {
const variables: string[] = [];
const optionalVariables: string[] = [];
path
.split('/')
.map(v => {
const match = v.match(/^:([^/:?]+)(\?)?$/);
if (match) {
variables.push(match[1]);
if(match[2]) optionalVariables.push(match[1]);
}
});
return { path, variables, optionalVariables };
}
/**
* Parse Sails ORM models (runtime versions from `sails.models`).
*
* @param sails
*/
export const parseModels = (sails: Sails.Sails): NameKeyMap<SwaggerSailsModel> => {
const filteredModels = pickBy(sails.models, (model /*, _identity */) => {
// consider all models except associative tables and 'Archive' model special case
return !!model.globalId && model.globalId !== 'Archive';
});
return mapValues(filteredModels, model => {
return {
globalId: model.globalId,
primaryKey: model.primaryKey,
identity: model.identity,
attributes: model.attributes,
associations: model.associations,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
swagger: (model as any).swagger || {}
};
});
}
/**
* Parse array of routes capture from Sails 'router:bind' events.
*
* @note See detailed background in implementation comments.
*
* @param boundRoutes
* @param models
* @param sails
*/
export const parseBoundRoutes = (boundRoutes: Array<Sails.Route>,
models: NameKeyMap<SwaggerSailsModel>, sails: Sails.Sails): SwaggerRouteInfo[] => {
/* example of Sails.Route (in particular `options`) for standard blueprint */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const standardBlueprintRouteExampleForReference = {
path: '/user',
target: '[Function: routeTargetFnWrapper]',
verb: 'get',
options: {
model: 'user',
associations: [ { alias: 'pets', type: 'collection', collection: 'pet', via: 'owner' } ],
autoWatch: true,
detectedVerb: { verb: '', original: '/user', path: '/user' },
action: 'user/find',
_middlewareType: 'BLUEPRINT: find',
skipRegex: []
},
originalFn: { /*[Function] */ _middlewareType: 'BLUEPRINT: find' }
};
/* example of standard blueprint route but with standard action overridden in controller */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const standardBlueprintRouteWithOverriddenActionExampleForReference = {
path: '/user',
target: '[Function: routeTargetFnWrapper]',
verb: 'post',
options: {
model: 'user',
associations: [ /* [Object], [Object], [Object] */ ],
autoWatch: true,
detectedVerb: { verb: '', original: '/user', path: '/user' },
action: 'user/create',
_middlewareType: 'ACTION: user/create',
skipRegex: []
},
originalFn: /* [Function] */ { _middlewareType: 'ACTION: user/create' }
};
/* example of Sails.Route for custom route targetting blueprint action */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const customRouteTargettingBlueprintExampleForReference = {
path: '/user/test2/:phoneNumber',
target: '[Function]',
verb: 'get',
options: {
detectedVerb: { verb: '', original: '/user/test2/:phoneNumber', path: '/user/test2/:phoneNumber' },
swagger: { summary: 'Unusual route to access `find` blueprint' },
action: 'user/find',
_middlewareType: 'BLUEPRINT: find',
skipRegex: [/^[^?]*\/[^?/]+\.[^?/]+(\?.*)?$/],
skipAssets: true
},
originalFn: { /* [Function] */ _middlewareType: 'BLUEPRINT: find' }
};
/* example of Sails.Route for custom route action */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const customRouteTargettingActionExampleForReference = {
path: '/api/v2/reporting/period-summary',
target: '[Function: routeTargetFnWrapper]',
verb: 'get',
options: {
detectedVerb: { verb: '', original: '/api/v2/reporting/period-summary', path: '/api/v2/reporting/period-summary' },
action: 'reporting/periodsummary/run',
_middlewareType: 'ACTION: reporting/periodsummary/run',
skipRegex: []
},
originalFn:
{ /* [Function] */ _middlewareType: 'ACTION: reporting/periodsummary/run' }
};
/*
* Background notes on Sails 'router:bind' events.
*
* Sails 'router:bind' emits events for the action **and** all middleware
* (run before the action itself) applicable to the route. Events are emitted
* in the order executed i.e. middleware (CORS, policies etc) with action handler
* last.
*
* We filter based on `options._middlewareType` (taking actions and blueprints,
* ignoring others) and merge for unique `verb`/`path` tuples.
*
* Note that:
* 1. Middleware typically includes options of the final action (except
* CORS setHeaders it would seem).
* 2. The value `originalFn._middlewareType` can be used to determine
* the nature of the middleware/action itself.
*
* @see https://github.com/balderdashy/sails/blob/master/lib/EVENTS.md#routerbind
*/
/*
* Background notes on `options.action`.
*
* Note that 'router:bind' events have a normalised action identity; lowercase, with
* `Controller` removed and dots with slashes (`.`'s replaced with `/`'s).
*
* @see https://github.com/balderdashy/sails/blob/ef8e98f09d9a97ea9a22b1a7c961800bc906c061/lib/router/index.js#L455
*/
/*
* Background on `options` element of 'router:bind' events.
*
* Options contains values from several possible sources:
* 1. Sails configuration `config/routes.js` route target objects (including
* all actions and actions targetting a blueprint action).
* 2. Sails hook initialization `hook.routes.before` or `hook.routes.after`.
* 3. Sails automatic blueprint routes.
*
* Most (all?) actions include the following options:
* - action e.g. 'user/find'
* - _middlewareType e.g. 'BLUEPRINT: find', 'ACTION: user/logout' or 'ACTION: subdir/actions2'
*
* Automatic blueprint routes also include:
* - model - the identity of the model that a particular blueprint action should target
* - alias - for blueprint actions that directly involve an association, indicates the name of the associating attribute
* - associations - copy of `sails.models[identity].associations`
*
* Whilst automatic blueprints `options.model` is set (see above), Sails `parseBlueprintOptions()`
* (see below) uses the model identity parsed from the action 'user/find' --> model 'User', blueprint action 'find'.
* This rule (parsing from action) is used below.
*
* We can pick up `swagger` objects from either custom routes or hook routes.
*
* @see https://sailsjs.com/documentation/reference/request-req/req-options
* @see https://sailsjs.com/documentation/concepts/extending-sails/hooks/hook-specification/routes
* @see https://github.com/balderdashy/sails/blob/master/lib/hooks/blueprints/parse-blueprint-options.js#L58
*/
/*
* Background on shortcut route patterns used to detect blueprint shortcut routes.
*
* The following patterns are used to detect shortcut blueprint routes:
* - GET /:modelIdentity/find
* - GET /:modelIdentity/find/:id
* - GET /:modelIdentity/create
* - GET /:modelIdentity/update/:id
* - GET /:modelIdentity/destroy/:id
* - GET /:modelIdentity/:parentid/:association/add/:childid
* - GET /:modelIdentity/:parentid/:association/remove/:childid
* - GET /:modelIdentity/:parentid/:association/replace?association=[1,2...]
*/
// key is `${verb}|${path}`, used to merge duplicate routes as per notes above
const routeLookup: NameKeyMap<Sails.Route> = {};
const ignoreDuplicateCheck: NameKeyMap<boolean> = {};
return boundRoutes
.map(route => {
const verb = route.verb.toLowerCase();
// ignore RegExp-based routes
if(typeof route.path !== 'string') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const routeKey = verb + '|' + (route.path as any).toString();
if (!ignoreDuplicateCheck[routeKey]) {
ignoreDuplicateCheck[routeKey] = true;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (typeof (route.path as any).exec === 'function') { // test for RegExp
sails.log.warn(`WARNING: sails-hook-swagger-generator: Ignoring regular expression based bound route '${route.verb} ${route.path}' - you will need to document manually if required`);
} else {
sails.log.warn(`WARNING: sails-hook-swagger-generator: Ignoring route with unrecognised path '${route.verb} ${route.path}' - you will need to document manually if required`);
}
}
return undefined;
}
// remove duplicates base on verb+path, merging options (overwriting); see notes above
const routeKey = verb + '|' + route.path;
if(!routeLookup[routeKey]) {
routeLookup[routeKey] = {
...route,
options: { ...route.options }
};
return routeLookup[routeKey];
} else {
Object.assign(routeLookup[routeKey].options, route.options);
return undefined;
}
})
.map(route => {
if(!route) { // ignore removed duplicates
return undefined;
}
const verb = route.verb.toLowerCase();
const routeOptions = route.options;
let _middlewareType, mwtAction;
if (routeOptions._middlewareType) {
// ACTION | BLUEPRINT | CORS HOOK | POLICY | VIEWS HOOK | CSRF HOOK | * HOOK
const match = routeOptions._middlewareType.match(/^([^:]+):\s+(.+)$/);
if (match) {
_middlewareType = match[1].toLowerCase();
mwtAction = match[2];
if (_middlewareType !== 'action' && _middlewareType !== 'blueprint') {
sails.log.silly(`DEBUG: sails-hook-swagger-generator: Ignoring bound route '${route.verb} ${route.path}' bound to middleware of type '${routeOptions._middlewareType}'`);
return undefined;
}
} else {
sails.log.warn(`WARNING: sails-hook-swagger-generator: Ignoring bound route '${route.verb} ${route.path}' bound to middleware with unrecognised type '${routeOptions._middlewareType}'`);
return undefined;
}
} else {
sails.log.verbose(`WARNING: sails-hook-swagger-generator: Ignoring bound route '${route.verb} ${route.path}' as middleware type missing`);
return undefined;
}
const middlewareType = _middlewareType === 'blueprint' ? MiddlewareType.BLUEPRINT : MiddlewareType.ACTION;
const parsedPath = parsePath(route.path);
// model-based (blueprint or other) actions (of the form `{modelIdentity}/{action}`)
const [modelIdentity, blueprintAction, ...tail] = routeOptions.action.split('/');
if (tail.length === 0) {
const model = models[modelIdentity!];
if (model) { // blueprint / model-based action
if (middlewareType === MiddlewareType.BLUEPRINT && mwtAction !== blueprintAction) {
sails.log.warn(`WARNING: sails-hook-swagger-generator: Bound route '${route.verb} ${route.path}' has blueprint action mismatch '${blueprintAction}' != '${routeOptions._middlewareType}' (ignoring)`);
}
let isShortcutBlueprintRoute = false;
// test for shortcut blueprint routes
if (verb === 'get') {
// 1:prefix, 2:identity, 3:shortcut-action, 4:id
const re = /^(\/.+)?\/([^/]+)\/(find|create|update|destroy)(\/:id)?$/;
// 1:prefix, 2:identity, 3:id, 4:association, 5:shortcut-action, 6:id
const re2 = /^(\/.+)?\/([^/]+)\/(:parentid)\/([^/]+)\/(add|remove|replace)(\/:childid)?$/;
if (route.path.match(re) || route.path.match(re2)) {
// XXX TODO check identity & shortcut-action matches action
isShortcutBlueprintRoute = true;
}
}
return {
middlewareType,
verb: verb as HTTPMethodVerb,
...parsedPath, // path & variables
action: routeOptions.action,
actionType: 'function',
model,
associationAliases: routeOptions.alias ? [routeOptions.alias] : [],
blueprintAction,
isShortcutBlueprintRoute,
swagger: routeOptions.swagger,
} as SwaggerRouteInfo;
}
}
// fall-through --> non-model based action
return {
middlewareType,
verb: verb as HTTPMethodVerb,
...parsedPath, // path & variables
action: routeOptions.action || mwtAction || '_unknown',
actionType: 'function',
swagger: routeOptions.swagger,
} as SwaggerRouteInfo;
})
.filter(route => !!route) as SwaggerRouteInfo[];
}
/**
* Load and return details of all Sails controller files and actions.
*
* @note The loading mechanism is taken from Sails.
* @see https://github.com/balderdashy/sails/blob/master/lib/app/private/controller/load-action-modules.js#L27
*
* @param sails
*/
export const parseControllers = async (sails: Sails.Sails): Promise<SwaggerSailsControllers> => {
const controllersLoadedFromDisk = await new Promise((resolve, reject) => {
includeAll.optional({
dirname: sails.config.paths.controllers,
filter: /(^[^.]+\.(?:(?!md|txt).)+$)/,
flatten: true,
keepDirectoryPath: true,
}, (err: Error | string, files: IncludeAll.FilesDictionary) => {
if (err) reject(err);
resolve(files);
});
}) as IncludeAll.FilesDictionary;
const ret: SwaggerSailsControllers = {
controllerFiles: {},
actions: {}
};
// Traditional controllers are PascalCased and end with the word "Controller".
const traditionalRegex = new RegExp('^((?:(?:.*)/)*([0-9A-Z][0-9a-zA-Z_]*))Controller\\..+$');
// Actions are kebab-cased.
const actionRegex = new RegExp('^((?:(?:.*)/)*([a-z][a-z0-9-]*))\\..+$');
forEach(controllersLoadedFromDisk, (moduleDef) => {
let filePath = moduleDef.globalId;
if (filePath[0] === '.') { return; }
if (path.dirname(filePath) !== '.') {
filePath = path.dirname(filePath).replace(/\./g, '/') + '/' + path.basename(filePath);
}
/* traditional controllers */
let match = traditionalRegex.exec(filePath);
if (match) {
if (!isObject(moduleDef) || isArray(moduleDef) || isFunction(moduleDef)) { return; }
const moduleIdentity = match[1].toLowerCase();
const defaultTagName = path.basename(match[1]);
// store keyed on controller file identity
ret.controllerFiles[moduleIdentity] = {
...moduleDef,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
swagger: (moduleDef as any).swagger || {},
actionType: 'controller',
defaultTagName
};
// check for swagger.actions[] for which action dne AND convert to case-insensitive identities
const swaggerActions: NameKeyMap<SwaggerActionAttribute> = {};
forEach(ret.controllerFiles[moduleIdentity].swagger.actions || {}, (swaggerDef, actionName) => {
if (actionName === 'allActions') {
// proceed
} else if(!moduleDef[actionName]) {
sails.log.warn(`WARNING: sails-hook-swagger-generator: Controller '${filePath}' contains Swagger action definition for unknown action '${actionName}'`);
return;
}
const actionIdentity = actionName.toLowerCase();
if(swaggerActions[actionIdentity]) {
sails.log.warn(`WARNING: sails-hook-swagger-generator: Controller '${filePath}' contains Swagger action definition '${actionName}' which conflicts with a previously-loaded definition`);
}
swaggerActions[actionIdentity] = swaggerDef;
});
ret.controllerFiles[moduleIdentity].swagger.actions = swaggerActions;
forEach(moduleDef, (action, actionName) => {
if (isString(action)) { /* ignore */ return; }
else if (actionName === '_config') { /* ignore */ return; }
else if(actionName === 'swagger') { /* ignore */ return; }
else if(isFunction(action)) {
const actionIdentity = (moduleIdentity + '/' + actionName).toLowerCase();
if(ret.actions[actionIdentity]) {
// conflict --> dealt with by Sails loader so just ignore here
} else {
ret.actions[actionIdentity] = {
actionType: 'controller',
defaultTagName,
fn: action,
};
const _action = action as AnnotatedFunction;
if(_action.swagger) {
ret.actions[actionIdentity].swagger = _action.swagger;
}
}
}
});
/* else actions (standalone or actions2) */
} else if ((match = actionRegex.exec(filePath))) {
const actionIdentity = match[1].toLowerCase();
if (ret.actions[actionIdentity]) {
// conflict --> dealt with by Sails loader so just ignore here
return;
}
const actionType: ActionType = isFunction(moduleDef) ? 'standalone' : 'actions2';
const defaultTagName = path.basename(match[1]);
// store keyed on controller file identity
ret.controllerFiles[actionIdentity] = {
...moduleDef,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
swagger: (moduleDef as any).swagger || {},
actionType,
defaultTagName
};
if(isFunction(moduleDef)) {
ret.actions[actionIdentity] = {
actionType,
defaultTagName: path.basename(match[1]),
fn: moduleDef,
}
const _action = moduleDef as AnnotatedFunction;
if (_action.swagger) {
ret.actions[actionIdentity].swagger = _action.swagger;
}
} else if(!isUndefined(moduleDef.machine) || !isUndefined(moduleDef.friendlyName) || isFunction(moduleDef.fn)) {
// note no swagger here as this is captured at the controller file level above
ret.actions[actionIdentity] = {
actionType,
defaultTagName,
...(omit(moduleDef, 'swagger') as unknown as Sails.Actions2Machine)
};
}
// check for swagger.actions[] for which action dne
forEach(ret.controllerFiles[actionIdentity].swagger.actions || {}, (swaggerDef, actionName) => {
if (actionName === 'allActions') return;
if(actionName !== defaultTagName) {
sails.log.warn(`WARNING: sails-hook-swagger-generator: ${ret.actions[actionIdentity].actionType} action '${filePath}' contains Swagger action definition for unknown action '${actionName}' (expected '${defaultTagName}')`);
}
});
}
});
return ret;
}
/**
* Loads and parses model JSDoc, returning a map keyed on model identity.
*
* @note Identities lowercase.
*
* @param sails
* @param models
*/
export const parseModelsJsDoc = async (sails: Sails.Sails, models: NameKeyMap<SwaggerSailsModel>):
Promise<NameKeyMap<SwaggerModelAttribute>> => {
const ret: NameKeyMap<SwaggerModelAttribute> = {};
await Promise.all(
map(models, async (model, identity) => {
try {
const modelFile = require.resolve(path.join(sails.config.paths.models, model.globalId));
const swaggerDoc = await loadSwaggerDocComments(modelFile);
const modelJsDocPath = '/' + model.globalId;
ret[identity] = {
tags: swaggerDoc.tags,
components: swaggerDoc.components,
actions: {},
};
// check for paths for which an action dne AND convert to case-insensitive identities
forEach(swaggerDoc.paths, (swaggerDef, actionName) => {
if(actionName === modelJsDocPath) {
return;
} else if(actionName === '/allActions') {
// proceed
} else if (!actionName.startsWith('/') || !blueprintActions.includes(actionName.slice(1) as BluePrintAction)) {
sails.log.warn(`WARNING: sails-hook-swagger-generator: Model file '${model.globalId}' contains Swagger JSDoc action definition for unknown blueprint action '${actionName}'`);
return;
}
const actionIdentity = actionName.substring(1).toLowerCase(); // convert '/{action}' --> '{action}'
if (ret[identity].actions![actionIdentity]) {
sails.log.warn(`WARNING: sails-hook-swagger-generator: Model file '${model.globalId}' contains Swagger JSDoc action definition '${actionName}' which conflicts with a previously-loaded definition`);
}
// note coercion as non-standard swaggerDoc i.e. '/{action}' contains operation contents (no HTTP method specified)
ret[identity].actions![actionIdentity] = swaggerDef as SwaggerActionAttribute;
});
const modelJsDoc = swaggerDoc.paths['/' + model.globalId];
if(modelJsDoc) {
// note coercion as non-standard swaggerDoc i.e. '/{globalId}' contains operation contents (no HTTP method specified)
ret[identity].modelSchema = modelJsDoc as SwaggerModelSchemaAttribute;
}
} catch (err) {
sails.log.error(`ERROR: sails-hook-swagger-generator: Error resolving/loading model ${model.globalId}: ${err.message || ''}` /* , err */);
}
})
);
return ret;
}
/**
* Loads and parses controller JSDoc, returning a map keyed on controller file identity.
*
* @note Identities lowercase.
*
* @param sails
* @param controllers
*/
export const parseControllerJsDoc = async (sails: Sails.Sails, controllers: SwaggerSailsControllers):
Promise<NameKeyMap<SwaggerControllerAttribute>> => {
const ret: NameKeyMap<SwaggerControllerAttribute> = {};
await Promise.all(
map(controllers.controllerFiles, async (controller, identity) => {
try {
const controllerFile = path.join(sails.config.paths.controllers, controller.globalId);
const swaggerDoc = await loadSwaggerDocComments(controllerFile);
ret[identity] = {
tags: swaggerDoc.tags,
components: swaggerDoc.components,
actions: {},
};
// check for paths for which an action dne AND convert to case-insensitive identities
forEach(swaggerDoc.paths, (swaggerDef, actionName) => {
if(actionName === '/allActions') {
// proceed
} else if (controller.actionType === 'standalone' || controller.actionType === 'actions2') {
if(actionName !== `/${controller.defaultTagName}`) {
sails.log.warn(`WARNING: sails-hook-swagger-generator: ${controller.actionType} action '${controller.globalId}' contains Swagger JSDoc action definition for unknown action '${actionName}' (expected '/${controller.defaultTagName}')`);
return;
}
} else {
if (!actionName.startsWith('/') || !controller[actionName.slice(1)]) {
sails.log.warn(`WARNING: sails-hook-swagger-generator: Controller file '${controller.globalId}' contains Swagger JSDoc action defintion for unknown action '${actionName}'`);
return;
}
}
const actionIdentity = actionName.substring(1).toLowerCase(); // convert '/{action}' --> '{action}'
if (ret[identity].actions![actionIdentity]) {
sails.log.warn(`WARNING: sails-hook-swagger-generator: Controller file '${controller.globalId}' contains Swagger JSDoc action definition '${actionName}' which conflicts with a previously-loaded definition`);
}
// note coercion as non-standard swaggerDoc i.e. '/{action}' contains operation contents (no HTTP method specified)
ret[identity].actions![actionIdentity] = swaggerDef as SwaggerActionAttribute;
});
} catch (err) {
sails.log.error(`ERROR: sails-hook-swagger-generator: Error resolving/loading controller ${controller.globalId}: ${err.message || ''}` /* , err */);
}
})
);
return ret;
} | the_stack |
import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import * as chartjs from 'chart.js'
import * as $ from 'jquery';
import {DlaasService} from '../shared/services';
@Component({
selector: 'analytics-main',
templateUrl: './main.component.html',
encapsulation: ViewEncapsulation.None
})
export class AnalyticsMainComponent implements OnInit {
charts: any[] = [];
time_from: any = 0;
time_to: any = 0;
constructor(private dlaas: DlaasService) {
}
ngOnInit() {
this.show('dailyJobs');
this.loadCharts();
}
// TODO: make this more efficient by either
// (1) filtering server-side, or
// (2) not reloading the data when filtering client-side
filterDates(entries: Map<string, any>[]): Map<string, any>[] {
let result: Map<string, any>[] = [];
this.time_from = parseInt(this.time_from);
this.time_to = parseInt(this.time_to);
if(this.time_from < 2000000000) {
this.time_from *= 1000;
}
if(this.time_to < 2000000000) {
this.time_to *= 1000;
}
var self = this;
entries.forEach(function(entry) {
var date = Date.parse(entry['training_status']['submission_timestamp']);
if((self.time_from <= 0 || date >= self.time_from) &&
(self.time_to <= 0 || date <= self.time_to)) {
result.push(entry);
}
});
return result;
}
mergeEntries(data: Map<string, any>): Map<string, any>[] {
let result: Map<string, any>[] = [];
for (var key in data) {
Array.prototype.push.apply(result, data[key]);
}
result = this.filterDates(result);
return result;
}
extractMap(data: any[], keyFunction: (name: any) => string) {
var result = {};
data.forEach(function (entry) {
var key = keyFunction(entry);
if (!result[key]) {
result[key] = [];
}
result[key].push(entry);
});
return result;
}
extractDays(data: any) {
return this.extractMap(data, function (entry) {
return entry.training_status.submission_timestamp.substring(0, 10);
});
}
extractCPUs(data: any) {
return this.extractMap(data, function (entry) {
return entry.training.resources.cpus;
});
}
extractGPUs(data: any) {
return this.extractMap(data, function (entry) {
return entry.training.resources.gpus;
});
}
extractGPUsSum(data: any) {
return this.extractMap(data, function (entry) {
var learners = entry.training.resources.learners || 1;
return (entry.training.resources.gpus * learners).toString();
});
}
extractFrameworks(data: any) {
return this.extractMap(data, function (entry) {
return entry.model_definition.framework.name;
});
}
extractLearners(data: any) {
return this.extractMap(data, function (entry) {
return entry.training.resources.learners;
});
}
chartDailyUsers(data: any) {
var entries = this.mergeEntries(data['results']);
var daysMap = this.extractDays(entries);
var days = Object.keys(daysMap).sort();
var list: any[] = [];
days.forEach(function (day) {
var users: string[] = [];
daysMap[day].forEach(function (entry: any) {
if (users.indexOf(entry.user_id) < 0) {
users.push(entry.user_id);
}
});
list.push(users.length);
});
this.renderChart('chart_dailyUsers', 'Daily Users', list, days);
}
chartDailyJobs(data: Map<string,any>) {
var entries = this.mergeEntries(data["results"]);
var daysMap = this.extractDays(entries);
var days = Object.keys(daysMap).sort();
var values: number[] = [];
days.forEach(function (day) {
values.push(daysMap[day].length);
});
this.renderChart('chart_dailyJobs', 'Daily Jobs', values, days);
}
chartGPUsTimeline(data: any) {
var entries = this.mergeEntries(data.results);
var daysMap = this.extractDays(entries);
var days = Object.keys(daysMap).sort();
var values: number[] = [];
days.forEach(function (day) {
var gpusSum = 0;
daysMap[day].forEach(function (entry: any) {
gpusSum += entry.training.resources.gpus;
});
values.push(gpusSum);
});
this.renderChart('chart_GPUs_timeline', 'Daily GPU Usage', values, days);
}
chartCPUs(data: any) {
var entries = this.mergeEntries(data.results);
var cpusMap = this.extractCPUs(entries);
var cpus = Object.keys(cpusMap);
var values: number[] = [];
cpus.forEach(function (cpu) {
values.push(cpusMap[cpu].length);
});
this.renderChart('chart_CPUs', 'Job CPUs', values, cpus, 'pie');
}
chartGPUs(data: any) {
var entries = this.mergeEntries(data.results);
var gpusMap = this.extractGPUs(entries);
var gpus = Object.keys(gpusMap);
var values: number[] = [];
gpus.forEach(function (gpu) {
values.push(gpusMap[gpu].length);
});
this.renderChart('chart_GPUs', 'GPUs per Trainer', values, gpus, 'pie');
}
chartGPUsSum(data: any) {
var entries = this.mergeEntries(data.results);
var gpusMap = this.extractGPUsSum(entries);
var gpus = Object.keys(gpusMap);
var values: number[] = [];
gpus.forEach(function (gpu) {
values.push(gpusMap[gpu].length);
});
this.renderChart('chart_sumGPUs', 'GPUs per Job', values, gpus, 'pie');
}
chartFrameworks(data: any) {
var entries = this.mergeEntries(data.results);
var map = this.extractFrameworks(entries);
var keys = Object.keys(map);
var values: number[] = [];
keys.forEach(function (key) {
values.push(map[key].length);
});
this.renderChart('chart_frameworks', 'DL Frameworks', values, keys, 'pie');
}
chartLearners(data: any) {
var entries = this.mergeEntries(data.results);
var map = this.extractLearners(entries);
var keys = Object.keys(map);
var values: number[] = [];
keys.forEach(function (key) {
values.push(map[key].length);
});
this.renderChart('chart_learners', '# Learners', values, keys, 'pie');
}
chartQueueingTimes(data: any) {
var buckets = [4, 6, 8, 10, 12, 14, 16, -1];
return this.chartTimes(data, 'queueTimes', 'Queueing Times', buckets,
function(entry) {
return Date.parse(entry.training_status.submission_timestamp);
}, function(entry) {
return Date.parse(entry.training_status.download_start_timestamp);
});
}
chartDownloadTimes(data: any) {
var buckets = [2, 4, 8, 16, 32, 64, 128, -1];
return this.chartTimes(data, 'dlTimes', 'Downloading Times', buckets,
function(entry) {
return Date.parse(entry.training_status.download_start_timestamp);
}, function(entry) {
return Date.parse(entry.training_status.process_start_timestamp);
});
}
chartTrainTimes(data: any) {
return this.chartTimes(data, 'trainTimes', 'Training Times', null,
function(entry) {
return Date.parse(entry.training_status.process_start_timestamp);
}, function(entry) {
return Date.parse(entry.training_status.completion_timestamp);
});
}
chartTimes(data: any, chartID: string, title: string, buckets: any[],
lower: (entry: any) => number, upper: (entry: any) => number) {
var entries = this.mergeEntries(data.results);
if(!buckets) {
buckets = [15, 30, 60, 120, 240, 480, 960, -1];
}
var values: number[] = [];
while(values.length < buckets.length) {
values.push(0);
}
entries.forEach(function (entry) {
var start = lower(entry);
var end = upper(entry);
var duration = end - start;
if(isNaN(duration) || duration <= 0) {
return;
}
for(var i = 0; i < buckets.length; i ++) {
if(buckets[i] < 0 || duration < buckets[i] * 1000) {
values[i] ++;
break;
}
}
});
for(var i = 0; i < buckets.length; i ++) {
buckets[i] = '< ' + buckets[i] + 's';
}
buckets[buckets.length - 1] = 'max';
this.renderChart('chart_' + chartID, title, values, buckets, 'bar');
}
isSourceSelected(source: string) {
return $('#source_' + source).prop('checked');
}
ajax(request: any) {
return $.ajax(request);
}
loadData() {
var sources: any[] = [];
var self = this;
['local', 'cruiser1', 'cruiser2'].forEach(function (source) {
if (self.isSourceSelected(source)) {
sources.push(source);
}
});
return this.dlaas.getTrainingJobs(sources);
}
resetCharts() {
this.charts.forEach(function (chart: any) {
chart.destroy();
});
this.charts = [];
}
renderChart(id: string, title: string, data: any[], ticks: any[], type: string = null) {
var ctx = ($('#' + id)[0] as HTMLCanvasElement).getContext('2d');
var datasets = [];
var entry = {
label: title || 'Chart',
data: data,
backgroundColor: bgColors
};
if (type == 'pie') {
var bgColors: any[] = [];
ticks.forEach(function () {
var color = 'rgb(' + Math.round(Math.random() * 200) + ',' +
Math.round(Math.random() * 200) + ',' +
Math.round(Math.random() * 200) + ')';
bgColors.push(color);
});
entry.backgroundColor = bgColors;
}
datasets.push(entry);
type = type || 'line';
var chart = new chartjs.Chart(ctx, {
type: type,
data: {
labels: ticks,
datasets: datasets
}
});
this.charts.push(chart);
$('#loading').hide();
}
show(id: string) {
$('.content').hide();
$('#div_' + id).show();
$('#div_' + id + ' .content').show();
}
loadCharts() {
$('#loading').show();
$('#errorMsg').text("");
this.resetCharts();
let self = this;
this.loadData().subscribe(function (data: any) {
var dataMap: Map<string,any> = data
self.chartDailyJobs(dataMap);
self.chartDailyUsers(dataMap);
self.chartCPUs(dataMap);
self.chartGPUs(dataMap);
self.chartGPUsSum(dataMap);
self.chartGPUsTimeline(dataMap);
self.chartFrameworks(dataMap);
self.chartLearners(dataMap);
self.chartQueueingTimes(dataMap);
self.chartDownloadTimes(dataMap);
self.chartTrainTimes(dataMap);
}, function (error) {
$('#errorMsg').text("Error loading the data.");
$('#loading').hide();
});
}
} | the_stack |
import { PropOptions } from '@vue/composition-api'
import { castArray, isEqual } from 'lodash'
import { PropType } from 'vue'
import { z } from 'zod'
import { makeProps } from './make-props'
import { silenceConsole } from './test-utils/silence-console'
import { refinementNonEmpty } from './zod-refinements'
declare global {
namespace jest {
interface Matchers<R> {
toBeRequired(): R
toBeType(expectedPropType: PropType<unknown>): R
toDefaultTo(defaultValue: unknown): R
toValidate(...cases: unknown[]): R
}
}
}
expect.extend({
toBeRequired(prop: PropOptions<unknown, boolean>) {
const passNoDefault = prop.default === undefined
const passRequired = prop.required === true
return {
message: () => {
if (!passNoDefault)
return `Expected “prop.default” to be “undefined”. Was “${prop.default}”`
if (!passRequired)
return `Expected “prop.required” to be “true”. Was “${prop.required}”`
return 'valid'
},
pass: passNoDefault && passRequired,
}
},
toBeType(prop: PropOptions<unknown, boolean>, expected: PropType<unknown>) {
const actualPropTypes = new Set(castArray(prop.type as PropType<unknown>))
const expectedPropTypes = new Set(castArray(expected))
const pass = isEqual(actualPropTypes, expectedPropTypes)
return {
message: () =>
pass
? 'valid'
: this.utils.printDiffOrStringify(
expectedPropTypes,
actualPropTypes,
'Expected prop.type',
'Received prop.type',
this.expand,
),
pass,
}
},
toDefaultTo(prop: PropOptions<unknown, boolean>, expectedDefault: unknown) {
if (typeof prop.default !== 'function')
return {
message: () => 'Expected “prop.default” to be a function',
pass: false,
}
const actualDefault = prop.default()
const passDefault = isEqual(actualDefault, expectedDefault)
const passNoRequired = prop.required === undefined
return {
message: () => {
if (!passDefault)
return this.utils.printDiffOrStringify(
expectedDefault,
actualDefault,
'Expected prop.default',
'Received prop.default',
this.expand,
)
if (!passNoRequired)
return this.utils.printDiffOrStringify(
undefined,
prop.required,
'Expected prop.required',
'Received prop.required',
this.expand,
)
return 'valid'
},
pass: passDefault && passNoRequired,
}
},
toValidate(prop: PropOptions<unknown, boolean>, ...cases: unknown[]) {
const { validator } = prop
if (validator === undefined)
return {
message: () => 'Expected prop.validator to exist',
pass: false,
}
const successfulCases = cases.filter((c) => validator(c))
const failedCases = cases.filter((c) => !validator(c))
const wrongCases = this.isNot ? successfulCases : failedCases
const pass = wrongCases.length === 0
return {
message: () => {
if (pass) return 'valid'
const list = wrongCases
.map((x) => `“${JSON.stringify(x)}” (${typeof x})`)
.join(', ')
return `Expected ${list} to be ${
this.isNot ? 'invalid' : 'valid'
} values for the validator`
},
pass: this.isNot ? !pass : pass, // negate as jest expects pass: false for isNot
}
},
})
describe('array', () => {
beforeAll(silenceConsole)
const ARRAY_SUCCESS = [[], [0], [1], [13, 8, 5, 3, 2, 1]]
const ARRAY_FAILURE = [{}, true, false, 'string', [true], [{}], ['string']]
it('generates vue prop for schema “z.array(z.number())”', () => {
const schema = z.object({
prop: z.array(z.number()),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType(Array)
expect(prop).toValidate(...ARRAY_SUCCESS)
expect(prop).not.toValidate(...ARRAY_FAILURE, null, undefined)
})
it('generates vue prop for schema “z.array(z.number()).nullable()”', () => {
const schema = z.object({
prop: z.array(z.number()).nullable(),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType(Array)
expect(prop).toValidate(...ARRAY_SUCCESS, null)
expect(prop).not.toValidate(...ARRAY_FAILURE, undefined)
})
it('generates vue prop for schema “z.array(z.number()).default()”', () => {
const schema = z.object({
prop: z.array(z.number()).default(() => []),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo([])
expect(prop).toBeType(Array)
expect(prop).toValidate(...ARRAY_SUCCESS, undefined)
expect(prop).not.toValidate(...ARRAY_FAILURE, null)
})
it('generates vue prop for schema “z.array(z.number()).nullable().default()”', () => {
const schema = z.object({
prop: z.array(z.number()).nullable().default(null),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo(null)
expect(prop).toBeType(Array)
expect(prop).toValidate(...ARRAY_SUCCESS, null, undefined)
expect(prop).not.toValidate(...ARRAY_FAILURE)
})
it('generates vue prop for schema “z.array(z.number()).nullable().default().refine(...refinementNonEmpty)”', () => {
const schema = z.object({
prop: z
.array(z.number())
.refine(...refinementNonEmpty)
.nullable()
.default(null),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo(null)
expect(prop).toBeType(Array)
expect(prop).toValidate(
...ARRAY_SUCCESS.filter((x) => x.length !== 0),
null,
undefined,
)
expect(prop).not.toValidate(...ARRAY_FAILURE, [])
})
})
describe('boolean', () => {
beforeAll(silenceConsole)
const BOOLEAN_SUCCESS = [true, false]
const BOOLEAN_FAILURE = ['true', 'false', 1, [], {}]
it('generates vue prop for schema “z.boolean()”', () => {
const schema = z.object({
prop: z.boolean(),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType(Boolean)
expect(prop).toValidate(...BOOLEAN_SUCCESS)
expect(prop).not.toValidate(...BOOLEAN_FAILURE, null, undefined)
})
it('generates vue prop for schema “z.boolean().nullable()”', () => {
const schema = z.object({
prop: z.boolean().nullable(),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType(Boolean)
expect(prop).toValidate(...BOOLEAN_SUCCESS, null)
expect(prop).not.toValidate(...BOOLEAN_FAILURE, undefined)
})
it('generates vue prop for schema “z.boolean().default()”', () => {
const schema = z.object({
prop: z.boolean().default(true),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo(true)
expect(prop).toBeType(Boolean)
expect(prop).toValidate(...BOOLEAN_SUCCESS, undefined)
expect(prop).not.toValidate(...BOOLEAN_FAILURE, null)
})
it('generates vue prop for schema “z.boolean().nullable().default()”', () => {
const schema = z.object({
prop: z.boolean().nullable().default(null),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo(null)
expect(prop).toBeType(Boolean)
expect(prop).toValidate(...BOOLEAN_SUCCESS, null, undefined)
expect(prop).not.toValidate(...BOOLEAN_FAILURE)
})
})
describe('date', () => {
beforeAll(silenceConsole)
const getRandomDate = () => new Date(1549312452000)
const DATE_SUCCESS = [new Date(), getRandomDate()]
const DATE_FAILURE = ['true', 'false', 1, [], {}, false]
it('generates vue prop for schema “z.date()”', () => {
const schema = z.object({
prop: z.date(),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType(Date)
expect(prop).toValidate(...DATE_SUCCESS)
expect(prop).not.toValidate(...DATE_FAILURE, null, undefined)
})
it('generates vue prop for schema “z.date().nullable()”', () => {
const schema = z.object({
prop: z.date().nullable(),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType(Date)
expect(prop).toValidate(...DATE_SUCCESS, null)
expect(prop).not.toValidate(...DATE_FAILURE, undefined)
})
it('generates vue prop for schema “z.date().default()”', () => {
const schema = z.object({
prop: z.date().default(getRandomDate()),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo(getRandomDate())
expect(prop).toBeType(Date)
expect(prop).toValidate(...DATE_SUCCESS, undefined)
expect(prop).not.toValidate(...DATE_FAILURE, null)
})
it('generates vue prop for schema “z.date().nullable().default()”', () => {
const schema = z.object({
prop: z.date().nullable().default(null),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo(null)
expect(prop).toBeType(Date)
expect(prop).toValidate(...DATE_SUCCESS, null, undefined)
expect(prop).not.toValidate(...DATE_FAILURE)
})
})
describe('function', () => {
beforeAll(silenceConsole)
const FUNCTION_SUCCESS = [() => null, () => undefined, () => 'test']
const FUNCTION_FAILURE = ['string', true]
it('generates vue prop for schema “z.function()”', () => {
const schema = z.object({
prop: z.function(),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType(Function)
expect(prop).toValidate(...FUNCTION_SUCCESS)
expect(prop).not.toValidate(...FUNCTION_FAILURE, null, undefined)
})
it('generates vue prop for schema “z.function().nullable()”', () => {
const schema = z.object({
prop: z.function().nullable(),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType(Function)
expect(prop).toValidate(...FUNCTION_SUCCESS, null)
expect(prop).not.toValidate(...FUNCTION_FAILURE, undefined)
})
it('generates vue prop for schema “z.function().default()”', () => {
const schema = z.object({
prop: z.function().default(() => undefined),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo(undefined)
expect(prop).toBeType(Function)
expect(prop).toValidate(...FUNCTION_SUCCESS) // see below
expect(prop).not.toValidate(...FUNCTION_FAILURE, null)
/**
* HACK: This is actually a minor bug in zod, theoretically this
* should be true, however `.function().default()` doesn’t set
* this to optional correctly. This can be safely ignored
* since vue doesn’t even run the validator when passing `undefined`
*
* @see {@link https://github.com/colinhacks/zod/issues/647}
*/
expect(prop).not.toValidate(undefined)
})
it('generates vue prop for schema “z.function().nullable().default()”', () => {
const schema = z.object({
prop: z.function().nullable().default(null),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo(null)
expect(prop).toBeType(Function)
expect(prop).toValidate(...FUNCTION_SUCCESS, null, undefined)
expect(prop).not.toValidate(...FUNCTION_FAILURE)
})
})
describe('nativeEnum', () => {
beforeAll(silenceConsole)
enum TestEnum {
KEY_A = 'VALUE_A',
KEY_B = 'VALUE_B',
KEY_C = 'VALUE_C',
}
const ENUM_SUCCESS = [TestEnum.KEY_A, TestEnum.KEY_B, TestEnum.KEY_C]
const ENUM_FAILURE = ['VALUE_D', 'string', [], {}, false]
it('generates vue prop for schema “z.nativeEnum()”', () => {
const schema = z.object({
prop: z.nativeEnum(TestEnum),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType(String)
expect(prop).toValidate(...ENUM_SUCCESS)
expect(prop).not.toValidate(...ENUM_FAILURE, null, undefined)
})
it('generates vue prop for schema “z.nativeEnum().nullable()”', () => {
const schema = z.object({
prop: z.nativeEnum(TestEnum).nullable(),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType(String)
expect(prop).toValidate(...ENUM_SUCCESS, null)
expect(prop).not.toValidate(...ENUM_FAILURE, undefined)
})
it('generates vue prop for schema “z.nativeEnum().default()”', () => {
const schema = z.object({
prop: z.nativeEnum(TestEnum).default(() => TestEnum.KEY_A),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo(TestEnum.KEY_A)
expect(prop).toBeType(String)
expect(prop).toValidate(...ENUM_SUCCESS, undefined)
expect(prop).not.toValidate(...ENUM_FAILURE, null)
})
it('generates vue prop for schema “z.nativeEnum().nullable().default()”', () => {
const schema = z.object({
prop: z.nativeEnum(TestEnum).nullable().default(null),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo(null)
expect(prop).toBeType(String)
expect(prop).toValidate(...ENUM_SUCCESS, null, undefined)
expect(prop).not.toValidate(...ENUM_FAILURE)
})
})
const NUMBER_SUCCESS = [
-1,
0,
1,
1.5,
42,
Number.EPSILON,
Number.MAX_SAFE_INTEGER,
Number.MIN_SAFE_INTEGER,
Number.MAX_VALUE,
Number.MIN_VALUE,
Number.POSITIVE_INFINITY, // See https://github.com/colinhacks/zod/issues/512
Number.NEGATIVE_INFINITY, // See https://github.com/colinhacks/zod/issues/512
]
describe('number', () => {
beforeAll(silenceConsole)
const NUMBER_FAILURE = [{}, [], 'string', false, Number.NaN]
it('generates vue prop for schema “z.number()”', () => {
const schema = z.object({
prop: z.number(),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType(Number)
expect(prop).toValidate(...NUMBER_SUCCESS)
expect(prop).not.toValidate(...NUMBER_FAILURE, null, undefined)
})
it('generates vue prop for schema “z.number().nullable()”', () => {
const schema = z.object({
prop: z.number().nullable(),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType(Number)
expect(prop).toValidate(...NUMBER_SUCCESS, null)
expect(prop).not.toValidate(...NUMBER_FAILURE, undefined)
})
it('generates vue prop for schema “z.number().default()”', () => {
const schema = z.object({
prop: z.number().default(1),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo(1)
expect(prop).toBeType(Number)
expect(prop).toValidate(...NUMBER_SUCCESS, undefined)
expect(prop).not.toValidate(...NUMBER_FAILURE, null)
})
it('generates vue prop for schema “z.number().nullable().default()”', () => {
const schema = z.object({
prop: z.number().nullable().default(null),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo(null)
expect(prop).toBeType(Number)
expect(prop).toValidate(...NUMBER_SUCCESS, null, undefined)
expect(prop).not.toValidate(...NUMBER_FAILURE)
})
})
describe('number.int', () => {
beforeAll(silenceConsole)
const NUMBER_INT_SUCCESS = [
-1,
0,
1,
42,
Number.MAX_SAFE_INTEGER,
Number.MIN_SAFE_INTEGER,
]
const NUMBER_INT_FAILURE = [
'string',
[],
{},
1.5,
false,
Number.EPSILON,
Number.NaN,
Number.NEGATIVE_INFINITY,
Number.POSITIVE_INFINITY,
]
it('generates vue prop for schema “z.number().int()”', () => {
const schema = z.object({
prop: z.number().int(),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType(Number)
expect(prop).toValidate(...NUMBER_INT_SUCCESS)
expect(prop).not.toValidate(...NUMBER_INT_FAILURE, null, undefined)
})
it('generates vue prop for schema “z.number().int().nullable()”', () => {
const schema = z.object({
prop: z.number().int().nullable(),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType(Number)
expect(prop).toValidate(...NUMBER_INT_SUCCESS, null)
expect(prop).not.toValidate(...NUMBER_INT_FAILURE, undefined)
})
it('generates vue prop for schema “z.number().int().default()”', () => {
const schema = z.object({
prop: z.number().int().default(1),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo(1)
expect(prop).toBeType(Number)
expect(prop).toValidate(...NUMBER_INT_SUCCESS, undefined)
expect(prop).not.toValidate(...NUMBER_INT_FAILURE, null)
})
it('generates vue prop for schema “z.number().int().nullable().default()”', () => {
const schema = z.object({
prop: z.number().int().nullable().default(null),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo(null)
expect(prop).toBeType(Number)
expect(prop).toValidate(...NUMBER_INT_SUCCESS, null, undefined)
expect(prop).not.toValidate(...NUMBER_INT_FAILURE)
})
})
describe('object', () => {
beforeAll(silenceConsole)
const OBJECT_SUCCESS = [
{ key: true },
{ key: false },
{ key: true, otherKey: 'no' },
]
const OBJECT_FAILURE = [{ key: null }, {}, [], 'string']
it('generates vue prop for schema “z.object()”', () => {
const schema = z.object({
prop: z.object({ key: z.boolean() }),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType(Object)
expect(prop).toValidate(...OBJECT_SUCCESS)
expect(prop).not.toValidate(...OBJECT_FAILURE, null, undefined)
})
it('generates vue prop for schema “z.object().nullable()”', () => {
const schema = z.object({
prop: z.object({ key: z.boolean() }).nullable(),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType(Object)
expect(prop).toValidate(...OBJECT_SUCCESS, null)
expect(prop).not.toValidate(...OBJECT_FAILURE, undefined)
})
it('generates vue prop for schema “z.object().default()”', () => {
const schema = z.object({
prop: z.object({ key: z.boolean() }).default(() => ({ key: true })),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo({ key: true })
expect(prop).toBeType(Object)
expect(prop).toValidate(...OBJECT_SUCCESS, undefined)
expect(prop).not.toValidate(...OBJECT_FAILURE, null)
})
it('generates vue prop for schema “z.object().nullable().default()”', () => {
const schema = z.object({
prop: z.object({ key: z.boolean() }).nullable().default(null),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo(null)
expect(prop).toBeType(Object)
expect(prop).toValidate(...OBJECT_SUCCESS, null, undefined)
expect(prop).not.toValidate(...OBJECT_FAILURE)
})
})
const STRING_SUCCESS = ['string', '']
describe('string', () => {
beforeAll(silenceConsole)
const STRING_FAILURE = [[], {}, 0, 1]
it('generates vue prop for schema “z.string()”', () => {
const schema = z.object({
prop: z.string(),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType(String)
expect(prop).toValidate(...STRING_SUCCESS)
expect(prop).not.toValidate(...STRING_FAILURE, null, undefined)
})
it('generates vue prop for schema “z.string().nullable()”', () => {
const schema = z.object({
prop: z.string().nullable(),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType(String)
expect(prop).toValidate(...STRING_SUCCESS, null)
expect(prop).not.toValidate(...STRING_FAILURE, undefined)
})
it('generates vue prop for schema “z.string().default()”', () => {
const schema = z.object({
prop: z.string().default('test'),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo('test')
expect(prop).toBeType(String)
expect(prop).toValidate(...STRING_SUCCESS, undefined)
expect(prop).not.toValidate(...STRING_FAILURE, null)
})
it('generates vue prop for schema “z.string().nullable().default()”', () => {
const schema = z.object({
prop: z.string().nullable().default(null),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo(null)
expect(prop).toBeType(String)
expect(prop).toValidate(...STRING_SUCCESS, null, undefined)
expect(prop).not.toValidate(...STRING_FAILURE)
})
})
describe('union', () => {
beforeAll(silenceConsole)
const UNION_SUCCESS = [...NUMBER_SUCCESS, ...STRING_SUCCESS]
const UNION_FAILURE = [[], {}, true, false]
it('generates vue prop for schema “z.union()”', () => {
const schema = z.object({
prop: z.union([z.number(), z.string()]),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType([Number, String])
expect(prop).toValidate(...UNION_SUCCESS)
expect(prop).not.toValidate(...UNION_FAILURE, null, undefined)
})
it('generates vue prop for schema “z.union().nullable()”', () => {
const schema = z.object({
prop: z.union([z.number(), z.string()]).nullable(),
})
const { prop } = makeProps(schema)
expect(prop).toBeRequired()
expect(prop).toBeType([Number, String])
expect(prop).toValidate(...UNION_SUCCESS, null)
expect(prop).not.toValidate(...UNION_FAILURE, undefined)
})
it('generates vue prop for schema “z.union().default()”', () => {
const schema = z.object({
prop: z.union([z.number(), z.string()]).default('test'),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo('test')
expect(prop).toBeType([Number, String])
expect(prop).toValidate(...UNION_SUCCESS, undefined)
expect(prop).not.toValidate(...UNION_FAILURE, null)
})
it('generates vue prop for schema “z.union().nullable().default()”', () => {
const schema = z.object({
prop: z.union([z.number(), z.string()]).nullable().default(null),
})
const { prop } = makeProps(schema)
expect(prop).toDefaultTo(null)
expect(prop).toBeType([Number, String])
expect(prop).toValidate(...UNION_SUCCESS, null, undefined)
expect(prop).not.toValidate(...UNION_FAILURE)
})
}) | the_stack |
import crypto from 'crypto';
import { promisify } from 'util';
import { deflateRaw } from 'zlib';
import * as dbutils from '../db/utils';
import * as metrics from '../opentelemetry/metrics';
import saml from '@boxyhq/saml20';
import claims from '../saml/claims';
import {
IOAuthController,
JacksonOption,
OAuthReqBody,
OAuthTokenReq,
OAuthTokenRes,
Profile,
SAMLResponsePayload,
Storable,
} from '../typings';
import { JacksonError } from './error';
import * as allowed from './oauth/allowed';
import * as codeVerifier from './oauth/code-verifier';
import * as redirect from './oauth/redirect';
import { relayStatePrefix, IndexNames, OAuthErrorResponse, getErrorMessage } from './utils';
const deflateRawAsync = promisify(deflateRaw);
const validateResponse = async (rawResponse: string, validateOpts) => {
const profile = await saml.validate(rawResponse, validateOpts);
if (profile && profile.claims) {
// we map claims to our attributes id, email, firstName, lastName where possible. We also map original claims to raw
profile.claims = claims.map(profile.claims);
// some providers don't return the id in the assertion, we set it to a sha256 hash of the email
if (!profile.claims.id && profile.claims.email) {
profile.claims.id = crypto.createHash('sha256').update(profile.claims.email).digest('hex');
}
}
return profile;
};
function getEncodedTenantProduct(param: string): { tenant: string | null; product: string | null } | null {
try {
const sp = new URLSearchParams(param);
const tenant = sp.get('tenant');
const product = sp.get('product');
if (tenant && product) {
return {
tenant: sp.get('tenant'),
product: sp.get('product'),
};
}
return null;
} catch (err) {
return null;
}
}
export class OAuthController implements IOAuthController {
private configStore: Storable;
private sessionStore: Storable;
private codeStore: Storable;
private tokenStore: Storable;
private opts: JacksonOption;
constructor({ configStore, sessionStore, codeStore, tokenStore, opts }) {
this.configStore = configStore;
this.sessionStore = sessionStore;
this.codeStore = codeStore;
this.tokenStore = tokenStore;
this.opts = opts;
}
private resolveMultipleConfigMatches(
samlConfigs,
idp_hint,
originalParams,
isIdpFlow = false
): { resolvedSamlConfig?: unknown; redirect_url?: string; app_select_form?: string } {
if (samlConfigs.length > 1) {
if (idp_hint) {
return { resolvedSamlConfig: samlConfigs.find(({ clientID }) => clientID === idp_hint) };
} else if (this.opts.idpDiscoveryPath) {
if (!isIdpFlow) {
// redirect to IdP selection page
const idpList = samlConfigs.map(({ idpMetadata: { provider }, clientID }) =>
JSON.stringify({
provider,
clientID,
})
);
return {
redirect_url: redirect.success(this.opts.externalUrl + this.opts.idpDiscoveryPath, {
...originalParams,
idp: idpList,
}),
};
} else {
const appList = samlConfigs.map(({ product, name, description, clientID }) => ({
product,
name,
description,
clientID,
}));
return {
app_select_form: saml.createPostForm(this.opts.idpDiscoveryPath, [
{
name: 'SAMLResponse',
value: originalParams.SAMLResponse,
},
{
name: 'app',
value: encodeURIComponent(JSON.stringify(appList)),
},
]),
};
}
}
}
return {};
}
public async authorize(body: OAuthReqBody): Promise<{ redirect_url?: string; authorize_form?: string }> {
const {
response_type = 'code',
client_id,
redirect_uri,
state,
tenant,
product,
access_type,
scope,
code_challenge,
code_challenge_method = '',
// eslint-disable-next-line @typescript-eslint/no-unused-vars
provider = 'saml',
idp_hint,
} = body;
let requestedTenant = tenant;
let requestedProduct = product;
metrics.increment('oauthAuthorize');
if (!redirect_uri) {
throw new JacksonError('Please specify a redirect URL.', 400);
}
let samlConfig;
if (tenant && product) {
const samlConfigs = await this.configStore.getByIndex({
name: IndexNames.TenantProduct,
value: dbutils.keyFromParts(tenant, product),
});
if (!samlConfigs || samlConfigs.length === 0) {
throw new JacksonError('SAML configuration not found.', 403);
}
samlConfig = samlConfigs[0];
// Support multiple matches
const { resolvedSamlConfig, redirect_url } = this.resolveMultipleConfigMatches(samlConfigs, idp_hint, {
response_type,
client_id,
redirect_uri,
state,
tenant,
product,
code_challenge,
code_challenge_method,
provider,
});
if (redirect_url) {
return { redirect_url };
}
if (resolvedSamlConfig) {
samlConfig = resolvedSamlConfig;
}
} else if (client_id && client_id !== '' && client_id !== 'undefined' && client_id !== 'null') {
// if tenant and product are encoded in the client_id then we parse it and check for the relevant config(s)
let sp = getEncodedTenantProduct(client_id);
if (!sp && access_type) {
sp = getEncodedTenantProduct(access_type);
}
if (!sp && scope) {
sp = getEncodedTenantProduct(scope);
}
if (sp && sp.tenant && sp.product) {
requestedTenant = sp.tenant;
requestedProduct = sp.product;
const samlConfigs = await this.configStore.getByIndex({
name: IndexNames.TenantProduct,
value: dbutils.keyFromParts(sp.tenant, sp.product),
});
if (!samlConfigs || samlConfigs.length === 0) {
throw new JacksonError('SAML configuration not found.', 403);
}
samlConfig = samlConfigs[0];
// Support multiple matches
const { resolvedSamlConfig, redirect_url } = this.resolveMultipleConfigMatches(
samlConfigs,
idp_hint,
{
response_type,
client_id,
redirect_uri,
state,
tenant,
product,
code_challenge,
code_challenge_method,
provider,
}
);
if (redirect_url) {
return { redirect_url };
}
if (resolvedSamlConfig) {
samlConfig = resolvedSamlConfig;
}
} else {
samlConfig = await this.configStore.get(client_id);
if (samlConfig) {
requestedTenant = samlConfig.tenant;
requestedProduct = samlConfig.product;
}
}
} else {
throw new JacksonError('You need to specify client_id or tenant & product', 403);
}
if (!samlConfig) {
throw new JacksonError('SAML configuration not found.', 403);
}
if (!allowed.redirect(redirect_uri, samlConfig.redirectUrl)) {
throw new JacksonError('Redirect URL is not allowed.', 403);
}
if (!state) {
return {
redirect_url: OAuthErrorResponse({
error: 'invalid_request',
error_description: 'Please specify a state to safeguard against XSRF attacks',
redirect_uri,
}),
};
}
if (response_type !== 'code') {
return {
redirect_url: OAuthErrorResponse({
error: 'unsupported_response_type',
error_description: 'Only Authorization Code grant is supported',
redirect_uri,
}),
};
}
let ssoUrl;
let post = false;
const { sso } = samlConfig.idpMetadata;
if ('redirectUrl' in sso) {
// HTTP Redirect binding
ssoUrl = sso.redirectUrl;
} else if ('postUrl' in sso) {
// HTTP-POST binding
ssoUrl = sso.postUrl;
post = true;
} else {
return {
redirect_url: OAuthErrorResponse({
error: 'invalid_request',
error_description: 'SAML binding could not be retrieved',
redirect_uri,
}),
};
}
try {
const samlReq = saml.request({
ssoUrl,
entityID: this.opts.samlAudience!,
callbackUrl: this.opts.externalUrl + this.opts.samlPath,
signingKey: samlConfig.certs.privateKey,
publicKey: samlConfig.certs.publicKey,
});
const sessionId = crypto.randomBytes(16).toString('hex');
const requested = { client_id, state } as Record<string, string>;
if (requestedTenant) {
requested.tenant = requestedTenant;
}
if (requestedProduct) {
requested.product = requestedProduct;
}
if (idp_hint) {
requested.idp_hint = idp_hint;
}
await this.sessionStore.put(sessionId, {
id: samlReq.id,
redirect_uri,
response_type,
state,
code_challenge,
code_challenge_method,
requested,
});
const relayState = relayStatePrefix + sessionId;
let redirectUrl;
let authorizeForm;
if (!post) {
// HTTP Redirect binding
redirectUrl = redirect.success(ssoUrl, {
RelayState: relayState,
SAMLRequest: Buffer.from(await deflateRawAsync(samlReq.request)).toString('base64'),
});
} else {
// HTTP POST binding
authorizeForm = saml.createPostForm(ssoUrl, [
{
name: 'RelayState',
value: relayState,
},
{
name: 'SAMLRequest',
value: Buffer.from(samlReq.request).toString('base64'),
},
]);
}
return {
redirect_url: redirectUrl,
authorize_form: authorizeForm,
};
} catch (err: unknown) {
return {
redirect_url: OAuthErrorResponse({
error: 'server_error',
error_description: getErrorMessage(err),
redirect_uri,
}),
};
}
}
public async samlResponse(
body: SAMLResponsePayload
): Promise<{ redirect_url?: string; app_select_form?: string }> {
const { SAMLResponse, idp_hint } = body;
let RelayState = body.RelayState || ''; // RelayState will contain the sessionId from earlier quasi-oauth flow
const isIdPFlow = !RelayState.startsWith(relayStatePrefix);
if (!this.opts.idpEnabled && isIdPFlow) {
// IDP is disabled so block the request
throw new JacksonError(
'IdP (Identity Provider) flow has been disabled. Please head to your Service Provider to login.',
403
);
}
RelayState = RelayState.replace(relayStatePrefix, '');
const rawResponse = Buffer.from(SAMLResponse, 'base64').toString();
const issuer = saml.parseIssuer(rawResponse);
if (!issuer) {
throw new JacksonError('Issuer not found.', 403);
}
const samlConfigs = await this.configStore.getByIndex({
name: IndexNames.EntityID,
value: issuer,
});
if (!samlConfigs || samlConfigs.length === 0) {
throw new JacksonError('SAML configuration not found.', 403);
}
let samlConfig = samlConfigs[0];
if (isIdPFlow) {
RelayState = '';
const { resolvedSamlConfig, app_select_form } = this.resolveMultipleConfigMatches(
samlConfigs,
idp_hint,
{ SAMLResponse },
true
);
if (app_select_form) {
return { app_select_form };
}
if (resolvedSamlConfig) {
samlConfig = resolvedSamlConfig;
}
}
let session;
if (RelayState !== '') {
session = await this.sessionStore.get(RelayState);
if (!session) {
throw new JacksonError('Unable to validate state from the origin request.', 403);
}
}
if (!isIdPFlow) {
// Resolve if there are multiple matches for SP login. TODO: Support multiple matches for IdP login
samlConfig =
samlConfigs.length === 1
? samlConfigs[0]
: samlConfigs.filter((c) => {
return (
c.clientID === session?.requested?.client_id ||
(c.tenant === session?.requested?.tenant && c.product === session?.requested?.product)
);
})[0];
}
if (!samlConfig) {
throw new JacksonError('SAML configuration not found.', 403);
}
const validateOpts: Record<string, string> = {
thumbprint: samlConfig.idpMetadata.thumbprint,
audience: this.opts.samlAudience!,
privateKey: samlConfig.certs.privateKey,
};
if (session && session.redirect_uri && !allowed.redirect(session.redirect_uri, samlConfig.redirectUrl)) {
throw new JacksonError('Redirect URL is not allowed.', 403);
}
if (session && session.id) {
validateOpts.inResponseTo = session.id;
}
let profile;
const redirect_uri = (session && session.redirect_uri) || samlConfig.defaultRedirectUrl;
try {
profile = await validateResponse(rawResponse, validateOpts);
} catch (err: unknown) {
// return error to redirect_uri
return {
redirect_url: OAuthErrorResponse({
error: 'access_denied',
error_description: getErrorMessage(err),
redirect_uri,
}),
};
}
// store details against a code
const code = crypto.randomBytes(20).toString('hex');
const codeVal: Record<string, unknown> = {
profile,
clientID: samlConfig.clientID,
clientSecret: samlConfig.clientSecret,
requested: session?.requested,
};
if (session) {
codeVal.session = session;
}
try {
await this.codeStore.put(code, codeVal);
} catch (err: unknown) {
// return error to redirect_uri
return {
redirect_url: OAuthErrorResponse({
error: 'server_error',
error_description: getErrorMessage(err),
redirect_uri,
}),
};
}
const params: Record<string, string> = {
code,
};
if (session && session.state) {
params.state = session.state;
}
const redirectUrl = redirect.success(redirect_uri, params);
// delete the session
try {
await this.sessionStore.delete(RelayState);
} catch (_err) {
// ignore error
}
return { redirect_url: redirectUrl };
}
/**
* @swagger
*
* /oauth/token:
* post:
* summary: Code exchange
* operationId: oauth-code-exchange
* tags:
* - OAuth
* consumes:
* - application/x-www-form-urlencoded
* parameters:
* - name: grant_type
* in: formData
* type: string
* description: Grant type should be 'authorization_code'
* default: authorization_code
* required: true
* - name: client_id
* in: formData
* type: string
* description: Use the client_id returned by the SAML config API
* required: true
* - name: client_secret
* in: formData
* type: string
* description: Use the client_secret returned by the SAML config API
* required: true
* - name: redirect_uri
* in: formData
* type: string
* description: Redirect URI
* required: true
* - name: code
* in: formData
* type: string
* description: Code
* required: true
* responses:
* '200':
* description: Success
* schema:
* type: object
* properties:
* access_token:
* type: string
* token_type:
* type: string
* expires_in:
* type: string
* example:
* access_token: 8958e13053832b5af58fdf2ee83f35f5d013dc74
* token_type: bearer
* expires_in: 300
*/
public async token(body: OAuthTokenReq): Promise<OAuthTokenRes> {
const { client_id, client_secret, code_verifier, code, grant_type = 'authorization_code' } = body;
metrics.increment('oauthToken');
if (grant_type !== 'authorization_code') {
throw new JacksonError('Unsupported grant_type', 400);
}
if (!code) {
throw new JacksonError('Please specify code', 400);
}
const codeVal = await this.codeStore.get(code);
if (!codeVal || !codeVal.profile) {
throw new JacksonError('Invalid code', 403);
}
if (code_verifier) {
// PKCE flow
let cv = code_verifier;
if (codeVal.session.code_challenge_method.toLowerCase() === 's256') {
cv = codeVerifier.encode(code_verifier);
}
if (codeVal.session.code_challenge !== cv) {
throw new JacksonError('Invalid code_verifier', 401);
}
} else if (client_id && client_secret) {
// check if we have an encoded client_id
if (client_id !== 'dummy') {
const sp = getEncodedTenantProduct(client_id);
if (!sp) {
// OAuth flow
if (client_id !== codeVal.clientID || client_secret !== codeVal.clientSecret) {
throw new JacksonError('Invalid client_id or client_secret', 401);
}
} else {
// encoded client_id, verify client_secret
if (client_secret !== this.opts.clientSecretVerifier) {
throw new JacksonError('Invalid client_secret', 401);
}
}
} else {
if (client_secret !== this.opts.clientSecretVerifier && client_secret !== codeVal.clientSecret) {
throw new JacksonError('Invalid client_secret', 401);
}
}
} else if (codeVal && codeVal.session) {
throw new JacksonError('Please specify client_secret or code_verifier', 401);
}
// store details against a token
const token = crypto.randomBytes(20).toString('hex');
const tokenVal = {
...codeVal.profile,
requested: codeVal.requested,
};
await this.tokenStore.put(token, tokenVal);
// delete the code
try {
await this.codeStore.delete(code);
} catch (_err) {
// ignore error
}
return {
access_token: token,
token_type: 'bearer',
expires_in: this.opts.db.ttl!,
};
}
/**
* @swagger
*
* /oauth/userinfo:
* get:
* summary: Get profile
* operationId: oauth-get-profile
* tags:
* - OAuth
* responses:
* '200':
* description: Success
* schema:
* type: object
* properties:
* id:
* type: string
* email:
* type: string
* firstName:
* type: string
* lastName:
* type: string
* example:
* id: 32b5af58fdf
* email: jackson@coolstartup.com
* firstName: SAML
* lastName: Jackson
*/
public async userInfo(token: string): Promise<Profile> {
const rsp = await this.tokenStore.get(token);
metrics.increment('oauthUserInfo');
if (!rsp || !rsp.claims) {
throw new JacksonError('Invalid token', 403);
}
return {
...rsp.claims,
requested: rsp.requested,
};
}
} | the_stack |
import {
basename,
dirname,
Document,
DOMParser,
Element,
join,
} from "./deps.ts";
import {
decoder,
encoder,
getLocalDependencyPaths,
isLocalUrl,
md5,
qs,
} from "./util.ts";
import { wasmPath } from "./install_util.ts";
import { bundleByEsbuild } from "./bundle_util.ts";
import { logger } from "./logger_util.ts";
import { compile as compileSass } from "./sass_util.ts";
import type { File } from "./types.ts";
/**
* Options for asset generation.
*
* @property watchPaths true when the system is watching the paths i.e. packup serve
* @property onBuild The hook which is called when the build is finished. Used when `packup serve`
*/
type GenerateAssetsOptions = {
watchPaths?: boolean;
onBuild?: () => void;
insertLivereloadScript?: boolean;
livereloadPort?: number;
mainAs404?: boolean;
publicUrl: string;
};
/**
* Generates assets from the given entrypoint path (html).
* Also returns watch paths when `watchPaths` option is true.
*
* Used both in `packup build` and `packup serve`.
*/
export async function generateAssets(
path: string,
opts: GenerateAssetsOptions,
): Promise<[AsyncGenerator<File, void, void>, string[]]> {
const buildStarted = Date.now();
const htmlAsset = await HtmlAsset.create(path);
const { pageName, base } = htmlAsset;
const pathPrefix = opts.publicUrl || ".";
const assets = [...htmlAsset.extractReferencedAssets()];
if (opts.insertLivereloadScript) {
htmlAsset.insertScriptTag(
`http://localhost:${opts.livereloadPort!}/livereload.js`,
);
}
const generator = (async function* () {
for (const a of assets) {
// TODO(kt3k): These can be concurrent
const files = await a.createFileObject({ pageName, base, pathPrefix });
for (const file of files) yield file;
}
// This needs to be the last.
const files = await htmlAsset.createFileObject({
pageName,
base,
pathPrefix,
});
for (const file of files) yield file;
if (opts.mainAs404) {
yield Object.assign(
(await htmlAsset.createFileObject({ pageName, base, pathPrefix }))[0],
{ name: "404" },
);
}
logger.log(`${path} bundled in ${Date.now() - buildStarted}ms`);
// If build hook is set, call it. Used for live reloading.
opts.onBuild?.();
logger.debug("onBuild");
})();
const watchPaths = opts.watchPaths
? (await Promise.all(assets.map((a) => a.getWatchPaths(htmlAsset.base))))
.flat()
: [];
return [generator, [path, ...watchPaths]];
}
/**
* Builds the entrypoint and watches the all files referenced from the entrypoint.
* If any change is happend in any of the watched paths, then builds again and update
* the watching paths. Used in `packup serve`.
*/
export async function* watchAndGenAssets(
path: string,
opts: GenerateAssetsOptions,
): AsyncGenerator<File, void, void> {
opts = {
...opts,
watchPaths: true,
insertLivereloadScript: true,
};
let [assets, watchPaths] = await generateAssets(path, opts);
while (true) {
for await (const file of assets) {
yield file;
}
const watcher = Deno.watchFs(watchPaths);
for await (const e of watcher) {
logger.log("Changed: " + e.paths.join(""));
break;
// watcher.close();
}
logger.log("Rebuilding");
await new Promise<void>((resolve) => setTimeout(() => resolve(), 100));
[assets, watchPaths] = await generateAssets(path, opts);
}
}
type CreateFileObjectParams = {
pageName: string;
base: string;
pathPrefix: string;
};
type Asset = {
getWatchPaths(base: string): Promise<string[]>;
createFileObject(params: CreateFileObjectParams): Promise<File[]>;
};
/** HtmlAsset represents the html file */
class HtmlAsset implements Asset {
static async create(path: string): Promise<HtmlAsset> {
logger.debug("Reading", path);
const html = decoder.decode(await Deno.readFile(path));
return new HtmlAsset(html, path);
}
#doc: Document;
#path: string;
base: string;
#filename: string;
pageName: string;
constructor(html: string, path: string) {
this.#doc = new DOMParser().parseFromString(html, "text/html")!;
this.#path = path;
this.base = dirname(path);
this.#filename = basename(path);
if (!this.#filename.endsWith(".html")) {
throw new Error(`Entrypoint needs to be an html file: ${path}`);
}
this.pageName = this.#filename.replace(/\.html$/, "");
if (!this.pageName) {
throw new Error(`Bad entrypoint name: ${path}`);
}
}
extractReferencedAssets() {
return extractReferencedAssets(this.#doc);
}
createFileObject(_params: CreateFileObjectParams) {
return Promise.resolve([Object.assign(
new Blob([encoder.encode(this.#doc.body.parentElement!.outerHTML)]),
{ name: this.#filename },
)]);
}
getWatchPaths() {
return Promise.resolve([this.#path]);
}
insertScriptTag(path: string) {
const script = this.#doc.createElement("script");
script.setAttribute("src", path);
this.#doc.body.insertBefore(script, null);
}
}
/** ScssAsset represents a <link rel="stylesheet"> tag in the html */
class CssAsset implements Asset {
static create(link: Element): CssAsset | null {
const href = link.getAttribute("href");
const rel = link.getAttribute("rel");
if (rel !== "stylesheet") {
return null;
}
if (!href) {
logger.warn(
"<link> tag has rel=stylesheet attribute, but doesn't have href attribute",
);
return null;
}
if (href.startsWith("https://") || href.startsWith("http://")) {
// If href starts with http(s):// schemes, we consider these as
// external reference. So skip handling these
return null;
}
if (href.endsWith(".scss")) {
return new ScssAsset(href, link);
}
return new CssAsset(href, link);
}
_el: Element;
_href: string;
_dest?: string;
constructor(href: string, link: Element) {
this._el = link;
this._href = href;
}
getWatchPaths(base: string): Promise<string[]> {
return Promise.resolve([join(base, this._href)]);
}
async createFileObject(
{ pageName, base, pathPrefix }: CreateFileObjectParams,
): Promise<File[]> {
const data = await Deno.readFile(join(base, this._href));
this._dest = `${pageName}.${md5(data)}.css`;
this._el.setAttribute("href", join(pathPrefix, this._dest));
return [Object.assign(new Blob([data]), { name: this._dest })];
}
}
/** ScssAsset represents a <link rel="stylesheet"> tag
* with href having .scss extension in the html */
class ScssAsset extends CssAsset {
// TODO(kt3k): implement getWatchPaths correctly
async createFileObject(
{ pageName, base, pathPrefix }: CreateFileObjectParams,
): Promise<File[]> {
const scss = await Deno.readFile(join(base, this._href));
this._dest = `${pageName}.${md5(scss)}.css`;
this._el.setAttribute("href", join(pathPrefix, this._dest));
return [Object.assign(new Blob([await compileSass(decoder.decode(scss))]), {
name: this._dest,
})];
}
}
/** ScriptAsset represents a <script> tag in the html */
class ScriptAsset implements Asset {
static create(script: Element): ScriptAsset | null {
const src = script.getAttribute("src");
if (!src) {
// this <script> should contain inline scripts.
return null;
}
if (src.startsWith("http://") || src.startsWith("https://")) {
// If "src" starts with http(s):// schemes, we consider these as
// external reference. So skip handling these
return null;
}
return new ScriptAsset(src, script);
}
#src: string;
#dest?: string;
#el: Element;
constructor(src: string, script: Element) {
this.#src = src;
this.#el = script;
}
async getWatchPaths(base: string): Promise<string[]> {
return await getLocalDependencyPaths(join(base, this.#src));
}
async createFileObject({
pageName,
base,
pathPrefix,
}: CreateFileObjectParams): Promise<File[]> {
const path = join(base, this.#src);
const data = await bundleByEsbuild(path, wasmPath());
this.#dest = `${pageName}.${md5(data)}.js`;
this.#el.setAttribute("src", join(pathPrefix, this.#dest));
return [Object.assign(new Blob([data]), { name: this.#dest })];
}
}
/** ImageAsset represents a `<img>` tag in the html */
class ImageAsset implements Asset {
static create(img: Element): ImageAsset | null {
let sources: string[] = [];
const src = img.getAttribute("src");
const srcset = img.getAttribute("srcset");
if (img.tagName === "IMG" && !src) {
logger.warn("<img> tag doesn't have src attribute");
return null;
}
if (src && isLocalUrl(src)) sources.push(src);
if (srcset) {
sources.push(
...srcset
.split(",") // Separate the different srcset
.filter(Boolean) // Remove empty strings
.map((src) => src.trim()) // Remove white spaces
.map((src) => src.split(" ")[0]) // Separate the source from the size
.filter(isLocalUrl), // Remove external references
);
}
// Remove duplicates
sources = [...new Set(sources)];
// If "src" or "srcset" only have external references, skip handling
if (sources.length === 0) return null;
return new ImageAsset(sources, img);
}
#sources: string[];
#el: Element;
constructor(sources: string[], image: Element) {
this.#sources = sources;
this.#el = image;
}
async getWatchPaths(base: string): Promise<string[]> {
const localDependencyPaths: Promise<string[]>[] = [];
for (const src of this.#sources) {
localDependencyPaths.push(getLocalDependencyPaths(join(base, src)));
}
return (await Promise.all(localDependencyPaths))
.flatMap((path) => path); // Flatten result
}
async createFileObject(
{ pageName, base, pathPrefix }: CreateFileObjectParams,
): Promise<File[]> {
// TODO(tjosepo): Find a way to avoid creating copies of the same image
// when creating a bundle
const files: File[] = [];
for (const src of this.#sources) {
const data = await Deno.readFile(join(base, src));
const [, extension] = src.match(/\.([\w]+)$/) ?? [];
const dest = `${pageName}.${md5(data)}.${extension}`;
if (this.#el.getAttribute("src")?.match(src)) {
this.#el.setAttribute("src", join(pathPrefix, dest));
}
const srcset = this.#el.getAttribute("srcset");
if (srcset?.includes(src)) {
// TODO(tjosepo): Find a better way to replace the old src with the new
// dest without only using `string.replace()`
this.#el.setAttribute(
"srcset",
srcset.replace(src, join(pathPrefix, dest)),
);
}
files.push(Object.assign(new Blob([data]), { name: dest }));
}
return files;
}
}
export function* extractReferencedAssets(
doc: Document,
): Generator<Asset, void, void> {
yield* extractReferencedScripts(doc);
yield* extractReferencedStyleSheets(doc);
yield* extractReferencedImages(doc);
}
function* extractReferencedScripts(
doc: Document,
): Generator<Asset, void, void> {
for (const s of qs(doc, "script")) {
const asset = ScriptAsset.create(s);
if (asset) yield asset;
}
}
function* extractReferencedStyleSheets(
doc: Document,
): Generator<Asset, void, void> {
for (const link of qs(doc, "link")) {
const asset = CssAsset.create(link);
if (asset) yield asset;
}
}
function* extractReferencedImages(
doc: Document,
): Generator<Asset, void, void> {
for (const img of [...qs(doc, "img"), ...qs(doc, "source")]) {
const asset = ImageAsset.create(img);
if (asset) yield asset;
}
} | the_stack |
declare class FBSDKAccessToken extends NSObject implements FBSDKTokenStringProviding, NSCopying, NSObjectProtocol, NSSecureCoding {
static alloc(): FBSDKAccessToken; // inherited from NSObject
static new(): FBSDKAccessToken; // inherited from NSObject
static refreshCurrentAccessTokenWithCompletion(completion: (p1: FBSDKGraphRequestConnecting, p2: any, p3: NSError) => void): void;
readonly appID: string;
readonly dataAccessExpirationDate: Date;
readonly dataAccessExpired: boolean;
readonly declinedPermissions: NSSet<string>;
readonly expirationDate: Date;
readonly expired: boolean;
readonly expiredPermissions: NSSet<string>;
readonly permissions: NSSet<string>;
readonly refreshDate: Date;
readonly tokenString: string;
readonly userID: string;
static currentAccessToken: FBSDKAccessToken;
static readonly currentAccessTokenIsActive: boolean;
static tokenCache: FBSDKTokenCaching;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding
static readonly tokenString: string; // inherited from FBSDKTokenStringProviding
constructor(o: { coder: NSCoder; }); // inherited from NSCoding
constructor(o: { tokenString: string; permissions: NSArray<string> | string[]; declinedPermissions: NSArray<string> | string[]; expiredPermissions: NSArray<string> | string[]; appID: string; userID: string; expirationDate: Date; refreshDate: Date; dataAccessExpirationDate: Date; });
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
encodeWithCoder(coder: NSCoder): void;
hasGranted(permission: string): boolean;
initWithCoder(coder: NSCoder): this;
initWithTokenStringPermissionsDeclinedPermissionsExpiredPermissionsAppIDUserIDExpirationDateRefreshDateDataAccessExpirationDate(tokenString: string, permissions: NSArray<string> | string[], declinedPermissions: NSArray<string> | string[], expiredPermissions: NSArray<string> | string[], appID: string, userID: string, expirationDate: Date, refreshDate: Date, dataAccessExpirationDate: Date): this;
isEqual(object: any): boolean;
isEqualToAccessToken(token: FBSDKAccessToken): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
self(): this;
}
declare var FBSDKAccessTokenChangeNewKey: string;
declare var FBSDKAccessTokenChangeOldKey: string;
declare var FBSDKAccessTokenDidChangeNotification: string;
declare var FBSDKAccessTokenDidChangeUserIDKey: string;
declare var FBSDKAccessTokenDidExpireKey: string;
interface FBSDKAccessTokenProviding {
}
declare var FBSDKAccessTokenProviding: {
prototype: FBSDKAccessTokenProviding;
};
interface FBSDKAccessTokenSetting {
}
declare var FBSDKAccessTokenSetting: {
prototype: FBSDKAccessTokenSetting;
};
declare const enum FBSDKAdvertisingTrackingStatus {
Allowed = 0,
Disallowed = 1,
Unspecified = 2
}
interface FBSDKAppAvailabilityChecker {
isFacebookAppInstalled: boolean;
isMessengerAppInstalled: boolean;
}
declare var FBSDKAppAvailabilityChecker: {
prototype: FBSDKAppAvailabilityChecker;
};
declare var FBSDKAppEventCity: string;
declare var FBSDKAppEventCountry: string;
declare var FBSDKAppEventDateOfBirth: string;
declare var FBSDKAppEventEmail: string;
declare var FBSDKAppEventExternalId: string;
declare var FBSDKAppEventFirstName: string;
declare var FBSDKAppEventGender: string;
declare var FBSDKAppEventLastName: string;
declare var FBSDKAppEventNameAchievedLevel: string;
declare var FBSDKAppEventNameAdClick: string;
declare var FBSDKAppEventNameAdImpression: string;
declare var FBSDKAppEventNameAddedPaymentInfo: string;
declare var FBSDKAppEventNameAddedToCart: string;
declare var FBSDKAppEventNameAddedToWishlist: string;
declare var FBSDKAppEventNameCompletedRegistration: string;
declare var FBSDKAppEventNameCompletedTutorial: string;
declare var FBSDKAppEventNameContact: string;
declare var FBSDKAppEventNameCustomizeProduct: string;
declare var FBSDKAppEventNameDonate: string;
declare var FBSDKAppEventNameFindLocation: string;
declare var FBSDKAppEventNameInitiatedCheckout: string;
declare var FBSDKAppEventNamePurchased: string;
declare var FBSDKAppEventNameRated: string;
declare var FBSDKAppEventNameSchedule: string;
declare var FBSDKAppEventNameSearched: string;
declare var FBSDKAppEventNameSpentCredits: string;
declare var FBSDKAppEventNameStartTrial: string;
declare var FBSDKAppEventNameSubmitApplication: string;
declare var FBSDKAppEventNameSubscribe: string;
declare var FBSDKAppEventNameUnlockedAchievement: string;
declare var FBSDKAppEventNameViewedContent: string;
declare var FBSDKAppEventParameterEventName: string;
declare var FBSDKAppEventParameterLogTime: string;
declare var FBSDKAppEventParameterNameAdType: string;
declare var FBSDKAppEventParameterNameContent: string;
declare var FBSDKAppEventParameterNameContentID: string;
declare var FBSDKAppEventParameterNameContentType: string;
declare var FBSDKAppEventParameterNameCurrency: string;
declare var FBSDKAppEventParameterNameDescription: string;
declare var FBSDKAppEventParameterNameLevel: string;
declare var FBSDKAppEventParameterNameMaxRatingValue: string;
declare var FBSDKAppEventParameterNameNumItems: string;
declare var FBSDKAppEventParameterNameOrderID: string;
declare var FBSDKAppEventParameterNamePaymentInfoAvailable: string;
declare var FBSDKAppEventParameterNameRegistrationMethod: string;
declare var FBSDKAppEventParameterNameSearchString: string;
declare var FBSDKAppEventParameterNameSuccess: string;
declare var FBSDKAppEventParameterProductAppLinkAndroidAppName: string;
declare var FBSDKAppEventParameterProductAppLinkAndroidPackage: string;
declare var FBSDKAppEventParameterProductAppLinkAndroidUrl: string;
declare var FBSDKAppEventParameterProductAppLinkIOSAppName: string;
declare var FBSDKAppEventParameterProductAppLinkIOSAppStoreID: string;
declare var FBSDKAppEventParameterProductAppLinkIOSUrl: string;
declare var FBSDKAppEventParameterProductAppLinkIPadAppName: string;
declare var FBSDKAppEventParameterProductAppLinkIPadAppStoreID: string;
declare var FBSDKAppEventParameterProductAppLinkIPadUrl: string;
declare var FBSDKAppEventParameterProductAppLinkIPhoneAppName: string;
declare var FBSDKAppEventParameterProductAppLinkIPhoneAppStoreID: string;
declare var FBSDKAppEventParameterProductAppLinkIPhoneUrl: string;
declare var FBSDKAppEventParameterProductAppLinkWindowsPhoneAppID: string;
declare var FBSDKAppEventParameterProductAppLinkWindowsPhoneAppName: string;
declare var FBSDKAppEventParameterProductAppLinkWindowsPhoneUrl: string;
declare var FBSDKAppEventParameterProductCategory: string;
declare var FBSDKAppEventParameterProductCustomLabel0: string;
declare var FBSDKAppEventParameterProductCustomLabel1: string;
declare var FBSDKAppEventParameterProductCustomLabel2: string;
declare var FBSDKAppEventParameterProductCustomLabel3: string;
declare var FBSDKAppEventParameterProductCustomLabel4: string;
declare var FBSDKAppEventParameterValueNo: string;
declare var FBSDKAppEventParameterValueYes: string;
declare var FBSDKAppEventPhone: string;
declare var FBSDKAppEventState: string;
declare var FBSDKAppEventZip: string;
declare class FBSDKAppEvents extends NSObject {
static alloc(): FBSDKAppEvents; // inherited from NSObject
static augmentHybridWKWebView(webView: WKWebView): void;
static clearUserData(): void;
static clearUserDataForType(type: string): void;
static clearUserID(): void;
static flush(): void;
static getUserData(): string;
static logEvent(eventName: string): void;
static logEventParameters(eventName: string, parameters: NSDictionary<string, any>): void;
static logEventValueToSum(eventName: string, valueToSum: number): void;
static logEventValueToSumParameters(eventName: string, valueToSum: number, parameters: NSDictionary<string, any>): void;
static logEventValueToSumParametersAccessToken(eventName: string, valueToSum: number, parameters: NSDictionary<string, any>, accessToken: FBSDKAccessToken): void;
static logInternalEventParametersIsImplicitlyLogged(eventName: string, parameters: NSDictionary<string, any>, isImplicitlyLogged: boolean): void;
static logInternalEventParametersIsImplicitlyLoggedAccessToken(eventName: string, parameters: NSDictionary<string, any>, isImplicitlyLogged: boolean, accessToken: FBSDKAccessToken): void;
static logProductItemAvailabilityConditionDescriptionImageLinkLinkTitlePriceAmountCurrencyGtinMpnBrandParameters(itemID: string, availability: FBSDKProductAvailability, condition: FBSDKProductCondition, description: string, imageLink: string, link: string, title: string, priceAmount: number, currency: string, gtin: string, mpn: string, brand: string, parameters: NSDictionary<string, any>): void;
static logPurchaseCurrency(purchaseAmount: number, currency: string): void;
static logPurchaseCurrencyParameters(purchaseAmount: number, currency: string, parameters: NSDictionary<string, any>): void;
static logPurchaseCurrencyParametersAccessToken(purchaseAmount: number, currency: string, parameters: NSDictionary<string, any>, accessToken: FBSDKAccessToken): void;
static logPushNotificationOpen(payload: NSDictionary<string, any>): void;
static logPushNotificationOpenAction(payload: NSDictionary<string, any>, action: string): void;
static new(): FBSDKAppEvents; // inherited from NSObject
static requestForCustomAudienceThirdPartyIDWithAccessToken(accessToken: FBSDKAccessToken): FBSDKGraphRequest;
static sendEventBindingsToUnity(): void;
static setIsUnityInit(isUnityInit: boolean): void;
static setPushNotificationsDeviceToken(deviceToken: NSData): void;
static setPushNotificationsDeviceTokenString(deviceTokenString: string): void;
static setUserDataForType(data: string, type: string): void;
static setUserEmailFirstNameLastNamePhoneDateOfBirthGenderCityStateZipCountry(email: string, firstName: string, lastName: string, phone: string, dateOfBirth: string, gender: string, city: string, state: string, zip: string, country: string): void;
static readonly anonymousID: string;
static flushBehavior: FBSDKAppEventsFlushBehavior;
static loggingOverrideAppID: string;
static readonly shared: FBSDKAppEvents;
static userID: string;
activateApp(): void;
clearUserData(): void;
clearUserDataForType(type: string): void;
getUserData(): string;
setUserDataForType(data: string, type: string): void;
setUserEmailFirstNameLastNamePhoneDateOfBirthGenderCityStateZipCountry(email: string, firstName: string, lastName: string, phone: string, dateOfBirth: string, gender: string, city: string, state: string, zip: string, country: string): void;
}
declare const enum FBSDKAppEventsFlushBehavior {
Auto = 0,
ExplicitOnly = 1
}
declare var FBSDKAppEventsLoggingResultNotification: string;
declare var FBSDKAppEventsOverrideAppIDBundleKey: string;
declare class FBSDKAppLink extends NSObject {
static alloc(): FBSDKAppLink; // inherited from NSObject
static appLinkWithSourceURLTargetsWebURL(sourceURL: NSURL, targets: NSArray<FBSDKAppLinkTarget> | FBSDKAppLinkTarget[], webURL: NSURL): FBSDKAppLink;
static new(): FBSDKAppLink; // inherited from NSObject
readonly sourceURL: NSURL;
readonly targets: NSArray<FBSDKAppLinkTarget>;
readonly webURL: NSURL;
}
declare var FBSDKAppLinkNavigateBackToReferrerEventName: string;
declare var FBSDKAppLinkNavigateInEventName: string;
declare var FBSDKAppLinkNavigateOutEventName: string;
declare class FBSDKAppLinkNavigation extends NSObject {
static alloc(): FBSDKAppLinkNavigation; // inherited from NSObject
static callbackAppLinkDataForAppWithNameUrl(appName: string, url: string): NSDictionary<string, NSDictionary<string, string>>;
static navigateToAppLinkError(link: FBSDKAppLink): FBSDKAppLinkNavigationType;
static navigateToURLHandler(destination: NSURL, handler: (p1: FBSDKAppLinkNavigationType, p2: NSError) => void): void;
static navigateToURLResolverHandler(destination: NSURL, resolver: FBSDKAppLinkResolving, handler: (p1: FBSDKAppLinkNavigationType, p2: NSError) => void): void;
static navigationTypeForLink(link: FBSDKAppLink): FBSDKAppLinkNavigationType;
static navigationWithAppLinkExtrasAppLinkData(appLink: FBSDKAppLink, extras: NSDictionary<string, any>, appLinkData: NSDictionary<string, any>): FBSDKAppLinkNavigation;
static navigationWithAppLinkExtrasAppLinkDataSettings(appLink: FBSDKAppLink, extras: NSDictionary<string, any>, appLinkData: NSDictionary<string, any>, settings: FBSDKSettingsProtocol): FBSDKAppLinkNavigation;
static new(): FBSDKAppLinkNavigation; // inherited from NSObject
static resolveAppLinkHandler(destination: NSURL, handler: (p1: FBSDKAppLink, p2: NSError) => void): void;
static resolveAppLinkResolverHandler(destination: NSURL, resolver: FBSDKAppLinkResolving, handler: (p1: FBSDKAppLink, p2: NSError) => void): void;
readonly appLink: FBSDKAppLink;
readonly appLinkData: NSDictionary<string, any>;
readonly extras: NSDictionary<string, any>;
readonly navigationType: FBSDKAppLinkNavigationType;
static defaultResolver: FBSDKAppLinkResolving;
navigate(): FBSDKAppLinkNavigationType;
}
declare const enum FBSDKAppLinkNavigationType {
Failure = 0,
Browser = 1,
App = 2
}
declare var FBSDKAppLinkParseEventName: string;
declare class FBSDKAppLinkResolver extends NSObject implements FBSDKAppLinkResolving {
static alloc(): FBSDKAppLinkResolver; // inherited from NSObject
static new(): FBSDKAppLinkResolver; // inherited from NSObject
static resolver(): FBSDKAppLinkResolver;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
appLinkFromURLHandler(url: NSURL, handler: (p1: FBSDKAppLink, p2: NSError) => void): void;
appLinksFromURLsHandler(urls: NSArray<NSURL> | NSURL[], handler: (p1: NSDictionary<NSURL, FBSDKAppLink>, p2: NSError) => void): void;
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
self(): this;
}
declare class FBSDKAppLinkResolverRequestBuilder extends NSObject {
static alloc(): FBSDKAppLinkResolverRequestBuilder; // inherited from NSObject
static new(): FBSDKAppLinkResolverRequestBuilder; // inherited from NSObject
getIdiomSpecificField(): string;
requestForURLs(urls: NSArray<NSURL> | NSURL[]): FBSDKGraphRequest;
}
interface FBSDKAppLinkResolving extends NSObjectProtocol {
appLinkFromURLHandler(url: NSURL, handler: (p1: FBSDKAppLink, p2: NSError) => void): void;
}
declare var FBSDKAppLinkResolving: {
prototype: FBSDKAppLinkResolving;
};
declare class FBSDKAppLinkTarget extends NSObject {
static alloc(): FBSDKAppLinkTarget; // inherited from NSObject
static appLinkTargetWithURLAppStoreIdAppName(url: NSURL, appStoreId: string, appName: string): FBSDKAppLinkTarget;
static new(): FBSDKAppLinkTarget; // inherited from NSObject
readonly URL: NSURL;
readonly appName: string;
readonly appStoreId: string;
}
declare class FBSDKAppLinkUtility extends NSObject {
static alloc(): FBSDKAppLinkUtility; // inherited from NSObject
static appInvitePromotionCodeFromURL(url: NSURL): string;
static fetchDeferredAppLink(handler: (p1: NSURL, p2: NSError) => void): void;
static isMatchURLScheme(scheme: string): boolean;
static new(): FBSDKAppLinkUtility; // inherited from NSObject
}
declare var FBSDKAppLinkVersion: string;
interface FBSDKAppURLSchemeProviding {
appURLScheme(): string;
validateURLSchemes(): void;
}
declare var FBSDKAppURLSchemeProviding: {
prototype: FBSDKAppURLSchemeProviding;
};
declare class FBSDKApplicationDelegate extends NSObject {
static alloc(): FBSDKApplicationDelegate; // inherited from NSObject
static new(): FBSDKApplicationDelegate; // inherited from NSObject
static readonly sharedInstance: FBSDKApplicationDelegate;
addObserver(observer: FBSDKApplicationObserving): void;
applicationDidFinishLaunchingWithOptions(application: UIApplication, launchOptions: NSDictionary<string, any>): boolean;
applicationOpenURLOptions(application: UIApplication, url: NSURL, options: NSDictionary<string, any>): boolean;
applicationOpenURLSourceApplicationAnnotation(application: UIApplication, url: NSURL, sourceApplication: string, annotation: any): boolean;
initializeSDK(): void;
removeObserver(observer: FBSDKApplicationObserving): void;
}
interface FBSDKApplicationObserving extends NSObjectProtocol {
applicationDidBecomeActive?(application: UIApplication): void;
applicationDidEnterBackground?(application: UIApplication): void;
applicationDidFinishLaunchingWithOptions?(application: UIApplication, launchOptions: NSDictionary<string, any>): boolean;
applicationOpenURLSourceApplicationAnnotation?(application: UIApplication, url: NSURL, sourceApplication: string, annotation: any): boolean;
applicationWillResignActive?(application: UIApplication): void;
}
declare var FBSDKApplicationObserving: {
prototype: FBSDKApplicationObserving;
};
declare class FBSDKAuthenticationToken extends NSObject implements FBSDKAuthenticationTokenProviding, FBSDKAuthenticationTokenSetting, NSCopying, NSObjectProtocol, NSSecureCoding {
static alloc(): FBSDKAuthenticationToken; // inherited from NSObject
static new(): FBSDKAuthenticationToken; // inherited from NSObject
readonly graphDomain: string;
readonly nonce: string;
readonly tokenString: string;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
static readonly currentAuthenticationToken: FBSDKAuthenticationToken; // inherited from FBSDKAuthenticationTokenProviding
static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding
static tokenCache: FBSDKTokenCaching; // inherited from FBSDKAuthenticationTokenProviding
constructor(o: { coder: NSCoder; }); // inherited from NSCoding
claims(): FBSDKAuthenticationTokenClaims;
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
encodeWithCoder(coder: NSCoder): void;
initWithCoder(coder: NSCoder): this;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
self(): this;
}
declare class FBSDKAuthenticationTokenClaims extends NSObject {
static alloc(): FBSDKAuthenticationTokenClaims; // inherited from NSObject
static new(): FBSDKAuthenticationTokenClaims; // inherited from NSObject
readonly aud: string;
readonly email: string;
readonly exp: number;
readonly familyName: string;
readonly givenName: string;
readonly iat: number;
readonly iss: string;
readonly jti: string;
readonly middleName: string;
readonly name: string;
readonly nonce: string;
readonly picture: string;
readonly sub: string;
readonly userAgeRange: NSDictionary<string, number>;
readonly userBirthday: string;
readonly userFriends: NSArray<string>;
readonly userGender: string;
readonly userHometown: NSDictionary<string, string>;
readonly userLink: string;
readonly userLocation: NSDictionary<string, string>;
}
interface FBSDKAuthenticationTokenProviding {
}
declare var FBSDKAuthenticationTokenProviding: {
prototype: FBSDKAuthenticationTokenProviding;
};
interface FBSDKAuthenticationTokenSetting {
}
declare var FBSDKAuthenticationTokenSetting: {
prototype: FBSDKAuthenticationTokenSetting;
};
declare class FBSDKBridgeAPI extends NSObject implements FBSDKBridgeAPIRequestOpening, FBSDKURLOpener {
static alloc(): FBSDKBridgeAPI; // inherited from NSObject
static new(): FBSDKBridgeAPI; // inherited from NSObject
readonly active: boolean;
static readonly sharedInstance: FBSDKBridgeAPI;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
constructor(o: { processInfo: any; logger: FBSDKLogger; urlOpener: any; bridgeAPIResponseFactory: any; frameworkLoader: any; appURLSchemeProvider: FBSDKAppURLSchemeProviding; });
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
initWithProcessInfoLoggerUrlOpenerBridgeAPIResponseFactoryFrameworkLoaderAppURLSchemeProvider(processInfo: any, logger: FBSDKLogger, urlOpener: any, bridgeAPIResponseFactory: any, frameworkLoader: any, appURLSchemeProvider: FBSDKAppURLSchemeProviding): this;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
openBridgeAPIRequestUseSafariViewControllerFromViewControllerCompletionBlock(request: NSObject, useSafariViewController: boolean, fromViewController: UIViewController, completionBlock: (p1: FBSDKBridgeAPIResponse) => void): void;
openURLSenderHandler(url: NSURL, sender: FBSDKURLOpening, handler: (p1: boolean, p2: NSError) => void): void;
openURLWithSafariViewControllerSenderFromViewControllerHandler(url: NSURL, sender: FBSDKURLOpening, fromViewController: UIViewController, handler: (p1: boolean, p2: NSError) => void): void;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
self(): this;
sessionCompletionHandler(): (p1: NSURL, p2: NSError) => void;
}
declare var FBSDKBridgeAPIAppIDKey: string;
interface FBSDKBridgeAPIProtocol extends NSObjectProtocol {
requestURLWithActionIDSchemeMethodNameMethodVersionParametersError(actionID: string, scheme: string, methodName: string, methodVersion: string, parameters: NSDictionary<string, any>): NSURL;
responseParametersForActionIDQueryParametersCancelledError(actionID: string, queryParameters: NSDictionary<string, any>, cancelledRef: interop.Pointer | interop.Reference<boolean>): NSDictionary<string, any>;
}
declare var FBSDKBridgeAPIProtocol: {
prototype: FBSDKBridgeAPIProtocol;
};
declare const enum FBSDKBridgeAPIProtocolType {
Native = 0,
Web = 1
}
declare class FBSDKBridgeAPIRequest extends NSObject implements FBSDKBridgeAPIRequestProtocol, NSCopying {
static alloc(): FBSDKBridgeAPIRequest; // inherited from NSObject
static bridgeAPIRequestWithProtocolTypeSchemeMethodNameMethodVersionParametersUserInfo(protocolType: FBSDKBridgeAPIProtocolType, scheme: string, methodName: string, methodVersion: string, parameters: NSDictionary<string, any>, userInfo: NSDictionary<string, any>): FBSDKBridgeAPIRequest;
static new(): FBSDKBridgeAPIRequest; // inherited from NSObject
readonly methodVersion: string;
readonly parameters: NSDictionary<string, any>;
readonly userInfo: NSDictionary<string, any>;
readonly actionID: string; // inherited from FBSDKBridgeAPIRequestProtocol
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly methodName: string; // inherited from FBSDKBridgeAPIRequestProtocol
readonly protocol: FBSDKBridgeAPIProtocol; // inherited from FBSDKBridgeAPIRequestProtocol
readonly protocolType: FBSDKBridgeAPIProtocolType; // inherited from FBSDKBridgeAPIRequestProtocol
readonly scheme: string; // inherited from FBSDKBridgeAPIRequestProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
requestURL(): NSURL;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
self(): this;
}
interface FBSDKBridgeAPIRequestCreating {
bridgeAPIRequestWithProtocolTypeSchemeMethodNameMethodVersionParametersUserInfo(protocolType: FBSDKBridgeAPIProtocolType, scheme: string, methodName: string, methodVersion: string, parameters: NSDictionary<string, any>, userInfo: NSDictionary<string, any>): FBSDKBridgeAPIRequestProtocol;
}
declare var FBSDKBridgeAPIRequestCreating: {
prototype: FBSDKBridgeAPIRequestCreating;
};
interface FBSDKBridgeAPIRequestOpening extends NSObjectProtocol {
openBridgeAPIRequestUseSafariViewControllerFromViewControllerCompletionBlock(request: NSObject, useSafariViewController: boolean, fromViewController: UIViewController, completionBlock: (p1: FBSDKBridgeAPIResponse) => void): void;
openURLSenderHandler(url: NSURL, sender: FBSDKURLOpening, handler: (p1: boolean, p2: NSError) => void): void;
openURLWithSafariViewControllerSenderFromViewControllerHandler(url: NSURL, sender: FBSDKURLOpening, fromViewController: UIViewController, handler: (p1: boolean, p2: NSError) => void): void;
}
declare var FBSDKBridgeAPIRequestOpening: {
prototype: FBSDKBridgeAPIRequestOpening;
};
interface FBSDKBridgeAPIRequestProtocol extends NSCopying, NSObjectProtocol {
actionID: string;
methodName: string;
protocol: FBSDKBridgeAPIProtocol;
protocolType: FBSDKBridgeAPIProtocolType;
scheme: string;
requestURL(): NSURL;
}
declare var FBSDKBridgeAPIRequestProtocol: {
prototype: FBSDKBridgeAPIRequestProtocol;
};
declare class FBSDKBridgeAPIResponse extends NSObject implements NSCopying, NSObjectProtocol {
static alloc(): FBSDKBridgeAPIResponse; // inherited from NSObject
static bridgeAPIResponseCancelledWithRequest(request: NSObject): FBSDKBridgeAPIResponse;
static bridgeAPIResponseWithRequestError(request: NSObject, error: NSError): FBSDKBridgeAPIResponse;
static bridgeAPIResponseWithRequestResponseURLSourceApplicationError(request: NSObject, responseURL: NSURL, sourceApplication: string): FBSDKBridgeAPIResponse;
static new(): FBSDKBridgeAPIResponse; // inherited from NSObject
readonly cancelled: boolean;
readonly error: NSError;
readonly request: NSObject;
readonly responseParameters: NSDictionary<string, any>;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
self(): this;
}
declare var FBSDKBridgeAPISchemeSuffixKey: string;
declare var FBSDKBridgeAPIVersionKey: string;
declare class FBSDKButton extends FBSDKImpressionTrackingButton {
static alloc(): FBSDKButton; // inherited from NSObject
static appearance(): FBSDKButton; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): FBSDKButton; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): FBSDKButton; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKButton; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): FBSDKButton; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKButton; // inherited from UIAppearance
static buttonWithConfigurationPrimaryAction(configuration: UIButtonConfiguration, primaryAction: UIAction): FBSDKButton; // inherited from UIButton
static buttonWithType(buttonType: UIButtonType): FBSDKButton; // inherited from UIButton
static buttonWithTypePrimaryAction(buttonType: UIButtonType, primaryAction: UIAction): FBSDKButton; // inherited from UIButton
static new(): FBSDKButton; // inherited from NSObject
static systemButtonWithImageTargetAction(image: UIImage, target: any, action: string): FBSDKButton; // inherited from UIButton
static systemButtonWithPrimaryAction(primaryAction: UIAction): FBSDKButton; // inherited from UIButton
readonly implicitlyDisabled: boolean;
checkImplicitlyDisabled(): void;
configureWithIconTitleBackgroundColorHighlightedColor(icon: FBSDKIcon, title: string, backgroundColor: UIColor, highlightedColor: UIColor): void;
configureWithIconTitleBackgroundColorHighlightedColorSelectedTitleSelectedIconSelectedColorSelectedHighlightedColor(icon: FBSDKIcon, title: string, backgroundColor: UIColor, highlightedColor: UIColor, selectedTitle: string, selectedIcon: FBSDKIcon, selectedColor: UIColor, selectedHighlightedColor: UIColor): void;
defaultBackgroundColor(): UIColor;
logTapEventWithEventNameParameters(eventName: string, parameters: NSDictionary<string, any>): void;
sizeThatFitsTitle(size: CGSize, title: string): CGSize;
textSizeForTextFontConstrainedSizeLineBreakMode(text: string, font: UIFont, constrainedSize: CGSize, lineBreakMode: NSLineBreakMode): CGSize;
}
interface FBSDKButtonImpressionTracking extends NSObjectProtocol {
analyticsParameters: NSDictionary<string, any>;
impressionTrackingEventName: string;
impressionTrackingIdentifier: string;
}
declare var FBSDKButtonImpressionTracking: {
prototype: FBSDKButtonImpressionTracking;
};
declare var FBSDKCATransform3DIdentity: CATransform3D;
declare const enum FBSDKCoreError {
ErrorReserved = 0,
ErrorEncryption = 1,
ErrorInvalidArgument = 2,
ErrorUnknown = 3,
ErrorNetwork = 4,
ErrorAppEventsFlush = 5,
ErrorGraphRequestNonTextMimeTypeReturned = 6,
ErrorGraphRequestProtocolMismatch = 7,
ErrorGraphRequestGraphAPI = 8,
ErrorDialogUnavailable = 9,
ErrorAccessTokenRequired = 10,
ErrorAppVersionUnsupported = 11,
ErrorBrowserUnavailable = 12,
ErrorBridgeAPIInterruption = 13,
ErrorBridgeAPIResponse = 14
}
declare var FBSDKDialogConfigurationNameMessage: string;
declare var FBSDKDialogConfigurationNameShare: string;
declare class FBSDKDynamicFrameworkLoaderProxy extends NSObject {
static alloc(): FBSDKDynamicFrameworkLoaderProxy; // inherited from NSObject
static loadkSecAttrAccessibleAfterFirstUnlockThisDeviceOnly(): any;
static new(): FBSDKDynamicFrameworkLoaderProxy; // inherited from NSObject
}
declare class FBSDKError extends NSObject {
static alloc(): FBSDKError; // inherited from NSObject
static errorWithCodeMessage(code: number, message: string): NSError;
static errorWithCodeMessageUnderlyingError(code: number, message: string, underlyingError: NSError): NSError;
static errorWithDomainCodeMessage(domain: string, code: number, message: string): NSError;
static errorWithDomainCodeMessageUnderlyingError(domain: string, code: number, message: string, underlyingError: NSError): NSError;
static errorWithDomainCodeUserInfoMessageUnderlyingError(domain: string, code: number, userInfo: NSDictionary<string, any>, message: string, underlyingError: NSError): NSError;
static invalidArgumentErrorWithDomainNameValueMessage(domain: string, name: string, value: any, message: string): NSError;
static invalidArgumentErrorWithDomainNameValueMessageUnderlyingError(domain: string, name: string, value: any, message: string, underlyingError: NSError): NSError;
static invalidArgumentErrorWithNameValueMessage(name: string, value: any, message: string): NSError;
static isNetworkError(error: NSError): boolean;
static new(): FBSDKError; // inherited from NSObject
static requiredArgumentErrorWithDomainNameMessage(domain: string, name: string, message: string): NSError;
static unknownErrorWithMessage(message: string): NSError;
}
declare var FBSDKErrorArgumentCollectionKey: string;
declare var FBSDKErrorArgumentNameKey: string;
declare var FBSDKErrorArgumentValueKey: string;
declare var FBSDKErrorDeveloperMessageKey: string;
declare var FBSDKErrorDomain: string;
declare var FBSDKErrorLocalizedDescriptionKey: string;
declare var FBSDKErrorLocalizedTitleKey: string;
interface FBSDKErrorRecoveryAttempting extends NSObjectProtocol {
attemptRecoveryFromErrorOptionIndexCompletionHandler(error: NSError, recoveryOptionIndex: number, completionHandler: (p1: boolean) => void): void;
}
declare var FBSDKErrorRecoveryAttempting: {
prototype: FBSDKErrorRecoveryAttempting;
};
declare const enum FBSDKFeature {
None = 0,
Core = 16777216,
AppEvents = 16842752,
CodelessEvents = 16843008,
RestrictiveDataFiltering = 16843264,
AAM = 16843520,
PrivacyProtection = 16843776,
SuggestedEvents = 16843777,
IntelligentIntegrity = 16843778,
ModelRequest = 16843779,
EventDeactivation = 16844032,
SKAdNetwork = 16844288,
SKAdNetworkConversionValue = 16844289,
ATELogging = 16844544,
AEM = 16844800,
Instrument = 16908288,
CrashReport = 16908544,
CrashShield = 16908545,
ErrorReport = 16908800,
Login = 33554432,
Share = 50331648,
GamingServices = 67108864
}
interface FBSDKFeatureChecking {
checkFeatureCompletionBlock(feature: FBSDKFeature, completionBlock: (p1: boolean) => void): void;
isEnabled(feature: FBSDKFeature): boolean;
}
declare var FBSDKFeatureChecking: {
prototype: FBSDKFeatureChecking;
};
declare class FBSDKGraphErrorRecoveryProcessor extends NSObject {
static alloc(): FBSDKGraphErrorRecoveryProcessor; // inherited from NSObject
static new(): FBSDKGraphErrorRecoveryProcessor; // inherited from NSObject
constructor(o: { accessTokenString: string; });
initWithAccessTokenString(accessTokenString: string): this;
processErrorRequestDelegate(error: NSError, request: FBSDKGraphRequestProtocol, delegate: FBSDKGraphErrorRecoveryProcessorDelegate): boolean;
}
interface FBSDKGraphErrorRecoveryProcessorDelegate extends NSObjectProtocol {
processorDidAttemptRecoveryDidRecoverError(processor: FBSDKGraphErrorRecoveryProcessor, didRecover: boolean, error: NSError): void;
processorWillProcessErrorError?(processor: FBSDKGraphErrorRecoveryProcessor, error: NSError): boolean;
}
declare var FBSDKGraphErrorRecoveryProcessorDelegate: {
prototype: FBSDKGraphErrorRecoveryProcessorDelegate;
};
declare class FBSDKGraphRequest extends NSObject implements FBSDKGraphRequestProtocol {
static alloc(): FBSDKGraphRequest; // inherited from NSObject
static new(): FBSDKGraphRequest; // inherited from NSObject
readonly HTTPMethod: string; // inherited from FBSDKGraphRequestProtocol
readonly flags: FBSDKGraphRequestFlags; // inherited from FBSDKGraphRequestProtocol
graphErrorRecoveryDisabled: boolean; // inherited from FBSDKGraphRequestProtocol
readonly graphPath: string; // inherited from FBSDKGraphRequestProtocol
readonly hasAttachments: boolean; // inherited from FBSDKGraphRequestProtocol
parameters: NSDictionary<string, any>; // inherited from FBSDKGraphRequestProtocol
readonly tokenString: string; // inherited from FBSDKGraphRequestProtocol
readonly version: string; // inherited from FBSDKGraphRequestProtocol
constructor(o: { graphPath: string; });
constructor(o: { graphPath: string; HTTPMethod: string; });
constructor(o: { graphPath: string; parameters: NSDictionary<string, any>; });
constructor(o: { graphPath: string; parameters: NSDictionary<string, any>; flags: FBSDKGraphRequestFlags; });
constructor(o: { graphPath: string; parameters: NSDictionary<string, any>; HTTPMethod: string; });
constructor(o: { graphPath: string; parameters: NSDictionary<string, any>; tokenString: string; HTTPMethod: string; flags: FBSDKGraphRequestFlags; });
constructor(o: { graphPath: string; parameters: NSDictionary<string, any>; tokenString: string; version: string; HTTPMethod: string; });
formattedDescription(): string;
initWithGraphPath(graphPath: string): this;
initWithGraphPathHTTPMethod(graphPath: string, method: string): this;
initWithGraphPathParameters(graphPath: string, parameters: NSDictionary<string, any>): this;
initWithGraphPathParametersFlags(graphPath: string, parameters: NSDictionary<string, any>, requestFlags: FBSDKGraphRequestFlags): this;
initWithGraphPathParametersHTTPMethod(graphPath: string, parameters: NSDictionary<string, any>, method: string): this;
initWithGraphPathParametersTokenStringHTTPMethodFlags(graphPath: string, parameters: NSDictionary<string, any>, tokenString: string, HTTPMethod: string, flags: FBSDKGraphRequestFlags): this;
initWithGraphPathParametersTokenStringVersionHTTPMethod(graphPath: string, parameters: NSDictionary<string, any>, tokenString: string, version: string, method: string): this;
setGraphErrorRecoveryDisabled(disable: boolean): void;
startWithCompletion(completion: (p1: FBSDKGraphRequestConnecting, p2: any, p3: NSError) => void): FBSDKGraphRequestConnecting;
}
interface FBSDKGraphRequestConnecting {
delegate: FBSDKGraphRequestConnectionDelegate;
timeout: number;
addRequestCompletion(request: FBSDKGraphRequestProtocol, handler: (p1: FBSDKGraphRequestConnecting, p2: any, p3: NSError) => void): void;
cancel(): void;
start(): void;
}
declare var FBSDKGraphRequestConnecting: {
prototype: FBSDKGraphRequestConnecting;
};
declare class FBSDKGraphRequestConnection extends NSObject implements FBSDKGraphRequestConnecting {
static alloc(): FBSDKGraphRequestConnection; // inherited from NSObject
static new(): FBSDKGraphRequestConnection; // inherited from NSObject
delegateQueue: NSOperationQueue;
readonly urlResponse: NSHTTPURLResponse;
static defaultConnectionTimeout: number;
delegate: FBSDKGraphRequestConnectionDelegate; // inherited from FBSDKGraphRequestConnecting
timeout: number; // inherited from FBSDKGraphRequestConnecting
addRequestCompletion(request: FBSDKGraphRequestProtocol, handler: (p1: FBSDKGraphRequestConnecting, p2: any, p3: NSError) => void): void;
addRequestNameCompletion(request: FBSDKGraphRequestProtocol, name: string, completion: (p1: FBSDKGraphRequestConnecting, p2: any, p3: NSError) => void): void;
addRequestParametersCompletion(request: FBSDKGraphRequestProtocol, parameters: NSDictionary<string, any>, completion: (p1: FBSDKGraphRequestConnecting, p2: any, p3: NSError) => void): void;
cancel(): void;
overrideGraphAPIVersion(version: string): void;
start(): void;
}
interface FBSDKGraphRequestConnectionDelegate extends NSObjectProtocol {
requestConnectionDidFailWithError?(connection: FBSDKGraphRequestConnecting, error: NSError): void;
requestConnectionDidFinishLoading?(connection: FBSDKGraphRequestConnecting): void;
requestConnectionDidSendBodyDataTotalBytesWrittenTotalBytesExpectedToWrite?(connection: FBSDKGraphRequestConnecting, bytesWritten: number, totalBytesWritten: number, totalBytesExpectedToWrite: number): void;
requestConnectionWillBeginLoading?(connection: FBSDKGraphRequestConnecting): void;
}
declare var FBSDKGraphRequestConnectionDelegate: {
prototype: FBSDKGraphRequestConnectionDelegate;
};
declare class FBSDKGraphRequestConnectionFactory extends NSObject implements FBSDKGraphRequestConnectionFactoryProtocol {
static alloc(): FBSDKGraphRequestConnectionFactory; // inherited from NSObject
static new(): FBSDKGraphRequestConnectionFactory; // inherited from NSObject
createGraphRequestConnection(): FBSDKGraphRequestConnecting;
}
interface FBSDKGraphRequestConnectionFactoryProtocol {
createGraphRequestConnection(): FBSDKGraphRequestConnecting;
}
declare var FBSDKGraphRequestConnectionFactoryProtocol: {
prototype: FBSDKGraphRequestConnectionFactoryProtocol;
};
declare class FBSDKGraphRequestDataAttachment extends NSObject {
static alloc(): FBSDKGraphRequestDataAttachment; // inherited from NSObject
static new(): FBSDKGraphRequestDataAttachment; // inherited from NSObject
readonly contentType: string;
readonly data: NSData;
readonly filename: string;
constructor(o: { data: NSData; filename: string; contentType: string; });
initWithDataFilenameContentType(data: NSData, filename: string, contentType: string): this;
}
declare const enum FBSDKGraphRequestError {
Other = 0,
Transient = 1,
Recoverable = 2
}
declare var FBSDKGraphRequestErrorGraphErrorCodeKey: string;
declare var FBSDKGraphRequestErrorGraphErrorSubcodeKey: string;
declare var FBSDKGraphRequestErrorHTTPStatusCodeKey: string;
declare var FBSDKGraphRequestErrorKey: string;
declare var FBSDKGraphRequestErrorParsedJSONResponseKey: string;
declare class FBSDKGraphRequestFactory extends NSObject implements FBSDKGraphRequestFactoryProtocol {
static alloc(): FBSDKGraphRequestFactory; // inherited from NSObject
static new(): FBSDKGraphRequestFactory; // inherited from NSObject
createGraphRequestWithGraphPath(graphPath: string): FBSDKGraphRequestProtocol;
createGraphRequestWithGraphPathParameters(graphPath: string, parameters: NSDictionary<string, any>): FBSDKGraphRequestProtocol;
createGraphRequestWithGraphPathParametersFlags(graphPath: string, parameters: NSDictionary<string, any>, flags: FBSDKGraphRequestFlags): FBSDKGraphRequestProtocol;
createGraphRequestWithGraphPathParametersHTTPMethod(graphPath: string, parameters: NSDictionary<string, any>, method: string): FBSDKGraphRequestProtocol;
createGraphRequestWithGraphPathParametersTokenStringHTTPMethodFlags(graphPath: string, parameters: NSDictionary<string, any>, tokenString: string, method: string, flags: FBSDKGraphRequestFlags): FBSDKGraphRequestProtocol;
createGraphRequestWithGraphPathParametersTokenStringVersionHTTPMethod(graphPath: string, parameters: NSDictionary<string, any>, tokenString: string, version: string, method: string): FBSDKGraphRequestProtocol;
}
interface FBSDKGraphRequestFactoryProtocol {
createGraphRequestWithGraphPath(graphPath: string): FBSDKGraphRequestProtocol;
createGraphRequestWithGraphPathParameters(graphPath: string, parameters: NSDictionary<string, any>): FBSDKGraphRequestProtocol;
createGraphRequestWithGraphPathParametersFlags(graphPath: string, parameters: NSDictionary<string, any>, flags: FBSDKGraphRequestFlags): FBSDKGraphRequestProtocol;
createGraphRequestWithGraphPathParametersHTTPMethod(graphPath: string, parameters: NSDictionary<string, any>, method: string): FBSDKGraphRequestProtocol;
createGraphRequestWithGraphPathParametersTokenStringHTTPMethodFlags(graphPath: string, parameters: NSDictionary<string, any>, tokenString: string, method: string, flags: FBSDKGraphRequestFlags): FBSDKGraphRequestProtocol;
createGraphRequestWithGraphPathParametersTokenStringVersionHTTPMethod(graphPath: string, parameters: NSDictionary<string, any>, tokenString: string, version: string, method: string): FBSDKGraphRequestProtocol;
}
declare var FBSDKGraphRequestFactoryProtocol: {
prototype: FBSDKGraphRequestFactoryProtocol;
};
declare const enum FBSDKGraphRequestFlags {
None = 0,
SkipClientToken = 2,
DoNotInvalidateTokenOnError = 4,
DisableErrorRecovery = 8
}
interface FBSDKGraphRequestProtocol {
HTTPMethod: string;
flags: FBSDKGraphRequestFlags;
graphErrorRecoveryDisabled: boolean;
graphPath: string;
hasAttachments: boolean;
parameters: NSDictionary<string, any>;
tokenString: string;
version: string;
formattedDescription(): string;
startWithCompletion(completion: (p1: FBSDKGraphRequestConnecting, p2: any, p3: NSError) => void): FBSDKGraphRequestConnecting;
}
declare var FBSDKGraphRequestProtocol: {
prototype: FBSDKGraphRequestProtocol;
};
declare var FBSDKHTTPMethodDELETE: string;
declare var FBSDKHTTPMethodGET: string;
declare var FBSDKHTTPMethodPOST: string;
declare class FBSDKIcon extends NSObject {
static alloc(): FBSDKIcon; // inherited from NSObject
static new(): FBSDKIcon; // inherited from NSObject
pathWithSize(size: CGSize): any;
}
declare class FBSDKImpressionTrackingButton extends UIButton {
static alloc(): FBSDKImpressionTrackingButton; // inherited from NSObject
static appearance(): FBSDKImpressionTrackingButton; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): FBSDKImpressionTrackingButton; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): FBSDKImpressionTrackingButton; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKImpressionTrackingButton; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): FBSDKImpressionTrackingButton; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKImpressionTrackingButton; // inherited from UIAppearance
static buttonWithConfigurationPrimaryAction(configuration: UIButtonConfiguration, primaryAction: UIAction): FBSDKImpressionTrackingButton; // inherited from UIButton
static buttonWithType(buttonType: UIButtonType): FBSDKImpressionTrackingButton; // inherited from UIButton
static buttonWithTypePrimaryAction(buttonType: UIButtonType, primaryAction: UIAction): FBSDKImpressionTrackingButton; // inherited from UIButton
static new(): FBSDKImpressionTrackingButton; // inherited from NSObject
static systemButtonWithImageTargetAction(image: UIImage, target: any, action: string): FBSDKImpressionTrackingButton; // inherited from UIButton
static systemButtonWithPrimaryAction(primaryAction: UIAction): FBSDKImpressionTrackingButton; // inherited from UIButton
}
declare class FBSDKInternalUtility extends NSObject implements FBSDKAppAvailabilityChecker, FBSDKAppURLSchemeProviding, FBSDKInternalUtilityProtocol, FBSDKURLHosting {
static alloc(): FBSDKInternalUtility; // inherited from NSObject
static new(): FBSDKInternalUtility; // inherited from NSObject
readonly bundleForStrings: NSBundle;
static readonly sharedUtility: FBSDKInternalUtility;
readonly isFacebookAppInstalled: boolean; // inherited from FBSDKAppAvailabilityChecker
readonly isMSQRDPlayerAppInstalled: boolean; // inherited from FBSDKInternalUtilityProtocol
readonly isMessengerAppInstalled: boolean; // inherited from FBSDKAppAvailabilityChecker
URLWithSchemeHostPathQueryParametersError(scheme: string, host: string, path: string, queryParameters: NSDictionary<string, any>): NSURL;
appURLScheme(): string;
appURLWithHostPathQueryParametersError(host: string, path: string, queryParameters: NSDictionary<string, any>): NSURL;
checkRegisteredCanOpenURLScheme(urlScheme: string): void;
extractPermissionsFromResponseGrantedPermissionsDeclinedPermissionsExpiredPermissions(responseObject: NSDictionary<string, any>, grantedPermissions: NSMutableSet<any>, declinedPermissions: NSMutableSet<any>, expiredPermissions: NSMutableSet<any>): void;
facebookURLWithHostPrefixPathQueryParametersError(hostPrefix: string, path: string, queryParameters: NSDictionary<string, any>): NSURL;
findWindow(): UIWindow;
isBrowserURL(URL: NSURL): boolean;
isRegisteredCanOpenURLScheme(urlScheme: string): boolean;
isRegisteredURLScheme(urlScheme: string): boolean;
objectIsEqualToObject(object: any, other: any): boolean;
parametersFromFBURL(url: NSURL): NSDictionary<string, any>;
registerTransientObject(object: any): void;
topMostViewController(): UIViewController;
unregisterTransientObject(object: any): void;
validateAppID(): void;
validateRequiredClientAccessToken(): string;
validateURLSchemes(): void;
viewControllerForView(view: UIView): UIViewController;
}
interface FBSDKInternalUtilityProtocol {
isFacebookAppInstalled: boolean;
isMSQRDPlayerAppInstalled: boolean;
URLWithSchemeHostPathQueryParametersError(scheme: string, host: string, path: string, queryParameters: NSDictionary<string, any>): NSURL;
checkRegisteredCanOpenURLScheme(urlScheme: string): void;
registerTransientObject(object: any): void;
unregisterTransientObject(object: any): void;
validateURLSchemes(): void;
}
declare var FBSDKInternalUtilityProtocol: {
prototype: FBSDKInternalUtilityProtocol;
};
declare class FBSDKKeychainStore extends NSObject implements FBSDKKeychainStoreProtocol {
static alloc(): FBSDKKeychainStore; // inherited from NSObject
static new(): FBSDKKeychainStore; // inherited from NSObject
readonly accessGroup: string;
readonly service: string;
constructor(o: { service: string; accessGroup: string; });
dataForKey(key: string): NSData;
dictionaryForKey(key: string): NSDictionary<string, any>;
initWithServiceAccessGroup(service: string, accessGroup: string): this;
queryForKey(key: string): NSMutableDictionary<string, any>;
setDataForKeyAccessibility(value: NSData, key: string, accessibility: any): boolean;
setDictionaryForKeyAccessibility(value: NSDictionary<string, any>, key: string, accessibility: any): boolean;
setStringForKeyAccessibility(value: string, key: string, accessibility: any): boolean;
stringForKey(key: string): string;
}
declare class FBSDKKeychainStoreFactory extends NSObject implements FBSDKKeychainStoreProviding {
static alloc(): FBSDKKeychainStoreFactory; // inherited from NSObject
static new(): FBSDKKeychainStoreFactory; // inherited from NSObject
createKeychainStoreWithServiceAccessGroup(service: string, accessGroup: string): FBSDKKeychainStoreProtocol;
}
interface FBSDKKeychainStoreProtocol {
dictionaryForKey(key: string): NSDictionary<string, any>;
setDictionaryForKeyAccessibility(value: NSDictionary<string, any>, key: string, accessibility: any): boolean;
setStringForKeyAccessibility(value: string, key: string, accessibility: any): boolean;
stringForKey(key: string): string;
}
declare var FBSDKKeychainStoreProtocol: {
prototype: FBSDKKeychainStoreProtocol;
};
interface FBSDKKeychainStoreProviding {
createKeychainStoreWithServiceAccessGroup(service: string, accessGroup: string): FBSDKKeychainStoreProtocol;
}
declare var FBSDKKeychainStoreProviding: {
prototype: FBSDKKeychainStoreProviding;
};
declare class FBSDKLocation extends NSObject implements NSCopying, NSObjectProtocol, NSSecureCoding {
static alloc(): FBSDKLocation; // inherited from NSObject
static locationFromDictionary(dictionary: NSDictionary<string, string>): FBSDKLocation;
static new(): FBSDKLocation; // inherited from NSObject
readonly id: string;
readonly name: string;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding
constructor(o: { coder: NSCoder; }); // inherited from NSCoding
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
encodeWithCoder(coder: NSCoder): void;
initWithCoder(coder: NSCoder): this;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
self(): this;
}
declare class FBSDKLogger extends NSObject {
static alloc(): FBSDKLogger; // inherited from NSObject
static new(): FBSDKLogger; // inherited from NSObject
static singleShotLogEntryLogEntry(loggingBehavior: string, logEntry: string): void;
}
interface FBSDKLogging {
contents: string;
loggingBehavior: string;
initWithLoggingBehavior?(loggingBehavior: string): FBSDKLogging;
logEntry(logEntry: string): void;
}
declare var FBSDKLogging: {
prototype: FBSDKLogging;
singleShotLogEntryLogEntry(loggingBehavior: string, logEntry: string): void;
};
declare var FBSDKLoggingBehaviorAccessTokens: string;
declare var FBSDKLoggingBehaviorAppEvents: string;
declare var FBSDKLoggingBehaviorCacheErrors: string;
declare var FBSDKLoggingBehaviorDeveloperErrors: string;
declare var FBSDKLoggingBehaviorGraphAPIDebugInfo: string;
declare var FBSDKLoggingBehaviorGraphAPIDebugWarning: string;
declare var FBSDKLoggingBehaviorInformational: string;
declare var FBSDKLoggingBehaviorNetworkRequests: string;
declare var FBSDKLoggingBehaviorPerformanceCharacteristics: string;
declare var FBSDKLoggingBehaviorUIControlErrors: string;
declare class FBSDKLoginTooltip extends NSObject {
static alloc(): FBSDKLoginTooltip; // inherited from NSObject
static new(): FBSDKLoginTooltip; // inherited from NSObject
readonly enabled: boolean;
readonly text: string;
constructor(o: { text: string; enabled: boolean; });
initWithTextEnabled(text: string, enabled: boolean): this;
}
declare class FBSDKMeasurementEvent extends NSObject {
static alloc(): FBSDKMeasurementEvent; // inherited from NSObject
static new(): FBSDKMeasurementEvent; // inherited from NSObject
}
declare var FBSDKMeasurementEventArgsKey: string;
declare var FBSDKMeasurementEventNameKey: string;
declare var FBSDKMeasurementEventNotification: string;
interface FBSDKMutableCopying extends NSCopying, NSMutableCopying, NSObjectProtocol {
mutableCopy(): any;
}
declare var FBSDKMutableCopying: {
prototype: FBSDKMutableCopying;
};
declare var FBSDKNonJSONResponseProperty: string;
declare const enum FBSDKProductAvailability {
InStock = 0,
OutOfStock = 1,
PreOrder = 2,
AvailableForOrder = 3,
Discontinued = 4
}
declare const enum FBSDKProductCondition {
New = 0,
Refurbished = 1,
Used = 2
}
declare class FBSDKProfile extends NSObject implements FBSDKProfileProviding, NSCopying, NSSecureCoding {
static alloc(): FBSDKProfile; // inherited from NSObject
static enableUpdatesOnAccessTokenChange(enable: boolean): void;
static fetchCachedProfile(): FBSDKProfile;
static loadCurrentProfileWithCompletion(completion: (p1: FBSDKProfile, p2: NSError) => void): void;
static new(): FBSDKProfile; // inherited from NSObject
readonly ageRange: FBSDKUserAgeRange;
readonly birthday: Date;
readonly email: string;
readonly firstName: string;
readonly friendIDs: NSArray<string>;
readonly gender: string;
readonly hometown: FBSDKLocation;
readonly imageURL: NSURL;
readonly lastName: string;
readonly linkURL: NSURL;
readonly location: FBSDKLocation;
readonly middleName: string;
readonly name: string;
readonly refreshDate: Date;
readonly userID: string;
static currentProfile: FBSDKProfile; // inherited from FBSDKProfileProviding
static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding
constructor(o: { coder: NSCoder; }); // inherited from NSCoding
constructor(o: { userID: string; firstName: string; middleName: string; lastName: string; name: string; linkURL: NSURL; refreshDate: Date; });
constructor(o: { userID: string; firstName: string; middleName: string; lastName: string; name: string; linkURL: NSURL; refreshDate: Date; imageURL: NSURL; email: string; friendIDs: NSArray<string> | string[]; birthday: Date; ageRange: FBSDKUserAgeRange; hometown: FBSDKLocation; location: FBSDKLocation; gender: string; });
constructor(o: { userID: string; firstName: string; middleName: string; lastName: string; name: string; linkURL: NSURL; refreshDate: Date; imageURL: NSURL; email: string; friendIDs: NSArray<string> | string[]; birthday: Date; ageRange: FBSDKUserAgeRange; hometown: FBSDKLocation; location: FBSDKLocation; gender: string; isLimited: boolean; });
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
encodeWithCoder(coder: NSCoder): void;
imageURLForPictureModeSize(mode: FBSDKProfilePictureMode, size: CGSize): NSURL;
initWithCoder(coder: NSCoder): this;
initWithUserIDFirstNameMiddleNameLastNameNameLinkURLRefreshDate(userID: string, firstName: string, middleName: string, lastName: string, name: string, linkURL: NSURL, refreshDate: Date): this;
initWithUserIDFirstNameMiddleNameLastNameNameLinkURLRefreshDateImageURLEmailFriendIDsBirthdayAgeRangeHometownLocationGender(userID: string, firstName: string, middleName: string, lastName: string, name: string, linkURL: NSURL, refreshDate: Date, imageURL: NSURL, email: string, friendIDs: NSArray<string> | string[], birthday: Date, ageRange: FBSDKUserAgeRange, hometown: FBSDKLocation, location: FBSDKLocation, gender: string): this;
initWithUserIDFirstNameMiddleNameLastNameNameLinkURLRefreshDateImageURLEmailFriendIDsBirthdayAgeRangeHometownLocationGenderIsLimited(userID: string, firstName: string, middleName: string, lastName: string, name: string, linkURL: NSURL, refreshDate: Date, imageURL: NSURL, email: string, friendIDs: NSArray<string> | string[], birthday: Date, ageRange: FBSDKUserAgeRange, hometown: FBSDKLocation, location: FBSDKLocation, gender: string, isLimited: boolean): this;
isEqualToProfile(profile: FBSDKProfile): boolean;
}
declare var FBSDKProfileChangeNewKey: string;
declare var FBSDKProfileChangeOldKey: string;
declare var FBSDKProfileDidChangeNotification: string;
declare const enum FBSDKProfilePictureMode {
Square = 0,
Normal = 1,
Album = 2,
Small = 3,
Large = 4
}
declare class FBSDKProfilePictureView extends UIView {
static alloc(): FBSDKProfilePictureView; // inherited from NSObject
static appearance(): FBSDKProfilePictureView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): FBSDKProfilePictureView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): FBSDKProfilePictureView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKProfilePictureView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): FBSDKProfilePictureView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKProfilePictureView; // inherited from UIAppearance
static new(): FBSDKProfilePictureView; // inherited from NSObject
pictureMode: FBSDKProfilePictureMode;
profileID: string;
constructor(o: { frame: CGRect; profile: FBSDKProfile; });
constructor(o: { profile: FBSDKProfile; });
initWithFrameProfile(frame: CGRect, profile: FBSDKProfile): this;
initWithProfile(profile: FBSDKProfile): this;
setNeedsImageUpdate(): void;
}
interface FBSDKProfileProviding {
}
declare var FBSDKProfileProviding: {
prototype: FBSDKProfileProviding;
fetchCachedProfile(): FBSDKProfile;
};
declare class FBSDKServerConfigurationProvider extends NSObject {
static alloc(): FBSDKServerConfigurationProvider; // inherited from NSObject
static new(): FBSDKServerConfigurationProvider; // inherited from NSObject
readonly loggingToken: string;
cachedSmartLoginOptions(): number;
loadServerConfigurationWithCompletionBlock(completionBlock: (p1: FBSDKLoginTooltip, p2: NSError) => void): void;
useSafariViewControllerForDialogName(dialogName: string): boolean;
}
declare class FBSDKSettings extends NSObject implements FBSDKSettingsProtocol {
static alloc(): FBSDKSettings; // inherited from NSObject
static disableLoggingBehavior(loggingBehavior: string): void;
static enableLoggingBehavior(loggingBehavior: string): void;
static isAdvertiserTrackingEnabled(): boolean;
static new(): FBSDKSettings; // inherited from NSObject
static setAdvertiserTrackingEnabled(advertiserTrackingEnabled: boolean): boolean;
static setDataProcessingOptions(options: NSArray<string> | string[]): void;
static setDataProcessingOptionsCountryState(options: NSArray<string> | string[], country: number, state: number): void;
JPEGCompressionQuality: number;
autoLogAppEventsEnabled: boolean;
readonly defaultGraphAPIVersion: string;
skAdNetworkReportEnabled: boolean;
static JPEGCompressionQuality: number;
static SKAdNetworkReportEnabled: boolean;
static advertiserIDCollectionEnabled: boolean;
static appID: string;
static appURLSchemeSuffix: string;
static autoLogAppEventsEnabled: boolean;
static clientToken: string;
static codelessDebugLogEnabled: boolean;
static readonly defaultGraphAPIVersion: string;
static displayName: string;
static facebookDomainPart: string;
static graphAPIVersion: string;
static graphErrorRecoveryEnabled: boolean;
static limitEventAndDataUsage: boolean;
static readonly sdkVersion: string;
static readonly sharedSettings: FBSDKSettings;
static shouldUseCachedValuesForExpensiveMetadata: boolean;
advertiserIDCollectionEnabled: boolean; // inherited from FBSDKSettingsProtocol
advertiserTrackingEnabled: boolean; // inherited from FBSDKSettingsProtocol
readonly advertiserTrackingEnabledTimestamp: Date; // inherited from FBSDKSettingsProtocol
readonly advertisingTrackingStatus: FBSDKAdvertisingTrackingStatus; // inherited from FBSDKSettingsProtocol
appID: string; // inherited from FBSDKSettingsProtocol
appURLSchemeSuffix: string; // inherited from FBSDKSettingsProtocol
clientToken: string; // inherited from FBSDKSettingsProtocol
codelessDebugLogEnabled: boolean; // inherited from FBSDKSettingsProtocol
displayName: string; // inherited from FBSDKSettingsProtocol
facebookDomainPart: string; // inherited from FBSDKSettingsProtocol
readonly graphAPIDebugParamValue: string; // inherited from FBSDKSettingsProtocol
readonly graphAPIVersion: string; // inherited from FBSDKSettingsProtocol
readonly installTimestamp: Date; // inherited from FBSDKSettingsProtocol
readonly isAutoLogAppEventsEnabled: boolean; // inherited from FBSDKSettingsProtocol
readonly isDataProcessingRestricted: boolean; // inherited from FBSDKSettingsProtocol
isEventDataUsageLimited: boolean; // inherited from FBSDKSettingsProtocol
isGraphErrorRecoveryEnabled: boolean; // inherited from FBSDKSettingsProtocol
readonly isSKAdNetworkReportEnabled: boolean; // inherited from FBSDKSettingsProtocol
readonly isSetATETimeExceedsInstallTime: boolean; // inherited from FBSDKSettingsProtocol
loggingBehaviors: NSSet<string>; // inherited from FBSDKSettingsProtocol
readonly sdkVersion: string; // inherited from FBSDKSettingsProtocol
shouldUseCachedValuesForExpensiveMetadata: boolean; // inherited from FBSDKSettingsProtocol
shouldUseTokenOptimizations: boolean; // inherited from FBSDKSettingsProtocol
userAgentSuffix: string; // inherited from FBSDKSettingsProtocol
static loggingBehaviors: NSSet<string>; // inherited from FBSDKSettingsProtocol
disableLoggingBehavior(loggingBehavior: string): void;
enableLoggingBehavior(loggingBehavior: string): void;
}
interface FBSDKSettingsLogging {
logIfSDKSettingsChanged(): void;
logWarnings(): void;
recordInstall(): void;
}
declare var FBSDKSettingsLogging: {
prototype: FBSDKSettingsLogging;
};
interface FBSDKSettingsProtocol {
advertiserIDCollectionEnabled: boolean;
advertiserTrackingEnabled: boolean;
advertiserTrackingEnabledTimestamp: Date;
advertisingTrackingStatus: FBSDKAdvertisingTrackingStatus;
appID: string;
appURLSchemeSuffix: string;
clientToken: string;
codelessDebugLogEnabled: boolean;
displayName: string;
facebookDomainPart: string;
graphAPIDebugParamValue: string;
graphAPIVersion: string;
installTimestamp: Date;
isAutoLogAppEventsEnabled: boolean;
isDataProcessingRestricted: boolean;
isEventDataUsageLimited: boolean;
isGraphErrorRecoveryEnabled: boolean;
isSKAdNetworkReportEnabled: boolean;
isSetATETimeExceedsInstallTime: boolean;
loggingBehaviors: NSSet<string>;
sdkVersion: string;
shouldUseCachedValuesForExpensiveMetadata: boolean;
shouldUseTokenOptimizations: boolean;
userAgentSuffix: string;
}
declare var FBSDKSettingsProtocol: {
prototype: FBSDKSettingsProtocol;
};
declare class FBSDKShareDialogConfiguration extends NSObject {
static alloc(): FBSDKShareDialogConfiguration; // inherited from NSObject
static new(): FBSDKShareDialogConfiguration; // inherited from NSObject
readonly defaultShareMode: string;
shouldUseNativeDialogForDialogName(dialogName: string): boolean;
shouldUseSafariViewControllerForDialogName(dialogName: string): boolean;
}
interface FBSDKTokenCaching extends NSObjectProtocol {
accessToken: FBSDKAccessToken;
authenticationToken: FBSDKAuthenticationToken;
}
declare var FBSDKTokenCaching: {
prototype: FBSDKTokenCaching;
};
interface FBSDKTokenStringProviding {
}
declare var FBSDKTokenStringProviding: {
prototype: FBSDKTokenStringProviding;
};
declare class FBSDKTransformer extends NSObject {
static alloc(): FBSDKTransformer; // inherited from NSObject
static new(): FBSDKTransformer; // inherited from NSObject
CATransform3DConcatB(a: CATransform3D, b: CATransform3D): CATransform3D;
CATransform3DMakeScaleSySz(sx: number, sy: number, sz: number): CATransform3D;
CATransform3DMakeTranslationTyTz(tx: number, ty: number, tz: number): CATransform3D;
}
declare class FBSDKURL extends NSObject {
static URLWithInboundURLSourceApplication(url: NSURL, sourceApplication: string): FBSDKURL;
static URLWithURL(url: NSURL): FBSDKURL;
static alloc(): FBSDKURL; // inherited from NSObject
static new(): FBSDKURL; // inherited from NSObject
readonly appLinkData: NSDictionary<string, any>;
readonly appLinkExtras: NSDictionary<string, any>;
readonly appLinkReferer: FBSDKAppLink;
readonly inputQueryParameters: NSDictionary<string, any>;
readonly inputURL: NSURL;
readonly isAutoAppLink: boolean;
readonly targetQueryParameters: NSDictionary<string, any>;
readonly targetURL: NSURL;
}
interface FBSDKURLHosting {
appURLWithHostPathQueryParametersError(host: string, path: string, queryParameters: NSDictionary<string, any>): NSURL;
facebookURLWithHostPrefixPathQueryParametersError(hostPrefix: string, path: string, queryParameters: NSDictionary<string, any>): NSURL;
}
declare var FBSDKURLHosting: {
prototype: FBSDKURLHosting;
};
interface FBSDKURLOpener {
openURLSenderHandler(url: NSURL, sender: FBSDKURLOpening, handler: (p1: boolean, p2: NSError) => void): void;
openURLWithSafariViewControllerSenderFromViewControllerHandler(url: NSURL, sender: FBSDKURLOpening, fromViewController: UIViewController, handler: (p1: boolean, p2: NSError) => void): void;
}
declare var FBSDKURLOpener: {
prototype: FBSDKURLOpener;
};
interface FBSDKURLOpening extends NSObjectProtocol {
applicationDidBecomeActive(application: UIApplication): void;
applicationOpenURLSourceApplicationAnnotation(application: UIApplication, url: NSURL, sourceApplication: string, annotation: any): boolean;
canOpenURLForApplicationSourceApplicationAnnotation(url: NSURL, application: UIApplication, sourceApplication: string, annotation: any): boolean;
isAuthenticationURL(url: NSURL): boolean;
shouldStopPropagationOfURL?(url: NSURL): boolean;
}
declare var FBSDKURLOpening: {
prototype: FBSDKURLOpening;
};
declare class FBSDKUserAgeRange extends NSObject implements NSCopying, NSObjectProtocol, NSSecureCoding {
static ageRangeFromDictionary(dictionary: NSDictionary<string, number>): FBSDKUserAgeRange;
static alloc(): FBSDKUserAgeRange; // inherited from NSObject
static new(): FBSDKUserAgeRange; // inherited from NSObject
readonly max: number;
readonly min: number;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding
constructor(o: { coder: NSCoder; }); // inherited from NSCoding
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
encodeWithCoder(coder: NSCoder): void;
initWithCoder(coder: NSCoder): this;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
self(): this;
}
declare class FBSDKUtility extends NSObject {
static SHA256Hash(input: NSObject): string;
static URLDecode(value: string): string;
static URLEncode(value: string): string;
static alloc(): FBSDKUtility; // inherited from NSObject
static dictionaryWithQueryString(queryString: string): NSDictionary<string, string>;
static getGraphDomainFromToken(): string;
static new(): FBSDKUtility; // inherited from NSObject
static queryStringWithDictionaryError(dictionary: NSDictionary<string, any>): string;
static startGCDTimerWithIntervalBlock(interval: number, block: () => void): NSObject;
static stopGCDTimer(timer: NSObject): void;
static unversionedFacebookURLWithHostPrefixPathQueryParametersError(hostPrefix: string, path: string, queryParameters: NSDictionary<string, any>): NSURL;
}
declare class FBSDKWebDialog extends NSObject {
static alloc(): FBSDKWebDialog; // inherited from NSObject
static createAndShowParametersFrameDelegateWindowFinder(name: string, parameters: NSDictionary<string, any>, frame: CGRect, delegate: FBSDKWebDialogDelegate, windowFinder: FBSDKWindowFinding): FBSDKWebDialog;
static dialogWithNameDelegate(name: string, delegate: FBSDKWebDialogDelegate): FBSDKWebDialog;
static new(): FBSDKWebDialog; // inherited from NSObject
static showWithNameParametersDelegate(name: string, parameters: NSDictionary<string, any>, delegate: FBSDKWebDialogDelegate): FBSDKWebDialog;
shouldDeferVisibility: boolean;
windowFinder: FBSDKWindowFinding;
}
interface FBSDKWebDialogDelegate {
webDialogDidCancel(webDialog: FBSDKWebDialog): void;
webDialogDidCompleteWithResults(webDialog: FBSDKWebDialog, results: NSDictionary<string, any>): void;
webDialogDidFailWithError(webDialog: FBSDKWebDialog, error: NSError): void;
}
declare var FBSDKWebDialogDelegate: {
prototype: FBSDKWebDialogDelegate;
};
declare class FBSDKWebDialogView extends UIView {
static alloc(): FBSDKWebDialogView; // inherited from NSObject
static appearance(): FBSDKWebDialogView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): FBSDKWebDialogView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): FBSDKWebDialogView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKWebDialogView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): FBSDKWebDialogView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKWebDialogView; // inherited from UIAppearance
static configureWithWebViewProviderUrlOpener(provider: any, urlOpener: any): void;
static new(): FBSDKWebDialogView; // inherited from NSObject
delegate: FBSDKWebDialogViewDelegate;
loadURL(URL: NSURL): void;
stopLoading(): void;
}
interface FBSDKWebDialogViewDelegate extends NSObjectProtocol {
webDialogViewDidCancel(webDialogView: FBSDKWebDialogView): void;
webDialogViewDidCompleteWithResults(webDialogView: FBSDKWebDialogView, results: NSDictionary<string, any>): void;
webDialogViewDidFailWithError(webDialogView: FBSDKWebDialogView, error: NSError): void;
webDialogViewDidFinishLoad(webDialogView: FBSDKWebDialogView): void;
}
declare var FBSDKWebDialogViewDelegate: {
prototype: FBSDKWebDialogViewDelegate;
};
declare class FBSDKWebViewAppLinkResolver extends NSObject implements FBSDKAppLinkResolving {
static alloc(): FBSDKWebViewAppLinkResolver; // inherited from NSObject
static new(): FBSDKWebViewAppLinkResolver; // inherited from NSObject
static readonly sharedInstance: FBSDKWebViewAppLinkResolver;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
appLinkFromURLHandler(url: NSURL, handler: (p1: FBSDKAppLink, p2: NSError) => void): void;
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
self(): this;
}
interface FBSDKWindowFinding {
findWindow(): UIWindow;
}
declare var FBSDKWindowFinding: {
prototype: FBSDKWindowFinding;
};
declare function fb_randomString(numberOfBytes: number): string;
declare function fbsdkdfl_SLComposeViewControllerClass(): typeof NSObject;
declare function fbsdkdfl_SLServiceTypeFacebook(): string; | the_stack |
import { promises as fs } from 'fs'
import path from 'path'
import xml2js from 'xml2js'
import { serializeBlueprint } from '../build/soong'
import { aapt2 } from '../util/process'
import { exists, listFilesRecursive } from '../util/fs'
import { XML_HEADER } from '../util/headers'
import { parseLines } from '../util/parse'
import { EXT_PARTITIONS } from '../util/partitions'
import { Filters, filterValue } from '../config/filters'
const TARGET_PACKAGE_PATTERN = makeManifestRegex('targetPackage')
const TARGET_NAME_PATTERN = makeManifestRegex('targetName')
// This is terrible, but aapt2 doesn't escape strings properly and some of these
// strings contain double quotes, which break our parser.
const EXCLUDE_LOCALES = new Set(['ar', 'iw'])
// Diff exclusions
const DIFF_EXCLUDE_TYPES = new Set(['raw', 'xml', 'color'])
const DIFF_MAP_PACKAGES = new Map([
['com.google.android.wifi.resources', 'com.android.wifi.resources'],
['com.google.android.connectivity.resources', 'com.android.connectivity.resources'],
['com.google.android.networkstack', 'com.android.networkstack'],
['com.google.android.networkstack.tethering', 'com.android.networkstack.tethering'],
['com.google.android.permissioncontroller', 'com.android.permissioncontroller'],
])
const XML_BUILDER = new xml2js.Builder()
export type ResValue = number | boolean | string | Array<ResValue>
export interface ResKey {
targetPkg: string
targetName: string | null
type: string
key: string
flags: string | null
}
export type ResValues = Map<string, ResValue>
export type PartResValues = { [part: string]: ResValues }
function makeManifestRegex(attr: string) {
return new RegExp(
/^\s+A: http:\/\/schemas.android.com\/apk\/res\/android:/.source +
attr +
/\(0x[a-z0-9]+\)="(.+)" \(Raw: ".*$/.source,
'm', // multiline flag
)
}
function encodeResKey(key: ResKey) {
// pkg/name:type/key|flags
return (
`${key.targetPkg}${key.targetName?.length ? `/${key.targetName}` : ''}:` +
`${key.type}/${key.key}${key.flags?.length ? `|${key.flags}` : ''}`
)
}
export function decodeResKey(encoded: string) {
let [tpn, tkf] = encoded.split(':')
let [targetPkg, targetName] = tpn.split('/')
let [type, kf] = tkf.split('/')
let [key, flags] = kf.split('|')
return {
targetPkg,
targetName: targetName != undefined ? targetName : null,
type,
key,
flags: flags != undefined ? flags : null,
} as ResKey
}
function toResKey(
targetPkg: string,
targetName: string | null,
type: string | null,
key: string | null,
flags: string | null,
) {
return encodeResKey({
targetPkg,
targetName,
type: type!,
key: key!,
flags: flags!,
})
}
function finishArray(
values: Map<string, ResValue>,
targetPkg: string,
targetName: string | null,
type: string | null,
key: string | null,
flags: string | null,
arrayLines: Array<string> | null,
) {
// Exclude problematic locales and types (ID references)
let rawValue = arrayLines!.join('\n')
if (EXCLUDE_LOCALES.has(flags!) || rawValue.startsWith('[@0x')) {
return
}
let array = parseAaptJson(rawValue) as Array<ResValue>
// Change to typed array?
if (typeof array[0] === 'string') {
type = 'string-array'
} else if (typeof array[0] === 'number') {
// Float arrays are just <array>, so check for integers
if (array.find(v => !Number.isInteger(v)) == undefined) {
type = 'integer-array'
}
}
values.set(toResKey(targetPkg, targetName, type, key, flags), array)
}
function parseAaptJson(value: string) {
// Fix backslash escapes
value = value.replaceAll(/\\/g, '\\\\')
// Parse hex arrays
value = value.replaceAll(/\b0x[0-9a-f]+\b/g, value => `${parseInt(value.slice(2), 16)}`)
return JSON.parse(value)
}
function parseRsrcLines(rsrc: string, targetPkg: string, targetName: string | null) {
// Finished values with encoded res keys
let values: ResValues = new Map<string, ResValue>()
// Current resource state machine
let curType: string | null = null
let curKey: string | null = null
let curFlags: string | null = null
let curArray: Array<string> | null = null
// Parse line-by-line
for (let line of parseLines(rsrc)) {
// Start resource
let resStart = line.match(/^resource 0x[a-z0-9]+ (.+)$/)
if (resStart) {
// Finish last array?
if (curArray != null) {
finishArray(values, targetPkg, targetName, curType, curKey, curFlags, curArray)
}
let keyParts = resStart[1]!.split('/')
curType = keyParts[0]
curKey = keyParts[1]
curFlags = null
curArray = null
continue
}
// New resource is array
let arrayLine = line.match(/^\(([a-zA-Z0-9\-_+]*)\) \(array\) size=\d+$/)
if (arrayLine) {
// Finish last array?
if (curArray != null) {
finishArray(values, targetPkg, targetName, curType, curKey, curFlags, curArray)
}
// Start new array
curFlags = arrayLine[1]
curArray = []
continue
}
// New value
let valueLine = line.match(/^\(([a-zA-Z0-9\-_+]*)\) (.+)$/)
if (valueLine) {
curFlags = valueLine![1]
// Exclude broken locales and styles for now
if (EXCLUDE_LOCALES.has(curFlags!) || curType == 'style') {
continue
}
let value: ResValue
let rawValue = valueLine![2]
if (rawValue.startsWith('(file) ')) {
// Return @[path]
value = `@${rawValue.split(' ')[1]}`
} else if (curType == 'dimen') {
// Keep dimensions as strings to preserve unit
value = rawValue
} else if (curType == 'color') {
// Raw hex code
value = rawValue
} else if (rawValue.startsWith('0x')) {
// Hex integer
value = parseInt(rawValue.slice(2), 16)
} else if (rawValue.startsWith('(styled string) ')) {
// Skip styled strings for now
continue
} else if (curType == 'string') {
// Don't rely on quotes for simple strings
value = rawValue.slice(1, -1)
} else {
value = parseAaptJson(rawValue)
}
values.set(toResKey(targetPkg, targetName, curType, curKey, curFlags), value)
}
// New type section
let typeLine = line.match(/^type .+$/)
if (typeLine) {
// Just skip this line. Next resource/end will finish the last array, and this
// shouldn't be added to the last array.
continue
}
// Continuation of array?
if (curArray != null) {
curArray.push(line)
}
}
// Finish remaining array?
if (curArray != null) {
finishArray(values, targetPkg, targetName, curType, curKey, curFlags, curArray)
}
return values
}
async function parseOverlayApksRecursive(
aapt2Path: string,
overlaysDir: string,
pathCallback?: (path: string) => void,
filters: Filters | null = null,
) {
let values: ResValues = new Map<string, ResValue>()
for await (let apkPath of listFilesRecursive(overlaysDir)) {
if (path.extname(apkPath) != '.apk') {
continue
}
if (pathCallback != undefined) {
pathCallback(apkPath)
}
if (filters != null && !filterValue(filters, path.relative(overlaysDir, apkPath))) {
continue
}
// Check the manifest for eligibility first
let manifest = await aapt2(aapt2Path, 'dump', 'xmltree', '--file', 'AndroidManifest.xml', apkPath)
// Overlays that have categories are user-controlled, so they're not relevant here
if (manifest.includes('A: http://schemas.android.com/apk/res/android:category(')) {
continue
}
// Prop-guarded overlays are almost always in AOSP already, so don't bother checking them
if (manifest.includes('A: http://schemas.android.com/apk/res/android:requiredSystemPropertyName(')) {
continue
}
// Get the target package
let match = manifest.match(TARGET_PACKAGE_PATTERN)
if (!match) throw new Error(`Overlay ${apkPath} is missing target package`)
let targetPkg = match[1]
// Get the target overlayable config name, if it exists
match = manifest.match(TARGET_NAME_PATTERN)
let targetName = match == undefined ? null : match[1]
// Overlay is eligible, now read the resource table
let rsrc = await aapt2(aapt2Path, 'dump', 'resources', apkPath)
let apkValues = parseRsrcLines(rsrc, targetPkg, targetName)
// Merge overlayed values
for (let [key, value] of apkValues) {
values.set(key, value)
}
}
return values
}
export async function parsePartOverlayApks(
aapt2Path: string,
root: string,
pathCallback?: (path: string) => void,
filters: Filters | null = null,
) {
let partValues: PartResValues = {}
for (let partition of EXT_PARTITIONS) {
let src = `${root}/${partition}/overlay`
if (!(await exists(src))) {
continue
}
partValues[partition] = await parseOverlayApksRecursive(aapt2Path, src, pathCallback, filters)
}
return partValues
}
function shouldDeleteKey(filters: Filters, rawKey: string, { targetPkg, type, key, flags }: ResKey) {
// Simple exclusion sets
if (DIFF_EXCLUDE_TYPES.has(type)) {
return true
}
// Exclude localized values for now
if (flags != null) {
return true
}
// User-provided filters
if (!filterValue(filters, rawKey)) {
return true
}
return false
}
function filterValues(keyFilters: Filters, valueFilters: Filters, values: ResValues) {
for (let [rawKey, value] of values.entries()) {
let key = decodeResKey(rawKey)
if (shouldDeleteKey(keyFilters, rawKey, key) || (typeof value === 'string' && !filterValue(valueFilters, value))) {
// Key/value filter
values.delete(rawKey)
} else if (DIFF_MAP_PACKAGES.has(key.targetPkg)) {
// Package map
let targetPkg = DIFF_MAP_PACKAGES.get(key.targetPkg)!
let newKey = encodeResKey({
...key,
targetPkg,
})
values.delete(rawKey)
values.set(newKey, value)
}
}
}
export function diffPartOverlays(
pvRef: PartResValues,
pvNew: PartResValues,
keyFilters: Filters,
valueFilters: Filters,
) {
let missingPartValues: PartResValues = {}
for (let [partition, valuesNew] of Object.entries(pvNew)) {
let valuesRef = pvRef[partition]
let missingValues: ResValues = new Map<string, ResValue>()
// Filter values first
filterValues(keyFilters, valueFilters, valuesRef)
filterValues(keyFilters, valueFilters, valuesNew)
// Find missing overlays
for (let [key, refValue] of valuesRef.entries()) {
if (!valuesNew.has(key)) {
missingValues.set(key, refValue)
}
}
if (missingValues.size > 0) {
missingPartValues[partition] = missingValues
}
}
return missingPartValues
}
function serializeXmlObject(obj: any) {
return XML_HEADER + XML_BUILDER.buildObject(obj).replace(/^<\?xml.*>$/m, '')
}
export async function serializePartOverlays(partValues: PartResValues, overlaysDir: string) {
let buildPkgs = []
for (let [partition, values] of Object.entries(partValues)) {
// Group by package and target name
let pkgValues = new Map<string, Map<ResKey, ResValue>>()
for (let [key, value] of values.entries()) {
let keyInfo = decodeResKey(key)
let pkgNameKey = `${keyInfo.targetPkg}${keyInfo.targetName?.length ? `/${keyInfo.targetName}` : ''}`
if (pkgValues.has(pkgNameKey)) {
pkgValues.get(pkgNameKey)!.set(keyInfo, value)
} else {
pkgValues.set(pkgNameKey, new Map<ResKey, ResValue>([[keyInfo, value]]))
}
}
// Now serialize each (package,target)-partition combination
for (let [pkgNameKey, values] of pkgValues.entries()) {
let [targetPkg, targetName] = pkgNameKey.split('/')
let genTarget = pkgNameKey.replace('/', '__')
let rroName = `${genTarget}.auto_generated_rro_${partition}_adevtool__`
let bp = serializeBlueprint({
modules: [
{
_type: 'runtime_resource_overlay',
name: rroName,
...(partition == 'system_ext' && { system_ext_specific: true }),
...(partition == 'product' && { product_specific: true }),
...(partition == 'vendor' && { soc_specific: true }),
...(partition == 'odm' && { device_specific: true }),
},
],
})
let manifest = serializeXmlObject({
manifest: {
$: {
'xmlns:android': 'http://schemas.android.com/apk/res/android',
package: rroName,
},
overlay: [
{
$: {
'android:targetPackage': targetPkg,
'android:targetName': targetName,
'android:isStatic': 'true',
'android:priority': '1',
},
},
],
application: [{ $: { 'android:hasCode': 'false' } }],
},
})
let valuesObj = { resources: {} as { [type: string]: Array<any> } }
for (let [{ type, key }, value] of values.entries()) {
let entry = {
$: {
name: key,
},
} as { [key: string]: any }
if (type.includes('array')) {
entry.item = (value as Array<any>).map(v => JSON.stringify(v))
} else {
entry._ = value
}
if (valuesObj.resources.hasOwnProperty(type)) {
valuesObj.resources[type].push(entry)
} else {
valuesObj.resources[type] = [entry]
}
}
let valuesXml = serializeXmlObject(valuesObj)
// Write files
let overlayDir = `${overlaysDir}/${partition}_${genTarget}`
let resDir = `${overlayDir}/res/values`
await fs.mkdir(resDir, { recursive: true })
await fs.writeFile(`${overlayDir}/Android.bp`, bp)
await fs.writeFile(`${overlayDir}/AndroidManifest.xml`, manifest)
await fs.writeFile(`${resDir}/values.xml`, valuesXml)
buildPkgs.push(rroName)
}
}
return buildPkgs
} | the_stack |
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { Clear } from '../actions/actions';
import { Create, CreateMany } from '../actions/create-actions';
import { Delete, DeleteMany } from '../actions/delete-actions';
import { DeleteByKey, DeleteManyByKeys } from '../actions/delete-by-key-actions';
import { Deselect, DeselectAll, DeselectMany, DeselectManyByKeys } from '../actions/deselection-actions';
import { Change, Edit, EditByKey, EditNew, EndEdit } from '../actions/edit-actions';
import { Load, LoadIfNecessary } from '../actions/load-actions';
import { LoadAll, LoadAllIfNecessary } from '../actions/load-all-actions';
import { LoadMany, LoadManyIfNecessary } from '../actions/load-many-actions';
import { LoadPage, LoadPageIfNecessary } from '../actions/load-page-actions';
import { LoadRange, LoadRangeIfNecessary } from '../actions/load-range-actions';
import { Replace, ReplaceMany } from '../actions/replace-actions';
import { Select, SelectByKey, SelectMany, SelectManyByKeys, SelectMore, SelectMoreByKeys } from '../actions/selection-actions';
import { Update, UpdateMany } from '../actions/update-actions';
import { Upsert, UpsertMany } from '../actions/upsert-actions';
import { Page, Range } from '../models';
import { EntityIdentity } from '../types/entity-identity';
import { IEntityDictionary } from './entity-state';
import { IEntityFacade } from './facade';
import { ISelectorMap } from './selector-map';
/**
* Builds a new facade class for the specified entity model and parent state.
* @param selectors - the selector map for the specified entity
*/
export const buildFacade = <TModel, TParentState>(selectors: ISelectorMap<TParentState, TModel>) => {
const BaseFacade = class Facade implements IEntityFacade<TModel> {
modelType: new () => TModel;
store: Store<any>;
constructor(modelType: new () => TModel, store: Store<any>) {
this.modelType = modelType;
this.store = store;
this.all$ = this.store.select(selectors.selectAll);
this.sorted$ = this.store.select(selectors.selectAllSorted);
this.entities$ = this.store.select(selectors.selectEntities);
this.ids$ = this.store.select(selectors.selectIds);
this.total$ = this.store.select(selectors.selectTotal);
this.hasEntities$ = this.store.select(selectors.selectHasEntities);
this.hasNoEntities$ = this.store.select(selectors.selectHasNoEntities);
this.total$ = this.store.select(selectors.selectTotal);
this.current$ = this.store.select(selectors.selectCurrentEntity);
this.currentKey$ = this.store.select(selectors.selectCurrentEntityKey);
this.currentSet$ = this.store.select(selectors.selectCurrentEntities);
this.currentSetKeys$ = this.store.select(selectors.selectCurrentEntitiesKeys);
this.edited$ = this.store.select(selectors.selectEditedEntity);
this.isDirty$ = this.store.select(selectors.selectIsDirty);
this.currentPage$ = this.store.select(selectors.selectCurrentPage);
this.currentRange$ = this.store.select(selectors.selectCurrentRange);
this.totalPageable$ = this.store.select(selectors.selectTotalPageable);
this.isLoading$ = this.store.select(selectors.selectIsLoading);
this.isSaving$ = this.store.select(selectors.selectIsSaving);
this.isDeleting$ = this.store.select(selectors.selectIsDeleting);
this.loadedAt$ = this.store.select(selectors.selectLoadedAt);
this.savedAt$ = this.store.select(selectors.selectSavedAt);
this.createdAt$ = this.store.select(selectors.selectCreatedAt);
this.updatedAt$ = this.store.select(selectors.selectUpdatedAt);
this.replacedAt$ = this.store.select(selectors.selectReplacedAt);
this.deletedAt$ = this.store.select(selectors.selectDeletedAt);
}
// region Selections
all$: Observable<TModel[]>;
sorted$: Observable<TModel[]>;
entities$: Observable<IEntityDictionary<TModel>>;
ids$: Observable<EntityIdentity[]>;
total$: Observable<number>;
hasEntities$: Observable<boolean>;
hasNoEntities$: Observable<boolean>;
current$: Observable<TModel>;
currentKey$: Observable<EntityIdentity>;
currentSet$: Observable<TModel[]>;
currentSetKeys$: Observable<EntityIdentity[]>;
edited$: Observable<Partial<TModel>>;
isDirty$: Observable<boolean>;
currentPage$: Observable<Page>;
currentRange$: Observable<Range>;
totalPageable$: Observable<number>;
isLoading$: Observable<boolean>;
isSaving$: Observable<boolean>;
isDeleting$: Observable<boolean>;
loadedAt$: Observable<Date>;
savedAt$: Observable<Date>;
createdAt$: Observable<Date>;
updatedAt$: Observable<Date>;
replacedAt$: Observable<Date>;
deletedAt$: Observable<Date>;
customSorted$(name: string): Observable<TModel[]> {
return this.store.select(selectors.selectCustomSorted, { name });
}
// endregion
// region Activities
select(entity: TModel, correlationId?: string): string {
const action = new Select(this.modelType, entity, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
selectByKey(key: EntityIdentity, correlationId?: string): string {
const action = new SelectByKey(this.modelType, key, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
selectMany(entities: TModel[], correlationId?: string): string {
const action = new SelectMany(this.modelType, entities, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
selectMore(entities: TModel[], correlationId?: string): string {
const action = new SelectMore(this.modelType, entities, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
selectManyByKeys(keys: EntityIdentity[], correlationId?: string): string {
const action = new SelectManyByKeys(this.modelType, keys, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
selectMoreByKeys(keys: EntityIdentity[], correlationId?: string): string {
const action = new SelectMoreByKeys(this.modelType, keys, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
deselect(correlationId?: string): string {
const action = new Deselect(this.modelType, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
deselectMany(entities: TModel[], correlationId?: string): string {
const action = new DeselectMany(this.modelType, entities, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
deselectManyByKeys(keys: EntityIdentity[], correlationId?: string): string {
const action = new DeselectManyByKeys(this.modelType, keys, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
deselectAll(correlationId?: string): string {
const action = new DeselectAll(this.modelType, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
edit(entity: Partial<TModel>, correlationId?: string): string {
const action = new Edit(this.modelType, entity, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
editNew(entity?: Partial<TModel>, correlationId?: string): string {
const action = new EditNew(this.modelType, entity, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
editByKey(key: EntityIdentity, correlationId?: string): string {
const action = new EditByKey(this.modelType, key, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
change(entity: Partial<TModel>, correlationId?: string): string {
const action = new Change(this.modelType, entity, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
endEdit(correlationId?: string): string {
const action = new EndEdit(this.modelType, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
load(keys?: any, criteria?: any, correlationId?: string): string {
const action = new Load(this.modelType, keys, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
loadIfNecessary(keys?: any, criteria?: any, maxAge?: number, correlationId?: string): string {
const action = new LoadIfNecessary(this.modelType, keys, maxAge, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
loadMany(criteria?: any, correlationId?: string): string {
const action = new LoadMany(this.modelType, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
loadManyIfNecessary(criteria?: any, maxAge?: number, correlationId?: string): string {
const action = new LoadManyIfNecessary(this.modelType, maxAge, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
loadAll(criteria?: any, correlationId?: string): string {
const action = new LoadAll(this.modelType, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
loadAllIfNecessary(criteria?: any, maxAge?: number, correlationId?: string): string {
const action = new LoadAllIfNecessary(this.modelType, maxAge, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
loadPage(page: Page, criteria?: any, correlationId?: string): string {
const action = new LoadPage(this.modelType, page, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
loadPageIfNecessary(page: Page, criteria?: any, maxAge?: number, correlationId?: string): string {
const action = new LoadPageIfNecessary(this.modelType, page, maxAge, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
loadRange(range: Range, criteria?: any, correlationId?: string): string {
const action = new LoadRange(this.modelType, range, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
loadRangeIfNecessary(range: Range, criteria?: any, maxAge?: number, correlationId?: string): string {
const action = new LoadRangeIfNecessary(this.modelType, range, maxAge, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
create(entity: TModel, criteria?: any, correlationId?: string): string {
const action = new Create(this.modelType, entity, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
createMany(entities: TModel[], criteria?: any, correlationId?: string): string {
const action = new CreateMany(this.modelType, entities, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
update(entity: TModel, criteria?: any, correlationId?: string): string {
const action = new Update(this.modelType, entity, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
updateMany(entities: TModel[], criteria?: any, correlationId?: string): string {
const action = new UpdateMany(this.modelType, entities, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
upsert(entity: TModel, criteria?: any, correlationId?: string): string {
const action = new Upsert(this.modelType, entity, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
upsertMany(entities: TModel[], criteria?: any, correlationId?: string): string {
const action = new UpsertMany(this.modelType, entities, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
replace(entity: TModel, criteria?: any, correlationId?: string): string {
const action = new Replace(this.modelType, entity, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
replaceMany(entities: TModel[], criteria?: any, correlationId?: string): string {
const action = new ReplaceMany(this.modelType, entities, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
delete(entity: TModel, criteria?: any, correlationId?: string): string {
const action = new Delete(this.modelType, entity, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
deleteMany(entities: TModel[], criteria?: any, correlationId?: string): string {
const action = new DeleteMany(this.modelType, entities, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
deleteByKey(key: string | number, criteria?: any, correlationId?: string): string {
const action = new DeleteByKey(this.modelType, key, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
deleteManyByKeys(keys: EntityIdentity[], criteria?: any, correlationId?: string): string {
const action = new DeleteManyByKeys(this.modelType, keys, criteria, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
clear(correlationId?: string): string {
const action = new Clear(this.modelType, correlationId);
this.store.dispatch(action);
return action.correlationId;
}
// endregion
};
return BaseFacade;
}; | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/billingProfilesMappers";
import * as Parameters from "../models/parameters";
import { BillingManagementClientContext } from "../billingManagementClientContext";
/** Class representing a BillingProfiles. */
export class BillingProfiles {
private readonly client: BillingManagementClientContext;
/**
* Create a BillingProfiles.
* @param {BillingManagementClientContext} client Reference to the service client.
*/
constructor(client: BillingManagementClientContext) {
this.client = client;
}
/**
* Lists the billing profiles that a user has access to. The operation is supported for billing
* accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement.
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param [options] The optional parameters
* @returns Promise<Models.BillingProfilesListByBillingAccountResponse>
*/
listByBillingAccount(billingAccountName: string, options?: Models.BillingProfilesListByBillingAccountOptionalParams): Promise<Models.BillingProfilesListByBillingAccountResponse>;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param callback The callback
*/
listByBillingAccount(billingAccountName: string, callback: msRest.ServiceCallback<Models.BillingProfileListResult>): void;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param options The optional parameters
* @param callback The callback
*/
listByBillingAccount(billingAccountName: string, options: Models.BillingProfilesListByBillingAccountOptionalParams, callback: msRest.ServiceCallback<Models.BillingProfileListResult>): void;
listByBillingAccount(billingAccountName: string, options?: Models.BillingProfilesListByBillingAccountOptionalParams | msRest.ServiceCallback<Models.BillingProfileListResult>, callback?: msRest.ServiceCallback<Models.BillingProfileListResult>): Promise<Models.BillingProfilesListByBillingAccountResponse> {
return this.client.sendOperationRequest(
{
billingAccountName,
options
},
listByBillingAccountOperationSpec,
callback) as Promise<Models.BillingProfilesListByBillingAccountResponse>;
}
/**
* Gets a billing profile by its ID. The operation is supported for billing accounts with agreement
* type Microsoft Customer Agreement or Microsoft Partner Agreement.
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param [options] The optional parameters
* @returns Promise<Models.BillingProfilesGetResponse>
*/
get(billingAccountName: string, billingProfileName: string, options?: Models.BillingProfilesGetOptionalParams): Promise<Models.BillingProfilesGetResponse>;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param callback The callback
*/
get(billingAccountName: string, billingProfileName: string, callback: msRest.ServiceCallback<Models.BillingProfile>): void;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param options The optional parameters
* @param callback The callback
*/
get(billingAccountName: string, billingProfileName: string, options: Models.BillingProfilesGetOptionalParams, callback: msRest.ServiceCallback<Models.BillingProfile>): void;
get(billingAccountName: string, billingProfileName: string, options?: Models.BillingProfilesGetOptionalParams | msRest.ServiceCallback<Models.BillingProfile>, callback?: msRest.ServiceCallback<Models.BillingProfile>): Promise<Models.BillingProfilesGetResponse> {
return this.client.sendOperationRequest(
{
billingAccountName,
billingProfileName,
options
},
getOperationSpec,
callback) as Promise<Models.BillingProfilesGetResponse>;
}
/**
* Creates or updates a billing profile. The operation is supported for billing accounts with
* agreement type Microsoft Customer Agreement or Microsoft Partner Agreement.
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param parameters The new or updated billing profile.
* @param [options] The optional parameters
* @returns Promise<Models.BillingProfilesCreateOrUpdateResponse>
*/
createOrUpdate(billingAccountName: string, billingProfileName: string, parameters: Models.BillingProfile, options?: msRest.RequestOptionsBase): Promise<Models.BillingProfilesCreateOrUpdateResponse> {
return this.beginCreateOrUpdate(billingAccountName,billingProfileName,parameters,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.BillingProfilesCreateOrUpdateResponse>;
}
/**
* Creates or updates a billing profile. The operation is supported for billing accounts with
* agreement type Microsoft Customer Agreement or Microsoft Partner Agreement.
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param parameters The new or updated billing profile.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginCreateOrUpdate(billingAccountName: string, billingProfileName: string, parameters: Models.BillingProfile, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
billingAccountName,
billingProfileName,
parameters,
options
},
beginCreateOrUpdateOperationSpec,
options);
}
/**
* Lists the billing profiles that a user has access to. The operation is supported for billing
* accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.BillingProfilesListByBillingAccountNextResponse>
*/
listByBillingAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingProfilesListByBillingAccountNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByBillingAccountNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.BillingProfileListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByBillingAccountNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingProfileListResult>): void;
listByBillingAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingProfileListResult>, callback?: msRest.ServiceCallback<Models.BillingProfileListResult>): Promise<Models.BillingProfilesListByBillingAccountNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByBillingAccountNextOperationSpec,
callback) as Promise<Models.BillingProfilesListByBillingAccountNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listByBillingAccountOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles",
urlParameters: [
Parameters.billingAccountName
],
queryParameters: [
Parameters.apiVersion0,
Parameters.expand
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BillingProfileListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}",
urlParameters: [
Parameters.billingAccountName,
Parameters.billingProfileName
],
queryParameters: [
Parameters.apiVersion0,
Parameters.expand
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BillingProfile
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}",
urlParameters: [
Parameters.billingAccountName,
Parameters.billingProfileName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.BillingProfile,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.BillingProfile,
headersMapper: Mappers.BillingProfilesCreateOrUpdateHeaders
},
202: {
headersMapper: Mappers.BillingProfilesCreateOrUpdateHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse,
headersMapper: Mappers.BillingProfilesCreateOrUpdateHeaders
}
},
serializer
};
const listByBillingAccountNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BillingProfileListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
}; | the_stack |
import * as React from "react";
import { SyntheticEvent } from "react";
import { componentStateEngine, StateEngine } from "./stateEngine";
import { FieldProps, FieldRecord, makeField } from "./Field";
import {
validFn,
FieldResult,
isInvalidResult,
Validator,
isCovalidateResult,
CovalidatedFieldResult,
InvalidFieldResult
} from "./validation/index";
export type FieldValue = string | number;
export type FieldValueMap = Record<string, FieldValue>;
export type FieldMap = Record<string, FieldRecord>;
export type FormEventHandler = (values: FieldMap) => void | Promise<void>;
export type MaybeFormEventHandler = FormEventHandler | undefined;
/**
* Props supplied to the render component passed to Form
* TOwnProps is the type of the Form render components own props
* TFieldOwnProps is the type of the Field render components own props
*/
export interface InjectedFormProps<
TOwnProps extends object | void = void,
TFieldOwnProps extends object | void = void
> {
Field: React.StatelessComponent<FieldProps<TFieldOwnProps>>;
form: React.DetailedHTMLProps<
React.FormHTMLAttributes<HTMLFormElement>,
HTMLFormElement
>;
values: FieldMap;
meta: {
valid: boolean;
submitted: boolean;
errors: Record<string, InvalidFieldResult>;
isValidating: boolean;
isSubmitting: boolean;
};
actions: {
reset: () => void;
submit: () => void;
};
ownProps: TOwnProps;
}
/**
* Props that can be passed to Form
*/
export interface FormProps<
T extends object | void = {},
U extends object | void = {}
> {
name: string;
render: React.SFC<InjectedFormProps<T, U>>;
validators?: Record<string, Validator<FieldValue>>;
initialValues?: FieldValueMap;
onSubmit?: FormEventHandler;
onSubmitFailed?: FormEventHandler;
onChange?: FormEventHandler;
renderProps?: T;
stateEngine?: StateEngine<FormState>;
}
export interface FormState {
fields: FieldMap;
submitted: boolean;
meta: {
validation: FieldResult;
isSubmitting: boolean;
};
}
export class Form<
T extends object | void,
U extends object | void
> extends React.Component<FormProps<T, U>, FormState> {
static defaultProps: Partial<FormProps<any, any>> = {
initialValues: {},
onSubmit: () => {},
onSubmitFailed: () => {},
onChange: () => {},
renderProps: {}
};
private Field: React.StatelessComponent<FieldProps<U>>;
private stateEngine: StateEngine<FormState>;
/**
* When a Form is instantiated, generate a state engine with initial empty
* state - this will be filled in by Fields, and create the Field component
* that will be injected.
*/
constructor(props: FormProps<T, U>) {
super(props);
this.stateEngine =
props.stateEngine ||
componentStateEngine(this, {
fields: {},
submitted: false,
meta: {
validation: {
valid: true
},
isSubmitting: false
}
});
this.makeField();
}
componentWillReceiveProps(nextProps: FormProps<T, U>) {
if (nextProps.validators !== this.props.validators) {
this.makeField(false);
}
return true;
}
/**
* Generates the Field that will be passed in InjectedFormProps
*/
private makeField = (resetField = true) => {
this.Field = makeField(
{
onChange: this.handleFieldChange,
getInitialValue: this.getInitialValue
},
this.stateEngine,
resetField
) as any;
};
/**
* Reset everything to initial values
* State will be fleshed out by Field children when they are recreated
*/
private reset = () => {
this.stateEngine
.set({
fields: {},
submitted: false
})
.then(() => this.makeField())
.then(() => this.forceUpdate());
};
/**
* Allows Fields to get to their initial state
*/
private getInitialValue = (name: string) =>
(this.props.initialValues as FieldValueMap)[name] || "";
/**
* Is every field passing validation
*/
private allValid = (validationResult: FieldMap): boolean => {
return (
this.stateEngine.select(s => s.meta.validation.valid) &&
Object.values(validationResult).every(
r => (r.meta.validation ? r.meta.validation.valid : true)
)
);
};
/**
* If there is a validator for field with name of {name}
* then run it, otherwise return valid
*/
private validate = async (
name: string,
value: FieldValue | undefined
): Promise<FieldResult | CovalidatedFieldResult> => {
const fields = this.stateEngine.select(s => s.fields);
if (this.props.validators && this.props.validators.form) {
const formResult = await this.props.validators.form("", fields);
if (isCovalidateResult(formResult)) {
await formResult.covalidate.map(field =>
this.validate(field, fields[field].value)
);
} else {
await this.stateEngine.set(({ meta }) => ({
meta: {
...meta,
validation: formResult
}
}));
}
}
if (!this.props.validators) {
return validFn();
}
const validator = this.props.validators[name];
if (!validator) {
return validFn();
}
const result = await validator(value, fields);
return result;
};
/**
* Called by Fields when their value changes
* If a form onChange handler was passed as a prop, call it
*/
private handleFieldChange = async (
fieldName: string,
value: FieldValue | undefined
) => {
await this.stateEngine.set(({ fields }) => ({
fields: {
...fields,
[fieldName]: {
...fields[fieldName],
value,
meta: {
...(fields[fieldName] || {}).meta,
isValidating: true
}
}
}
}));
this.validate(fieldName, value).then(validation => {
if (isCovalidateResult(validation)) {
Promise.all(
validation.covalidate.map(async covalidatedField => ({
covalidatedField,
result: await this.validate(
covalidatedField,
this.stateEngine.select(
s => s.fields[covalidatedField].value
)
)
}))
).then(covalidateResults => {
this.stateEngine.set(({ fields }) => ({
fields: {
...fields,
...covalidateResults.reduce(
(out, { covalidatedField, result }) => ({
...out,
[covalidatedField]: {
...fields[covalidatedField],
meta: {
...(fields[covalidatedField] || {})
.meta,
validation: result,
isValidating: false
}
}
}),
{}
),
[fieldName]: {
...fields[fieldName],
meta: {
...(fields[fieldName] || {}).meta,
validation: validation.result,
isValidating: false
}
}
}
}));
});
} else {
this.stateEngine.set(({ fields }) => ({
fields: {
...fields,
[fieldName]: {
...fields[fieldName],
meta: {
...(fields[fieldName] || {}).meta,
validation,
isValidating: false
}
}
}
}));
}
});
(this.props.onChange as FormEventHandler)(
this.stateEngine.select(s => s.fields)
);
};
/**
* On submit call either props.onSubmit or props.onFailedSubmit
* depending on current validation status
*/
private handleSubmit = (
onSubmit: MaybeFormEventHandler,
onFailedSubmit: MaybeFormEventHandler,
valid: boolean,
fields: FieldMap
) => (e?: SyntheticEvent<any>) => {
e && e.preventDefault();
this.stateEngine.set(({ meta }) => ({
submitted: true,
meta: { ...meta, isSubmitting: true }
}));
Promise.resolve(
valid
? (onSubmit as FormEventHandler)(fields)
: (onFailedSubmit as FormEventHandler)(fields)
).then(() =>
this.stateEngine.set(({ meta }) => ({
meta: {
...meta,
isSubmitting: false
}
}))
);
};
render() {
const {
render,
onSubmit,
onSubmitFailed,
name,
renderProps
} = this.props;
const {
submitted,
fields,
meta: { validation, isSubmitting }
} = this.stateEngine.get();
const valid = this.allValid(fields);
/**
* Filters out all keys from validationResult where valid is true,
* if form is valid then we know this will be an empty object, so we can
* just return that
*/
const validationResult = valid
? {}
: Object.entries(fields).reduce(
(out, [key, value]) =>
Object.assign(
{},
out,
isInvalidResult(value.meta.validation)
? {
[key]: value.meta.validation
}
: {}
),
isInvalidResult(validation) ? { form: validation } : {}
);
const isValidating = Object.values(fields).some(
field => field.meta.isValidating
);
const submit = this.handleSubmit(
onSubmit,
onSubmitFailed,
valid,
fields
);
return render({
ownProps: renderProps as T,
meta: {
valid,
submitted,
errors: validationResult,
isValidating,
isSubmitting
},
Field: this.Field,
values: fields,
actions: {
reset: this.reset,
submit
},
form: {
name,
onSubmit: submit
}
});
}
} | the_stack |
import type { Importer } from './importer';
declare const address: string;
declare const debugMode: boolean;
declare const mode: string;
declare const hotReload: boolean;
type MapValue<T extends Map<any, any>> = ReturnType<T['get']>;
type DependentTree = {
file: string;
dependents: DependentTree[];
}
interface ReboostGlobalObject {
reload: () => void;
}
export interface ReboostPrivateObject {
Hot_Map: HotMapType;
Hot_Data_Map: Map<string, any>;
setDependencies(file: string, dependencies: string[]): void;
dependentTreeFor(file: string): DependentTree;
}
const debug = (...data: any) => debugMode && console.log(...data);
const Reboost: ReboostGlobalObject = {
// eslint-disable-next-line no-constant-condition
reload: () => (false && debugMode) ? console.log('TRIGGER RELOAD') : self.location.reload()
};
const Private = ((): ReboostPrivateObject => {
type P = ReboostPrivateObject;
const dependentsMap = new Map<string, Set<string>>();
const setDependencies: P['setDependencies'] = (file, dependencies) => {
dependencies.forEach((dependency) => {
const dependents = dependentsMap.get(dependency);
if (!dependents) {
dependentsMap.set(dependency, new Set([file]))
} else {
dependents.add(file);
}
});
}
const dependentTreeFor: P['dependentTreeFor'] = (file) => {
const dependentTrees: DependentTree[] = [];
const dependents = dependentsMap.get(file) || ([] as string[]);
dependents.forEach((dFile: string) => {
dependentTrees.push(dependentTreeFor(dFile));
});
return {
file: file,
dependents: dependentTrees
}
}
return {
Hot_Map: new Map(),
Hot_Data_Map: new Map(),
setDependencies,
dependentTreeFor
}
})();
Object.defineProperty(Reboost, '[[Private]]', { get: () => Private });
{
const aSelf = self as any;
if (!aSelf.process) {
aSelf.process = { env: { NODE_ENV: mode } };
} else {
let a = aSelf.process;
if (a) a = a.env;
if (a) a.NODE_ENV = mode;
}
aSelf['Reboost'] = Reboost;
}
{
const makeLoopGuard = (max: number) => {
let count = 0;
return {
call() {
if (++count > max) {
throw new Error(`Loop crossed the limit of ${max}`);
}
}
}
}
let lostConnection = false;
const connectWebsocket = () => {
const socket = new WebSocket(`ws://${address.replace(/^https?:\/\//, '')}`);
const fileLastChangedRecord = {} as Record<string, number>;
let importer: Importer;
let loadImporter: Promise<any>;
socket.addEventListener('open', () => {
console.log('[reboost] Connected to the server');
lostConnection = false;
loadImporter = new Promise<void>((resolve) => {
import(`${address}/importer`).then((mod) => {
importer = mod.default;
resolve();
})
});
});
socket.addEventListener('message', async ({ data }) => {
const { type, file: emitterFile } = JSON.parse(data) as {
type: string;
file: string;
};
const { Hot_Map, Hot_Data_Map } = Private;
if (type === 'change') {
console.log(`[reboost] Changed ${emitterFile}`);
if (!hotReload) {
console.log('[reboost] Hot Reload is disabled. Triggering full reload.');
return Reboost.reload();
}
const fileLastUpdated = fileLastChangedRecord[emitterFile];
const now = fileLastChangedRecord[emitterFile] = Date.now();
// Apply Hot Reload only if file's last updated time is greater that 0.8s
if ((typeof fileLastUpdated === 'undefined') || (((now - fileLastUpdated) / 1000) > 0.8)) {
await loadImporter;
const guard = makeLoopGuard(1000);
const checkedFiles = new Set<string>();
let bubbleUpDependents: DependentTree[];
let nextBubbleUpDependents = [Private.dependentTreeFor(emitterFile)];
let emitterFileData: MapValue<HotMapType>;
let handler;
let updatedModuleInstance: any;
let hotData: Record<string, any>;
while (nextBubbleUpDependents.length > 0) {
guard.call();
bubbleUpDependents = nextBubbleUpDependents;
nextBubbleUpDependents = [];
for (const { file, dependents } of bubbleUpDependents) {
debug('[Hot Reload] Checking -', file);
if (checkedFiles.has(file)) continue;
checkedFiles.add(file);
if ((emitterFileData = Hot_Map.get(file))) {
if (emitterFileData.declined) Reboost.reload();
hotData = {};
emitterFileData.listeners.forEach(({ dispose }) => dispose && dispose(hotData));
Hot_Data_Map.set(file, hotData);
updatedModuleInstance = await import(`${address}/transformed?q=${encodeURIComponent(file)}&t=${now}`);
updatedModuleInstance = importer.All(updatedModuleInstance);
// If the module is self accepted, just call the self accept handler
// and finish the update (don't bubble up)
if ((handler = emitterFileData.listeners.get(file)) && handler.accept) {
debug('[Hot Reload] Self accepted by', file);
handler.accept(updatedModuleInstance);
} else {
dependents.forEach((tree) => {
if ((handler = emitterFileData.listeners.get(tree.file)) && handler.accept) {
debug('[Hot Reload] Accepted by', tree.file);
handler.accept(updatedModuleInstance);
} else {
nextBubbleUpDependents.push(tree);
}
});
}
Hot_Data_Map.delete(file);
} else if (dependents.length > 0) {
nextBubbleUpDependents.push(...dependents);
} else {
debug('[Hot Reload] Triggering full page reload. The file has no parent -', file);
Reboost.reload();
}
}
if (nextBubbleUpDependents.length === 0) {
debug('[Hot Reload] Completed update');
}
}
}
} else if (type === 'unlink') {
Reboost.reload();
}
});
socket.addEventListener('close', () => {
if (!lostConnection) {
lostConnection = true;
console.log('[reboost] Lost connection to the server. Trying to reconnect...');
}
setTimeout(() => connectWebsocket(), 5000);
});
}
connectWebsocket();
}
// -----------------
// Hot Reloader Code
// -----------------
type AcceptCB = {
/**
* @param module The updated module
*/
(module: any): void;
}
type DisposeCB = {
/**
* @param data A object that you can use to pass the data to the updated module
*/
(data: Record<string, any>): void;
}
export interface HandlerObject {
accept?: AcceptCB;
dispose?: DisposeCB;
}
export type HotMapType = Map<string, {
declined: boolean;
listeners: Map<string, HandlerObject>
}>;
const getEmitterFileData = (emitterFile: string) => {
if (!Private.Hot_Map.has(emitterFile)) {
Private.Hot_Map.set(emitterFile, {
declined: false,
listeners: new Map()
});
}
return Private.Hot_Map.get(emitterFile);
}
const getListenerFileData = (emitterFile: string, listenerFile: string) => {
const listenedFileData = getEmitterFileData(emitterFile);
if (!listenedFileData.listeners.has(listenerFile)) listenedFileData.listeners.set(listenerFile, {});
return listenedFileData.listeners.get(listenerFile);
}
type CallbackT<T> = 'accept' extends T ? AcceptCB : DisposeCB;
export class Hot {
private filePath: string;
constructor(filePath: string) {
this.filePath = filePath;
}
private async callSetter<T extends 'accept' | 'dispose'>(
type: T,
a: string | CallbackT<T>,
b?: CallbackT<T>
) {
let dependencyFilePath: string;
let callback: CallbackT<T>;
if (typeof a === 'function') {
// Self
dependencyFilePath = this.filePath;
callback = a;
} else {
dependencyFilePath = await this.resolveDependency(a, type);
callback = b;
}
const listenerData = getListenerFileData(dependencyFilePath, this.filePath);
if (!listenerData[type]) listenerData[type] = callback;
}
private async resolveDependency(dependency: string, fnName: 'accept' | 'dispose' | 'decline') {
const response = await fetch(`${address}/resolve?from=${this.filePath}&to=${dependency}`);
if (!response.ok) {
console.error(`[reboost] Unable to resolve dependency "${dependency}" of "${this.filePath}" while using hot.${fnName}()`);
return 'UNRESOLVED';
}
return response.text();
}
/** The data passed from the disposal callbacks */
get data(): Record<string, any> {
return Private.Hot_Data_Map.get(this.filePath);
}
/** The id of the module, it can be used as a key to store data about the module */
get id(): string {
return this.filePath;
}
/**
* Sets accept listener for the module itself
* @param callback The callback which will be triggered on module update
*/
accept(callback: AcceptCB): void;
/**
* Sets accept listener for a dependency of the module
* @param dependency Path to the dependency
* @param callback The callback which will be triggered on module update
*/
accept(dependency: string, callback: AcceptCB): void;
accept(a: string | AcceptCB, b?: AcceptCB) {
this.callSetter('accept', a, b);
}
/**
* Sets dispose listener for the module itself
* @param callback The callback which will triggered on module disposal
*/
dispose(callback: DisposeCB): void;
/**
* Sets dispose listener for a dependency of the module
* @param dependency Path to the dependency
* @param callback The callback which will triggered on module disposal
*/
dispose(dependency: string, callback: DisposeCB): void;
dispose(a: string | DisposeCB, b?: DisposeCB) {
this.callSetter('dispose', a, b);
}
/** Marks the module itself as not Hot Reload-able */
decline(): void;
/**
* Marks the dependency of the module as not Hot Reload-able
* @param dependency Path to the dependency
*/
decline(dependency: string): void;
async decline(dependency?: string) {
getEmitterFileData(
dependency || await this.resolveDependency(dependency, 'decline')
).declined = true;
}
/** Invalidates the Hot Reload phase and causes a full page reload */
invalidate(): void {
Reboost.reload();
}
// TODO: Remove these in v1.0
private get self() {
return {
accept: this.selfAccept.bind(this),
dispose: this.selfDispose.bind(this)
}
}
private selfAccept(callback: AcceptCB) {
this.accept(callback);
}
private selfDispose(callback: DisposeCB) {
this.dispose(callback);
}
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [mediapackage-vod](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awselementalmediapackagevod.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class MediapackageVod extends PolicyStatement {
public servicePrefix = 'mediapackage-vod';
/**
* Statement provider for service [mediapackage-vod](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awselementalmediapackagevod.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to configure egress access logs for a PackagingGroup
*
* Access Level: Write
*
* Dependent actions:
* - iam:CreateServiceLinkedRole
*
* https://docs.aws.amazon.com/mediapackage-vod/latest/apireference/packaging_groups-id-configure_logs.html#packaging_groups-id-configure_logsput
*/
public toConfigureLogs() {
return this.to('ConfigureLogs');
}
/**
* Grants permission to create an asset in AWS Elemental MediaPackage
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/mediapackage-vod/latest/apireference/assets.html#assetspost
*/
public toCreateAsset() {
return this.to('CreateAsset');
}
/**
* Grants permission to create a packaging configuration in AWS Elemental MediaPackage
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/mediapackage-vod/latest/apireference/packaging_configurations.html#packaging_configurationspost
*/
public toCreatePackagingConfiguration() {
return this.to('CreatePackagingConfiguration');
}
/**
* Grants permission to create a packaging group in AWS Elemental MediaPackage
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/mediapackage-vod/latest/apireference/packaging_groups.html#packaging_groupspost
*/
public toCreatePackagingGroup() {
return this.to('CreatePackagingGroup');
}
/**
* Grants permission to delete an asset in AWS Elemental MediaPackage
*
* Access Level: Write
*
* https://docs.aws.amazon.com/mediapackage-vod/latest/apireference/assets-id.html#assets-iddelete
*/
public toDeleteAsset() {
return this.to('DeleteAsset');
}
/**
* Grants permission to delete a packaging configuration in AWS Elemental MediaPackage
*
* Access Level: Write
*
* https://docs.aws.amazon.com/mediapackage-vod/latest/apireference/packaging_configurations-id.html#packaging_configurations-iddelete
*/
public toDeletePackagingConfiguration() {
return this.to('DeletePackagingConfiguration');
}
/**
* Grants permission to delete a packaging group in AWS Elemental MediaPackage
*
* Access Level: Write
*
* https://docs.aws.amazon.com/mediapackage-vod/latest/apireference/packaging_groups-id.html#packaging_groups-iddelete
*/
public toDeletePackagingGroup() {
return this.to('DeletePackagingGroup');
}
/**
* Grants permission to view the details of an asset in AWS Elemental MediaPackage
*
* Access Level: Read
*
* https://docs.aws.amazon.com/mediapackage-vod/latest/apireference/assets-id.html#assets-idget
*/
public toDescribeAsset() {
return this.to('DescribeAsset');
}
/**
* Grants permission to view the details of a packaging configuration in AWS Elemental MediaPackage
*
* Access Level: Read
*
* https://docs.aws.amazon.com/mediapackage-vod/latest/apireference/packaging_configurations-id.html#packaging_configurations-idget
*/
public toDescribePackagingConfiguration() {
return this.to('DescribePackagingConfiguration');
}
/**
* Grants permission to view the details of a packaging group in AWS Elemental MediaPackage
*
* Access Level: Read
*
* https://docs.aws.amazon.com/mediapackage-vod/latest/apireference/packaging_groups-id.html#packaging_groups-idget
*/
public toDescribePackagingGroup() {
return this.to('DescribePackagingGroup');
}
/**
* Grants permission to view a list of assets in AWS Elemental MediaPackage
*
* Access Level: List
*
* https://docs.aws.amazon.com/mediapackage-vod/latest/apireference/assets.html#assetsget
*/
public toListAssets() {
return this.to('ListAssets');
}
/**
* Grants permission to view a list of packaging configurations in AWS Elemental MediaPackage
*
* Access Level: List
*
* https://docs.aws.amazon.com/mediapackage-vod/latest/apireference/packaging_configurations.html#packaging_configurationsget
*/
public toListPackagingConfigurations() {
return this.to('ListPackagingConfigurations');
}
/**
* Grants permission to view a list of packaging groups in AWS Elemental MediaPackage
*
* Access Level: List
*
* https://docs.aws.amazon.com/mediapackage-vod/latest/apireference/packaging_groups.html#packaging_groupsget
*/
public toListPackagingGroups() {
return this.to('ListPackagingGroups');
}
/**
* Grants permission to list the tags assigned to a PackagingGroup, PackagingConfiguration, or Asset.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/mediapackage-vod/latest/apireference/tags-resource-arn.html#tags-resource-arnget
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to assign tags to a PackagingGroup, PackagingConfiguration, or Asset.
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/mediapackage-vod/latest/apireference/tags-resource-arn.html#tags-resource-arnpost
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to delete tags from a PackagingGroup, PackagingConfiguration, or Asset.
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/mediapackage-vod/latest/apireference/tags-resource-arn.html#tags-resource-arndelete
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to update a packaging group in AWS Elemental MediaPackage
*
* Access Level: Write
*
* https://docs.aws.amazon.com/mediapackage-vod/latest/apireference/packaging_groups-id.html#packaging_groups-idput
*/
public toUpdatePackagingGroup() {
return this.to('UpdatePackagingGroup');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"ConfigureLogs",
"CreateAsset",
"CreatePackagingConfiguration",
"CreatePackagingGroup",
"DeleteAsset",
"DeletePackagingConfiguration",
"DeletePackagingGroup",
"UpdatePackagingGroup"
],
"Read": [
"DescribeAsset",
"DescribePackagingConfiguration",
"DescribePackagingGroup",
"ListTagsForResource"
],
"List": [
"ListAssets",
"ListPackagingConfigurations",
"ListPackagingGroups"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type assets to the statement
*
* https://docs.aws.amazon.com/mediapackage/latest/ug/asset.html
*
* @param assetIdentifier - Identifier for the assetIdentifier.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onAssets(assetIdentifier: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:mediapackage-vod:${Region}:${Account}:assets/${AssetIdentifier}';
arn = arn.replace('${AssetIdentifier}', assetIdentifier);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type packaging-configurations to the statement
*
* https://docs.aws.amazon.com/mediapackage/latest/ug/pkg-cfig.html
*
* @param packagingConfigurationIdentifier - Identifier for the packagingConfigurationIdentifier.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onPackagingConfigurations(packagingConfigurationIdentifier: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:mediapackage-vod:${Region}:${Account}:packaging-configurations/${PackagingConfigurationIdentifier}';
arn = arn.replace('${PackagingConfigurationIdentifier}', packagingConfigurationIdentifier);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type packaging-groups to the statement
*
* https://docs.aws.amazon.com/mediapackage/latest/ug/pkg-group.html
*
* @param packagingGroupIdentifier - Identifier for the packagingGroupIdentifier.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onPackagingGroups(packagingGroupIdentifier: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:mediapackage-vod:${Region}:${Account}:packaging-groups/${PackagingGroupIdentifier}';
arn = arn.replace('${PackagingGroupIdentifier}', packagingGroupIdentifier);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import {LibraryAddEvent, LibraryEvent, LibraryModifyEvent, LibraryRemoveEvent} from "./Library";
import {File, FileBuilder} from "./File";
import {CanvasScreen} from "trs80-emulator-web";
import {
defer,
getLabelNodeForTextButton,
makeIcon,
makeIconButton,
makeTagCapsule,
makeTextButton,
TRASH_TAG
} from "./Utils";
import {clearElement} from "teamten-ts-utils";
import {Context} from "./Context";
import {PageTab} from "./PageTab";
import {TagSet} from "./TagSet";
import {PageTabs} from "./PageTabs";
const FILE_ID_ATTR = "data-file-id";
const IMPORT_FILE_LABEL = "Import File";
/**
* Quotes for the "no filter" error page.
*/
const NO_FILTER_QUOTE = [
"No dance for you.",
"I'm disappointed.",
"Try being less demanding.",
"And it's not for lack of trying.",
"Try doing literally anything else.",
];
/**
* Get a random quote for the "no filter" error page.
*/
function getRandomNoFilterQuote(): string {
return NO_FILTER_QUOTE[Math.floor(Math.random()*NO_FILTER_QUOTE.length)];
}
/**
* A TRS-80-like cursor in HTML.
*/
class AuthenticCursor {
// This is 7 ticks of the Model III timer (30 Hz).
private static readonly BLINK_PERIOD_MS = 233;
public readonly node: HTMLElement;
public readonly handle: number;
public visible = true;
constructor() {
this.node = document.createElement("span");
this.node.classList.add("authentic-cursor");
this.update();
this.handle = window.setInterval(() => {
this.visible = !this.visible;
this.update();
}, AuthenticCursor.BLINK_PERIOD_MS);
}
/**
* Stop the cursor. Only call this once.
*/
public disable() {
this.node.remove();
window.clearInterval(this.handle);
}
/**
* Set the correct block for the current visibility.
*/
private update() {
if (this.visible) {
this.node.innerText = "\uE0B0"; // 131, bottom two pixels.
} else {
this.node.innerText = "\uE080"; // 128, blank.
}
}
}
/**
* Tap for the Your Files UI.
*/
export class YourFilesTab extends PageTab {
private readonly context: Context;
private readonly filesDiv: HTMLElement;
private readonly emptyLibrary: HTMLElement;
private readonly emptyTitle: HTMLElement;
private readonly emptyBody: HTMLElement;
private emptyQuote: string | undefined = undefined;
// If empty, show all files except Trash. Otherwise show only files that have all of these tags.
private readonly includeTags = new TagSet();
// Exclude files that have any of these tags.
private readonly excludeTags = new TagSet();
private searchString: string = "";
private readonly tagEditor: HTMLElement;
private readonly blankScreen: HTMLElement;
private forceShowSearch = false;
private readonly searchButton: HTMLButtonElement;
private searchCursor: AuthenticCursor | undefined = undefined;
private readonly openTrashButton: HTMLElement;
private libraryInSync = false;
constructor(context: Context, pageTabs: PageTabs) {
super("Your Files", context.user !== undefined);
this.context = context;
// Make this blank screen synchronously so that it's immediately available when populating the file list.
this.blankScreen = new CanvasScreen().asImage();
this.element.classList.add("your-files-tab");
context.onUser.subscribe(user => {
this.visible = user !== undefined;
pageTabs.configurationChanged();
});
this.filesDiv = document.createElement("div");
this.filesDiv.classList.add("files");
this.element.append(this.filesDiv);
this.emptyLibrary = document.createElement("div");
this.emptyLibrary.classList.add("empty-library");
this.element.append(this.emptyLibrary);
this.emptyTitle = document.createElement("h2");
this.emptyBody = document.createElement("article");
const demon = document.createElement("img");
demon.src = "/demon.png";
this.emptyLibrary.append(this.emptyTitle, this.emptyBody, demon);
// Register for changes to library.
this.libraryInSync = this.context.library.inSync;
this.context.library.onEvent.subscribe(e => this.onLibraryEvent(e));
this.context.library.onInSync.subscribe(inSync => this.onLibraryInSync(inSync));
const actionBar = document.createElement("div");
actionBar.classList.add("action-bar");
this.element.append(actionBar);
this.openTrashButton = makeTextButton("Open Trash", "delete", "open-trash-button",
() => this.openTrash());
this.tagEditor = document.createElement("div");
this.tagEditor.classList.add("tag-editor");
this.searchButton = makeTextButton("Search", "search", "search-button", () => {
this.forceShowSearch = true;
this.refreshFilter();
});
const spacer = document.createElement("div");
spacer.classList.add("action-bar-spacer");
const exportAllButton = makeTextButton("Export All", "get_app", "export-all-button",
() => this.exportAll());
const uploadButton = makeTextButton(IMPORT_FILE_LABEL, "publish", "import-file-button",
() => this.uploadFile());
actionBar.append(this.openTrashButton, this.tagEditor,this.searchButton, spacer, exportAllButton, uploadButton);
// Populate initial library state. Sort the files so that the screenshots get loaded in
// display order and the top (visible) ones are done first.
this.context.library.getAllFiles().sort(File.compare).forEach(f => this.addFile(f));
// Sort again anyway, since this updates various things.
this.sortFiles();
}
onKeyDown(e: KeyboardEvent): boolean {
// Plain letter.
if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {
this.searchString += e.key;
this.refreshFilter();
return true;
} else if (e.key === "Backspace" && this.searchString.length > 0) {
// Backspace.
if (e.ctrlKey || e.altKey) {
// Backspace word. Mac uses Alt and Windows uses Ctrl, so support both.
this.searchString = this.searchString.replace(/\S*\s*$/, "");
} else if (e.metaKey) {
// Backspace all.
this.searchString = "";
} else {
// Backspace letter.
this.searchString = this.searchString.substr(0, this.searchString.length - 1);
}
this.forceShowSearch = false;
this.refreshFilter();
return true;
}
return super.onKeyDown(e);
}
/**
* Handle change to library files.
*/
private onLibraryEvent(event: LibraryEvent): void {
if (event instanceof LibraryAddEvent) {
this.addFile(event.newFile);
this.sortFiles();
}
if (event instanceof LibraryModifyEvent) {
// Probably not worth modifying in-place.
this.removeFile(event.oldFile.id);
this.addFile(event.newFile);
this.sortFiles();
}
if (event instanceof LibraryRemoveEvent) {
this.removeFile(event.oldFile.id);
this.refreshFilter();
}
}
/**
* React to whether library is now fully in sync.
*/
private onLibraryInSync(inSync: boolean): void {
this.libraryInSync = inSync;
this.refreshFilter();
}
/**
* Start a download of all data in the database.
*/
private exportAll(): void {
// Download info about all files.
const allFiles = {
version: 1,
files: this.context.library.getAllFiles().map(f => f.asMap()),
};
const contents = JSON.stringify(allFiles);
const blob = new Blob([contents], {type: "application/json"});
const a = document.createElement("a");
a.href = window.URL.createObjectURL(blob);
a.download = "my-trs-80.json";
a.click();
}
/**
* Configure and open the "open file" dialog for importing files.
*/
private uploadFile(): void {
const uploadElement = document.createElement("input");
uploadElement.type = "file";
uploadElement.accept = ".cas, .bas, .cmd, .dmk, .dsk, .jv1, .jv3, .3bn";
uploadElement.multiple = true;
uploadElement.addEventListener("change", () => {
const user = this.context.user;
if (user === undefined) {
console.error("Can't import with signed-out user");
return;
}
const files = uploadElement.files ?? [];
const openFilePanel = files.length === 1;
for (const f of files) {
f.arrayBuffer()
.then(arrayBuffer => {
const bytes = new Uint8Array(arrayBuffer);
this.importFile(user.uid, f.name, bytes, openFilePanel);
})
.catch(error => {
// TODO
console.error(error);
});
}
});
uploadElement.click();
}
/**
* Add an uploaded file to our library.
* @param uid user ID.
* @param filename original filename from the user.
* @param binary raw binary of the file.
* @param openFilePanel whether to open the file panel for this file after importing it.
*/
private importFile(uid: string, filename: string, binary: Uint8Array, openFilePanel: boolean): void {
let name = filename;
// Remove extension.
const i = name.lastIndexOf(".");
if (i > 0) {
name = name.substr(0, i);
}
// Capitalize.
name = name.substr(0, 1).toUpperCase() + name.substr(1).toLowerCase();
// All-caps for filename.
filename = filename.toUpperCase();
let file = new FileBuilder()
.withUid(uid)
.withName(name)
.withFilename(filename)
.withBinary(binary)
.build();
this.context.db.addFile(file)
.then(docRef => {
file = file.builder().withId(docRef.id).build();
this.context.library.addFile(file);
if (openFilePanel) {
this.context.openFilePanel(file);
}
})
.catch(error => {
// TODO
console.error("Error adding document: ", error);
});
}
/**
* Add a file to the list of files in the library.
*/
private addFile(file: File): void {
const fileDiv = document.createElement("div");
fileDiv.classList.add("file");
fileDiv.setAttribute(FILE_ID_ATTR, file.id);
this.filesDiv.append(fileDiv);
const screenshotsDiv = document.createElement("div");
screenshotsDiv.classList.add("screenshots");
fileDiv.append(screenshotsDiv);
screenshotsDiv.append(this.blankScreen.cloneNode(true));
defer(() => {
const screen = new CanvasScreen();
if (file.screenshots.length > 0) {
screen.displayScreenshot(file.screenshots[0]);
} else {
screenshotsDiv.classList.add("missing");
}
screen.asImageAsync().then(image => {
clearElement(screenshotsDiv);
screenshotsDiv.append(image)
});
});
const nameDiv = document.createElement("div");
nameDiv.classList.add("name");
nameDiv.innerText = file.name;
if (file.releaseYear !== "") {
const releaseYearSpan = document.createElement("span");
releaseYearSpan.classList.add("release-year");
releaseYearSpan.innerText = " (" + file.releaseYear + ")";
nameDiv.append(releaseYearSpan);
}
fileDiv.append(nameDiv);
const filenameDiv = document.createElement("div");
filenameDiv.classList.add("filename");
filenameDiv.innerText = file.filename;
fileDiv.append(filenameDiv);
const noteDiv = document.createElement("div");
noteDiv.classList.add("note");
noteDiv.innerText = [file.author, file.note].filter(field => field !== "").join(" — ");
fileDiv.append(noteDiv);
const tagsDiv = document.createElement("span");
tagsDiv.classList.add("tags");
for (const tag of file.getAllTags().asArray()) {
tagsDiv.append(makeTagCapsule({
tag: tag,
clickCallback: (e) => {
if (e.shiftKey) {
this.excludeTags.add(tag);
} else {
this.includeTags.add(tag);
}
this.refreshFilter();
},
}));
}
fileDiv.append(tagsDiv);
const buttonsDiv = document.createElement("div");
buttonsDiv.classList.add("buttons");
fileDiv.append(buttonsDiv);
const playButton = makeIconButton(makeIcon("play_arrow"), "Run program", () => {
this.context.runProgram(file);
this.context.panelManager.close();
});
playButton.classList.add("play-button");
buttonsDiv.append(playButton);
const infoButton = makeIconButton(makeIcon("edit"), "File information", () => {
this.context.openFilePanel(file);
});
infoButton.classList.add("info-button");
buttonsDiv.append(infoButton);
}
/**
* Remove a file from the UI by its ID.
*/
private removeFile(fileId: string): void {
const element = this.getFileElementById(fileId);
if (element !== undefined) {
element.remove();
} else {
console.error("removeFile(): No element with file ID " + fileId);
}
}
/**
* Update the hidden flags based on a new tag filter.
*/
private refreshFilter(): void {
let anyFiles = false;
let anyVisible = false;
// Parse out the search terms.
const searchWords = this.searchString.split(/\W+/).filter(s => s !== "");
if (false) { // TODO delete
console.log("-----------------");
for (const file of this.context.library.getAllFiles()) {
if (this.context.library.isDuplicate(file)) {
console.log(file.name, file.filename);
}
}
}
// Update hidden.
for (const fileDiv of this.filesDiv.children) {
let hidden = false;
const fileId = fileDiv.getAttribute(FILE_ID_ATTR);
if (fileId !== null) {
const file = this.context.library.getFile(fileId);
if (file !== undefined) {
anyFiles = true;
const fileTags = file.getAllTags();
// Only show files that have all the filter items.
if (!this.includeTags.isEmpty() && !fileTags.hasAll(this.includeTags)) {
hidden = true;
}
// If we're not explicitly filtering for trash, hide files in the trash.
if (!this.includeTags.has(TRASH_TAG) && fileTags.has(TRASH_TAG)) {
hidden = true;
}
// Excluded tags.
if (fileTags.hasAny(this.excludeTags)) {
hidden = true;
}
// Must match every word.
if (!searchWords.every(word => file.matchesFilterPrefix(word))) {
hidden = true;
}
}
}
fileDiv.classList.toggle("hidden", hidden);
if (!hidden) {
anyVisible = true;
}
}
// Update whether the splash screen is shown.
let displaySplashScreen: boolean;
if (this.libraryInSync) {
if (anyFiles) {
if (anyVisible) {
displaySplashScreen = false;
this.emptyQuote = undefined;
} else {
displaySplashScreen = true;
this.emptyTitle.innerText = "No files match your filter.";
if (this.emptyQuote === undefined) {
this.emptyQuote = getRandomNoFilterQuote();
}
this.emptyBody.innerText = this.emptyQuote;
}
} else {
displaySplashScreen = true;
this.emptyTitle.innerText = "You have no files in your library!";
this.emptyBody.innerHTML = `Upload a file from your computer using the “${IMPORT_FILE_LABEL.replace(/ /g, " ")}” button below, or import one from the RetroStore tab.`;
}
} else {
// Just show nothing at all while loading the library.
displaySplashScreen = false;
}
this.filesDiv.classList.toggle("hidden", displaySplashScreen);
this.emptyLibrary.classList.toggle("hidden", !displaySplashScreen);
// Update filter UI in the action bar.
const allTags = new TagSet();
allTags.addAll(this.includeTags);
allTags.addAll(this.excludeTags);
if (allTags.isEmpty()) {
this.tagEditor.classList.add("hidden");
this.openTrashButton.classList.toggle("hidden", !this.anyFileInTrash());
} else {
this.tagEditor.classList.remove("hidden");
this.openTrashButton.classList.add("hidden");
clearElement(this.tagEditor);
this.tagEditor.append("Filter tags:");
for (const tag of allTags.asArray()) {
const isExclude = this.excludeTags.has(tag);
this.tagEditor.append(makeTagCapsule({
tag: tag,
iconName: "clear",
exclude: isExclude,
clickCallback: () => {
if (isExclude) {
this.excludeTags.remove(tag);
} else {
this.includeTags.remove(tag);
}
this.refreshFilter();
},
}));
}
}
// Draw search prefix.
const labelNode = getLabelNodeForTextButton(this.searchButton);
clearElement(labelNode);
if (this.searchString !== "" || this.forceShowSearch) {
const searchStringNode = document.createElement("span");
searchStringNode.classList.add("search-string");
searchStringNode.innerText = this.searchString;
if (this.searchCursor === undefined) {
this.searchCursor = new AuthenticCursor();
}
labelNode.append("Search:", searchStringNode, this.searchCursor.node);
} else {
labelNode.innerText = "Search";
if (this.searchCursor !== undefined) {
this.searchCursor.disable();
this.searchCursor = undefined;
}
}
}
/**
* Whether there's anything in the trash.
*/
private anyFileInTrash(): boolean {
for (const file of this.context.library.getAllFiles()) {
if (file.tags.indexOf(TRASH_TAG) >= 0) {
return true;
}
}
return false;
}
/**
* Adds trash to the filter.
*/
private openTrash(): void {
this.includeTags.add(TRASH_TAG);
this.refreshFilter();
}
/**
* Return an element for a file given its ID, or undefined if not found.
*/
private getFileElementById(fileId: string): Element | undefined {
let selectors = ":scope > [" + FILE_ID_ATTR + "=\"" + fileId + "\"]";
const element = this.filesDiv.querySelector(selectors);
return element === null ? undefined : element;
}
/**
* Sort files already displayed.
*/
private sortFiles(): void {
// Sort existing files.
const fileElements: {file: File, element: Element}[] = [];
for (const element of this.filesDiv.children) {
const fileId = element.getAttribute(FILE_ID_ATTR);
if (fileId !== null) {
const file = this.context.library.getFile(fileId);
if (file !== undefined) {
fileElements.push({file: file, element: element});
}
}
}
fileElements.sort((a, b) => File.compare(a.file, b.file));
// Repopulate the UI in the right order.
clearElement(this.filesDiv);
this.filesDiv.append(... fileElements.map(e => e.element));
// Update the hidden flags.
this.refreshFilter();
}
} | the_stack |
import {
ADD_LISTITEM,
ADD_LISTITEMS,
REMOVE_LISTITEM,
GET_LISTITEMS,
GOT_LISTITEMS,
GET_LISTITEMSERROR,
GOT_LISTITEM,
GET_LISTITEMERROR,
CLEAR_LISTITEMS,
SAVE_LISTITEM,//save locally
UNDO_LISTITEMCHANGES,
UPDATE_LISTITEM,//save to sharepoint
UPDATE_LISTITEM_ERROR,
UPDATE_LISTITEM_SUCCESS,
ADDED_NEW_ITEM_TO_SHAREPOINT,
REMOVE_LISTITEM_SUCCESS,
REMOVE_LISTITEM_ERROR
} from "../constants";
import "whatwg-fetch";
import * as utils from "../utils/utils";
import * as _ from "lodash";
import { Web, TypedHash } from "sp-pnp-js";
import ListItem from "../model/ListItem";
import GridRowStatus from "../Model/GridRowStatus";
import { Log } from "@microsoft/sp-core-library";
import ListDefinition from "../model/ListDefinition";
import ColumnDefinition from "../model/ColumnDefinition";
export function clearListItems() {
return {
type: CLEAR_LISTITEMS,
payload: {
}
};
}
export function addListItem(listItem: ListItem) {
return {
type: ADD_LISTITEM,
payload: {
listItem: listItem
}
};
}
export function removeListItem(dispatch: any, listItem: ListItem, listDefinition: ListDefinition): any {
const weburl = utils.ParseSPField(listDefinition.webLookup).id;
const listid = utils.ParseSPField(listDefinition.listLookup).id;
const web = new Web(weburl);
switch (listItem.__metadata__GridRowStatus) {
case GridRowStatus.toBeDeleted:
web.lists.getById(listid).items.getById(listItem.ID).recycle()
.then((response) => {
// shouwld have an option to rfresh here in cas of calculated columns
const gotListItems = removeListItemSuccessAction(listItem);
dispatch(gotListItems); // need to ewname this one to be digfferent from the omported ome
})
.catch((error) => {
console.log(error);
dispatch(removeListItemErrorAction(error)); // need to ewname this one to be digfferent from the omported ome
});
return {
type: REMOVE_LISTITEM,
payload: {
listItem: listItem
}
};
default:
Log.warn("ListItemContainer", "Invalid GrodrowStatus in update ListiteRender-- " + listItem.__metadata__GridRowStatus.toString());
}
}
export function removeListItemSuccessAction(listItem) {
return {
type: REMOVE_LISTITEM_SUCCESS,
payload: {
listItem: listItem
}
};
}
export function removeListItemErrorAction(listItem) {
return {
type: REMOVE_LISTITEM_ERROR,
payload: {
listItem: listItem
}
};
}
export function addListItems(listItems: ListItem[]) {
return {
type: ADD_LISTITEMS,
payload: {
listItems: listItems
}
};
}
export function listDefinitionIsValid(listDefinition: ListDefinition): boolean {
if (listDefinition.webLookup === null) {
return false;
}
if (listDefinition.listLookup === null) {
return false;
}
if (listDefinition.columnReferences === null) {
return false;
}
return true;
}
/**
* Action to update a listitem in sharepoint
*/
export function updateListItemAction(dispatch: any, listDefinition: ListDefinition, listItem: ListItem): any {
const weburl = utils.ParseSPField(listDefinition.webLookup).id;
const listid = utils.ParseSPField(listDefinition.listLookup).id;
const web = new Web(weburl);
let typedHash: TypedHash<string | number | boolean> = {};
for (const columnRef of listDefinition.columnReferences) {
let fieldName = utils.ParseSPField(columnRef.name).id;
switch (columnRef.fieldDefinition.TypeAsString) {
case "Counter": // do not send ID to shareppoint as a data field
break;
case "Lookup":
if (listItem[fieldName]) {// field may not be set
typedHash[fieldName + "Id"] = listItem[fieldName].Id;
}
break;
case "User":
if (listItem[fieldName]) {// field may not be set
typedHash[fieldName + "Id"] = listItem[fieldName].Id;
}
break;
default:
typedHash[fieldName] = listItem[fieldName];
}
}
switch (listItem.__metadata__GridRowStatus) {
case GridRowStatus.modified:
case GridRowStatus.pristine:// if user cjust chnage the listedef
const promise = web.lists.getById(listid).items.getById(listItem.ID).update(typedHash, listItem["odata.etag"])
.then((response) => {
getListItem(listDefinition, listItem.ID)
.then((r) => {
// srfresh here in cas of calculated columns
r.__metadata__ListDefinitionId = listDefinition.guid; // save my listdef, so i can get the columnReferences later
r.__metadata__GridRowStatus = GridRowStatus.pristine; // save my listdef, so i can get the columnReferences later
const gotListItems = updateListItemSuccessAction(r);
dispatch(gotListItems); // need to ewname this one to be digfferent from the omported ome
});
})
.catch((error) => {
console.log(error);
dispatch(updateListItemErrorAction(error)); // need to ewname this one to be digfferent from the omported ome
});
const action = {
type: UPDATE_LISTITEM,
payload: {
promise: promise
}
};
return action;
case GridRowStatus.new:
const mewpromise = web.lists.getById(listid).items.add(typedHash)
.then((response) => {//
const itemId = response.data.Id;
getListItem(listDefinition, itemId)
.then((r) => {
/**
* data recived after adding an item is NOT the same as we recive from a get
* need to fetch item and wap it in
*/
r.__metadata__ListDefinitionId = listDefinition.guid; // save my listdef, so i can get the columnReferences later
r.__metadata__GridRowStatus = GridRowStatus.pristine; // save my listdef, so i can get the columnReferences later
const actiom = addedNewItemInSharepouint(r, listItem);
dispatch(actiom); // need to ewname this one to be digfferent from the omported ome
})
.catch((error) => {
console.log(error);
dispatch(updateListItemErrorAction(error)); // need to ewname this one to be digfferent from the omported ome
});
});
return {
type: UPDATE_LISTITEM,
payload: {
promise: mewpromise
}
};
default:
return; // action called on item with ibalid state
}
}
export function updateListItemErrorAction(error) {
return {
type: UPDATE_LISTITEM_ERROR,
payload: {
error: error
}
};
}
/**
* called after an item was added to the local cache, updated, then sent to sharepoint.
* We need to replace our local copy, with the real valuse that we got back from sharepoint
*/
export function addedNewItemInSharepouint(listItem, localCopy) {
return {
type: ADDED_NEW_ITEM_TO_SHAREPOINT,
payload: {
listItem: listItem,
localCopy: localCopy
}
};
}
export function updateListItemSuccessAction(listItem) {
return {
type: UPDATE_LISTITEM_SUCCESS,
payload: {
listItem: listItem
}
};
}
export function getListItem(listDefinition: ListDefinition, itemId: number): Promise<any> {
let fieldnames = new Array<string>();
let expands = new Array<string>();
for (const columnreference of listDefinition.columnReferences) {
switch (columnreference.fieldDefinition.TypeAsString) {
case "Lookup":
expands.push(columnreference.fieldDefinition.InternalName);
fieldnames.push(columnreference.fieldDefinition.InternalName + "/" + columnreference.fieldDefinition.LookupField);
fieldnames.push(columnreference.fieldDefinition.InternalName + "/Id");
break;
case "User":
// url is ?$select=Author/Name,Author/Title&$expand=Author/Id
expands.push(columnreference.fieldDefinition.InternalName + "/Id");
fieldnames.push(columnreference.fieldDefinition.InternalName + "/Title");
fieldnames.push(columnreference.fieldDefinition.InternalName + "/Id");
fieldnames.push(columnreference.fieldDefinition.InternalName + "/Name");
break;
default:
const internalName = utils.ParseSPField(columnreference.name).id;
fieldnames.push(internalName); // need to split
}
}
const weburl = utils.ParseSPField(listDefinition.webLookup).id;
const listid = utils.ParseSPField(listDefinition.listLookup).id;
const web = new Web(weburl);
let promise: Promise<any> = web.lists.getById(listid).items.getById(itemId).select(fieldnames.concat("GUID").concat("Id").join(",")).expand(expands.join(",")).get();
return promise;
}
export function getListItemErrorAction(error) {
return {
type: GET_LISTITEMERROR,
payload: {
error: error
}
};
}
export function gotListItemAction(item) {
return {
type: GOT_LISTITEM,
payload: {
item: item
}
};
}
export function getListItemsAction(dispatch: any, listDefinitions: Array<ListDefinition>, columnDefinitions: Array<ColumnDefinition>): any {
dispatch(clearListItems());
const promises: Array<Promise<any>> = new Array<Promise<any>>();
for (const listDefinition of listDefinitions) {
if (!listDefinitionIsValid(listDefinition)) {
break;
}
let fieldnames = new Array<string>();
let expands = new Array<string>();
for (const columnreference of listDefinition.columnReferences) {
switch (columnreference.fieldDefinition.TypeAsString) {
case "Lookup":
expands.push(columnreference.fieldDefinition.InternalName);
fieldnames.push(columnreference.fieldDefinition.InternalName + "/" + columnreference.fieldDefinition.LookupField);
fieldnames.push(columnreference.fieldDefinition.InternalName + "/Id");
break;
case "User":
// url is ?$select=Author/Name,Author/Title&$expand=Author/Id
expands.push(columnreference.fieldDefinition.InternalName + "/Id");
fieldnames.push(columnreference.fieldDefinition.InternalName + "/Title");
fieldnames.push(columnreference.fieldDefinition.InternalName + "/Id");
fieldnames.push(columnreference.fieldDefinition.InternalName + "/Name");
break;
default:
const internalName = utils.ParseSPField(columnreference.name).id;
fieldnames.push(internalName); // need to split
}
}
const weburl = utils.ParseSPField(listDefinition.webLookup).id;
const listid = utils.ParseSPField(listDefinition.listLookup).id;
const web = new Web(weburl);
const promise = web.lists.getById(listid).items.select(fieldnames.concat("GUID").concat("Id").join(",")).expand(expands.join(",")).get()
.then((response) => {
const data = _.map(response, (item: any) => {
item.__metadata__ListDefinitionId = listDefinition.guid; // save my listdef, so i can get the columnReferences later
item.__metadata__GridRowStatus = GridRowStatus.pristine;
return item;
});
console.log(data);
const gotListItems = gotListItemsAction(data,listDefinitions,columnDefinitions);
dispatch(gotListItems); // need to ewname this one to be digfferent from the omported ome
})
.catch((error) => {
console.log(error);
dispatch(getListItemsErrorAction(error)); // need to ewname this one to be digfferent from the omported ome
});
promises.push(promise);
}
const action = {
type: GET_LISTITEMS,
payload: {
promise: Promise.all(promises)
}
};
return action;
}
export function getListItemsErrorAction(error) {
return {
type: GET_LISTITEMSERROR,
payload: {
error: error
}
};
}
export function gotListItemsAction(items: Array<ListItem>, listDefinitions: Array<ListDefinition>, columnDefinitions: Array<ColumnDefinition>) {
return {
type: GOT_LISTITEMS,
payload: {
items: items,
listDefinitions: listDefinitions,
columnDefinitions: columnDefinitions
}
};
}
export function saveListItemAction(listItem: ListItem) {
const action = {
type: SAVE_LISTITEM,
payload: {
listItem
}
};
return action;
}
export function undoListItemChangesAction(listItem: ListItem) {
const action = {
type: UNDO_LISTITEMCHANGES,
payload: {
listItem
}
};
return action;
} | the_stack |
import React from 'react';
import {FormattedMessage} from 'react-intl';
import {isEmail} from 'mattermost-redux/utils/helpers';
import {debounce} from 'mattermost-redux/actions/helpers';
import FormattedMarkdownMessage from 'components/formatted_markdown_message';
import InviteIcon from 'components/widgets/icons/invite_icon';
import CloseCircleIcon from 'components/widgets/icons/close_circle_icon';
import UpgradeLink from 'components/widgets/links/upgrade_link';
import ChannelsInput from 'components/widgets/inputs/channels_input.jsx';
import UsersEmailsInput from 'components/widgets/inputs/users_emails_input.jsx';
import withGetCloudSubscription from '../../common/hocs/cloud/with_get_cloud_subscription';
import {Channel} from 'mattermost-redux/types/channels';
import {UserProfile} from 'mattermost-redux/types/users';
import './invitation_modal_guests_step.scss';
import {t} from 'utils/i18n.jsx';
import {localizeMessage} from 'utils/utils.jsx';
import {PropsFromRedux} from './index';
type OwnProps = {
teamName: string;
myInvitableChannels: Channel[];
currentTeamId: string;
searchProfiles: (term: string, options?: Record<string, unknown>) => Promise<{ data: UserProfile[] }>;
searchChannels: (teamId: string, term: string) => Promise<Channel[]>;
defaultChannels?: Channel[];
defaultMessage?: string;
onEdit: (hasChanges: boolean) => void;
onSubmit: (users: string[], emails: string[], channels: Channel[], message: string, extraUserText: string, extraChannelText: string) => Promise<void>;
emailInvitationsEnabled: boolean;
}
type Props = OwnProps & PropsFromRedux
type State = {
customMessageOpen: boolean;
customMessage: string;
usersAndEmails: string[];
channels: Channel[];
usersInputValue: string;
channelsInputValue: string;
termWithoutResults?: string | null;
}
class InvitationModalGuestsStep extends React.PureComponent<Props, State> {
private textareaRef = React.createRef<HTMLTextAreaElement>();
constructor(props: Props) {
super(props);
this.textareaRef = React.createRef();
this.state = {
customMessageOpen: Boolean(props.defaultMessage),
customMessage: props.defaultMessage || '',
usersAndEmails: [],
channels: props.defaultChannels || [],
usersInputValue: '',
channelsInputValue: '',
};
}
onUsersEmailsChange = (usersAndEmails: string[]) => {
this.setState({usersAndEmails});
this.props.onEdit(usersAndEmails.length > 0 || this.state.channels.length > 0 || this.state.customMessage !== '' || this.state.usersInputValue !== '' || this.state.channelsInputValue !== '');
}
onChannelsChange = (channels: Channel[]) => {
this.setState({channels});
this.props.onEdit(this.state.usersAndEmails.length > 0 || channels.length > 0 || this.state.customMessage !== '' || this.state.usersInputValue !== '' || this.state.channelsInputValue !== '');
}
onMessageChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
this.setState({customMessage: e.target.value});
this.props.onEdit(this.state.usersAndEmails.length > 0 || this.state.channels.length > 0 || e.target.value !== '' || this.state.usersInputValue !== '' || this.state.channelsInputValue !== '');
}
onUsersInputChange = (usersInputValue: string) => {
this.setState({usersInputValue});
this.props.onEdit(this.state.usersAndEmails.length > 0 || this.state.channels.length > 0 || this.state.customMessage !== '' || usersInputValue !== '' || this.state.channelsInputValue !== '');
}
onChannelsInputChange = (channelsInputValue: string) => {
this.setState({channelsInputValue});
this.props.onEdit(this.state.usersAndEmails.length > 0 || this.state.channels.length > 0 || this.state.customMessage !== '' || this.state.usersInputValue !== '' || channelsInputValue !== '');
}
debouncedSearchProfiles = debounce((term, callback) => {
this.props.searchProfiles(term).then(({data}) => {
callback(data);
if (data.length === 0) {
this.setState({termWithoutResults: term});
} else {
this.setState({termWithoutResults: null});
}
}).catch(() => {
callback([]);
});
}, 150);
usersLoader = (term: string, callback: (options?: Array<Record<'username | email', string>>) => void) => {
if (this.state.termWithoutResults && term.startsWith(this.state.termWithoutResults)) {
callback([]);
return;
}
try {
this.debouncedSearchProfiles(term, callback);
} catch (error) {
callback([]);
}
}
debouncedSearchChannels = debounce((term) => this.props.searchChannels(this.props.currentTeamId, term), 150);
channelsLoader = async (value: string) => {
if (!value) {
return this.props.myInvitableChannels;
}
this.debouncedSearchChannels(value);
return this.props.myInvitableChannels.filter((channel) => {
return channel.display_name.toLowerCase().startsWith(value.toLowerCase()) || channel.name.toLowerCase().startsWith(value.toLowerCase());
});
}
openCustomMessage = () => {
this.setState({customMessageOpen: true});
setTimeout(() => {
if (this.textareaRef.current) {
this.textareaRef.current.focus();
}
});
}
closeCustomMessage = () => {
this.setState({customMessageOpen: false});
}
sendInvites = () => {
const users = [];
const emails = [];
for (const userOrEmail of this.state.usersAndEmails) {
if (isEmail(userOrEmail)) {
emails.push(userOrEmail);
} else {
users.push(userOrEmail);
}
}
this.props.onSubmit(users, emails, this.state.channels, this.state.customMessageOpen ? this.state.customMessage : '', this.state.usersInputValue, this.state.channelsInputValue);
}
getRemainingUsers = () => {
const {subscriptionStats} = this.props;
const {usersAndEmails} = this.state;
return subscriptionStats && subscriptionStats.remaining_seats - usersAndEmails.length;
}
shouldShowPickerError = () => {
const {
userLimit,
userIsAdmin,
isCloud,
subscriptionStats,
} = this.props;
if (subscriptionStats && subscriptionStats.is_paid_tier === 'true') {
return false;
}
if (userLimit === '0' || !userIsAdmin || !isCloud) {
return false;
}
// usersRemaining is calculated against the limit, the current users, and how many are being invited in the current flow
const usersRemaining = this.getRemainingUsers();
if (usersRemaining === 0 && this.state.usersInputValue !== '') {
return true;
} else if (usersRemaining < 0) {
return true;
}
return false;
};
render() {
let inputPlaceholder = localizeMessage('invitation_modal.guests.search-and-add.placeholder', 'Add guests or email addresses');
let noMatchMessageId = t('invitation_modal.guests.users_emails_input.no_user_found_matching');
let noMatchMessageDefault = 'No one found matching **{text}**. Enter their email to invite them.';
if (!this.props.emailInvitationsEnabled) {
inputPlaceholder = localizeMessage('invitation_modal.guests.search-and-add.placeholder-email-disabled', 'Add guests');
noMatchMessageId = t('invitation_modal.guests.users_emails_input.no_user_found_matching-email-disabled');
noMatchMessageDefault = 'No one found matching **{text}**';
}
const {subscriptionStats} = this.props;
const remainingUsers = subscriptionStats && subscriptionStats.remaining_seats;
return (
<div className='InvitationModalGuestsStep'>
<div className='modal-icon'>
<InviteIcon/>
</div>
<h1 id='invitation_modal_title'>
<FormattedMarkdownMessage
id='invitation_modal.guests.title'
defaultMessage='Invite **Guests** to {teamName}'
values={{teamName: this.props.teamName}}
/>
</h1>
<div
className='add-people'
data-testid='addPeople'
>
<h5>
<FormattedMessage
id='invitation_modal.guests.add_people.title'
defaultMessage='Invite People'
/>
</h5>
<div data-testid='emailPlaceholder'>
<UsersEmailsInput
usersLoader={this.usersLoader}
placeholder={inputPlaceholder}
ariaLabel={localizeMessage(
'invitation_modal.guests.add_people.title',
'Invite People',
)}
showError={this.shouldShowPickerError()}
errorMessageId={t(
'invitation_modal.invite_members.hit_cloud_user_limit',
)}
errorMessageDefault={
'You can only invite **{num} more {num, plural, one {member} other {members}}** to the team on the free tier.'
}
errorMessageValues={{
num: remainingUsers < 0 ? '0' : remainingUsers,
}}
extraErrorText={(<UpgradeLink/>)}
onChange={this.onUsersEmailsChange}
value={this.state.usersAndEmails}
onInputChange={this.onUsersInputChange}
inputValue={this.state.usersInputValue}
validAddressMessageId={t(
'invitation_modal.guests.users_emails_input.valid_email',
)}
validAddressMessageDefault='Invite **{email}** as a guest'
noMatchMessageId={noMatchMessageId}
noMatchMessageDefault={noMatchMessageDefault}
emailInvitationsEnabled={
this.props.emailInvitationsEnabled
}
/>
</div>
<div className='help-text'>
{this.props.emailInvitationsEnabled && (
<FormattedMessage
id='invitation_modal.guests.add_people.description'
defaultMessage='Add existing guests or send email invites to new guests.'
/>
)}
{!this.props.emailInvitationsEnabled && (
<FormattedMessage
id='invitation_modal.guests.add_people.description-email-disabled'
defaultMessage='Add existing guests.'
/>
)}
</div>
</div>
<div
className='add-channels'
data-testid='channelPlaceholder'
>
<h5>
<FormattedMessage
id='invitation_modal.guests.add_channels.title'
defaultMessage='Search and Add Channels'
/>
</h5>
<div>
<FormattedMessage
id='invitation_modal.guests.add_channels.placeholder'
defaultMessage='Search and add channels'
>
{(placeholder) => (
<ChannelsInput
placeholder={placeholder}
ariaLabel={localizeMessage(
'invitation_modal.guests.add_channels.title',
'Search and Add Channels',
)}
channelsLoader={this.channelsLoader}
onChange={this.onChannelsChange}
onInputChange={this.onChannelsInputChange}
inputValue={this.state.channelsInputValue}
value={this.state.channels}
/>
)}
</FormattedMessage>
</div>
<div className='help-text'>
<FormattedMessage
id='invitation_modal.guests.add-channels.description'
defaultMessage='Specify the channels the guests have access to.'
/>
</div>
</div>
<div
className='custom-message'
data-testid='customMessage'
>
{!this.state.customMessageOpen && (
<a
onClick={this.openCustomMessage}
href='#'
>
<FormattedMessage
id='invitation_modal.guests.custom-message.link'
defaultMessage='Set a custom message'
/>
</a>
)}
{this.state.customMessageOpen && (
<React.Fragment>
<div>
<FormattedMessage
id='invitation_modal.guests.custom-message.title'
defaultMessage='Custom message'
/>
<CloseCircleIcon
onClick={this.closeCustomMessage}
/>
</div>
<textarea
ref={this.textareaRef}
onChange={this.onMessageChange}
value={this.state.customMessage}
/>
</React.Fragment>
)}
<div className='help-text'>
<FormattedMessage
id='invitation_modal.guests.custom-message.description'
defaultMessage='Create a custom message to make your invite more personal.'
/>
</div>
</div>
<div className='invite-guests'>
<button
className={
'btn ' +
(this.state.channels.length === 0 ||
this.state.usersAndEmails.length === 0 ? 'btn-inactive' : 'btn-primary')
}
disabled={
this.state.channels.length === 0 ||
this.state.usersAndEmails.length === 0
}
onClick={this.sendInvites}
id='inviteGuestButton'
>
<FormattedMessage
id='invitation_modal.guests.invite_button'
defaultMessage='Invite Guests'
/>
</button>
</div>
</div>
);
}
}
export default withGetCloudSubscription(InvitationModalGuestsStep); | the_stack |
import { DEFAULT_GENERIC_PARAMETER_TYPE, DEFAULT_RESULT_CACHE, NEVER_TYPE } from "../constants";
import {
isSimpleTypeLiteral,
isSimpleTypePrimitive,
SimpleType,
SimpleTypeFunctionParameter,
SimpleTypeGenericArguments,
SimpleTypeGenericParameter,
SimpleTypeIntersection,
SimpleTypeKind,
SimpleTypeMemberNamed,
SimpleTypeObject,
SimpleTypeObjectTypeBase,
SimpleTypeTuple
} from "../simple-type";
import { simpleTypeToString } from "../transform/simple-type-to-string";
import { and, or } from "../utils/list-util";
import { resolveType as resolveTypeUnsafe } from "../utils/resolve-type";
import { extendTypeParameterMap, getTupleLengthType } from "../utils/simple-type-util";
import { isAssignableToSimpleTypeKind } from "./is-assignable-to-simple-type-kind";
import { SimpleTypeComparisonOptions } from "./simple-type-comparison-options";
interface IsAssignableToSimpleTypeInternalOptions {
config: SimpleTypeComparisonOptions;
cache: WeakMap<SimpleType, WeakMap<SimpleType, boolean>>;
insideType: Set<SimpleType>;
comparingTypes: Map<SimpleType, Set<SimpleType>>;
genericParameterMapA: Map<string, SimpleType>;
genericParameterMapB: Map<string, SimpleType>;
preventCaching: () => void;
operations: { value: number };
depth: number;
}
/**
* Returns if typeB is assignable to typeA.
* @param typeA Type A
* @param typeB Type B
* @param config
*/
export function isAssignableToSimpleType(typeA: SimpleType, typeB: SimpleType, config?: SimpleTypeComparisonOptions): boolean {
const userCache = config?.cache;
config = {
...config,
cache: undefined,
strict: config?.strict ?? true,
strictFunctionTypes: config?.strictFunctionTypes ?? config?.strict ?? true,
strictNullChecks: config?.strictNullChecks ?? config?.strict ?? true,
maxDepth: config?.maxDepth ?? 50,
maxOps: config?.maxOps ?? 1000
};
const cacheKey = `${config.strict}:${config.strictFunctionTypes}:${config.strictNullChecks}`;
const cache = DEFAULT_RESULT_CACHE.get(cacheKey) || new WeakMap();
DEFAULT_RESULT_CACHE.set(cacheKey, cache);
return isAssignableToSimpleTypeCached(typeA, typeB, {
config,
operations: { value: 0 },
depth: 0,
cache: userCache || cache,
insideType: new Set(),
comparingTypes: new Map(),
genericParameterMapA: new Map(),
genericParameterMapB: new Map(),
preventCaching: () => {}
});
}
function isAssignableToSimpleTypeCached(typeA: SimpleType, typeB: SimpleType, options: IsAssignableToSimpleTypeInternalOptions): boolean {
let typeACache = options.cache.get(typeA)!;
let preventCaching = false;
if (typeACache?.has(typeB)) {
if (options.config.debug) {
logDebug(
options,
"caching",
`Found cache when comparing: ${simpleTypeToStringLazy(typeA)} (${typeA.kind}) and ${simpleTypeToStringLazy(typeB)} (${typeB.kind}). Cache content: ${typeACache.get(typeB)}`
);
}
return typeACache.get(typeB)!;
}
// Call "isAssignableToSimpleTypeInternal" with a mutated options object
const result = isAssignableToSimpleTypeInternal(typeA, typeB, {
depth: options.depth,
operations: options.operations,
genericParameterMapA: options.genericParameterMapA,
genericParameterMapB: options.genericParameterMapB,
config: options.config,
insideType: options.insideType,
comparingTypes: options.comparingTypes,
cache: options.cache,
preventCaching: () => {
options.preventCaching();
preventCaching = true;
}
});
if (!preventCaching) {
/*if (options.config.debug) {
logDebug(
options,
"caching",
`Setting cache for comparison between ${simpleTypeToStringLazy(typeA)} (${typeA.kind}) and ${simpleTypeToStringLazy(typeB)} (${typeB.kind}). Result: ${result}`
);
}*/
if (typeACache == null) {
typeACache = new WeakMap();
options.cache.set(typeA, typeACache);
}
typeACache.set(typeB, result);
}
return result;
}
function isCacheableType(simpleType: SimpleType, options: IsAssignableToSimpleTypeInternalOptions): boolean {
switch (simpleType.kind) {
case "UNION":
case "INTERSECTION":
if (options.genericParameterMapA.size !== 0 || options.genericParameterMapB.size !== 0) {
return false;
}
break;
}
return !("typeParameters" in simpleType) && !["GENERIC_ARGUMENTS", "GENERIC_PARAMETER", "PROMISE", "LAZY"].includes(simpleType.kind);
}
function isAssignableToSimpleTypeInternal(typeA: SimpleType, typeB: SimpleType, options: IsAssignableToSimpleTypeInternalOptions): boolean {
// It's assumed that the "options" parameter is already an unique reference that is safe to mutate.
// Mutate depth and "operations"
options.depth = options.depth + 1;
options.operations.value++;
// Handle debugging nested calls to isAssignable
if (options.config.debug === true) {
logDebugHeader(typeA, typeB, options);
}
if (options.depth >= options.config.maxDepth! || options.operations.value >= options.config.maxOps!) {
options.preventCaching();
return true;
}
// When comparing types S and T, the relationship in question is assumed to be true
// for every directly or indirectly nested occurrence of the same S and the same T
if (options.comparingTypes.has(typeA)) {
if (options.comparingTypes.get(typeA)!.has(typeB)) {
options.preventCaching();
if (options.config.debug) {
logDebug(options, "comparing types", "Returns true because this relation is already being checking");
}
return true;
}
}
// We might need a better way of handling refs, but these check are good for now
if (options.insideType.has(typeA) || options.insideType.has(typeB)) {
if (options.config.debug) {
logDebug(
options,
"inside type",
`{${typeA.kind}, ${typeB.kind}} {typeA: ${options.insideType.has(typeA)}} {typeB: ${options.insideType.has(typeB)}} {insideTypeMap: ${Array.from(options.insideType.keys())
.map(t => simpleTypeToStringLazy(t))
.join()}}`
);
}
options.preventCaching();
return true;
}
// Handle two types being equal
// Types are not necessarily equal if they have typeParams because we still need to check the actual generic arguments
if (isCacheableType(typeA, options) && isCacheableType(typeB, options)) {
if (typeA === typeB) {
if (options.config.debug) {
logDebug(options, "equal", "The two types are equal!", typeA.kind, typeB.kind);
}
return true;
}
} else {
options.preventCaching();
}
// Make it possible to overwrite default behavior by running user defined logic for comparing types
if (options.config.isAssignable != null) {
const result = options.config.isAssignable(typeA, typeB, options.config);
if (result != null) {
//options.preventCaching();
return result;
}
}
// Any and unknown. Everything is assignable to "ANY" and "UNKNOWN"
if (typeA.kind === "UNKNOWN" || typeA.kind === "ANY") {
return true;
}
// Mutate options and add this comparison to "comparingTypes".
// Only do this if one of the types is not a primitive to save memory.
if (!isSimpleTypePrimitive(typeA) && !isSimpleTypePrimitive(typeB)) {
const comparingTypes = new Map(options.comparingTypes);
if (comparingTypes.has(typeA)) {
comparingTypes.get(typeA)!.add(typeB);
} else {
comparingTypes.set(typeA, new Set([typeB]));
}
options.comparingTypes = comparingTypes;
}
// #####################
// Expand typeB
// #####################
switch (typeB.kind) {
// [typeB] (expand)
case "UNION": {
// Some types seems to absorb other types when type checking a union (eg. 'unknown').
// Usually typescript will absorb those types for us, but not when working with generic parameters.
// The following line needs to be improved.
const types = typeB.types.filter(t => resolveType(t, options.genericParameterMapB) !== DEFAULT_GENERIC_PARAMETER_TYPE);
return and(types, childTypeB => isAssignableToSimpleTypeCached(typeA, childTypeB, options));
}
// [typeB] (expand)
case "INTERSECTION": {
// If we compare an intersection against an intersection, we need to compare from typeA and not typeB
// Example: [string, number] & [string] === [string, number] & [string]
if (typeA.kind === "INTERSECTION") {
break;
}
const combined = reduceIntersectionIfPossible(typeB, options.genericParameterMapB);
if (combined.kind === "NEVER") {
if (options.config.debug) {
logDebug(options, "intersection", `Combining types in intersection is impossible. Comparing with 'never' instead.`);
}
return isAssignableToSimpleTypeCached(typeA, { kind: "NEVER" }, options);
}
if (options.config.debug) {
if (combined !== typeB) {
logDebug(options, "intersection", `Types in intersection were combined into: ${simpleTypeToStringLazy(combined)}`);
}
}
if (combined.kind !== "INTERSECTION") {
return isAssignableToSimpleTypeCached(typeA, combined, options);
}
// An intersection type I is assignable to a type T if any type in I is assignable to T.
return or(combined.types, memberB => isAssignableToSimpleTypeCached(typeA, memberB, options));
}
// [typeB] (expand)
case "ALIAS": {
return isAssignableToSimpleTypeCached(typeA, typeB.target, options);
}
// [typeB] (expand)
case "GENERIC_ARGUMENTS": {
const updatedGenericParameterMapB = extendTypeParameterMap(typeB, options.genericParameterMapB);
if (options.config.debug) {
logDebug(
options,
"generic args",
"Expanding with typeB args: ",
Array.from(updatedGenericParameterMapB.entries())
.map(([name, type]) => `${name}=${simpleTypeToStringLazy(type)}`)
.join("; "),
"typeParameters" in typeB.target ? "" : "[No type parameters in target!]"
);
}
return isAssignableToSimpleTypeCached(typeA, typeB.target, {
...options,
genericParameterMapB: updatedGenericParameterMapB
});
}
// [typeB] (expand)
case "GENERIC_PARAMETER": {
const resolvedArgument = options.genericParameterMapB.get(typeB.name);
const realTypeB = resolvedArgument || typeB.default || DEFAULT_GENERIC_PARAMETER_TYPE;
if (options.config.debug) {
logDebug(
options,
"generic",
`Resolving typeB for param ${typeB.name} to:`,
simpleTypeToStringLazy(realTypeB),
", Default: ",
simpleTypeToStringLazy(typeB.default),
", In map: ",
options.genericParameterMapB.has(typeB.name),
", GenericParamMapB: ",
Array.from(options.genericParameterMapB.entries())
.map(([name, t]) => `${name}=${simpleTypeToStringLazy(t)}`)
.join("; ")
);
}
return isAssignableToSimpleTypeCached(typeA, realTypeB, options);
}
}
// #####################
// Compare typeB
// #####################
switch (typeB.kind) {
// [typeB] (compare)
case "ENUM_MEMBER": {
return isAssignableToSimpleTypeCached(typeA, typeB.type, options);
}
// [typeB] (compare)
case "ENUM": {
return and(typeB.types, childTypeB => isAssignableToSimpleTypeCached(typeA, childTypeB, options));
}
// [typeB] (compare)
case "UNDEFINED":
case "NULL": {
// When strict null checks are turned off, "undefined" and "null" are in the domain of every type but never
if (!options.config.strictNullChecks) {
return typeA.kind !== "NEVER";
}
break;
}
// [typeB] (compare)
case "ANY": {
// "any" can be assigned to anything but "never"
return typeA.kind !== "NEVER";
}
// [typeB] (compare)
case "NEVER": {
// "never" can be assigned to anything
return true;
}
}
// #####################
// Expand typeA
// #####################
switch (typeA.kind) {
// [typeA] (expand)
case "ALIAS": {
return isAssignableToSimpleTypeCached(typeA.target, typeB, options);
}
// [typeA] (expand)
case "GENERIC_PARAMETER": {
const resolvedArgument = options.genericParameterMapA.get(typeA.name);
const realTypeA = resolvedArgument || typeA.default || DEFAULT_GENERIC_PARAMETER_TYPE;
if (options.config.debug) {
logDebug(
options,
"generic",
`Resolving typeA for param ${typeA.name} to:`,
simpleTypeToStringLazy(realTypeA),
", Default: ",
simpleTypeToStringLazy(typeA.default),
", In map: ",
options.genericParameterMapA.has(typeA.name),
", GenericParamMapA: ",
Array.from(options.genericParameterMapA.entries())
.map(([name, t]) => `${name}=${simpleTypeToStringLazy(t)}`)
.join("; ")
);
}
return isAssignableToSimpleTypeCached(realTypeA, typeB, options);
}
// [typeA] (expand)
case "GENERIC_ARGUMENTS": {
const updatedGenericParameterMapA = extendTypeParameterMap(typeA, options.genericParameterMapA);
if (options.config.debug) {
logDebug(
options,
"generic args",
"Expanding with typeA args: ",
Array.from(updatedGenericParameterMapA.entries())
.map(([name, type]) => `${name}=${simpleTypeToStringLazy(type)}`)
.join("; "),
"typeParameters" in typeA.target ? "" : "[No type parameters in target!]"
);
}
return isAssignableToSimpleTypeCached(typeA.target, typeB, {
...options,
genericParameterMapA: updatedGenericParameterMapA
});
}
// [typeA] (expand)
case "UNION": {
// Some types seems to absorb other types when type checking a union (eg. 'unknown').
// Usually typescript will absorb those types for us, but not when working with generic parameters.
// The following line needs to be improved.
const types = typeA.types.filter(t => resolveType(t, options.genericParameterMapA) !== DEFAULT_GENERIC_PARAMETER_TYPE || typeB === DEFAULT_GENERIC_PARAMETER_TYPE);
return or(types, childTypeA => isAssignableToSimpleTypeCached(childTypeA, typeB, options));
}
// [typeA] (expand)
case "INTERSECTION": {
const combined = reduceIntersectionIfPossible(typeA, options.genericParameterMapA);
if (combined.kind === "NEVER") {
if (options.config.debug) {
logDebug(options, "intersection", `Combining types in intersection is impossible. Comparing with 'never' instead.`);
}
return isAssignableToSimpleTypeCached({ kind: "NEVER" }, typeB, options);
}
if (options.config.debug) {
if (combined !== typeA) {
logDebug(options, "intersection", `Types in intersection were combined into: ${simpleTypeToStringLazy(combined)}`);
}
}
if (combined.kind !== "INTERSECTION") {
return isAssignableToSimpleTypeCached(combined, typeB, options);
}
// A type T is assignable to an intersection type I if T is assignable to each type in I.
return and(combined.types, memberA => isAssignableToSimpleTypeCached(memberA, typeB, options));
}
}
// #####################
// Compare typeA
// #####################
switch (typeA.kind) {
// [typeA] (compare)
case "NON_PRIMITIVE": {
if (options.config.debug) {
logDebug(options, "object", `Checking if typeB is non-primitive [primitive=${isSimpleTypePrimitive(typeB)}] [hasName=${typeB.name != null}]`);
}
if (isSimpleTypePrimitive(typeB)) {
return typeB.name != null;
}
return typeB.kind !== "UNKNOWN";
}
// [typeA] (compare)
case "ARRAY": {
if (typeB.kind === "ARRAY") {
return isAssignableToSimpleTypeCached(typeA.type, typeB.type, options);
} else if (typeB.kind === "TUPLE") {
return and(typeB.members, memberB => isAssignableToSimpleTypeCached(typeA.type, memberB.type, options));
}
return false;
}
// [typeA] (compare)
case "ENUM": {
return or(typeA.types, childTypeA => isAssignableToSimpleTypeCached(childTypeA, typeB, options));
}
// [typeA] (compare)
case "NUMBER_LITERAL":
case "STRING_LITERAL":
case "BIG_INT_LITERAL":
case "BOOLEAN_LITERAL":
case "ES_SYMBOL_UNIQUE": {
return isSimpleTypeLiteral(typeB) ? typeA.value === typeB.value : false;
}
// [typeA] (compare)
case "ENUM_MEMBER": {
// You can always assign a "number" | "number literal" to a "number literal" enum member type.
if (resolveType(typeA.type, options.genericParameterMapA).kind === "NUMBER_LITERAL" && ["NUMBER", "NUMBER_LITERAL"].includes(typeB.kind)) {
if (typeB.name != null) {
return false;
}
return true;
}
return isAssignableToSimpleTypeCached(typeA.type, typeB, options);
}
// [typeA] (compare)
case "STRING":
case "BOOLEAN":
case "NUMBER":
case "ES_SYMBOL":
case "BIG_INT": {
if (typeB.name != null) {
return false;
}
if (isSimpleTypeLiteral(typeB)) {
return PRIMITIVE_TYPE_TO_LITERAL_MAP[typeA.kind] === typeB.kind;
}
return typeA.kind === typeB.kind;
}
// [typeA] (compare)
case "UNDEFINED":
case "NULL": {
return typeA.kind === typeB.kind;
}
// [typeA] (compare)
case "VOID": {
return typeB.kind === "VOID" || typeB.kind === "UNDEFINED";
}
// [typeA] (compare)
case "NEVER": {
return false;
}
// [typeA] (compare)
// https://www.typescriptlang.org/docs/handbook/type-compatibility.html#comparing-two-functions
case "FUNCTION":
case "METHOD": {
if ("call" in typeB && typeB.call != null) {
return isAssignableToSimpleTypeCached(typeA, typeB.call, options);
}
if (typeB.kind !== "FUNCTION" && typeB.kind !== "METHOD") return false;
if (typeB.parameters == null || typeB.returnType == null) return typeA.parameters == null || typeA.returnType == null;
if (typeA.parameters == null || typeA.returnType == null) return true;
// Any return type is assignable to void
if (options.config.debug) {
logDebug(options, "function", `Checking if return type of typeA is 'void'`);
}
if (!isAssignableToSimpleTypeKind(typeA.returnType, "VOID")) {
//if (!isAssignableToSimpleTypeInternal(typeA.returnType, { kind: "VOID" }, options)) {
if (options.config.debug) {
logDebug(options, "function", `Return type is not void. Checking return types`);
}
if (!isAssignableToSimpleTypeCached(typeA.returnType, typeB.returnType, options)) {
return false;
}
}
// Test "this" types
const typeAThisParam = typeA.parameters.find(arg => arg.name === "this");
const typeBThisParam = typeB.parameters.find(arg => arg.name === "this");
if (typeAThisParam != null && typeBThisParam != null) {
if (options.config.debug) {
logDebug(options, "function", `Checking 'this' param`);
}
if (!isAssignableToSimpleTypeCached(typeAThisParam.type, typeBThisParam.type, options)) {
return false;
}
}
// Get all "non-this" params
const paramTypesA = typeAThisParam == null ? typeA.parameters : typeA.parameters.filter(arg => arg !== typeAThisParam);
const paramTypesB = typeBThisParam == null ? typeB.parameters : typeB.parameters.filter(arg => arg !== typeBThisParam);
// A function with 0 params can be assigned to any other function
if (paramTypesB.length === 0) {
return true;
}
// A function with more required params than typeA isn't assignable
const requiredParamCountB = paramTypesB.reduce((sum, param) => (param.optional || param.rest ? sum : sum + 1), 0);
if (requiredParamCountB > paramTypesA.length) {
if (options.config.debug) {
logDebug(options, "function", `typeB has more required params than typeA: ${requiredParamCountB} > ${paramTypesA.length}`);
}
return false;
}
let prevParamA: SimpleTypeFunctionParameter | undefined = undefined;
let prevParamB: SimpleTypeFunctionParameter | undefined = undefined;
// Compare the types of each param
for (let i = 0; i < Math.max(paramTypesA.length, paramTypesB.length); i++) {
let paramA = paramTypesA[i];
let paramB = paramTypesB[i];
if (options.config.debug) {
logDebug(
options,
"function",
`${i} ['${paramA?.name || "???"}' AND '${paramB?.name || "???"}'] Checking parameters ${options.config.strictFunctionTypes ? "[contravariant]" : "[bivariant]"}: [${
paramA?.type == null ? "???" : simpleTypeToStringLazy(paramA.type)
} AND ${paramB?.type == null ? "???" : simpleTypeToStringLazy(paramB.type)}]`
);
}
// Try to find the last param in typeA. If it's a rest param, continue with that one
if (paramA == null && prevParamA?.rest) {
if (options.config.debug) {
logDebug(options, "function", `paramA is null and but last param in typeA is rest. Use that one.`);
}
paramA = prevParamA;
}
// Try to find the last param in typeB. If it's a rest param, continue with that one
if (paramB == null && prevParamB?.rest) {
if (options.config.debug) {
logDebug(options, "function", `paramB is null and but last param in typeB is rest. Use that one.`);
}
paramB = prevParamB;
}
prevParamA = paramA;
prevParamB = paramB;
// If paramA is not present, check if paramB is optional or not present as well
if (paramA == null) {
if (paramB != null && !paramB.optional && !paramB.rest) {
if (options.config.debug) {
logDebug(options, "function", `paramA is null and paramB is null, optional or has rest`);
}
return false;
}
if (options.config.debug) {
logDebug(options, "function", `paramA is null and paramB it not null, but is optional or has rest`);
}
continue;
}
// If paramB isn't present, check if paramA is optional
if (paramB == null) {
if (options.config.debug) {
logDebug(options, "function", `paramB is 'null' returning true`);
}
return true;
}
// Check if we are comparing a spread against a non-spread
const resolvedTypeA = resolveType(paramA.type, options.genericParameterMapA);
const resolvedTypeB = resolveType(paramB.type, options.genericParameterMapB);
// Unpack the array of rest parameters if possible
const paramAType = paramA.rest && resolvedTypeA.kind === "ARRAY" ? resolvedTypeA.type : paramA.type;
const paramBType = paramB.rest && resolvedTypeB.kind === "ARRAY" ? resolvedTypeB.type : paramB.type;
if (paramA.rest) {
if (options.config.debug) {
logDebug(options, "function", `paramA is 'rest' and has been resolved to '${simpleTypeToStringLazy(paramAType)}'`);
}
}
if (paramB.rest) {
if (options.config.debug) {
logDebug(options, "function", `paramB is 'rest' and has been resolved to '${simpleTypeToStringLazy(paramBType)}'`);
}
}
// Check if the param types are assignable
// Function parameter type checking is bivariant (when strictFunctionTypes is off) and contravariant (when strictFunctionTypes is on)
if (!options.config.strictFunctionTypes) {
if (options.config.debug) {
logDebug(options, "function", `Checking covariant relationship`);
}
// Strict is off, therefore start by checking the covariant.
// The contravariant relationship will be checked afterwards resulting in bivariant behavior
if (isAssignableToSimpleTypeCached(paramAType, paramBType, options)) {
// Continue to next parameter
continue;
}
}
// There is something strange going on where it seems checking two methods is less strict and checking two functions.
// I haven't found any documentation for this behavior, but it seems to be the case.
/* Examples (with strictFunctionTypes):
// -----------------------------
interface I1 {
test(b: string | null): void;
}
interface I2 {
test(a: string): void;
}
// This will not fail
const thisWillNotFail: I1 = {} as I2;
// -----------------------------
interface I3 {
test: (b: string | null) => void;
}
interface I4 {
test: (a: string) => void;
}
// This will fail with:
// Types of parameters 'a' and 'b' are incompatible.
// Type 'string | null' is not assignable to type 'string'.
// Type 'null' is not assignable to type 'string'
const thisWillFail: I3 = {} as I4;
*/
const newOptions = {
...options,
config:
typeA.kind === "METHOD" || typeB.kind === "METHOD"
? {
...options.config,
strictNullChecks: false,
strictFunctionTypes: false
}
: options.config,
cache: new WeakMap(),
genericParameterMapB: options.genericParameterMapA,
genericParameterMapA: options.genericParameterMapB
};
if (options.config.debug) {
logDebug(options, "function", `Checking contravariant relationship`);
}
// Contravariant
if (!isAssignableToSimpleTypeCached(paramBType, paramAType, newOptions)) {
return false;
}
}
return true;
}
// [typeA] (compare)
case "INTERFACE":
case "OBJECT":
case "CLASS": {
// If there are no members check that "typeB" is not assignable to a set of incompatible type kinds
// This is to check the empty object {} and Object
const typeAHasZeroMembers = isObjectEmpty(typeA, {
ignoreOptionalMembers: (["UNKNOWN", "NON_PRIMITIVE"] as SimpleTypeKind[]).includes(typeB.kind)
});
if (typeAHasZeroMembers && typeA.call == null && (typeA.ctor == null || typeA.kind === "CLASS")) {
if (options.config.debug) {
logDebug(options, "object-type", `typeA is the empty object '{}'`);
}
return !isAssignableToSimpleTypeKind(typeB, ["NULL", "UNDEFINED", "NEVER", "VOID", ...(options.config.strictNullChecks ? ["UNKNOWN"] : [])] as SimpleTypeKind[], {
matchAny: false
});
}
switch (typeB.kind) {
case "FUNCTION":
case "METHOD":
return typeA.call != null && isAssignableToSimpleTypeCached(typeA.call, typeB, options);
case "INTERFACE":
case "OBJECT":
case "CLASS": {
// Test both callable types
const membersA = typeA.members || [];
const membersB = typeB.members || [];
options.insideType = new Set([...options.insideType, typeA, typeB]);
// Check how many properties typeB has in common with typeA.
let membersInCommon = 0;
// Make sure that every required prop in typeA is present in typeB
const requiredMembersInTypeAExistsInTypeB = and(membersA, memberA => {
//if (memberA.optional) return true;
const memberB = membersB.find(memberB => memberA.name === memberB.name);
if (memberB != null) membersInCommon += 1;
return memberB == null
? // If corresponding "memberB" couldn't be found, return true if "memberA" is optional
memberA.optional
: // If corresponding "memberB" was found, return true if "memberA" is optional or "memberB" is not optional
memberA.optional || !memberB.optional;
});
if (!requiredMembersInTypeAExistsInTypeB) {
if (options.config.debug) {
logDebug(options, "object-type", `Didn't find required members from typeA in typeB`);
}
return false;
}
// Check if construct signatures are assignable (if any)
if (typeA.ctor != null && typeA.kind !== "CLASS") {
if (options.config.debug) {
logDebug(options, "object-type", `Checking if typeB.ctor is assignable to typeA.ctor`);
}
if (typeB.ctor != null && typeB.kind !== "CLASS") {
if (!isAssignableToSimpleTypeCached(typeA.ctor, typeB.ctor, options)) {
return false;
}
membersInCommon += 1;
} else {
if (options.config.debug) {
logDebug(options, "object-type", `Expected typeB.ctor to have a ctor`);
}
return false;
}
}
// Check if call signatures are assignable (if any)
if (typeA.call != null) {
if (options.config.debug) {
logDebug(options, "object-type", `Checking if typeB.call is assignable to typeA.call`);
}
if (typeB.call != null) {
if (!isAssignableToSimpleTypeCached(typeA.call, typeB.call, options)) {
return false;
}
membersInCommon += 1;
} else {
return false;
}
}
// They are not assignable if typeB has 0 members in common with typeA, and there are more than 0 members in typeB.
// The ctor of classes are not counted towards if typeB is empty
const typeBIsEmpty = membersB.length === 0 && typeB.call == null && ((typeB.kind !== "CLASS" && typeB.ctor == null) || typeB.kind === "CLASS");
if (membersInCommon === 0 && !typeBIsEmpty) {
if (options.config.debug) {
logDebug(options, "object-type", `typeB has 0 members in common with typeA and there are more than 0 members in typeB`);
}
return false;
}
// Ensure that every member in typeB is assignable to corresponding members in typeA
const membersInTypeBAreAssignableToMembersInTypeA = and(membersB, memberB => {
const memberA = membersA.find(memberA => memberA.name === memberB.name);
if (memberA == null) {
return true;
}
if (options.config.debug) {
logDebug(options, "object-type", `Checking member '${memberA.name}' types`);
}
return isAssignableToSimpleTypeCached(memberA.type, memberB.type, options);
});
if (options.config.debug) {
if (!membersInTypeBAreAssignableToMembersInTypeA) {
logDebug(options, "object-type", `Not all members in typeB is assignable to corresponding members in typeA`);
} else {
logDebug(options, "object-type", `All members were checked successfully`);
}
}
return membersInTypeBAreAssignableToMembersInTypeA;
}
default:
return false;
}
}
// [typeA] (compare)
case "TUPLE": {
if (typeB.kind !== "TUPLE") return false;
// Compare the length of each tuple, but compare the length type instead of the actual length
// We compare the length type because Typescript compares the type of the "length" member of tuples
if (!isAssignableToSimpleTypeCached(getTupleLengthType(typeA), getTupleLengthType(typeB), options)) {
return false;
}
// Compare if typeB elements are assignable to typeA's rest element
// Example: [string, ...boolean[]] === [any, true, 123]
if (typeA.rest && typeB.members.length > typeA.members.length) {
return and(typeB.members.slice(typeA.members.length), (memberB, i) => {
return isAssignableToSimpleTypeCached(typeA.members[typeA.members.length - 1].type, memberB.type, options);
});
}
// Compare that every type of typeB is assignable to corresponding members in typeA
return and(typeA.members, (memberA, i) => {
const memberB = typeB.members[i];
if (memberB == null) return memberA.optional;
return isAssignableToSimpleTypeCached(memberA.type, memberB.type, options);
});
}
// [typeA] (compare)
case "PROMISE": {
return typeB.kind === "PROMISE" && isAssignableToSimpleTypeCached(typeA.type, typeB.type, options);
}
// [typeA] (compare)
case "DATE": {
return typeB.kind === "DATE";
}
}
// If we some how end up here (we shouldn't), return "true" as a safe fallback
// @ts-ignore
return true;
}
function reduceIntersectionIfPossible(simpleType: SimpleTypeIntersection, parameterMap: Map<string, SimpleType>): SimpleType {
// DOCUMENTATION FROM TYPESCRIPT SOURCE CODE (getIntersectionType)
// We normalize combinations of intersection and union types based on the distributive property of the '&'
// operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection
// types with union type constituents into equivalent union types with intersection type constituents and
// effectively ensure that union types are always at the top level in type representations.
//
// We do not perform structural deduplication on intersection types. Intersection types are created only by the &
// type operator and we can't reduce those because we want to support recursive intersection types. For example,
// a type alias of the form "type List<T> = T & { next: List<T> }" cannot be reduced during its declaration.
// Also, unlike union types, the order of the constituent types is preserved in order that overload resolution
// for intersections of types with signatures can be deterministic.
// An intersection type is considered empty if it contains
// the type never, or
// more than one unit type or,
// an object type and a nullable type (null or undefined), or
// a string-like type and a type known to be non-string-like, or
// a number-like type and a type known to be non-number-like, or
// a symbol-like type and a type known to be non-symbol-like, or
// a void-like type and a type known to be non-void-like, or
// a non-primitive type and a type known to be primitive.
const typeKindMap = new Map<SimpleTypeKind, SimpleType[]>();
const primitiveSet = new Set<SimpleTypeKind>();
const primitiveLiteralSet = new Map<SimpleTypeKind, unknown>();
for (const member of simpleType.types) {
const resolvedType = resolveType(member, parameterMap);
typeKindMap.set(resolvedType.kind, [...(typeKindMap.get(resolvedType.kind) || []), resolvedType]);
switch (resolvedType.kind) {
case "NEVER":
return NEVER_TYPE;
}
if (isSimpleTypePrimitive(resolvedType)) {
if (isSimpleTypeLiteral(resolvedType)) {
if (primitiveLiteralSet.has(resolvedType.kind) && primitiveLiteralSet.get(resolvedType.kind) !== resolvedType.value) {
return NEVER_TYPE;
}
primitiveLiteralSet.set(resolvedType.kind, resolvedType.value);
} else {
primitiveSet.add(resolvedType.kind);
if (primitiveSet.size > 1) {
return NEVER_TYPE;
}
}
}
}
if ((typeKindMap.get("TUPLE")?.length || 0) > 1) {
let len: number | undefined = undefined;
for (const type of typeKindMap.get("TUPLE") as SimpleTypeTuple[]) {
if (len != null && len !== type.members.length) {
return NEVER_TYPE;
}
len = type.members.length;
}
}
if (typeKindMap.size === 1 && (typeKindMap.get("OBJECT")?.length || 0) > 1) {
const members = new Map<string, SimpleTypeMemberNamed>();
for (const type of typeKindMap.get("OBJECT") as SimpleTypeObject[]) {
for (const member of type.members || []) {
if (members.has(member.name)) {
const combinedMemberType = reduceIntersectionIfPossible({ kind: "INTERSECTION", types: [members.get(member.name)!.type, member.type] }, parameterMap);
if (combinedMemberType.kind === "NEVER") {
return combinedMemberType;
}
members.set(member.name, { ...member, type: combinedMemberType });
} else {
members.set(member.name, member);
}
}
}
return { ...(typeKindMap.get("OBJECT")![0] as SimpleTypeObject), members: Array.from(members.values()) };
}
return simpleType;
}
function isObjectEmpty(simpleType: SimpleTypeObjectTypeBase, { ignoreOptionalMembers }: { ignoreOptionalMembers?: boolean }): boolean {
return simpleType.members == null || simpleType.members.length === 0 || (ignoreOptionalMembers && !simpleType.members.some(m => !m.optional)) || false;
}
export function resolveType(simpleType: SimpleType, parameterMap: Map<string, SimpleType>): Exclude<SimpleType, SimpleTypeGenericParameter | SimpleTypeGenericArguments> {
return resolveTypeUnsafe(simpleType, parameterMap);
}
function logDebugHeader(typeA: SimpleType, typeB: SimpleType, options: IsAssignableToSimpleTypeInternalOptions): void {
const silentConfig = { ...options.config, debug: false, maxOps: 20, maxDepth: 20 };
let result: boolean | string;
try {
result = isAssignableToSimpleType(typeA, typeB, silentConfig);
} catch (e) {
result = e.message;
}
const depthChars = " ".repeat(options.depth);
const firstLogPart = ` ${depthChars}${simpleTypeToStringLazy(typeA)} ${colorText(options, ">:", "cyan")} ${simpleTypeToStringLazy(typeB)} [${typeA.kind} === ${typeB.kind}]`;
let text = `${firstLogPart} ${" ".repeat(Math.max(2, 120 - firstLogPart.length))}${colorText(options, options.depth, "yellow")} ### (${typeA.name || "???"} === ${
typeB.name || "???"
}) [result=${colorText(options, result, result === true ? "green" : "red")}]`;
if (options.depth >= 50) {
// Too deep
if (options.depth === 50) {
text = `Nested comparisons reach 100. Skipping logging...`;
} else {
return;
}
}
// eslint-disable-next-line no-console
(options.config.debugLog || console.log)(text);
}
function logDebug(options: IsAssignableToSimpleTypeInternalOptions, title: string, ...args: unknown[]): void {
const depthChars = " ".repeat(options.depth);
const text = `${depthChars} [${colorText(options, title, "blue")}] ${args.join(" ")}`;
// eslint-disable-next-line no-console
(options.config.debugLog || console.log)(colorText(options, text, "gray"));
}
function simpleTypeToStringLazy(simpleType: SimpleType | undefined): string {
if (simpleType == null) {
return "???";
}
return simpleTypeToString(simpleType);
}
function colorText(options: IsAssignableToSimpleTypeInternalOptions, text: unknown, color: "cyan" | "gray" | "red" | "blue" | "green" | "yellow"): string {
if (options.config.debugLog != null) {
return `${text}`;
}
const RESET = "\x1b[0m";
const COLOR = (() => {
switch (color) {
case "gray":
return "\x1b[2m\x1b[37m";
case "red":
return "\x1b[31m";
case "green":
return "\x1b[32m";
case "yellow":
return "\x1b[33m";
case "blue":
return "\x1b[34m";
case "cyan":
return "\x1b[2m\x1b[36m";
}
})();
return `${COLOR}${text}${RESET}`;
}
const PRIMITIVE_TYPE_TO_LITERAL_MAP = {
["STRING"]: "STRING_LITERAL",
["NUMBER"]: "NUMBER_LITERAL",
["BOOLEAN"]: "BOOLEAN_LITERAL",
["BIG_INT"]: "BIG_INT_LITERAL",
["ES_SYMBOL"]: "ES_SYMBOL_UNIQUE"
} as unknown as Record<SimpleTypeKind, SimpleTypeKind | undefined>;
/*const LITERAL_TYPE_TO_PRIMITIVE_TYPE_MAP = ({
["STRING_LITERAL"]: "STRING",
["NUMBER_LITERAL"]: "NUMBER",
["BOOLEAN_LITERAL"]: "BOOLEAN",
["BIG_INT_LITERAL"]: "BIG_INT",
["ES_SYMBOL_UNIQUE"]: "ES_SYMBOL"
} as unknown) as Record<SimpleTypeKind, SimpleTypeKind | undefined>;*/ | the_stack |
import { window, ViewColumn } from 'vscode';
import got from 'got';
import * as marked from 'marked';
import PluginData from '../models/NpmData';
import { NpmTreeItem } from '../utils/Interfaces';
export default class WebViews {
static async openWebView(npmPackage: NpmTreeItem) {
const {
links,
name,
version,
description,
} = npmPackage.command.arguments[0];
const readMe = await PluginData.mdToHtml(links.repository, links.homepage);
// turn npm package name from snake-case to standard capitalized title
const title = name
.replace(/-/g, ' ')
.replace(/^\w?|\s\w?/g, (match: string) => match.toUpperCase());
// createWebviewPanel takes in the type of the webview panel & Title of the panel & showOptions
const panel = window.createWebviewPanel(
'plugin',
`Gatsby Plugin: ${title}`,
ViewColumn.One
);
// create a header for each npm package and display README underneath header
// currently #install-btn does not work
panel.webview.html = `
<style>
.plugin-header {
position: fixed;
top: 0;
background-color: var(--vscode-editor-background);
width: 100vw;
}
#title-btn {
display: flex;
flex-direction: row;
align-items: center;
align-text: center;
}
#install-btn {
height: 1.5rem;
margin: 1rem;
}
body {
position: absolute;
top: 9rem;
}
</style>
<div class="plugin-header">
<div id="title-btn">
<h1 id="title">${title}</h1>
</div>
<p>Version: ${version}</p>
<p>${description}</p>
<hr class="solid">
</div>
${readMe}
`;
// close the webview when not looking at it
panel.onDidChangeViewState((e) => {
if (!e.webviewPanel.active) {
panel.dispose();
}
});
}
// open webview readme fo the Gatsby CLI commands
static async openCommandDocs() {
const url =
'https://raw.githubusercontent.com/gatsbyjs/gatsby/master/packages/gatsby-cli/README.md';
const response = await got(url);
const readMe = marked(response.body);
const panel = window.createWebviewPanel(
'CLI Docs',
`CLI Docs`,
ViewColumn.One
);
panel.webview.html = `${readMe}`;
// close the webview when not looking at it
panel.onDidChangeViewState((e) => {
if (!e.webviewPanel.active) {
panel.dispose();
}
});
}
// Open webview readme of Plugin docs -- has to be seperate function because the command has to be pushed to subscriptions in extension.ts file -- same for starters and themes
static openPluginDocs() {
const panel = window.createWebviewPanel(
'Plugin Docs',
`Plugin Docs`,
ViewColumn.One
);
panel.webview.html = `
<h1>Plugins</h2>
<h2>Gatsby plugins are Node.js packages that implement Gatsby APIs. For larger, more complex sites, plugins let you modularize your site customizations into site-specific functionality.</h2>
<h3>⬅️ Install plugins using the download button in the Plugins Menu next to your selected plugin's name</h3>
<p>
One of the best ways to add functionality to Gatsby is through our plugin system. Gatsby is designed to be extensible, which means plugins are able to extend and modify just about everything Gatsby does.
<br><br>
Of the many possibilities, plugins can:
<br>
<ul>
<li>add external data or content (e.g. your CMS, static files, a REST API) to your Gatsby GraphQL data</li>
<li>transform data from other formats (e.g. Markdown, YAML, CSV) to JSON objects</li>
<li>add third-party services (e.g. Google Analytics, Instagram) to your site</li>
<li>add bundled, pre-configured functionality with themes
do anything you can dream up!</li>
</ul></p>
<h3>Using Gatsby Plugins through GatsbyHub in your new Gatsby site</h3>
<p>
Gatsby plugins are Node.js packages, so you can install them like other packages in node, and with GatsbyHub, you can now use the install button in the plugins menu sidebar.
<br><br>
Then update your gatsby-config.js file to include the new plugin in your plugins array.
<br>
<br>
For example, gatsby-transformer-json is a package that adds support for JSON files to the Gatsby data layer.
<br><br>
In your site’s gatsby-config.js you add gatsby-transformer-json to the plugins array like:
<br>
<code>module.exports = {
plugins: ['gatsby-transformer-json'],
}
</code>
<br><br>
Plugins can also take <a href="https://www.gatsbyjs.com/docs/using-a-plugin-in-your-site/">options</a>.
<br><br>
<a href="https://www.gatsbyjs.com/docs/what-is-a-plugin/">Read more about gatsby pluggins</a>
</p>
`;
// close the webview when not looking at it
panel.onDidChangeViewState((e) => {
if (!e.webviewPanel.active) {
panel.dispose();
}
});
}
// opens webview for Starter readmen has to be seperate function to push to subscriptions
static openStarterDocs() {
const panel = window.createWebviewPanel(
'Starter Docs',
`Starter Docs`,
ViewColumn.One
);
panel.webview.html = `
<h1>Starters</h2>
<h2>The Gatsby and GatsbyHub tool lets you install starters, which are boilerplate Gatsby sites maintained by the community and intended for jump-starting development quickly.</h2>
<h3>⬅️ Install starters using the download button in the Starters Menu next to your selected starter's name</h3>
<p>
You can begin by using the Gatsby default starter simply by pressing on the "New" button in the Commands Menu, or you can install any of the starters in the Starters Menu by clicking the download button.
<br><br>
<h3>Choosing a starter</h3>
<p>To choose a starter, first consider the functionality you need. Are you building an e-commerce site? A blog? Do you already know what data sources you’ll want to use? Find a starter that fulfills your requirements by searching through the Gatsby Starters Menu on the left.
<br><br>
If you’re not sure what to choose or want only the most essential functionality, try customizing either gatsby-starter-blog (if you’re primarily using this site as a blog) or gatsby-starter-default (which you can use by simply pressing the "New" button in the Commands Menu). These official starters are maintained by Gatsby and are great options, particularly for your first Gatsby site.
<br><br>
<h3>Modifying starters</h3>
<p>
Learn how to <a href="https://www.gatsbyjs.com/docs/modifying-a-starter/">modify a starter</a> in the Gatsby docs.
<br><br>
You can use official and community starters out of the box but you may want to customize their style and functionality.
<br><br>
What you need to know will depend on the starter you choose and the data or functionality you’d like to modify. Even if you choose not to modify the starter’s components, you may still want to update text, use data from an external source, and modify the style (CSS) of the site. To do this, you’ll write some <a href="https://www.gatsbyjs.com/docs/mdx/markdown-syntax/">Markdown</a> and <a href="https://www.digitalocean.com/community/tutorials/an-introduction-to-json">JSON</a>.
<br><br>
To modify the functionality of a starter, you’ll want a basic understanding of <a href="https://reactjs.org/docs/introducing-jsx.html">JSX</a> syntax for updating components and making new ones. You’ll also want some knowledge of <a href="https://www.gatsbyjs.com/docs/graphql-concepts/">GraphQL</a> for querying your data. Start with these and add to your skills as you continue to add functionality to your starter.
</p>
<p><a href="https://www.gatsbyjs.com/docs/starters/">Read more about Gatsby Starters</a></p>
`;
// close the webview when not looking at it
panel.onDidChangeViewState((e) => {
if (!e.webviewPanel.active) {
panel.dispose();
}
});
}
// opens webview for Themes readme -- has to be seperate function in order to be pushed to subscriptions in extension.ts
static openThemeDocs() {
const panel = window.createWebviewPanel(
'Theme Docs',
`Theme Docs`,
ViewColumn.One
);
panel.webview.html = `
<h1>Themes</h1>
<h2>Using a Gatsby theme, all of your default configuration (shared functionality, data sourcing, design) is abstracted out of your site, and into an installable package.</h2>
<h3>⬅️ Install themes using the download button in the Themes Menu next to your selected theme's name</h3>
<p>
This means that the configuration and functionality isn’t directly written into your project, but rather versioned, centrally managed, and installed as a dependency. You can seamlessly update a theme, compose themes together, and even swap out one compatible theme for another.
<br><br>
Gatsby themes are plugins that include a gatsby-config.js file and add pre-configured functionality, data sourcing, and/or UI code to Gatsby sites. You can think of Gatsby themes as separate Gatsby sites that can be put together and allow you to split up a larger Gatsby project!
</p>
<h3>Gatsby themes allow Gatsby site functionality to be packaged as a standalone product for others (and yourself!) to easily reuse. Using a traditional starter, all of your default configuration lives directly in your site. Using a theme, all of your default configuration lives in an npm package.</h3>
<p>
Themes solve the problems that traditional starters experience:
<ul>
<li>Sites created using a Gatsby theme can adopt upstream changes to the theme — themes are versioned packages that can be updated like any other package.</li>
<li>You can create multiple sites that consume the same theme. To make updates across those sites, you can update the central theme and bump the version in the sites through package.json files (rather than spending the time to tediously update the functionality of each individual site).</li>
<li>Themes are composable. You could install a blog theme alongside a notes theme, alongside an e-commerce theme (and so forth)</li>
</ul>
</p>
<h2>When should I use or build a theme?</h2>
<h3>Consider using a theme if:</h3>
<ul>
<li>You already have an existing Gatsby site and can’t start from a starter</li>
<li>You want to be able to update to the latest version of a feature on your site</li>
<li>You want multiple features on your site, but there is no starter with all the features — you can use multiple themes, composed in one Gatsby site</li>
</ul>
<h3>Consider building a theme if:</h3>
<ul>
<li>You plan on re-using similar functionality across multiple Gatsby sites</li>
<li>You would like to share new Gatsby functionality to the community</li>
</ul>
<p><a href="https://www.gatsbyjs.com/docs/themes/">Read more about Gatsby themes</a></p>
`;
// close the webview when not looking at it
panel.onDidChangeViewState((e) => {
if (!e.webviewPanel.active) {
panel.dispose();
}
});
}
} | the_stack |
import * as fs from 'fs';
import * as path from 'path';
import * as cxschema from '@aws-cdk/cloud-assembly-schema';
import { App, CfnParameter, CfnResource, Construct as CfnConstruct, Lazy, Stack, TreeInspector } from '../../lib/index';
abstract class AbstractCfnResource extends CfnResource {
constructor(scope: CfnConstruct, id: string) {
super(scope, id, {
type: 'CDK::UnitTest::MyCfnResource',
});
}
public inspect(inspector: TreeInspector) {
inspector.addAttribute('aws:cdk:cloudformation:type', 'CDK::UnitTest::MyCfnResource');
inspector.addAttribute('aws:cdk:cloudformation:props', this.cfnProperties);
}
protected abstract get cfnProperties(): { [key: string]: any };
}
describe('tree metadata', () => {
test('tree metadata is generated as expected', () => {
const app = new App();
const stack = new Stack(app, 'mystack');
new CfnConstruct(stack, 'myconstruct');
const assembly = app.synth();
const treeArtifact = assembly.tree();
expect(treeArtifact).toBeDefined();
expect(readJson(assembly.directory, treeArtifact!.file)).toEqual({
version: 'tree-0.1',
tree: expect.objectContaining({
id: 'App',
path: '',
children: {
Tree: expect.objectContaining({
id: 'Tree',
path: 'Tree',
}),
mystack: expect.objectContaining({
id: 'mystack',
path: 'mystack',
children: {
myconstruct: expect.objectContaining({
id: 'myconstruct',
path: 'mystack/myconstruct',
}),
},
}),
},
}),
});
});
test('tree metadata for a Cfn resource', () => {
class MyCfnResource extends AbstractCfnResource {
protected get cfnProperties(): { [key: string]: any } {
return {
mystringpropkey: 'mystringpropval',
mylistpropkey: ['listitem1'],
mystructpropkey: {
myboolpropkey: true,
mynumpropkey: 50,
},
};
}
}
const app = new App();
const stack = new Stack(app, 'mystack');
new MyCfnResource(stack, 'mycfnresource');
const assembly = app.synth();
const treeArtifact = assembly.tree();
expect(treeArtifact).toBeDefined();
expect(readJson(assembly.directory, treeArtifact!.file)).toEqual({
version: 'tree-0.1',
tree: expect.objectContaining({
id: 'App',
path: '',
children: {
Tree: expect.objectContaining({
id: 'Tree',
path: 'Tree',
}),
mystack: expect.objectContaining({
id: 'mystack',
path: 'mystack',
children: {
mycfnresource: expect.objectContaining({
id: 'mycfnresource',
path: 'mystack/mycfnresource',
attributes: {
'aws:cdk:cloudformation:type': 'CDK::UnitTest::MyCfnResource',
'aws:cdk:cloudformation:props': {
mystringpropkey: 'mystringpropval',
mylistpropkey: ['listitem1'],
mystructpropkey: {
myboolpropkey: true,
mynumpropkey: 50,
},
},
},
}),
},
}),
},
}),
});
});
test('tree metadata has construct class & version in there', () => {
// The runtime metadata this test relies on is only available if the most
// recent compile has happened using 'jsii', as the jsii compiler injects
// this metadata.
//
// If the most recent compile was using 'tsc', the metadata will not have
// been injected, and the test will fail.
//
// People may choose to run `tsc` directly (instead of `yarn build` for
// example) to escape the additional TSC compilation time that is necessary
// to run 'eslint', or the additional time that 'jsii' needs to analyze the
// type system), this test is allowed to fail if we're not running on CI.
//
// If the compile of this library has been done using `tsc`, the runtime
// information will always find `constructs.Construct` as the construct
// identifier, since `constructs` will have had a release build done using `jsii`.
//
// If this test is running on CodeBuild, we will require that the more specific
// class names are found. If this test is NOT running on CodeBuild, we will
// allow the specific class name (for a 'jsii' build) or the generic
// 'constructs.Construct' class name (for a 'tsc' build).
const app = new App();
const stack = new Stack(app, 'mystack');
new CfnResource(stack, 'myconstruct', { type: 'Aws::Some::Resource' });
const assembly = app.synth();
const treeArtifact = assembly.tree();
expect(treeArtifact).toBeDefined();
const codeBuild = !!process.env.CODEBUILD_BUILD_ID;
expect(readJson(assembly.directory, treeArtifact!.file)).toEqual({
version: 'tree-0.1',
tree: expect.objectContaining({
children: expect.objectContaining({
mystack: expect.objectContaining({
constructInfo: {
fqn: expect.stringMatching(codeBuild ? /\bStack$/ : /\bStack$|^constructs.Construct$/),
version: expect.any(String),
},
children: {
myconstruct: expect.objectContaining({
constructInfo: {
fqn: expect.stringMatching(codeBuild ? /\bCfnResource$/ : /\bCfnResource$|^constructs.Construct$/),
version: expect.any(String),
},
}),
},
}),
}),
}),
});
});
test('token resolution & cfn parameter', () => {
const app = new App();
const stack = new Stack(app, 'mystack');
const cfnparam = new CfnParameter(stack, 'mycfnparam');
class MyCfnResource extends AbstractCfnResource {
protected get cfnProperties(): { [key: string]: any } {
return {
lazykey: Lazy.string({ produce: () => 'LazyResolved!' }),
cfnparamkey: cfnparam,
};
}
}
new MyCfnResource(stack, 'mycfnresource');
const assembly = app.synth();
const treeArtifact = assembly.tree();
expect(treeArtifact).toBeDefined();
expect(readJson(assembly.directory, treeArtifact!.file)).toEqual({
version: 'tree-0.1',
tree: expect.objectContaining({
id: 'App',
path: '',
children: {
Tree: expect.objectContaining({
id: 'Tree',
path: 'Tree',
}),
mystack: expect.objectContaining({
id: 'mystack',
path: 'mystack',
children: {
mycfnparam: expect.objectContaining({
id: 'mycfnparam',
path: 'mystack/mycfnparam',
}),
mycfnresource: expect.objectContaining({
id: 'mycfnresource',
path: 'mystack/mycfnresource',
attributes: {
'aws:cdk:cloudformation:type': 'CDK::UnitTest::MyCfnResource',
'aws:cdk:cloudformation:props': {
lazykey: 'LazyResolved!',
cfnparamkey: { Ref: 'mycfnparam' },
},
},
}),
},
}),
},
}),
});
});
test('cross-stack tokens', () => {
class MyFirstResource extends AbstractCfnResource {
public readonly lazykey: string;
constructor(scope: CfnConstruct, id: string) {
super(scope, id);
this.lazykey = Lazy.string({ produce: () => 'LazyResolved!' });
}
protected get cfnProperties(): { [key: string]: any } {
return {
lazykey: this.lazykey,
};
}
}
class MySecondResource extends AbstractCfnResource {
public readonly myprop: string;
constructor(scope: CfnConstruct, id: string, myprop: string) {
super(scope, id);
this.myprop = myprop;
}
protected get cfnProperties(): { [key: string]: any } {
return {
myprop: this.myprop,
};
}
}
const app = new App();
const firststack = new Stack(app, 'myfirststack');
const firstres = new MyFirstResource(firststack, 'myfirstresource');
const secondstack = new Stack(app, 'mysecondstack');
new MySecondResource(secondstack, 'mysecondresource', firstres.lazykey);
const assembly = app.synth();
const treeArtifact = assembly.tree();
expect(treeArtifact).toBeDefined();
expect(readJson(assembly.directory, treeArtifact!.file)).toEqual({
version: 'tree-0.1',
tree: expect.objectContaining({
id: 'App',
path: '',
children: {
Tree: expect.objectContaining({
id: 'Tree',
path: 'Tree',
}),
myfirststack: expect.objectContaining({
id: 'myfirststack',
path: 'myfirststack',
children: {
myfirstresource: expect.objectContaining({
id: 'myfirstresource',
path: 'myfirststack/myfirstresource',
attributes: {
'aws:cdk:cloudformation:type': 'CDK::UnitTest::MyCfnResource',
'aws:cdk:cloudformation:props': {
lazykey: 'LazyResolved!',
},
},
}),
},
}),
mysecondstack: expect.objectContaining({
id: 'mysecondstack',
path: 'mysecondstack',
children: {
mysecondresource: expect.objectContaining({
id: 'mysecondresource',
path: 'mysecondstack/mysecondresource',
attributes: {
'aws:cdk:cloudformation:type': 'CDK::UnitTest::MyCfnResource',
'aws:cdk:cloudformation:props': {
myprop: 'LazyResolved!',
},
},
}),
},
}),
},
}),
});
});
test('failing nodes', () => {
class MyCfnResource extends CfnResource {
public inspect(_: TreeInspector) {
throw new Error('Forcing an inspect error');
}
}
const app = new App();
const stack = new Stack(app, 'mystack');
new MyCfnResource(stack, 'mycfnresource', {
type: 'CDK::UnitTest::MyCfnResource',
});
const assembly = app.synth();
const treeArtifact = assembly.tree();
expect(treeArtifact).toBeDefined();
const treenode = app.node.findChild('Tree');
const warn = treenode.node.metadataEntry.find((md) => {
return md.type === cxschema.ArtifactMetadataEntryType.WARN
&& /Forcing an inspect error/.test(md.data as string)
&& /mycfnresource/.test(md.data as string);
});
expect(warn).toBeDefined();
// assert that the rest of the construct tree is rendered
expect(readJson(assembly.directory, treeArtifact!.file)).toEqual({
version: 'tree-0.1',
tree: expect.objectContaining({
id: 'App',
path: '',
children: {
Tree: expect.objectContaining({
id: 'Tree',
path: 'Tree',
}),
mystack: expect.objectContaining({
id: 'mystack',
path: 'mystack',
}),
},
}),
});
});
});
function readJson(outdir: string, file: string) {
return JSON.parse(fs.readFileSync(path.join(outdir, file), 'utf-8'));
} | the_stack |
// IMPORTANT
// This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
// In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
// Generated from: https://safebrowsing.googleapis.com/$discovery/rest?version=v4
/// <reference types="gapi.client" />
declare namespace gapi.client {
/** Load Google Safe Browsing API v4 */
function load(name: "safebrowsing", version: "v4"): PromiseLike<void>;
function load(name: "safebrowsing", version: "v4", callback: () => any): void;
const encodedFullHashes: safebrowsing.EncodedFullHashesResource;
const encodedUpdates: safebrowsing.EncodedUpdatesResource;
const fullHashes: safebrowsing.FullHashesResource;
const threatListUpdates: safebrowsing.ThreatListUpdatesResource;
const threatLists: safebrowsing.ThreatListsResource;
const threatMatches: safebrowsing.ThreatMatchesResource;
namespace safebrowsing {
interface Checksum {
/**
* The SHA256 hash of the client state; that is, of the sorted list of all
* hashes present in the database.
*/
sha256?: string;
}
interface ClientInfo {
/**
* A client ID that (hopefully) uniquely identifies the client implementation
* of the Safe Browsing API.
*/
clientId?: string;
/** The version of the client implementation. */
clientVersion?: string;
}
interface Constraints {
/**
* Sets the maximum number of entries that the client is willing to have
* in the local database. This should be a power of 2 between 2**10 and
* 2**20. If zero, no database size limit is set.
*/
maxDatabaseEntries?: number;
/**
* The maximum size in number of entries. The update will not contain more
* entries than this value. This should be a power of 2 between 2**10 and
* 2**20. If zero, no update size limit is set.
*/
maxUpdateEntries?: number;
/**
* Requests the list for a specific geographic location. If not set the
* server may pick that value based on the user's IP address. Expects ISO
* 3166-1 alpha-2 format.
*/
region?: string;
/** The compression types supported by the client. */
supportedCompressions?: string[];
}
interface FetchThreatListUpdatesRequest {
/** The client metadata. */
client?: ClientInfo;
/** The requested threat list updates. */
listUpdateRequests?: ListUpdateRequest[];
}
interface FetchThreatListUpdatesResponse {
/** The list updates requested by the clients. */
listUpdateResponses?: ListUpdateResponse[];
/**
* The minimum duration the client must wait before issuing any update
* request. If this field is not set clients may update as soon as they want.
*/
minimumWaitDuration?: string;
}
interface FindFullHashesRequest {
/**
* Client metadata associated with callers of higher-level APIs built on top
* of the client's implementation.
*/
apiClient?: ClientInfo;
/** The client metadata. */
client?: ClientInfo;
/** The current client states for each of the client's local threat lists. */
clientStates?: string[];
/** The lists and hashes to be checked. */
threatInfo?: ThreatInfo;
}
interface FindFullHashesResponse {
/** The full hashes that matched the requested prefixes. */
matches?: ThreatMatch[];
/**
* The minimum duration the client must wait before issuing any find hashes
* request. If this field is not set, clients can issue a request as soon as
* they want.
*/
minimumWaitDuration?: string;
/**
* For requested entities that did not match the threat list, how long to
* cache the response.
*/
negativeCacheDuration?: string;
}
interface FindThreatMatchesRequest {
/** The client metadata. */
client?: ClientInfo;
/** The lists and entries to be checked for matches. */
threatInfo?: ThreatInfo;
}
interface FindThreatMatchesResponse {
/** The threat list matches. */
matches?: ThreatMatch[];
}
interface ListThreatListsResponse {
/** The lists available for download by the client. */
threatLists?: ThreatListDescriptor[];
}
interface ListUpdateRequest {
/** The constraints associated with this request. */
constraints?: Constraints;
/** The type of platform at risk by entries present in the list. */
platformType?: string;
/**
* The current state of the client for the requested list (the encrypted
* client state that was received from the last successful list update).
*/
state?: string;
/** The types of entries present in the list. */
threatEntryType?: string;
/** The type of threat posed by entries present in the list. */
threatType?: string;
}
interface ListUpdateResponse {
/**
* A set of entries to add to a local threat type's list. Repeated to allow
* for a combination of compressed and raw data to be sent in a single
* response.
*/
additions?: ThreatEntrySet[];
/**
* The expected SHA256 hash of the client state; that is, of the sorted list
* of all hashes present in the database after applying the provided update.
* If the client state doesn't match the expected state, the client must
* disregard this update and retry later.
*/
checksum?: Checksum;
/** The new client state, in encrypted format. Opaque to clients. */
newClientState?: string;
/** The platform type for which data is returned. */
platformType?: string;
/**
* A set of entries to remove from a local threat type's list. In practice,
* this field is empty or contains exactly one ThreatEntrySet.
*/
removals?: ThreatEntrySet[];
/**
* The type of response. This may indicate that an action is required by the
* client when the response is received.
*/
responseType?: string;
/** The format of the threats. */
threatEntryType?: string;
/** The threat type for which data is returned. */
threatType?: string;
}
interface MetadataEntry {
/** The metadata entry key. For JSON requests, the key is base64-encoded. */
key?: string;
/** The metadata entry value. For JSON requests, the value is base64-encoded. */
value?: string;
}
interface RawHashes {
/**
* The number of bytes for each prefix encoded below. This field can be
* anywhere from 4 (shortest prefix) to 32 (full SHA256 hash).
*/
prefixSize?: number;
/**
* The hashes, in binary format, concatenated into one long string. Hashes are
* sorted in lexicographic order. For JSON API users, hashes are
* base64-encoded.
*/
rawHashes?: string;
}
interface RawIndices {
/** The indices to remove from a lexicographically-sorted local list. */
indices?: number[];
}
interface RiceDeltaEncoding {
/** The encoded deltas that are encoded using the Golomb-Rice coder. */
encodedData?: string;
/**
* The offset of the first entry in the encoded data, or, if only a single
* integer was encoded, that single integer's value.
*/
firstValue?: string;
/**
* The number of entries that are delta encoded in the encoded data. If only a
* single integer was encoded, this will be zero and the single value will be
* stored in `first_value`.
*/
numEntries?: number;
/**
* The Golomb-Rice parameter, which is a number between 2 and 28. This field
* is missing (that is, zero) if `num_entries` is zero.
*/
riceParameter?: number;
}
interface ThreatEntry {
/**
* The digest of an executable in SHA256 format. The API supports both
* binary and hex digests. For JSON requests, digests are base64-encoded.
*/
digest?: string;
/**
* A hash prefix, consisting of the most significant 4-32 bytes of a SHA256
* hash. This field is in binary format. For JSON requests, hashes are
* base64-encoded.
*/
hash?: string;
/** A URL. */
url?: string;
}
interface ThreatEntryMetadata {
/** The metadata entries. */
entries?: MetadataEntry[];
}
interface ThreatEntrySet {
/** The compression type for the entries in this set. */
compressionType?: string;
/** The raw SHA256-formatted entries. */
rawHashes?: RawHashes;
/** The raw removal indices for a local list. */
rawIndices?: RawIndices;
/**
* The encoded 4-byte prefixes of SHA256-formatted entries, using a
* Golomb-Rice encoding. The hashes are converted to uint32, sorted in
* ascending order, then delta encoded and stored as encoded_data.
*/
riceHashes?: RiceDeltaEncoding;
/**
* The encoded local, lexicographically-sorted list indices, using a
* Golomb-Rice encoding. Used for sending compressed removal indices. The
* removal indices (uint32) are sorted in ascending order, then delta encoded
* and stored as encoded_data.
*/
riceIndices?: RiceDeltaEncoding;
}
interface ThreatInfo {
/** The platform types to be checked. */
platformTypes?: string[];
/** The threat entries to be checked. */
threatEntries?: ThreatEntry[];
/** The entry types to be checked. */
threatEntryTypes?: string[];
/** The threat types to be checked. */
threatTypes?: string[];
}
interface ThreatListDescriptor {
/** The platform type targeted by the list's entries. */
platformType?: string;
/** The entry types contained in the list. */
threatEntryType?: string;
/** The threat type posed by the list's entries. */
threatType?: string;
}
interface ThreatMatch {
/**
* The cache lifetime for the returned match. Clients must not cache this
* response for more than this duration to avoid false positives.
*/
cacheDuration?: string;
/** The platform type matching this threat. */
platformType?: string;
/** The threat matching this threat. */
threat?: ThreatEntry;
/** Optional metadata associated with this threat. */
threatEntryMetadata?: ThreatEntryMetadata;
/** The threat entry type matching this threat. */
threatEntryType?: string;
/** The threat type matching this threat. */
threatType?: string;
}
interface EncodedFullHashesResource {
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/**
* A client ID that (hopefully) uniquely identifies the client implementation
* of the Safe Browsing API.
*/
clientId?: string;
/** The version of the client implementation. */
clientVersion?: string;
/** A serialized FindFullHashesRequest proto. */
encodedRequest: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<FindFullHashesResponse>;
}
interface EncodedUpdatesResource {
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/**
* A client ID that uniquely identifies the client implementation of the Safe
* Browsing API.
*/
clientId?: string;
/** The version of the client implementation. */
clientVersion?: string;
/** A serialized FetchThreatListUpdatesRequest proto. */
encodedRequest: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<FetchThreatListUpdatesResponse>;
}
interface FullHashesResource {
/** Finds the full hashes that match the requested hash prefixes. */
find(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<FindFullHashesResponse>;
}
interface ThreatListUpdatesResource {
/**
* Fetches the most recent threat list updates. A client can request updates
* for multiple lists at once.
*/
fetch(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<FetchThreatListUpdatesResponse>;
}
interface ThreatListsResource {
/** Lists the Safe Browsing threat lists available for download. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListThreatListsResponse>;
}
interface ThreatMatchesResource {
/** Finds the threat entries that match the Safe Browsing lists. */
find(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<FindThreatMatchesResponse>;
}
}
} | the_stack |
import { Stack } from "@aws-cdk/core";
import * as lambda from "@aws-cdk/aws-lambda";
import * as defaults from '@aws-solutions-constructs/core';
import * as stepfunctions from '@aws-cdk/aws-stepfunctions';
import * as ec2 from "@aws-cdk/aws-ec2";
import { LambdaToStepfunctions } from '../lib';
import '@aws-cdk/assert/jest';
// --------------------------------------------------------------
// Test deployment with new Lambda function
// --------------------------------------------------------------
test('Test deployment with new Lambda function', () => {
// Stack
const stack = new Stack();
// Helper declaration
const startState = new stepfunctions.Pass(stack, 'StartState');
new LambdaToStepfunctions(stack, 'lambda-to-step-function-stack', {
lambdaFunctionProps: {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: lambda.Code.fromAsset(`${__dirname}/lambda`),
environment: {
LAMBDA_NAME: 'deploy-function'
}
},
stateMachineProps: {
definition: startState
}
});
expect(stack).toHaveResourceLike("AWS::Lambda::Function", {
Environment: {
Variables: {
LAMBDA_NAME: 'deploy-function',
STATE_MACHINE_ARN: {
Ref: 'lambdatostepfunctionstackStateMachine98EE8EFB'
}
}
}
});
});
// --------------------------------------------------------------
// Test deployment with existing Lambda function
// --------------------------------------------------------------
test('Test deployment with existing Lambda function', () => {
// Stack
const stack = new Stack();
// Helper declaration
const startState = new stepfunctions.Pass(stack, 'StartState');
const lambdaFunctionProps = {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: lambda.Code.fromAsset(`${__dirname}/lambda`),
environment: {
LAMBDA_NAME: 'existing-function'
}
};
const fn = defaults.deployLambdaFunction(stack, lambdaFunctionProps);
// Add the pattern
new LambdaToStepfunctions(stack, 'test-lambda-step-function-construct', {
existingLambdaObj: fn,
stateMachineProps: {
definition: startState
}
});
expect(stack).toHaveResourceLike("AWS::Lambda::Function", {
Environment: {
Variables: {
LAMBDA_NAME: 'existing-function'
}
}
});
});
// --------------------------------------------------------------
// Test invocation permissions
// --------------------------------------------------------------
test('Test invocation permissions', () => {
// Stack
const stack = new Stack();
// Helper declaration
const startState = new stepfunctions.Pass(stack, 'StartState');
const lambdaFunctionProps = {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: lambda.Code.fromAsset(`${__dirname}/lambda`),
environment: {
LAMBDA_NAME: 'existing-function'
}
};
const fn = defaults.deployLambdaFunction(stack, lambdaFunctionProps);
// Add the pattern
new LambdaToStepfunctions(stack, 'test-lambda-step-function-stack', {
existingLambdaObj: fn,
stateMachineProps: {
definition: startState
}
});
// Assertion 1
expect(stack).toHaveResourceLike("AWS::IAM::Policy", {
PolicyDocument: {
Statement: [
{
Action: [
"xray:PutTraceSegments",
"xray:PutTelemetryRecords"
],
Effect: "Allow",
Resource: "*"
},
{
Action: "states:StartExecution",
Effect: "Allow",
Resource: {
Ref: "testlambdastepfunctionstackStateMachine373C0BB9"
}
}
],
Version: "2012-10-17"
}
});
});
// --------------------------------------------------------------
// Test the properties
// --------------------------------------------------------------
test('Test the properties', () => {
// Stack
const stack = new Stack();
// Helper declaration
const startState = new stepfunctions.Pass(stack, 'StartState');
const pattern = new LambdaToStepfunctions(stack, 'lambda-to-step-function-stack', {
lambdaFunctionProps: {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: lambda.Code.fromAsset(`${__dirname}/lambda`),
environment: {
LAMBDA_NAME: 'existing-function'
}
},
stateMachineProps: {
definition: startState
}
});
// Assertion 1
const func = pattern.lambdaFunction;
expect(func).toBeDefined();
// Assertion 2
const stateMachine = pattern.stateMachine;
expect(stateMachine).toBeDefined();
// Assertion 3
const cwAlarm = pattern.cloudwatchAlarms;
expect(cwAlarm).toBeDefined();
expect(pattern.stateMachineLogGroup).toBeDefined();
});
// --------------------------------------------------------------
// Test the properties
// --------------------------------------------------------------
test('Test the properties with no CW Alarms', () => {
// Stack
const stack = new Stack();
// Helper declaration
const startState = new stepfunctions.Pass(stack, 'StartState');
const pattern = new LambdaToStepfunctions(stack, 'lambda-to-step-function-stack', {
lambdaFunctionProps: {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: lambda.Code.fromAsset(`${__dirname}/lambda`),
environment: {
LAMBDA_NAME: 'existing-function'
}
},
stateMachineProps: {
definition: startState
},
createCloudWatchAlarms: false
});
// Assertion 1
expect(pattern.lambdaFunction).toBeDefined();
// Assertion 2
expect(pattern.stateMachine).toBeDefined();
// Assertion 3
expect(pattern.cloudwatchAlarms).toBeUndefined();
expect(pattern.stateMachineLogGroup).toBeDefined();
});
// --------------------------------------------------------------
// Test lambda function custom environment variable
// --------------------------------------------------------------
test('Test lambda function custom environment variable', () => {
// Stack
const stack = new Stack();
// Helper declaration
const startState = new stepfunctions.Pass(stack, 'StartState');
new LambdaToStepfunctions(stack, 'lambda-to-step-function-stack', {
lambdaFunctionProps: {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: lambda.Code.fromAsset(`${__dirname}/lambda`)
},
stateMachineProps: {
definition: startState
},
stateMachineEnvironmentVariableName: 'CUSTOM_STATE_MAHINCE'
});
// Assertion
expect(stack).toHaveResourceLike('AWS::Lambda::Function', {
Handler: 'index.handler',
Runtime: 'nodejs14.x',
Environment: {
Variables: {
AWS_NODEJS_CONNECTION_REUSE_ENABLED: '1',
CUSTOM_STATE_MAHINCE: {
Ref: 'lambdatostepfunctionstackStateMachine98EE8EFB'
}
}
}
});
});
// --------------------------------------------------------------
// Test minimal deployment that deploys a VPC without vpcProps
// --------------------------------------------------------------
test("Test minimal deployment that deploys a VPC without vpcProps", () => {
// Stack
const stack = new Stack();
const startState = new stepfunctions.Pass(stack, 'StartState');
// Helper declaration
new LambdaToStepfunctions(stack, "lambda-to-stepfunctions-stack", {
lambdaFunctionProps: {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: lambda.Code.fromAsset(`${__dirname}/lambda`)
},
stateMachineProps: {
definition: startState
},
deployVpc: true
});
expect(stack).toHaveResource("AWS::Lambda::Function", {
VpcConfig: {
SecurityGroupIds: [
{
"Fn::GetAtt": [
"lambdatostepfunctionsstackReplaceDefaultSecurityGroupsecuritygroup0F25B19B",
"GroupId",
],
},
],
SubnetIds: [
{
Ref: "VpcisolatedSubnet1SubnetE62B1B9B",
},
{
Ref: "VpcisolatedSubnet2Subnet39217055",
},
],
},
});
expect(stack).toHaveResource("AWS::EC2::VPC", {
EnableDnsHostnames: true,
EnableDnsSupport: true,
});
expect(stack).toHaveResource("AWS::EC2::VPCEndpoint", {
VpcEndpointType: "Interface",
});
expect(stack).toCountResources("AWS::EC2::Subnet", 2);
expect(stack).toCountResources("AWS::EC2::InternetGateway", 0);
});
// --------------------------------------------------------------
// Test minimal deployment that deploys a VPC w/vpcProps
// --------------------------------------------------------------
test("Test minimal deployment that deploys a VPC w/vpcProps", () => {
// Stack
const stack = new Stack();
const startState = new stepfunctions.Pass(stack, 'StartState');
// Helper declaration
new LambdaToStepfunctions(stack, "lambda-to-stepfunctions-stack", {
lambdaFunctionProps: {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: lambda.Code.fromAsset(`${__dirname}/lambda`)
},
stateMachineProps: {
definition: startState
},
vpcProps: {
enableDnsHostnames: false,
enableDnsSupport: false,
cidr: "192.68.0.0/16",
},
deployVpc: true,
});
expect(stack).toHaveResource("AWS::Lambda::Function", {
VpcConfig: {
SecurityGroupIds: [
{
"Fn::GetAtt": [
"lambdatostepfunctionsstackReplaceDefaultSecurityGroupsecuritygroup0F25B19B",
"GroupId",
],
},
],
SubnetIds: [
{
Ref: "VpcisolatedSubnet1SubnetE62B1B9B",
},
{
Ref: "VpcisolatedSubnet2Subnet39217055",
},
],
},
});
expect(stack).toHaveResource("AWS::EC2::VPC", {
CidrBlock: "192.68.0.0/16",
EnableDnsHostnames: true,
EnableDnsSupport: true,
});
expect(stack).toHaveResource("AWS::EC2::VPCEndpoint", {
VpcEndpointType: "Interface",
});
expect(stack).toCountResources("AWS::EC2::Subnet", 2);
expect(stack).toCountResources("AWS::EC2::InternetGateway", 0);
});
// --------------------------------------------------------------
// Test minimal deployment with an existing VPC
// --------------------------------------------------------------
test("Test minimal deployment with an existing VPC", () => {
// Stack
const stack = new Stack();
const startState = new stepfunctions.Pass(stack, 'StartState');
const testVpc = new ec2.Vpc(stack, "test-vpc", {});
// Helper declaration
new LambdaToStepfunctions(stack, "lambda-to-stepfunctions-stack", {
lambdaFunctionProps: {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: lambda.Code.fromAsset(`${__dirname}/lambda`)
},
stateMachineProps: {
definition: startState
},
existingVpc: testVpc,
});
expect(stack).toHaveResource("AWS::Lambda::Function", {
VpcConfig: {
SecurityGroupIds: [
{
"Fn::GetAtt": [
"lambdatostepfunctionsstackReplaceDefaultSecurityGroupsecuritygroup0F25B19B",
"GroupId",
],
},
],
SubnetIds: [
{
Ref: "testvpcPrivateSubnet1Subnet865FB50A",
},
{
Ref: "testvpcPrivateSubnet2Subnet23D3396F",
},
],
},
});
expect(stack).toHaveResource("AWS::EC2::VPCEndpoint", {
VpcEndpointType: "Interface",
});
});
// --------------------------------------------------------------
// Test minimal deployment with an existing VPC and existing Lambda function not in a VPC
//
// buildLambdaFunction should throw an error if the Lambda function is not
// attached to a VPC
// --------------------------------------------------------------
test("Test minimal deployment with an existing VPC and existing Lambda function not in a VPC", () => {
// Stack
const stack = new Stack();
const startState = new stepfunctions.Pass(stack, 'StartState');
const testLambdaFunction = new lambda.Function(stack, 'test-lamba', {
runtime: lambda.Runtime.NODEJS_14_X,
handler: "index.handler",
code: lambda.Code.fromAsset(`${__dirname}/lambda`),
});
const testVpc = new ec2.Vpc(stack, "test-vpc", {});
// Helper declaration
const app = () => {
// Helper declaration
new LambdaToStepfunctions(stack, "lambda-to-stepfunctions-stack", {
existingLambdaObj: testLambdaFunction,
stateMachineProps: {
definition: startState
},
existingVpc: testVpc,
});
};
// Assertion
expect(app).toThrowError();
});
// --------------------------------------------------------------
// Test bad call with existingVpc and deployVpc
// --------------------------------------------------------------
test("Test bad call with existingVpc and deployVpc", () => {
// Stack
const stack = new Stack();
const startState = new stepfunctions.Pass(stack, 'StartState');
const testVpc = new ec2.Vpc(stack, "test-vpc", {});
const app = () => {
// Helper declaration
new LambdaToStepfunctions(stack, "lambda-to-stepfunctions-stack", {
lambdaFunctionProps: {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: lambda.Code.fromAsset(`${__dirname}/lambda`)
},
stateMachineProps: {
definition: startState
},
existingVpc: testVpc,
deployVpc: true,
});
};
// Assertion
expect(app).toThrowError();
}); | the_stack |
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { createHash, randomBytes, BinaryLike } from 'crypto'
import express from 'express'
import fs from 'fs'
import getPort from 'get-port'
import open from 'open'
import path from 'path'
import qs from 'qs'
import { SmartThingsURLProvider, defaultSmartThingsURLProvider, Authenticator } from '@smartthings/core-sdk'
import { logManager } from './logger'
export interface ClientIdProvider extends SmartThingsURLProvider {
clientId: string
baseOAuthInURL: string
oauthAuthTokenRefreshURL: string
}
export const defaultClientIdProvider: ClientIdProvider = {
...defaultSmartThingsURLProvider,
baseOAuthInURL: 'https://oauthin-regional.api.smartthings.com/oauth',
oauthAuthTokenRefreshURL: 'https://auth-global.api.smartthings.com/oauth/token',
clientId: 'd18cf96e-c626-4433-bf51-ddbb10c5d1ed',
}
// All the scopes the clientId we are using is configured to use.
const scopes = ['controller%3AstCli']
const postConfig = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
}
interface AuthenticationInfo {
accessToken: string
refreshToken: string
expires: Date
// scope is a space-separated list of scopes
// In the future, we could consider making the type `string | string[]`
scope: string
installedAppId: string
deviceId: string
}
function credentialsFile(): string {
if (!('_credentialsFile' in (global as { _credentialsFile?: string }))) {
throw new Error('LoginAuthenticator credentials file not set.')
}
return (global as unknown as { _credentialsFile: string })._credentialsFile
}
interface CredentialsFileData {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[profileName: string]: any
}
/**
* Convert to string and scrub sensitive values
* Meant to be used before logging
*/
function scrubAuthInfo(authInfo?: AuthenticationInfo): string {
const message = JSON.stringify(authInfo)
const tokenRegex = /"([\w]*token":"[0-9a-f]{8}).+?"/ig
return message.replace(tokenRegex, '"$1-xxxx-xxxx-xxxx-xxxxxxxxxxxx"')
}
export class LoginAuthenticator implements Authenticator {
public static init(credentialsFile: string): void {
(global as { _credentialsFile?: string })._credentialsFile = credentialsFile
const cliDir = path.dirname(credentialsFile)
fs.mkdirSync(cliDir, { recursive: true })
}
private clientId: string
private authenticationInfo?: AuthenticationInfo
private logger = logManager.getLogger('login-authenticator')
constructor(private profileName: string, private clientIdProvider: ClientIdProvider) {
this.logger.trace('constructing a LoginAuthenticator')
this.clientId = clientIdProvider.clientId
// we could consider doing this lazily at some point
const credentialsFileData = this.readCredentialsFile()
if (profileName in credentialsFileData) {
const authInfo = credentialsFileData[profileName]
this.authenticationInfo = {
...authInfo,
expires: new Date(authInfo.expires),
}
this.logger.trace(`authentication info from file = ${scrubAuthInfo(this.authenticationInfo)}`)
}
}
private base64URLEncode(data: Buffer): string {
return data.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '')
}
private sha256(data: BinaryLike): Buffer {
return createHash('sha256').update(data).digest()
}
private delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms))
}
private readCredentialsFile(): CredentialsFileData {
let fileData = '{}'
try {
fileData = fs.readFileSync(credentialsFile()).toString()
} catch (err) {
if (err.code !== 'ENOENT') { throw err }
}
return JSON.parse(fileData)
}
private writeCredentialsFile(credentialsFileData: CredentialsFileData): void {
fs.writeFileSync(credentialsFile(), JSON.stringify(credentialsFileData, null, 4))
fs.chmod(credentialsFile(), 0o600, err => {
if (err) {
this.logger.error('failed to set permissions on credentials file', err)
}
})
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private updateTokenFromResponse(response: AxiosResponse<any>): void {
const authenticationInfo = {
accessToken: response.data.access_token,
refreshToken: response.data.refresh_token,
expires: new Date(Date.now() + response.data.expires_in * 1000),
scope: response.data.scope,
installedAppId: response.data.installed_app_id,
deviceId: response.data.device_id,
}
const credentialsFileData = this.readCredentialsFile()
credentialsFileData[this.profileName] = authenticationInfo
this.writeCredentialsFile(credentialsFileData)
this.authenticationInfo = authenticationInfo
}
async login(): Promise<void> {
const verifier = this.base64URLEncode(randomBytes(32))
const app = express()
const port = await getPort({ port: [61973, 61974, 61975] })
const baseOAuthInURL = this.clientIdProvider.baseOAuthInURL
const codeChallenge = this.base64URLEncode(this.sha256(verifier))
const finishURL = `http://localhost:${port}/finish`
let loginFailed = false
app.get('/start', (req, res) => {
const redirectTo = `${baseOAuthInURL}/authorize?scope=${scopes.join('+')}&` +
`response_type=code&client_id=${this.clientId}&` +
`code_challenge=${codeChallenge}&code_challenge_method=S256&` +
`redirect_uri=${encodeURIComponent(finishURL)}&` +
'client_type=USER_LEVEL'
this.logger.trace(`redirecting to: ${redirectTo}`)
res.redirect(redirectTo)
})
app.get('/finish', (req, res) => {
if ('error' in req.query) {
this.logger.error(`received "${req.query.error}" error when trying to authenticate`)
if ('error_description' in req.query) {
this.logger.error(` ${req.query.error_description}`)
}
loginFailed = true
res.send('<html><body><h1>Failure trying to authenticate.</h1></body></html>')
return
}
const requestBody = {
'grant_type': 'authorization_code',
'client_id': this.clientId,
'code_verifier': verifier,
'code': req.query.code,
'redirect_uri': finishURL,
}
this.logger.trace(`making axios request to ${baseOAuthInURL}/token with:`)
this.logger.trace(` body: ${qs.stringify(requestBody)}`)
this.logger.trace(` config: ${JSON.stringify(postConfig)}`)
this.logger.trace(`code = ${req.query.code}`)
// I used this for debugging. Axios does not include the body of the response in any way I could find.
// this.logger.trace(`\n\nRun:\ncurl -i --request POST --url '${baseOAuthInURL}/token' --header 'content-type: application/x-www-form-urlencoded' ` +
// `--data grant_type=authorization_code --data 'client_id=${this.clientId}' --data code_verifier=${verifier} --data code=${req.query.code} ` +
// `--data 'redirect_uri=${finishURL}' --header 'X-ST-CORRELATION: ross-pkce-attempt'\n\n`)
axios.post(`${baseOAuthInURL}/token`, qs.stringify(requestBody), postConfig)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.then((response: AxiosResponse<any>) => {
this.updateTokenFromResponse(response)
res.send('<html><body><h1>You can close the window.</h1></body></html>')
})
.catch(err => {
this.logger.trace(`got error ${err.name}/${err}}/${err.message} trying to get final token`)
this.logger.trace(`err = ${JSON.stringify(err, null, 4)}`)
loginFailed = true
res.send('<html><body><h1>Failure trying retrieve token.</h1></body></html>')
})
})
const server = app.listen(port, async () => {
this.logger.trace(`listening on port ${port}`)
await open(`http://localhost:${port}/start`)
})
const startTime = Date.now()
const maxDelay = 10 * 60 * 1000 // wait up to ten minutes for login
this.authenticationInfo = undefined
// eslint-disable-next-line no-async-promise-executor
return new Promise(async (resolve, reject) => {
while (!loginFailed && !this.authenticationInfo && Date.now() < startTime + maxDelay) {
process.stderr.write('.')
await this.delay(1000)
}
server.close(err => {
if (err) {
this.logger.error(`error closing express server: ${err}`)
}
if (this.authenticationInfo) {
this.logger.trace(`got authentication info: ${scrubAuthInfo(this.authenticationInfo)}`)
resolve()
} else {
this.logger.trace('unable to get authentication info')
reject('unable to get authentication info')
}
})
})
}
async logout(): Promise<void> {
const credentialsFileData = this.readCredentialsFile()
delete credentialsFileData[this.profileName]
this.writeCredentialsFile(credentialsFileData)
}
private async refreshToken(): Promise<void> {
this.logger.trace('refreshing token')
const oauthAuthTokenRefreshURL = this.clientIdProvider.oauthAuthTokenRefreshURL
const requestBody = {
'grant_type': 'refresh_token',
'client_id': this.clientId,
'refresh_token': this.authenticationInfo?.refreshToken,
}
const postConfig = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
}
this.logger.trace(`making axios request to ${oauthAuthTokenRefreshURL} with:`)
this.logger.trace(` body: ${qs.stringify(requestBody)}`)
this.logger.trace(` config: ${JSON.stringify(postConfig)}`)
await axios.post(oauthAuthTokenRefreshURL, qs.stringify(requestBody), postConfig)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.then((response: AxiosResponse<any>) => {
this.updateTokenFromResponse(response)
})
.catch(err => {
this.logger.trace(`got error ${err.name}/${err}}/${err.message} trying to get refresh token`)
this.logger.trace(`err = ${JSON.stringify(err, null, 4)}`)
})
}
async authenticate(requestConfig: AxiosRequestConfig): Promise<AxiosRequestConfig> {
const token = await this.authenticateGeneric()
return {
...requestConfig,
headers: {
...requestConfig.headers,
Authorization: `Bearer ${token}`,
},
}
}
async authenticateGeneric(): Promise<string> {
this.logger.trace('authentication - enter')
// refresh if we have less than an hour left on the auth token
if (this.authenticationInfo && this.authenticationInfo.expires.getTime() < Date.now() + 60 * 60 * 1000) {
await this.refreshToken()
}
// log in if we don't have authentication info or the refresh failed
if (!this.authenticationInfo || this.authenticationInfo.expires.getTime() < Date.now() + 59 * 60 * 1000) {
await this.login()
}
if (this.authenticationInfo) {
return this.authenticationInfo.accessToken
}
throw new Error('unable to obtain user credentials')
}
} | the_stack |
import * as restm from 'typed-rest-client/RestClient';
import * as httpm from 'typed-rest-client/HttpClient';
import vsom = require('./VsoClient');
import basem = require('./ClientApiBases');
import serm = require('./Serialization');
import VsoBaseInterfaces = require('./interfaces/common/VsoBaseInterfaces');
import SecurityRolesInterfaces = require("./interfaces/SecurityRolesInterfaces");
export interface ISecurityRolesApi extends basem.ClientApiBase {
getRoleAssignments(scopeId: string, resourceId: string): Promise<SecurityRolesInterfaces.RoleAssignment[]>;
removeRoleAssignment(scopeId: string, resourceId: string, identityId: string): Promise<void>;
removeRoleAssignments(identityIds: string[], scopeId: string, resourceId: string): Promise<void>;
setRoleAssignment(roleAssignment: SecurityRolesInterfaces.UserRoleAssignmentRef, scopeId: string, resourceId: string, identityId: string): Promise<SecurityRolesInterfaces.RoleAssignment>;
setRoleAssignments(roleAssignments: SecurityRolesInterfaces.UserRoleAssignmentRef[], scopeId: string, resourceId: string): Promise<SecurityRolesInterfaces.RoleAssignment[]>;
getRoleDefinitions(scopeId: string): Promise<SecurityRolesInterfaces.SecurityRole[]>;
}
export class SecurityRolesApi extends basem.ClientApiBase implements ISecurityRolesApi {
constructor(baseUrl: string, handlers: VsoBaseInterfaces.IRequestHandler[], options?: VsoBaseInterfaces.IRequestOptions) {
super(baseUrl, handlers, 'node-SecurityRoles-api', options);
}
/**
* @param {string} scopeId
* @param {string} resourceId
*/
public async getRoleAssignments(
scopeId: string,
resourceId: string
): Promise<SecurityRolesInterfaces.RoleAssignment[]> {
return new Promise<SecurityRolesInterfaces.RoleAssignment[]>(async (resolve, reject) => {
let routeValues: any = {
scopeId: scopeId,
resourceId: resourceId
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"3.2-preview.1",
"securityroles",
"9461c234-c84c-4ed2-b918-2f0f92ad0a35",
routeValues);
let url: string = verData.requestUrl;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<SecurityRolesInterfaces.RoleAssignment[]>;
res = await this.rest.get<SecurityRolesInterfaces.RoleAssignment[]>(url, options);
let ret = this.formatResponse(res.result,
SecurityRolesInterfaces.TypeInfo.RoleAssignment,
true);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* @param {string} scopeId
* @param {string} resourceId
* @param {string} identityId
*/
public async removeRoleAssignment(
scopeId: string,
resourceId: string,
identityId: string
): Promise<void> {
return new Promise<void>(async (resolve, reject) => {
let routeValues: any = {
scopeId: scopeId,
resourceId: resourceId,
identityId: identityId
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"3.2-preview.1",
"securityroles",
"9461c234-c84c-4ed2-b918-2f0f92ad0a35",
routeValues);
let url: string = verData.requestUrl;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<void>;
res = await this.rest.del<void>(url, options);
let ret = this.formatResponse(res.result,
null,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* @param {string[]} identityIds
* @param {string} scopeId
* @param {string} resourceId
*/
public async removeRoleAssignments(
identityIds: string[],
scopeId: string,
resourceId: string
): Promise<void> {
return new Promise<void>(async (resolve, reject) => {
let routeValues: any = {
scopeId: scopeId,
resourceId: resourceId
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"3.2-preview.1",
"securityroles",
"9461c234-c84c-4ed2-b918-2f0f92ad0a35",
routeValues);
let url: string = verData.requestUrl;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<void>;
res = await this.rest.update<void>(url, identityIds, options);
let ret = this.formatResponse(res.result,
null,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* @param {SecurityRolesInterfaces.UserRoleAssignmentRef} roleAssignment
* @param {string} scopeId
* @param {string} resourceId
* @param {string} identityId
*/
public async setRoleAssignment(
roleAssignment: SecurityRolesInterfaces.UserRoleAssignmentRef,
scopeId: string,
resourceId: string,
identityId: string
): Promise<SecurityRolesInterfaces.RoleAssignment> {
return new Promise<SecurityRolesInterfaces.RoleAssignment>(async (resolve, reject) => {
let routeValues: any = {
scopeId: scopeId,
resourceId: resourceId,
identityId: identityId
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"3.2-preview.1",
"securityroles",
"9461c234-c84c-4ed2-b918-2f0f92ad0a35",
routeValues);
let url: string = verData.requestUrl;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<SecurityRolesInterfaces.RoleAssignment>;
res = await this.rest.replace<SecurityRolesInterfaces.RoleAssignment>(url, roleAssignment, options);
let ret = this.formatResponse(res.result,
SecurityRolesInterfaces.TypeInfo.RoleAssignment,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* @param {SecurityRolesInterfaces.UserRoleAssignmentRef[]} roleAssignments
* @param {string} scopeId
* @param {string} resourceId
*/
public async setRoleAssignments(
roleAssignments: SecurityRolesInterfaces.UserRoleAssignmentRef[],
scopeId: string,
resourceId: string
): Promise<SecurityRolesInterfaces.RoleAssignment[]> {
return new Promise<SecurityRolesInterfaces.RoleAssignment[]>(async (resolve, reject) => {
let routeValues: any = {
scopeId: scopeId,
resourceId: resourceId
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"3.2-preview.1",
"securityroles",
"9461c234-c84c-4ed2-b918-2f0f92ad0a35",
routeValues);
let url: string = verData.requestUrl;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<SecurityRolesInterfaces.RoleAssignment[]>;
res = await this.rest.replace<SecurityRolesInterfaces.RoleAssignment[]>(url, roleAssignments, options);
let ret = this.formatResponse(res.result,
SecurityRolesInterfaces.TypeInfo.RoleAssignment,
true);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* @param {string} scopeId
*/
public async getRoleDefinitions(
scopeId: string
): Promise<SecurityRolesInterfaces.SecurityRole[]> {
return new Promise<SecurityRolesInterfaces.SecurityRole[]>(async (resolve, reject) => {
let routeValues: any = {
scopeId: scopeId
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"3.2-preview.1",
"securityroles",
"f4cc9a86-453c-48d2-b44d-d3bd5c105f4f",
routeValues);
let url: string = verData.requestUrl;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<SecurityRolesInterfaces.SecurityRole[]>;
res = await this.rest.get<SecurityRolesInterfaces.SecurityRole[]>(url, options);
let ret = this.formatResponse(res.result,
null,
true);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
} | the_stack |
import { observable } from '@aurelia/runtime';
import { BenchmarkMeasurements, BrowserType, Measurement, totalDuration } from '@benchmarking-apps/test-result';
import { DI, IHttpClient, ILogger, PLATFORM } from 'aurelia';
export const IApi = DI.createInterface<IApi>('IApi', x => x.singleton(Api));
export interface IApi extends Api { }
export class Api {
public constructor(
@IHttpClient private readonly http: IHttpClient,
@ILogger private readonly logger: ILogger,
) {
this.logger = logger.scopeTo('Api');
http.configure(c => c.withDefaults({ mode: 'no-cors' }).withBaseUrl(`${PLATFORM.location.protocol}//${PLATFORM.location.host}/api/`));
}
// public async getAll(): Promise<DataSet> {
// const items = await (await this.http.get('measurements')).json() as DataItem[];
// const data = DataSet.create(items);
// this.logger.debug(`getAll()`, data);
// return data;
// }
public async getLatest(branch?: string, commit?: string, localOnly: boolean = false): Promise<BenchmarkMeasurements> {
const query = new URLSearchParams();
if (branch !== void 0) {
query.set('branch', branch);
}
if (commit !== void 0) {
query.set('commit', commit);
}
const qs = query.toString();
const response = await this.http.get(`measurements/latest${qs ? `?${qs}` : ''}`);
if (!response.ok) {
throw new Error('Error fetching data');
}
const items = await response.json() as BenchmarkMeasurements;
const data = BenchmarkMeasurements.create(items, localOnly);
this.logger.debug(`getLatest()`, data);
return data;
}
}
// const durationKeys = [
// 'durationInitialLoad',
// 'durationPopulation',
// 'durationUpdate',
// 'durationShowDetails',
// 'durationHideDetails',
// 'durationLocaleDe',
// 'durationLocaleEn',
// 'durationSortFirstName',
// 'durationSortFirstNameDesc',
// 'durationSortLastName',
// 'durationSortLastNameDesc',
// 'durationSortDob',
// 'durationSortDobDesc',
// 'durationFilterEmployed',
// 'durationFilterUnemployed',
// 'durationFilterNone',
// 'durationSelectFirst',
// 'durationDeleteFirst',
// 'durationDeleteAll',
// ] as const;
// export class DataSet {
// public readonly durationKeys = durationKeys;
// public readonly items: DataItem[];
// public constructor(
// items: DataItem[],
// ) {
// this.items = items.map(DataItem.create, this);
// }
// public static create(items: DataItem[]): DataSet {
// return new DataSet(items);
// }
// }
// function from_0_to_100(m: $Measurement): boolean {
// return m.initialPopulation === 0 && m.totalPopulation === 100;
// }
// function from_100_to_100(m: $Measurement): boolean {
// return m.initialPopulation === 100 && m.totalPopulation === 100;
// }
// function from_0_to_1000(m: $Measurement): boolean {
// return m.initialPopulation === 0 && m.totalPopulation === 1000;
// }
// function from_1000_to_1000(m: $Measurement): boolean {
// return m.initialPopulation === 1000 && m.totalPopulation === 1000;
// }
// export class DataItem {
// public readonly measurements: $Measurement[];
// public readonly measurement_0_100: $Measurement;
// public readonly measurement_100_100: $Measurement;
// public readonly measurement_0_1000: $Measurement;
// public readonly measurement_1000_1000: $Measurement;
// public constructor(
// public readonly dataSet: DataSet,
// public readonly ts_start: number,
// public readonly ts_end: number,
// public readonly branch: string,
// public readonly commit: string,
// measurements: $Measurement[],
// ) {
// this.measurements = measurements.map($Measurement.create, this);
// this.measurement_0_100 = this.measurements.find(from_0_to_100)!;
// this.measurement_100_100 = this.measurements.find(from_100_to_100)!;
// this.measurement_0_1000 = this.measurements.find(from_0_to_1000)!;
// this.measurement_1000_1000 = this.measurements.find(from_1000_to_1000)!;
// }
// public static create(this: DataSet, d: DataItem): DataItem {
// return new DataItem(
// this,
// d.ts_start,
// d.ts_end,
// d.branch,
// d.commit,
// d.measurements,
// );
// }
// public isValid(): boolean {
// return (
// Number.isFinite(this.ts_start) &&
// Number.isFinite(this.ts_end) &&
// typeof this.branch === 'string' &&
// typeof this.commit === 'string' &&
// this.measurements.every(isValid)
// );
// }
// }
// function isValid(m: $Measurement): boolean {
// return m.isValid();
// }
// export class $Measurement {
// public constructor(
// public readonly dataItem: DataItem,
// public readonly framework: string,
// public readonly frameworkVersion: string,
// public readonly browser: string,
// public readonly browserVersion: string,
// public readonly initialPopulation: number,
// public readonly totalPopulation: number,
// public readonly durationInitialLoad: number,
// public readonly durationPopulation: number | undefined,
// public readonly durationUpdate: number,
// public readonly durationShowDetails: number,
// public readonly durationHideDetails: number,
// public readonly durationLocaleDe: number,
// public readonly durationLocaleEn: number,
// public readonly durationSortFirstName: number,
// public readonly durationSortFirstNameDesc: number,
// public readonly durationSortLastName: number,
// public readonly durationSortLastNameDesc: number,
// public readonly durationSortDob: number,
// public readonly durationSortDobDesc: number,
// public readonly durationFilterEmployed: number,
// public readonly durationFilterUnemployed: number,
// public readonly durationFilterNone: number,
// public readonly durationSelectFirst: number,
// public readonly durationDeleteFirst: number,
// public readonly durationDeleteAll: number,
// ) { }
// public static create(this: DataItem, m: $Measurement): $Measurement {
// return new $Measurement(
// this,
// m.framework,
// m.frameworkVersion,
// m.browser,
// m.browserVersion,
// m.initialPopulation,
// m.totalPopulation,
// m.durationInitialLoad,
// m.durationPopulation,
// m.durationUpdate,
// m.durationShowDetails,
// m.durationHideDetails,
// m.durationLocaleDe,
// m.durationLocaleEn,
// m.durationSortFirstName,
// m.durationSortFirstNameDesc,
// m.durationSortLastName,
// m.durationSortLastNameDesc,
// m.durationSortDob,
// m.durationSortDobDesc,
// m.durationFilterEmployed,
// m.durationFilterUnemployed,
// m.durationFilterNone,
// m.durationSelectFirst,
// m.durationDeleteFirst,
// m.durationDeleteAll,
// );
// }
// public isValid(): boolean {
// return (
// typeof this.framework === 'string' &&
// typeof this.frameworkVersion === 'string' &&
// typeof this.browser === 'string' &&
// typeof this.browserVersion === 'string' &&
// Number.isFinite(this.initialPopulation) &&
// Number.isFinite(this.totalPopulation) &&
// this.dataItem.dataSet.durationKeys.every(isFiniteNumber, this)
// );
// }
// }
// function isFiniteNumber(this: Record<string, unknown>, key: string): boolean {
// return Number.isFinite(this[key]);
// }
export class AvgMeasurement {
public readonly id: string;
public readonly framework: string;
public readonly frameworkVersion: string;
public readonly initialPopulation: number;
public readonly totalPopulation: number;
public durationInitialLoad: number = 0;
public durationPopulation: number = 0;
public durationUpdate: number = 0;
public durationConditional: number = 0;
public durationTextUpdate: number = 0;
public durationSorting: number = 0;
public durationFilter: number = 0;
public durationSelectFirst: number = 0;
public durationDeleteFirst: number = 0;
public durationDeleteAll: number = 0;
private count = 0;
@totalDuration
public readonly totalDuration!: number;
public constructor(
measurement: Measurement | DenormalizedMeasurement
) {
const fx = this.framework = measurement.framework;
const fxVer = this.frameworkVersion = measurement.frameworkVersion;
this.initialPopulation = measurement.initialPopulation;
this.totalPopulation = measurement.totalPopulation;
this.id = `${fx}@${fxVer}`;
this.add(measurement);
}
public add(measurement: Measurement | DenormalizedMeasurement): void {
const n = this.count;
const n1 = ++this.count;
for (const [key, value] of Object.entries(measurement)) {
if (!key.startsWith('duration') || value === void 0) { continue; }
this[key] = ((this[key] as number * n) + value) / n1;
}
}
}
export class DenormalizedMeasurement {
public readonly id: string;
public readonly branch: string;
public readonly commit: string;
public readonly framework: string;
public readonly frameworkVersion: string;
public readonly browser: BrowserType;
public readonly browserVersion: string;
public readonly initialPopulation: number;
public readonly totalPopulation: number;
public readonly durationInitialLoad: number;
public readonly durationPopulation: number;
public readonly durationUpdate: number;
public readonly durationConditional: number;
public readonly durationTextUpdate: number;
public readonly durationSorting: number;
public readonly durationFilter: number;
public readonly durationSelectFirst: number;
public readonly durationDeleteFirst: number;
public readonly durationDeleteAll: number;
@totalDuration
public readonly totalDuration!: number;
public constructor(measurement: Measurement, bench: BenchmarkMeasurements) {
const fx = this.framework = measurement.framework;
const fxVer = this.frameworkVersion = measurement.frameworkVersion;
this.browser = measurement.browser;
this.browserVersion = measurement.browserVersion;
this.initialPopulation = measurement.initialPopulation;
this.totalPopulation = measurement.totalPopulation;
const branch = this.branch = bench.branch;
const commit = this.commit = bench.commit;
this.id = `${fx}@${fxVer}-${branch}(${commit.substring(0, 8)})`;
for (const [key, value] of Object.entries(measurement)) {
if (!key.startsWith('duration') || value === void 0) { continue; }
this[key] = value;
}
}
}
export enum BenchmarkContextErrors {
commitNotFound,
branchNotFound,
}
export class BenchmarkContext {
@observable({ callback: 'reset' }) public branch: string | undefined;
@observable({ callback: 'reset' }) public commit: string | undefined;
public error: BenchmarkContextErrors | null = null;
public data: BenchmarkMeasurements | null = null;
public constructor(
private readonly api: IApi,
private readonly localOnly: boolean,
) { }
public isEqual(that: BenchmarkContext): boolean {
if (this.branch === that.branch) {
const c1 = this.commit;
const c2 = that.commit;
if (c1 === c2) {
return true;
} else if ((c1?.substring(0, 7) ?? '') === (c2?.substring(0, 7) ?? '')) {
return true;
}
}
// At this point either we have different branches or 2 commits those are sufficiently different for same branch.
return false;
}
public async fetchData(): Promise<BenchmarkMeasurements | null> {
await this.$fetchData(this.branch, this.commit);
return this.data;
}
private async $fetchData(branch: string, commit?: string) {
try {
this.data = await this.api.getLatest(branch, commit, this.localOnly);
} catch {
if (commit !== void 0) {
this.error = BenchmarkContextErrors.commitNotFound;
await this.$fetchData(branch);
} else if (branch !== void 0) {
this.error = BenchmarkContextErrors.branchNotFound;
}
}
}
private reset() {
this.error = null;
this.data = null;
}
} | the_stack |
import React, { MouseEvent } from 'react'
import { FlatList, FlatListProps, LayoutChangeEvent, RecursiveArray, SectionList, SectionListProps, StyleProp, StyleSheet, VirtualizedList, VirtualizedListProps } from 'react-native'
import convertStyle from './convertStyle'
import cssToStyle from './cssToRN'
import { FontSizeContext, useFontSize, useHover, useLayout, useScreenSize, useZIndex, useMediaQuery } from './features'
import calculHash from './generateHash'
import type { Style, StyleMap, Units } from './types'
// We use this to cache the computed styles
const styleMap: StyleMap = {}
// We use this to share value within the component (Theme, Translation, whatever)
export const SharedValue = React.createContext<unknown>(undefined)
type Primitive = number | string | null | undefined | boolean
type Functs<T> = (arg: T & { rnCSS?: string; shared: unknown }) => Primitive
type OptionalProps = {
rnCSS?: `${string};`;
onMouseEnter?: (event: MouseEvent) => void;
onMouseLeave?: (event: MouseEvent) => void;
onLayout?: (event: LayoutChangeEvent) => void
children?: React.ReactNode;
style?: StyleProp<any>;
}
function buildCSSString<T extends { rnCSS?: string }> (chunks: TemplateStringsArray, functs: (Primitive | Functs<T>)[], props: T, shared: unknown) {
let computedString = chunks.map((chunk, i) => ([chunk, (functs[i] instanceof Function) ? (functs[i] as Functs<T>)({ ...props, shared }) : functs[i]])).flat().join('')
if (props.rnCSS) computedString += props.rnCSS.replace(/=/gm, ':') + ';'
return computedString
}
const styled = <Props, >(Component: React.ComponentType<Props>) => {
const styledComponent = <S, >(chunks: TemplateStringsArray, ...functs: (Primitive | Functs<S & Props>)[]) => {
const ForwardRefComponent = React.forwardRef<React.ComponentType<S & Props & OptionalProps>, S & Props & OptionalProps>((props: S & Props & OptionalProps, ref) => {
const units = React.useRef<Units>({ em: 16, vw: 1, vh: 1, vmin: 1, vmax: 1, rem: 16, px: 1, pt: 72 / 96, in: 96, pc: 9, cm: 96 / 2.54, mm: 96 / 25.4 })
const shared = React.useContext(SharedValue)
// Store the style for mutualization
const cssString = React.useRef(buildCSSString(chunks, functs, props, shared))
const [rnStyle, setRNStyle] = React.useState<Style>(cssToStyle(cssString.current))
React.useEffect(() => {
// Build the css string with the context
const css = buildCSSString(chunks, functs, props, shared)
cssString.current = css
// Try to load an existing style from the style map or save it for next time
const hash = calculHash(css)
const style = styleMap[hash]
if (style) {
setRNStyle(style.style)
style.usages++
}
else {
const rns = cssToStyle(css)
setRNStyle(rns)
styleMap[hash] = { style: rns, usages: 1 }
}
// When the style is not used anymore, we destroy it
return () => {
const style = styleMap[hash]
style.usages--
if (style.usages <= 0) delete styleMap[hash]
}
}, [props, shared])
// const [needsFontSize, setNeedsFontSize] = React.useState(false)
// const [needsScreenSize, setNeedsScreenSize] = React.useState(false)
const [needsLayout, setNeedsLayout] = React.useState(false)
// const [needsHover, setNeedsHover] = React.useState(false)
React.useEffect(() => {
const css = cssString.current
// setNeedsFontSize(!!css.match(/\b(\d+)(\.\d+)?em\b/)) // Do we need em units
// setNeedsScreenSize(!!css.match(/\b(\d+)(\.\d+)?v([hw]|min|max)\b/)) // Do we need vx units
setNeedsLayout(!!css.match(/\d%/)) // Do we need % units
// setNeedsHover(!!css.match(/&:hover/)) // Do we need to track the mouse
}, [cssString.current])
const finalStyle = { ...rnStyle }
delete finalStyle.media
delete finalStyle.hover
// Read all the data we might need
// Handle hover
const { onMouseEnter, onMouseLeave, style: hoverStyle } = useHover(rnStyle, props.onMouseEnter, props.onMouseLeave)
if (hoverStyle) Object.assign(finalStyle, hoverStyle)
// Calculate current em unit for media-queries
const { em: tempEm } = useFontSize(finalStyle.fontSize, units.current.rem)
if (units.current.em !== tempEm) units.current = { ...units.current, em: tempEm }
// Handle layout data needed for % units
const { width, height, onLayout } = useLayout(props.onLayout)
if (needsLayout && (units.current.width !== width || units.current.height !== height)) {
units.current = { ...units.current, width, height }
}
// Handle screen size needed for vw and wh units
const screenUnits = useScreenSize()
if (/* needsScreenSize && */(Object.keys(screenUnits) as (keyof typeof screenUnits)[]).find(key => units.current[key] !== screenUnits[key])) {
units.current = { ...units.current, ...screenUnits }
}
// apply media queries
const mediaQuery = useMediaQuery(rnStyle.media, units.current)
if (mediaQuery) Object.assign(finalStyle, mediaQuery)
// Handle em units
const { em } = useFontSize(finalStyle.fontSize, units.current.rem)
if (units.current.em !== em) units.current = { ...units.current, em }
if (finalStyle.fontSize) finalStyle.fontSize = em + 'px'
// We memoïze the style to keep the same reference if possible and change it only if the style changed
const calculatedStyle = React.useRef(finalStyle)
if (Object.keys(finalStyle).length !== Object.keys(calculatedStyle.current).length || (Object.keys(finalStyle) as (keyof typeof finalStyle)[]).find(key => calculatedStyle.current[key] !== finalStyle[key])) {
calculatedStyle.current = finalStyle
}
const styleConvertedFromCSS = React.useMemo(() => convertStyle(calculatedStyle.current, units.current), [calculatedStyle.current, units.current])
const zIndex = useZIndex(StyleSheet.flatten([props.style, styleConvertedFromCSS]).zIndex)
const style: StyleProp<any> = React.useMemo(() => {
const style = [] as RecursiveArray<any>
style.push(styleConvertedFromCSS)
if (props.style) style.push(props.style)
if (zIndex) style.push({ zIndex })
return style.length > 1 ? style : style[0]
}, [props.style, styleConvertedFromCSS, zIndex])
const newProps = { style, onMouseEnter, onMouseLeave, onLayout }
// Handle ellipsis
if (StyleSheet.flatten(style).textOverflow === 'ellipsis') Object.assign(newProps, { numberOfLines: 1 })
// The lines below can improve perfs, but it causes the component to remount when the font size changes
// const currentFontSize = React.useContext(FontSizeContext)
// if (em !== currentFontSize) {
if (finalStyle.fontSize) {
return <FontSizeContext.Provider value={em}>
<Component ref={ref} {...props} {...newProps} />
</FontSizeContext.Provider>
}
else {
return <Component ref={ref} {...props} {...newProps} />
}
})
return ForwardRefComponent as React.ForwardRefExoticComponent<Props & S & OptionalProps & { ref?: React.Ref<any> }>
}
// provide styled(Comp).attrs({} | () => {}) feature
styledComponent.attrs = <S, >(opts: Partial<S & Props> | ((props: S & Props) => Partial<S & Props>)) => (chunks: TemplateStringsArray, ...functs: (Primitive | Functs<S & Props>)[]) => {
const ComponentWithAttrs = styledComponent(chunks, ...functs)
const ForwardRefComponent = React.forwardRef<typeof Component, S & Props>((props: Props & S, ref) => {
const attrs = (opts instanceof Function) ? opts(props) : opts
return <ComponentWithAttrs ref={ref} {...props} {...attrs} />
})
// TODO : Find a way to remove from the Props the properties affected by opts
return ForwardRefComponent as React.ForwardRefExoticComponent<(Props | S) & OptionalProps & { ref?: React.Ref<any> }>
}
return styledComponent
}
export default styled
export const styledFlatList = <S, >(chunks: TemplateStringsArray, ...functs: (Primitive | Functs<S>)[]) => <Type, >(props: S & FlatListProps<Type> & OptionalProps) => invoke(styled<FlatListProps<Type>>(FlatList)(chunks, ...functs), props)
styledFlatList.attrs = <S, >(opts: Partial<S & FlatListProps<any>> | ((props: S & FlatListProps<any>) => Partial<S & FlatListProps<any>>)) => (chunks: TemplateStringsArray, ...functs: (Primitive | Functs<S & FlatListProps<any>>)[]) => <Props, >(componentProps: S & FlatListProps<Props> & OptionalProps) => invoke(styled<FlatListProps<Props>>(FlatList).attrs<S & FlatListProps<Props>>(opts)(chunks, ...functs), componentProps)
export const styledSectionList = <S, >(chunks: TemplateStringsArray, ...functs: (Primitive | Functs<S>)[]) => <Type, >(props: S & SectionListProps<Type> & OptionalProps) => invoke(styled<SectionListProps<Type>>(SectionList)(chunks, ...functs), props)
styledSectionList.attrs = <S, >(opts: Partial<S & SectionListProps<any>> | ((props: S & SectionListProps<any>) => Partial<S & SectionListProps<any>>)) => (chunks: TemplateStringsArray, ...functs: (Primitive | Functs<S & SectionListProps<any>>)[]) => <Props, >(componentProps: S & SectionListProps<Props> & OptionalProps) => invoke(styled<SectionListProps<Props>>(SectionList).attrs<S & SectionListProps<Props>>(opts)(chunks, ...functs), componentProps as any)
export const styledVirtualizedList = <S, >(chunks: TemplateStringsArray, ...functs: (Primitive | Functs<S>)[]) => <Type, >(props: S & VirtualizedListProps<Type> & OptionalProps) => invoke(styled<VirtualizedListProps<Type>>(VirtualizedList)(chunks, ...functs), props)
styledVirtualizedList.attrs = <S, >(opts: Partial<S & VirtualizedListProps<any>> | ((props: S & VirtualizedListProps<any>) => Partial<S & VirtualizedListProps<any>>)) => (chunks: TemplateStringsArray, ...functs: (Primitive | Functs<S & VirtualizedListProps<any>>)[]) => <Props, >(componentProps: S & VirtualizedListProps<Props> & OptionalProps) => invoke(styled<VirtualizedListProps<Props>>(VirtualizedList).attrs<S & VirtualizedListProps<Props>>(opts)(chunks, ...functs), componentProps)
function invoke<T> (Component: React.ComponentType<T>, props: T) {
return <Component {...props} />
} | the_stack |
'use strict';
//core
import * as util from 'util';
import * as assert from 'assert';
import * as path from 'path';
import * as cp from 'child_process';
import * as fs from 'fs';
//npm
import chalk from 'chalk';
const dashdash = require('dashdash');
import async = require('async');
import residence = require('residence');
const cwd = process.cwd();
let root = residence.findProjectRoot(cwd);
const treeify = require('treeify');
import mkdirp = require('mkdirp');
//project
import {makeFindProject, rootPaths} from '../../find-projects';
import {mapPaths} from '../../map-paths';
import {cleanCache} from '../../cache-clean';
import log from '../../logging';
import {getIgnore, getSearchRoots} from "../../handle-options";
import options, {NLURunOpts} from './cmd-line-opts';
import {runNPMLink} from '../../run-link';
import {createTree} from '../../create-visual-tree';
import {getCleanMap, getCleanMapOfOnlyPackagesWithNluJSONFiles} from '../../get-clean-final-map';
import {q} from '../../search-queue';
import {EVCb, NluConf, NluMap} from "../../index";
import {
globalConfigFilePath,
determineIfReinstallIsNeeded,
getDevKeys,
getProdKeys,
validateConfigFile,
validateOptions, mapConfigObject, getDepsListFromNluJSON, handleConfigCLIOpt
} from "../../utils";
import {NluGlobalSettingsConf} from "../../index";
//////////////////////////////////////////////////////////////////////////
process.once('exit', function (code) {
if (code !== 0) {
log.warn('NLU is exiting with code:', code, '\n');
}
else {
log.info('NLU is exiting with code:', code, '\n');
}
});
//////////////////////////////////////////////////////////////
const allowUnknown = process.argv.indexOf('--allow-unknown') > 0;
let opts: NLURunOpts, globalConf: NluGlobalSettingsConf, parser = dashdash.createParser({options, allowUnknown});
try {
opts = parser.parse(process.argv);
}
catch (e) {
log.error(chalk.magenta('CLI parsing error:'), chalk.magentaBright.bold(e.message));
process.exit(1);
}
if (opts.help) {
let help = parser.help({includeEnv: true}).trimRight();
console.log('usage: nlu run [OPTIONS]\n'
+ 'options:\n'
+ help);
process.exit(0);
}
try {
globalConf = require(globalConfigFilePath);
}
catch (err) {
log.warn('Could not load global config');
globalConf = {};
}
if (!(globalConf && typeof globalConf === 'object')) {
globalConf = {};
}
if (Array.isArray(globalConf)) {
globalConf = {};
}
const {nluFilePath, nluConfigRoot} = handleConfigCLIOpt(cwd, opts);
let pkg, conf: NluConf, hasNLUJSONFile = false;
try {
conf = require(nluFilePath);
opts.umbrella = opts.umbrella || Boolean(conf.umbrella);
hasNLUJSONFile = true;
}
catch (e) {
if (!opts.umbrella) {
log.error('Could not load your .nlu.json file at this path:', chalk.bold(nluFilePath));
log.error('Your project root is supposedly here:', chalk.bold(root));
log.error(chalk.magentaBright(e.message));
process.exit(1);
}
opts.all_packages = true;
conf = <NluConf>{
'npm-link-up': true,
linkable: false,
searchRoots: ['.'],
list: []
}
}
if (!root) {
if (!(opts.all_packages || opts.umbrella)) {
log.warn('You do not appear to be within an NPM project (no package.json could be found).');
log.warn(' => Your present working directory is =>', chalk.magenta.bold(cwd));
log.warn('Perhaps you meant to use the', chalk.bold('--umbrella'), 'CLI option?');
process.exit(1);
}
root = cwd;
}
try {
pkg = require(path.resolve(root + '/package.json'));
}
catch (e) {
if (!(opts.umbrella || opts.all_packages)) {
log.error('Bizarrely, you do not seem to have a "package.json" file in the root of your project.');
log.error('Your project root is supposedly here:', chalk.magenta(root));
log.error(e.message);
process.exit(1);
}
pkg = {
name: '(root)' // (dummy-root-package)
};
}
if (Array.isArray(conf.packages)) {
throw chalk.magenta(`"packages" property should be an object but no an array => ${util.inspect(conf)}`);
}
if ('packages' in conf) {
assert.strictEqual(typeof conf.packages, 'object', `packages" property should be an object => ${util.inspect(conf)}`)
}
conf.packages = conf.packages || {};
conf.localSettings = conf.localSettings || {};
if (!(conf.localSettings && typeof conf.localSettings === 'object')) {
conf.localSettings = {}
}
if (Array.isArray(conf.localSettings)) {
conf.localSettings = {};
}
opts = Object.assign({},
mapConfigObject(globalConf),
mapConfigObject(conf.localSettings),
opts
);
if (!validateOptions(opts)) {
log.error(chalk.bold('Your command line arguments were invalid, try:', chalk.magentaBright('nlu run --help')));
process.exit(1);
}
if (!validateConfigFile(conf)) {
console.error();
if (!opts.override) {
log.error(chalk.redBright('Your .nlu.json config file appears to be invalid. To override this, use --override.'));
process.exit(1);
}
}
const mainProjectName = pkg.name;
if (!mainProjectName) {
log.error('Ummmm, your package.json file does not have a name property. Fatal.');
process.exit(1);
}
if (opts.verbosity > 0) {
log.info(`We are running the "npm-link-up" tool for your project named "${chalk.magenta(mainProjectName)}".`);
}
const productionDepsKeys = getProdKeys(pkg);
const allDepsKeys = getDevKeys(pkg);
const list = getDepsListFromNluJSON(conf);
if (list.length < 1) {
if (!opts.all_packages) {
log.error(chalk.magenta(' => You do not have any dependencies listed in your .nlu.json file.'));
log.error(chalk.cyan.bold(util.inspect(conf)));
process.exit(1);
}
}
const searchRoots = getSearchRoots(opts, conf);
if (searchRoots.length < 1) {
log.error(chalk.red('No search-roots provided.'));
log.error('You should either update your .nlu.json config to have a searchRoots array.');
log.error('Or you can use the --search-root=X option at the command line.');
log.error(chalk.bold('Conveniently, you may include environment variables in your search root strings.'));
log.error('For example, to search everything starting from $HOME, you can use --search-root=$HOME option at the command line.');
log.error('However, it is highly recommended to choose a subdirectory from $HOME, since searching that many files can take some time.');
process.exit(1);
}
const inListButNotInDeps = list.filter(item => {
return !allDepsKeys.includes(item);
});
inListButNotInDeps.forEach(item => {
if (opts.verbosity > 1) {
log.warning('warning, the following item was listed in your .nlu.json file, ' +
'but is not listed in your package.json dependencies => "' + item + '".');
}
});
// we need to store a version of the list without the top level package's name
const originalList = list.slice(0);
if (!list.includes(mainProjectName)) {
// always include the very project's name
if (!opts.umbrella) {
list.push(mainProjectName); // TODO this might be causing the project to always link to itself?
}
}
const totalList = new Map();
list.forEach(l => {
totalList.set(l, true);
});
const ignore = getIgnore(conf, opts);
originalList.forEach((item: string) => {
if (opts.verbosity > 0) {
log.info(`The following dep will be linked to this project => "${chalk.gray.bold(item)}".`);
}
});
const map: NluMap = {};
if (opts.dry_run) {
log.warning(chalk.bold.gray('Because --dry-run was used, we are not actually linking projects together.'));
}
// add the main project to the map
// when we search for projects, we ignore any projects where package.json name is "mainProjectName"
const mainDep = map[root] = {
name: mainProjectName,
bin: null as any, // conf.bin ?
hasNLUJSONFile,
isMainProject: true,
linkToItself: conf.linkToItself,
runInstall: conf.alwaysReinstall,
path: root,
deps: list,
package: pkg,
searchRoots: null as Array<string>,
installedSet: new Set(),
linkedSet: {}
};
async.autoInject({
readNodeModulesFolders(cb: EVCb<any>) {
const nm = path.resolve(root + '/node_modules');
const keys = opts.production ? productionDepsKeys : allDepsKeys;
determineIfReinstallIsNeeded(nm, mainDep, keys, opts, (err, val) => {
if (err) {
return cb(err);
}
if (val === true) {
mainDep.runInstall = true;
opts.install_main = true;
}
cb(null);
});
},
ensureNodeModules(readNodeModulesFolders: any, cb: EVCb<any>) {
if (!readNodeModulesFolders) {
// no error reading node_modules dir
return process.nextTick(cb);
}
opts.install_main = true;
// we have to install, because node_modules does not exist
mkdirp(path.resolve(root + '/node_modules'), cb);
},
npmCacheClean(cb: EVCb<any>) {
if (opts.dry_run) {
return process.nextTick(cb);
}
if (!opts.clear_all_caches) {
return process.nextTick(cb);
}
log.info(`Cleaning the NPM cache.`);
cleanCache(cb);
},
mapSearchRoots(npmCacheClean: any, cb: EVCb<any>) {
opts.verbosity > 3 && log.info(`Mapping original search roots from your root project's "searchRoots" property.`);
mapPaths(searchRoots, nluConfigRoot, (err, roots) => {
if (err) {
return cb(err);
}
mainDep.searchRoots = roots.slice(0);
cb(err, roots);
});
},
findItems(mapSearchRoots: Array<string>, cb: EVCb<any>) {
let searchRoots = mapSearchRoots.slice(0);
if (opts.verbosity > 1) {
log.info('Beginning to search for NPM projects on your filesystem.');
}
if (opts.verbosity > 3) {
log.info('NPM-Link-Up will be searching these roots for relevant projects:');
log.info(chalk.magenta(util.inspect(searchRoots)));
}
if (opts.verbosity > 2) {
log.warning('Note that NPM-Link-Up may come across a project of yours that needs to search in directories');
log.warning('not covered by your original search roots, and these new directories will be searched as well.');
}
const status = {searching: true};
const findProject = makeFindProject(mainProjectName, totalList, map, ignore, opts, status, conf);
searchRoots.forEach(sr => {
q.push(cb => findProject(sr, cb));
});
if (q.idle()) {
return process.nextTick(cb, new Error('For some reason, no paths/items went onto the search queue.'));
}
let first = true;
q.error = q.drain = (err?: any) => {
if (err) {
status.searching = false;
log.error(chalk.magenta('There was a search queue processing error.'));
}
if (first) {
q.kill();
cb(err, {actuallyRan: true});
}
first = false;
};
},
runUtility(findItems: void, cb: EVCb<NluMap>) {
// TODO: filter excluded and completely excluded keys
const unfound = Array.from(totalList.keys()).filter(v => {
return !map[v];
});
if (false && unfound.length > 0) {
log.warn(`The following packages could ${chalk.bold('not')} be located:`);
for (let i of unfound.keys()) {
log.warn(chalk.bold(String(i + 1), chalk.bold.green(unfound[i])));
}
if (!opts.allow_missing) {
console.error();
log.warn('The following paths (and their subdirectories) were searched:');
rootPaths.forEach((v, i) => {
console.info('\t\t', `${chalk.blueBright.bold(String(i + 1))}.`, chalk.blueBright(v));
});
console.error();
log.error('because the --allow-missing flag was not use, we are exiting.');
process.exit(1);
}
}
let cleanMap: NluMap;
try {
if (opts.all_packages) {
cleanMap = getCleanMapOfOnlyPackagesWithNluJSONFiles(mainProjectName, map);
}
else {
cleanMap = getCleanMap(mainDep, map, opts);
}
}
catch (err) {
return process.nextTick(cb, err);
}
if (opts.dry_run) {
return process.nextTick(() => {
cb(null, cleanMap);
});
}
log.info('Beginning to actually link projects together...');
runNPMLink(cleanMap, opts, err => {
cb(err, cleanMap);
});
}
},
(err: any, results: any) => {
if (err) {
log.error('There was an error while running nlu run/add:');
log.error(chalk.magenta(util.inspect(err.message || err)));
return process.exit(1);
}
if (results.runUtility) {
// if runUtility is defined on results, then we actually ran the tool
log.good(chalk.green.underline('NPM-Link-Up run was successful. All done.'));
}
const cleanMap = results.runUtility;
if (cleanMap && typeof cleanMap === 'object') {
const treeObj = createTree(cleanMap, mainDep.path, mainDep, opts);
// const treeObj = createTree(cleanMap, mainProjectName, originalList, opts);
const treeString = treeify.asTree(treeObj, true);
const formattedStr = [''].concat(String(treeString).split('\n')).map(function (line) {
return ' look here: \t' + line;
}).concat('');
if (opts.verbosity > 1) {
console.log();
log.info(chalk.cyan.bold('NPM-Link-Up results as a visual:'), '\n');
// console.log('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^');
console.log(chalk.white(formattedStr.join('\n')));
// console.log('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^');
}
}
else {
log.warn('Missing map object; could not create dependency tree visualization.');
}
setTimeout(function () {
process.exit(0);
}, 100);
}); | the_stack |
import { BundleManager } from "../bundleManager";
import { InstanceManager } from "../instanceManager";
import { ServiceInstance } from "../service";
import { ServiceManager } from "../serviceManager";
import { emptySuccess, error, success } from "../utils/result";
import {
MockNodeCG,
testBundle,
testBundle2,
testInstance,
testInstance2,
testService,
testServiceInstance,
} from "./mocks";
describe("InstanceManager", () => {
const nodecg = new MockNodeCG();
const noConfigService = {
...testService,
serviceType: "noConfigTest",
createClient: jest.fn(),
requiresNoConfig: true,
};
const serviceManager = new ServiceManager(nodecg);
serviceManager.registerService(testService);
serviceManager.registerService(noConfigService);
const bundleManager = new BundleManager(nodecg);
const testBundleProvider = bundleManager.registerServiceDependency(testBundle, testService);
bundleManager.registerServiceDependency(testBundle2, testService);
let instanceManager: InstanceManager;
const changeCb = jest.fn();
beforeEach(() => {
instanceManager = new InstanceManager(nodecg, serviceManager, bundleManager);
instanceManager.on("change", changeCb);
});
afterEach(() => {
changeCb.mockReset();
bundleManager.removeAllListeners(); // Removes reregisterInstance callback that BundleManager adds in its constructor
});
describe("createServiceInstance", () => {
test("should work when name is unused and service exists", () => {
const res = instanceManager.createServiceInstance(testService.serviceType, testInstance);
expect(res.failed).toBe(false);
expect(changeCb).toHaveBeenCalledTimes(1);
// Make sure instance has been added to the instance list with the correct service type
expect(instanceManager.getServiceInstance(testInstance)).toBeDefined();
expect(instanceManager.getServiceInstance(testInstance)?.serviceType).toBe(testService.serviceType);
});
test("should set config to default config of service", () => {
instanceManager.createServiceInstance(testService.serviceType, testInstance);
expect(instanceManager.getServiceInstance(testInstance)?.config).toBe(testService.defaultConfig);
});
test("should create a client if service requires no configuration", () => {
noConfigService.createClient.mockReset();
instanceManager.createServiceInstance(noConfigService.serviceType, testInstance);
expect(noConfigService.createClient).toHaveBeenCalledTimes(1);
});
test("should error if name is empty", () => {
const res = instanceManager.createServiceInstance(testService.serviceType, "");
expect(res.failed).toBe(true);
if (res.failed) {
expect(res.errorMessage).toContain("name must not be empty");
}
expect(changeCb).not.toHaveBeenCalled();
});
test("should error if a service instance with the same name already exists", () => {
const res1 = instanceManager.createServiceInstance(testService.serviceType, testInstance);
expect(res1.failed).toBe(false);
const res2 = instanceManager.createServiceInstance(testService.serviceType, testInstance);
expect(res2.failed).toBe(true);
if (res2.failed) {
expect(res2.errorMessage).toContain("same name already exists");
}
expect(changeCb).toHaveBeenCalledTimes(1); // One time from the first registration. No second time because we had an error
});
test("should error if there is no service with the passed service type", () => {
const res = instanceManager.createServiceInstance("otherService", testInstance);
expect(res.failed).toBe(true);
if (res.failed) {
expect(res.errorMessage).toContain("service type hasn't been registered");
}
expect(changeCb).not.toHaveBeenCalled();
});
});
describe("deleteServiceInstance", () => {
beforeEach(() => {
instanceManager.createServiceInstance(testService.serviceType, testInstance);
changeCb.mockReset(); // Don't track the call caused by service instance creation
});
afterEach(() => {
testService.stopClient.mockReset();
nodecg.log.error.mockReset();
});
test("should delete instance from internal instance list", () => {
expect(instanceManager.deleteServiceInstance(testInstance)).toBe(true);
expect(instanceManager.getServiceInstance(testInstance)).toBeUndefined();
expect(instanceManager.getServiceInstances()).toStrictEqual({});
expect(changeCb).toHaveBeenCalledTimes(1);
});
test("should log an error if there was an error when stopping the client", () => {
// Set client which needs to exist if we want to have stopClient() called
const instance = instanceManager.getServiceInstance(testInstance);
if (!instance) throw new Error("instance was not saved");
instance.client = testServiceInstance.client;
// Mock stopClient() to throw a error
const errorMsg = "client error message";
testService.stopClient.mockImplementationOnce(() => {
throw new Error(errorMsg);
});
instanceManager.deleteServiceInstance(testInstance);
expect(nodecg.log.error).toHaveBeenCalledTimes(1);
expect(nodecg.log.error.mock.calls[0][0]).toContain(errorMsg);
});
test("should call stopClient() on service if a client exists", () => {
// Case 1: the instance has no client. No call to stopClient() should happen
instanceManager.deleteServiceInstance(testInstance);
expect(testService.stopClient).not.toHaveBeenCalled();
testService.stopClient.mockReset();
// Case 2: the instance has generated a client. It should be stopped with a call to stopClient()
instanceManager.createServiceInstance(testService.serviceType, testInstance);
const instance = instanceManager.getServiceInstance(testInstance);
if (!instance) throw new Error("instance was not saved");
instance.client = testServiceInstance.client;
expect(instanceManager.deleteServiceInstance(testInstance)).toBe(true);
expect(testService.stopClient).toHaveBeenCalledTimes(1);
expect(testService.stopClient).toHaveBeenCalledWith(testServiceInstance.client);
});
test("should log error if client cannot be stopped because the service could not be found", () => {
const instance = instanceManager.getServiceInstance(testInstance);
if (!instance) throw new Error("instance could not be found");
instance.client = testServiceInstance.client;
// oh no, the service just got deleted from ServiceManager. It cannot be looked up anymore.
const services = serviceManager.getServices().splice(0);
const res = instanceManager.deleteServiceInstance(testInstance);
// Re-add the removed services again so other tests can still use them
services.forEach((svc) => serviceManager.registerService(svc));
expect(res).toBe(true);
expect(nodecg.log.error).toHaveBeenCalledTimes(1);
expect(nodecg.log.error.mock.calls[0][0]).toContain("Failed to stop");
});
test("should unset all service dependencies that are assigned to this instance", () => {
// We create two bundles and two instances to make sure that
// deleting testInstance(1) does only unset the service dependencies of bundles
// that actually are assigned to this service instance and
// service dependencies that are assigned to other service instances should
// not be interfered with.
instanceManager.createServiceInstance(testService.serviceType, testInstance2);
const instance1 = instanceManager.getServiceInstance(testInstance);
const instance2 = instanceManager.getServiceInstance(testInstance2);
if (!instance1 || !instance2) throw new Error("instances were not saved");
bundleManager.setServiceDependency(testBundle, testInstance, instance1);
bundleManager.setServiceDependency(testBundle2, testInstance2, instance2);
expect(instanceManager.deleteServiceInstance(testInstance)).toBe(true);
const deps = bundleManager.getBundleDependencies();
expect(deps[testBundle]?.[0]?.serviceInstance).toBeUndefined();
expect(deps[testBundle2]?.[0]?.serviceInstance).toBe(testInstance2);
});
test("should error when service instance doesn't exists", () => {
// Note that we didn't create testInstance2 here
const result = instanceManager.deleteServiceInstance(testInstance2);
expect(result).toBe(false);
expect(changeCb).not.toHaveBeenCalled();
});
});
describe("updateInstanceConfig", () => {
const validConfig = "hello";
const schemaInvalidConfig = 5;
const funcInvalidConfig = "";
beforeEach(() => {
instanceManager.createServiceInstance(testService.serviceType, testInstance);
changeCb.mockReset(); // Don't count change event from service instance creation
// updateInstanceClient is big enough that it gets tested separately
// therefore we have just a empty mock implementation when testing updateInstanceConfig.
instanceManager.updateInstanceClient = jest.fn(() => Promise.resolve(emptySuccess()));
// This is our fake validateConfig function that gets used to make sure that the
// validateConfig function of a service gets called.
// It returns an error if the config string is empty and success otherwise.
testService.validateConfig.mockImplementation(async (config: string) => {
if (config.length === 0) return error("string is empty");
else return emptySuccess();
});
});
afterEach(() => {
testService.validateConfig.mockReset();
});
test("should update config synchronously if validation is not needed", async () => {
// Validation is disabled by last argument
const res = instanceManager.updateInstanceConfig(testInstance, validConfig, false);
// Config must be update right after the function returns. We DO NOT wait for the promise to resolve.
expect(instanceManager.getServiceInstance(testInstance)?.config).toBe(validConfig);
expect(changeCb).toHaveBeenCalledTimes(1);
expect((await res).failed).toBe(false);
});
test("should update config asynchronously if validation is needed", async () => {
const res = instanceManager.updateInstanceConfig(testInstance, validConfig);
// Right after function call it should still have the old config
expect(instanceManager.getServiceInstance(testInstance)?.config).toBe(testService.defaultConfig);
expect(changeCb).not.toHaveBeenCalled();
expect((await res).failed).toBe(false);
// After promise has resolved and validation passed the config should be set to the new one
expect(instanceManager.getServiceInstance(testInstance)?.config).toBe(validConfig);
expect(changeCb).toHaveBeenCalledTimes(1);
});
test("should validate config against json schema", async () => {
// The JSON schema of testService makes sure that only strings are passed in
// Using validSchema which is a string should be fine
const res1 = await instanceManager.updateInstanceConfig(testInstance, validConfig);
expect(res1.failed).toBe(false);
expect(changeCb).toHaveBeenCalledTimes(1); // validation passed, should emit change event
changeCb.mockReset();
// Using schemaInvalidConfig which is a number should error.
const res2 = await instanceManager.updateInstanceConfig(testInstance, schemaInvalidConfig);
expect(res2.failed).toBe(true);
if (res2.failed) {
expect(res2.errorMessage).toContain("data must be string");
}
// Validation failed, shouldn't update config and shouldn't emit change event
expect(instanceManager.getServiceInstance(testInstance)?.config).toBe(validConfig); // From the try before
expect(changeCb).not.toHaveBeenCalled();
});
test("should ignore json schema if not provided", async () => {
const svc = {
...testService,
serviceType: "noJsonSchemaSvc",
schema: undefined,
};
serviceManager.registerService(svc);
instanceManager.createServiceInstance(svc.serviceType, testInstance2);
const res = await instanceManager.updateInstanceConfig(testInstance2, validConfig);
expect(res.failed).toBe(false);
});
test("should validate config using the validateConfig() function of the service", async () => {
// Refer to the mock implementation of validateConfig up top for details
// Using validConfig with a non empty string should be fine
const res1 = await instanceManager.updateInstanceConfig(testInstance, validConfig);
expect(res1.failed).toBe(false);
expect(changeCb).toHaveBeenCalledTimes(1); // validation passed, should emit change event
changeCb.mockReset();
// Using funcInvalidConfig with a empty string should cause an error.
const res2 = await instanceManager.updateInstanceConfig(testInstance, funcInvalidConfig);
expect(res2.failed).toBe(true);
if (res2.failed) {
expect(res2.errorMessage).toContain("string is empty");
}
// Validation failed, shouldn't update config and shouldn't emit change event
expect(instanceManager.getServiceInstance(testInstance)?.config).toBe(validConfig); // From the try before
expect(changeCb).not.toHaveBeenCalled();
});
test("should error if service instance doesn't exists", async () => {
const res = await instanceManager.updateInstanceConfig("otherInstance", validConfig);
expect(res.failed).toBe(true); // otherInstance doesn't exist, just testInstance
if (res.failed) {
expect(res.errorMessage).toContain("instance doesn't exist");
}
});
test("should error if service of instance doesn't exists anymore", async () => {
const services = serviceManager.getServices().splice(0);
const res = await instanceManager.updateInstanceConfig(testInstance, validConfig);
services.forEach((svc) => serviceManager.registerService(svc));
expect(res.failed).toBe(true);
if (res.failed) {
expect(res.errorMessage).toContain("service");
expect(res.errorMessage).toContain("couldn't be found");
}
});
});
describe("updateInstanceClient", () => {
let inst: ServiceInstance<string, () => string>;
beforeEach(() => {
testService.createClient.mockImplementation(async (cfg) => success(() => cfg));
instanceManager.createServiceInstance(testService.serviceType, testInstance);
inst = instanceManager.getServiceInstance(testInstance) as ServiceInstance<string, () => string>;
});
afterEach(() => {
testService.createClient.mockReset();
testService.stopClient.mockReset();
nodecg.log.error.mockReset();
});
test("should create client if config is defined", async () => {
const res = await instanceManager.updateInstanceClient(inst, testInstance, testService);
expect(res.failed).toBe(false);
expect(inst.client).toBeDefined();
expect(inst.client?.()).toBe(inst.config);
expect(testService.createClient).toHaveBeenCalledTimes(1);
expect(testService.createClient).toHaveBeenCalledWith(inst.config);
});
test("should create client if no config is required, even if config is undefined", async () => {
instanceManager.createServiceInstance(noConfigService.serviceType, "noConfigInst");
const inst = instanceManager.getServiceInstance("noConfigInst") as ServiceInstance<string, () => string>;
noConfigService.createClient.mockReset();
noConfigService.createClient.mockImplementation(async () => success(() => "hello, no config provided"));
inst.config = undefined;
const res = await instanceManager.updateInstanceClient(inst, "noConfigInst", noConfigService);
expect(res.failed).toBe(false);
expect(noConfigService.createClient).toHaveBeenCalledTimes(1);
});
test("should not create client if config is undefined", async () => {
inst.config = undefined;
const res = await instanceManager.updateInstanceClient(inst, testInstance, testService);
expect(res.failed).toBe(false);
expect(inst.client).toBeUndefined();
expect(testService.createClient).not.toHaveBeenCalled();
});
test("should set client to undefined if createClient() errors", async () => {
const errorMessage = "some error message";
testService.createClient.mockImplementation(async () => error(errorMessage));
const res = await instanceManager.updateInstanceClient(inst, testInstance, testService);
expect(res.failed).toBe(true);
if (res.failed) {
expect(res.errorMessage).toContain("error while creating a client");
expect(res.errorMessage).toContain(errorMessage);
}
expect(inst.client).toBeUndefined();
});
test("should trigger bundle callbacks with new client", async () => {
bundleManager.setServiceDependency(testBundle, testInstance, inst);
const mockCallback = jest.fn();
testBundleProvider?.onAvailable(mockCallback);
const newMessage = "hello, I am a message from the newly created client";
inst.config = newMessage;
await instanceManager.updateInstanceClient(inst, testInstance, testService);
expect(mockCallback).toHaveBeenCalledTimes(1);
expect(mockCallback.mock.calls[0][0]?.()).toBe(newMessage); // Make sure new client ond not an old one was passed
});
test("should stop old client of the service instance, if one exists", async () => {
// Create the initial client with the default config
await instanceManager.updateInstanceClient(inst, testInstance, testService);
// Change config and re-update client
inst.config = "some other text";
const res = await instanceManager.updateInstanceClient(inst, testInstance, testService);
expect(res.failed).toBe(false);
expect(inst.client?.()).toBe(inst.config); // Current client should stem from new config
// Old client that still refers to old config has been stopped using stopClient() of the service
expect(testService.stopClient).toHaveBeenCalledTimes(1);
expect(testService.stopClient.mock.calls[0][0]?.()).toBe(testService.defaultConfig);
});
test("should log an error if stopping the old client using stopClient() throws an error", async () => {
// Create initial client
await instanceManager.updateInstanceClient(inst, testInstance, testService);
const errorMsg = "client stop error message";
testService.stopClient.mockImplementationOnce(() => {
throw new Error(errorMsg);
});
// Recreate client, which will result in call to stopClient() with old client
await instanceManager.updateInstanceClient(inst, testInstance, testService);
expect(nodecg.log.error).toHaveBeenCalledTimes(1);
expect(nodecg.log.error.mock.calls[0][0]).toContain(errorMsg);
});
});
describe("reregisterHandlersOfInstance", () => {
beforeEach(async () => {
instanceManager.createServiceInstance(testService.serviceType, testInstance);
testService.createClient.mockReset();
testService.createClient.mockImplementation((cfg) => success(() => cfg));
testService.removeHandlers.mockReset();
nodecg.log.error.mockReset();
});
test("should do nothing if passing undefined as instance name", () => {
bundleManager.emit("reregisterInstance", undefined);
expect(nodecg.log.error).not.toHaveBeenCalled(); // Ensure it didn't log a error because passing undefined must be supported
});
test("should error if a name of a non-existent instance was passed", () => {
bundleManager.emit("reregisterInstance", "nonExistentInstance");
expect(nodecg.log.error).toHaveBeenCalledTimes(1);
expect(nodecg.log.error.mock.calls[0][0]).toContain("instance not found");
});
test("should error if service of instance cannot be found anymore", () => {
// Remove service from ServiceManager so it cannot be found anymore
const services = serviceManager.getServices().splice(0);
bundleManager.emit("reregisterInstance", testInstance);
// Re-add the removed services again
services.forEach((svc) => serviceManager.registerService(svc));
expect(nodecg.log.error).toHaveBeenCalledTimes(1);
expect(nodecg.log.error.mock.calls[0][0]).toContain("can't get service");
});
test("should re-create client if reCreateClientToRemoveHandlers is set", () => {
const svc = {
...testService,
serviceType: "reCreateClientToRemoveHandlers",
reCreateClientToRemoveHandlers: true,
};
serviceManager.registerService(svc);
const instName = `${svc.serviceType}Inst`;
instanceManager.createServiceInstance(svc.serviceType, instName);
const inst = instanceManager.getServiceInstance(instName);
if (!inst) throw new Error("instance was not saved");
bundleManager.emit("reregisterInstance", instName);
expect(svc.removeHandlers).not.toHaveBeenCalled();
expect(svc.createClient).toHaveBeenCalledTimes(1);
expect(svc.createClient).toHaveBeenCalledWith(inst.config);
});
test("should do nothing if removeHandlers is not implemented by the service", () => {
const svc = {
...testService,
serviceType: "noRemoveHandlers",
removeHandlers: undefined,
};
serviceManager.registerService(svc);
const instName = `${svc.serviceType}Inst`;
instanceManager.createServiceInstance(svc.serviceType, instName);
const inst = instanceManager.getServiceInstance(instName);
if (!inst) throw new Error("instance was not saved");
const provider = bundleManager.registerServiceDependency(testBundle, svc);
bundleManager.setServiceDependency(testBundle, "noRemoveHandlersInst", inst);
const availabilityCb = jest.fn();
provider?.onAvailable(availabilityCb);
bundleManager.emit("reregisterInstance", instName);
expect(svc.createClient).not.toHaveBeenCalled();
expect(availabilityCb).not.toHaveBeenCalled();
});
test("should call removeHandlers() with client and re-add handlers by triggering bundle callbacks", () => {
const inst = instanceManager.getServiceInstance(testInstance);
if (!inst) throw new Error("testInstance not found");
inst.client = testServiceInstance.client;
bundleManager.setServiceDependency(testBundle, testInstance, inst);
const availabilityCb = jest.fn();
testBundleProvider?.onAvailable(availabilityCb);
testService.removeHandlers.mockReset();
bundleManager.emit("reregisterInstance", testInstance);
expect(testService.removeHandlers).toHaveBeenCalledTimes(1);
expect(testService.removeHandlers).toHaveBeenCalledWith(inst.client);
expect(testService.createClient).not.toHaveBeenCalled();
expect(availabilityCb).toHaveBeenCalledTimes(1);
expect(availabilityCb).toHaveBeenCalledWith(inst.client);
});
test("should error if call to removeHandlers() throws an error", () => {
const inst = instanceManager.getServiceInstance(testInstance);
if (!inst) throw new Error("testInstance not found");
inst.client = testServiceInstance.client;
const errorMsg = "remove handlers error message";
testService.removeHandlers.mockImplementationOnce(() => {
throw new Error(errorMsg);
});
bundleManager.emit("reregisterInstance", testInstance);
expect(nodecg.log.error).toHaveBeenCalledTimes(1);
expect(nodecg.log.error.mock.calls[0][0]).toContain(errorMsg);
});
});
}); | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type SaleLotsListTestsQueryVariables = {
saleSlug: string;
};
export type SaleLotsListTestsQueryResponse = {
readonly " $fragmentRefs": FragmentRefs<"SaleLotsList_saleArtworksConnection">;
};
export type SaleLotsListTestsQuery = {
readonly response: SaleLotsListTestsQueryResponse;
readonly variables: SaleLotsListTestsQueryVariables;
};
/*
query SaleLotsListTestsQuery(
$saleSlug: ID!
) {
...SaleLotsList_saleArtworksConnection_4BVn5U
}
fragment ArtworkGridItem_artwork on Artwork {
title
date
saleMessage
slug
internalID
artistNames
href
sale {
isAuction
isClosed
displayTimelyAt
endAt
id
}
saleArtwork {
counts {
bidderPositions
}
currentBid {
display
}
lotLabel
id
}
partner {
name
id
}
image {
url(version: "large")
aspectRatio
}
}
fragment InfiniteScrollArtworksGrid_connection on ArtworkConnectionInterface {
__isArtworkConnectionInterface: __typename
pageInfo {
hasNextPage
startCursor
endCursor
}
edges {
__typename
node {
slug
id
image {
aspectRatio
}
...ArtworkGridItem_artwork
}
... on Node {
__isNode: __typename
id
}
}
}
fragment SaleArtworkListItem_artwork on Artwork {
artistNames
date
href
image {
small: url(version: "small")
aspectRatio
height
width
}
saleMessage
slug
title
internalID
sale {
isAuction
isClosed
displayTimelyAt
endAt
id
}
saleArtwork {
counts {
bidderPositions
}
currentBid {
display
}
lotLabel
id
}
}
fragment SaleArtworkList_connection on ArtworkConnectionInterface {
__isArtworkConnectionInterface: __typename
edges {
__typename
node {
id
...SaleArtworkListItem_artwork
}
... on Node {
__isNode: __typename
id
}
}
}
fragment SaleLotsList_saleArtworksConnection_4BVn5U on Query {
saleArtworksConnection(saleID: $saleSlug, artistIDs: [], geneIDs: [], aggregations: [FOLLOWED_ARTISTS, ARTIST, MEDIUM, TOTAL], estimateRange: "", first: 10, includeArtworksByFollowedArtists: false, sort: "position") {
aggregations {
slice
counts {
count
name
value
}
}
counts {
followedArtists
total
}
edges {
node {
id
__typename
}
cursor
id
}
...SaleArtworkList_connection
...InfiniteScrollArtworksGrid_connection
pageInfo {
endCursor
hasNextPage
}
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = [
{
"defaultValue": null,
"kind": "LocalArgument",
"name": "saleSlug"
}
],
v1 = {
"kind": "Variable",
"name": "saleID",
"variableName": "saleSlug"
},
v2 = [
{
"kind": "Literal",
"name": "aggregations",
"value": [
"FOLLOWED_ARTISTS",
"ARTIST",
"MEDIUM",
"TOTAL"
]
},
{
"kind": "Literal",
"name": "artistIDs",
"value": ([]/*: any*/)
},
{
"kind": "Literal",
"name": "estimateRange",
"value": ""
},
{
"kind": "Literal",
"name": "first",
"value": 10
},
{
"kind": "Literal",
"name": "geneIDs",
"value": ([]/*: any*/)
},
{
"kind": "Literal",
"name": "includeArtworksByFollowedArtists",
"value": false
},
(v1/*: any*/),
{
"kind": "Literal",
"name": "sort",
"value": "position"
}
],
v3 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
v4 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v5 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
v6 = {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "String"
},
v7 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "FormattedNumber"
},
v8 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "String"
},
v9 = {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "ID"
},
v10 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Int"
},
v11 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Boolean"
};
return {
"fragment": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Fragment",
"metadata": null,
"name": "SaleLotsListTestsQuery",
"selections": [
{
"args": [
(v1/*: any*/)
],
"kind": "FragmentSpread",
"name": "SaleLotsList_saleArtworksConnection"
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Operation",
"name": "SaleLotsListTestsQuery",
"selections": [
{
"alias": null,
"args": (v2/*: any*/),
"concreteType": "SaleArtworksConnection",
"kind": "LinkedField",
"name": "saleArtworksConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "SaleArtworksAggregationResults",
"kind": "LinkedField",
"name": "aggregations",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "slice",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "AggregationCount",
"kind": "LinkedField",
"name": "counts",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "count",
"storageKey": null
},
(v3/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "value",
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "FilterSaleArtworksCounts",
"kind": "LinkedField",
"name": "counts",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "followedArtists",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "total",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "SaleArtwork",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v4/*: any*/),
(v5/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "cursor",
"storageKey": null
},
(v4/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "PageInfo",
"kind": "LinkedField",
"name": "pageInfo",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "endCursor",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "hasNextPage",
"storageKey": null
}
],
"storageKey": null
},
{
"kind": "InlineFragment",
"selections": [
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
(v5/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "artistNames",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "date",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "href",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "image",
"plural": false,
"selections": [
{
"alias": "small",
"args": [
{
"kind": "Literal",
"name": "version",
"value": "small"
}
],
"kind": "ScalarField",
"name": "url",
"storageKey": "url(version:\"small\")"
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "aspectRatio",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "height",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "width",
"storageKey": null
},
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "version",
"value": "large"
}
],
"kind": "ScalarField",
"name": "url",
"storageKey": "url(version:\"large\")"
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "saleMessage",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "slug",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "title",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "internalID",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Sale",
"kind": "LinkedField",
"name": "sale",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isAuction",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isClosed",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "displayTimelyAt",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "endAt",
"storageKey": null
},
(v4/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "SaleArtwork",
"kind": "LinkedField",
"name": "saleArtwork",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "SaleArtworkCounts",
"kind": "LinkedField",
"name": "counts",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "bidderPositions",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "SaleArtworkCurrentBid",
"kind": "LinkedField",
"name": "currentBid",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "display",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "lotLabel",
"storageKey": null
},
(v4/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Partner",
"kind": "LinkedField",
"name": "partner",
"plural": false,
"selections": [
(v3/*: any*/),
(v4/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
},
{
"kind": "TypeDiscriminator",
"abstractKey": "__isNode"
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "PageInfo",
"kind": "LinkedField",
"name": "pageInfo",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "startCursor",
"storageKey": null
}
],
"storageKey": null
}
],
"type": "ArtworkConnectionInterface",
"abstractKey": "__isArtworkConnectionInterface"
}
],
"storageKey": null
},
{
"alias": null,
"args": (v2/*: any*/),
"filters": [
"saleID",
"artistIDs",
"geneIDs",
"aggregations",
"estimateRange",
"includeArtworksByFollowedArtists",
"sort"
],
"handle": "connection",
"key": "SaleLotsList_saleArtworksConnection",
"kind": "LinkedHandle",
"name": "saleArtworksConnection"
}
]
},
"params": {
"id": "45967506c5f4f37bf69b7fde2f3d42b2",
"metadata": {
"relayTestingSelectionTypeInfo": {
"saleArtworksConnection": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "SaleArtworksConnection"
},
"saleArtworksConnection.__isArtworkConnectionInterface": (v6/*: any*/),
"saleArtworksConnection.aggregations": {
"enumValues": null,
"nullable": true,
"plural": true,
"type": "SaleArtworksAggregationResults"
},
"saleArtworksConnection.aggregations.counts": {
"enumValues": null,
"nullable": true,
"plural": true,
"type": "AggregationCount"
},
"saleArtworksConnection.aggregations.counts.count": {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "Int"
},
"saleArtworksConnection.aggregations.counts.name": (v6/*: any*/),
"saleArtworksConnection.aggregations.counts.value": (v6/*: any*/),
"saleArtworksConnection.aggregations.slice": {
"enumValues": [
"ARTIST",
"FOLLOWED_ARTISTS",
"MEDIUM",
"TOTAL"
],
"nullable": true,
"plural": false,
"type": "SaleArtworkAggregation"
},
"saleArtworksConnection.counts": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "FilterSaleArtworksCounts"
},
"saleArtworksConnection.counts.followedArtists": (v7/*: any*/),
"saleArtworksConnection.counts.total": (v7/*: any*/),
"saleArtworksConnection.edges": {
"enumValues": null,
"nullable": true,
"plural": true,
"type": "ArtworkEdgeInterface"
},
"saleArtworksConnection.edges.__isNode": (v6/*: any*/),
"saleArtworksConnection.edges.__typename": (v6/*: any*/),
"saleArtworksConnection.edges.cursor": (v8/*: any*/),
"saleArtworksConnection.edges.id": (v9/*: any*/),
"saleArtworksConnection.edges.node": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Artwork"
},
"saleArtworksConnection.edges.node.__typename": (v6/*: any*/),
"saleArtworksConnection.edges.node.artistNames": (v8/*: any*/),
"saleArtworksConnection.edges.node.date": (v8/*: any*/),
"saleArtworksConnection.edges.node.href": (v8/*: any*/),
"saleArtworksConnection.edges.node.id": (v9/*: any*/),
"saleArtworksConnection.edges.node.image": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Image"
},
"saleArtworksConnection.edges.node.image.aspectRatio": {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "Float"
},
"saleArtworksConnection.edges.node.image.height": (v10/*: any*/),
"saleArtworksConnection.edges.node.image.small": (v8/*: any*/),
"saleArtworksConnection.edges.node.image.url": (v8/*: any*/),
"saleArtworksConnection.edges.node.image.width": (v10/*: any*/),
"saleArtworksConnection.edges.node.internalID": (v9/*: any*/),
"saleArtworksConnection.edges.node.partner": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Partner"
},
"saleArtworksConnection.edges.node.partner.id": (v9/*: any*/),
"saleArtworksConnection.edges.node.partner.name": (v8/*: any*/),
"saleArtworksConnection.edges.node.sale": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Sale"
},
"saleArtworksConnection.edges.node.sale.displayTimelyAt": (v8/*: any*/),
"saleArtworksConnection.edges.node.sale.endAt": (v8/*: any*/),
"saleArtworksConnection.edges.node.sale.id": (v9/*: any*/),
"saleArtworksConnection.edges.node.sale.isAuction": (v11/*: any*/),
"saleArtworksConnection.edges.node.sale.isClosed": (v11/*: any*/),
"saleArtworksConnection.edges.node.saleArtwork": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "SaleArtwork"
},
"saleArtworksConnection.edges.node.saleArtwork.counts": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "SaleArtworkCounts"
},
"saleArtworksConnection.edges.node.saleArtwork.counts.bidderPositions": (v7/*: any*/),
"saleArtworksConnection.edges.node.saleArtwork.currentBid": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "SaleArtworkCurrentBid"
},
"saleArtworksConnection.edges.node.saleArtwork.currentBid.display": (v8/*: any*/),
"saleArtworksConnection.edges.node.saleArtwork.id": (v9/*: any*/),
"saleArtworksConnection.edges.node.saleArtwork.lotLabel": (v8/*: any*/),
"saleArtworksConnection.edges.node.saleMessage": (v8/*: any*/),
"saleArtworksConnection.edges.node.slug": (v9/*: any*/),
"saleArtworksConnection.edges.node.title": (v8/*: any*/),
"saleArtworksConnection.pageInfo": {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "PageInfo"
},
"saleArtworksConnection.pageInfo.endCursor": (v8/*: any*/),
"saleArtworksConnection.pageInfo.hasNextPage": {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "Boolean"
},
"saleArtworksConnection.pageInfo.startCursor": (v8/*: any*/)
}
},
"name": "SaleLotsListTestsQuery",
"operationKind": "query",
"text": null
}
};
})();
(node as any).hash = 'e6caed406d12630149d100ea7a00770e';
export default node; | the_stack |
import { ModuleRpcCommon } from '../common';
import { ClientProtocolError, ClientRpcError } from './errors';
import { BackoffOptions } from './backoff';
import { StreamProducer, Stream, transformStream } from './stream';
import { mapValuesWithStringKeys } from '../utils/utils';
import * as events from 'events';
import { retryStream } from './stream_retrier';
/**
* Default list of [[ModuleRpcCommon.RpcErrorType]] error types that
* should lead to an immediate failure and not to a retry.
*/
export const ERROR_TYPES_TO_FAIL_IMMEDIATELY: ModuleRpcCommon.RpcErrorType[] = [
ModuleRpcCommon.RpcErrorType.invalidArgument,
ModuleRpcCommon.RpcErrorType.notFound,
ModuleRpcCommon.RpcErrorType.alreadyExists,
ModuleRpcCommon.RpcErrorType.permissionDenied,
ModuleRpcCommon.RpcErrorType.failedPrecondition,
ModuleRpcCommon.RpcErrorType.unimplemented,
ModuleRpcCommon.RpcErrorType.internal,
ModuleRpcCommon.RpcErrorType.unauthenticated,
];
/**
* Default `shouldRetry` predicate.
*
* With this predicate, all errors lead to a retry except errors of
* class [[ClientProtocolError]] and of class [[ClientRpcError]] with
* type included in a specific subset of [[ModuleRpcCommon.RpcErrorType]].
*
* @see [[Service.withRetry]]
*/
export const DEFAULT_SHOULD_RETRY = (err: Error): boolean => {
if (err instanceof ClientProtocolError) {
return false;
} else if (
err instanceof ClientRpcError &&
ERROR_TYPES_TO_FAIL_IMMEDIATELY.includes(err.errorType)
) {
return false;
}
return true;
};
/**
* Implements a service from a [[StreamProducer]]. The StreamProducer
* is provided by a streaming protocol, for instance through [[getGrpcWebClient]] in the
* case of the gRPC-Web protocol.
*
* @typeparam serviceDefinition The definition of the service, enumerating all the
* methods and their request and response types.
* @typeparam ResponseContext The type of the response context that is transmitted along
* with the response to the client.
*/
export class Service<
serviceDefinition extends ModuleRpcCommon.ServiceDefinition,
ResponseContext
> {
/**
* @param serviceDefinition The definition of the service.
* @param streamProducer A handler that produces a stream of [[ResponseWithContext]]
* objects given a method name and an RPC request to which the transportation is delegated.
*/
constructor(
readonly serviceDefinition: serviceDefinition,
private readonly streamProducer: StreamProducer,
) {}
/**
* Retrieves a server stream from a method using a request.
*
* @return An object containing the response of the RPC and the context of
* the response (meta-information). The response context contains the information
* that is related to the "remote" aspect of the procedure call: it would be empty if
* the call were to be made within the same OS process.
*/
stream<method extends ModuleRpcCommon.MethodsFor<serviceDefinition>>(
method: method,
request:
| ModuleRpcCommon.RequestFor<serviceDefinition, method>
| (() => ModuleRpcCommon.RequestFor<serviceDefinition, method>),
): Stream<ResponseWithContext<serviceDefinition, method, ResponseContext>> {
return this.streamProducer<
ModuleRpcCommon.RequestFor<serviceDefinition, method>,
{
response: ModuleRpcCommon.ResponseFor<serviceDefinition, method>;
responseContext: ResponseContext;
}
>(method, request);
}
/**
* Calls a unary method on a request.
*
* The underlying server stream is retrieved and transformed into a promise.
*
* @return An object containing the response of the RPC and the context of
* the response (meta-information). The response context contains the information
* that is related to the "remote" aspect of the procedure call: it would be empty if
* the call were to be made within the same OS process.
*
* @throws [[ClientProtocolError]] if the remote implementation was not that of a unary method.
* @throws `Error` if errors were encountered during the streaming.
*
* @see [[streamAsPromise]]
*/
call<method extends ModuleRpcCommon.UnaryMethodsFor<serviceDefinition>>(
method: method,
request:
| ModuleRpcCommon.RequestFor<serviceDefinition, method>
| (() => ModuleRpcCommon.RequestFor<serviceDefinition, method>),
) {
return new Promise<
ResponseWithContext<serviceDefinition, method, ResponseContext>
>((accept, reject) => {
let message: {
response: ModuleRpcCommon.ResponseFor<serviceDefinition, method>;
responseContext: ResponseContext;
};
this.stream(method, request)
.on('message', msg => {
if (message) {
reject(
new ClientProtocolError(
method,
'expected unary method, but got more than one message from server',
),
);
} else {
message = msg;
}
})
.on('error', err => {
reject(err);
})
.on('complete', () => {
if (!message) {
reject(
new ClientProtocolError(
method,
'expected unary method, but got no message from server',
),
);
} else {
accept(message);
}
})
.on('canceled', () => {
reject(new ClientRpcError(ModuleRpcCommon.RpcErrorType.canceled));
})
.start();
});
}
/**
* Returns a service wrapped with a given retry policy that applies to all
* the methods of this service.
*
* @param backoffOptions Options for the exponential backoff.
* @param shouldRetry Determines whether an error should be retried (the
* function returns `true`) or the method should fail immediately.
*/
withRetry(
backoffOptions: Partial<BackoffOptions> = {},
shouldRetry: (err: Error) => boolean = DEFAULT_SHOULD_RETRY,
): ServiceRetrier<serviceDefinition, ResponseContext> {
return new ServiceRetrierImpl(this, backoffOptions, shouldRetry);
}
/**
* Return a "method map" service interface with which it is possible to call RPCs
* as "normal" JavaScript functions.
*
* @example ```Typescript
* // Before
* const service: Service<...> = ...;
* service.stream('serverStream', { foo: 'bar' })
* .on('message', ({ response, responseContext }) => { ... })
* .start();
* const { response, responseContext } = await service.call('unaryMethod', { foo: 'bar' });
*
* // After
* const methodMap = service.methodMap();
* methodMap.serverStream({ foo: 'bar' })
* .on('message', response => { ... })
* .start();
* const response = await methodMap.unaryMethod({ foo: 'bar' });
* ```
*/
methodMap(): ServiceMethodMap<serviceDefinition, ResponseContext> {
const methods = mapValuesWithStringKeys(
this.serviceDefinition,
(methodDefinition, method) => {
if (
methodDefinition.type ===
ModuleRpcCommon.ServiceMethodType.serverStream
) {
return (request: any) =>
transformStream(
this.stream(method, request),
({ response }) => response,
);
} else {
return async (request: any) => {
// Any-cast is the simplest way since it is difficult to type assert
// the fact that it is a unary method.
const { response } = await this.call(method as any, request);
return response;
};
}
},
) as any;
return {
...methods,
[serviceKey]: this,
};
}
}
/**
* A response with a response context for a given service method.
*
* @see [[Service.stream]]
*/
export interface ResponseWithContext<
serviceDefinition extends ModuleRpcCommon.ServiceDefinition,
method extends ModuleRpcCommon.MethodsFor<serviceDefinition>,
ResponseContext
> {
response: ModuleRpcCommon.ResponseFor<serviceDefinition, method>;
responseContext: ResponseContext;
}
/**
* Symbol used as a property name on a [[ServiceMethodMap]] to access the
* full service interface from a "method map" service interface.
*
* This symbol is private to this module as [[serviceInstance]] should
* be used externally instead of directly accessing the service instance
* using the symbol.
*/
const serviceKey = Symbol('serviceKey');
/**
* "Method map" service interface derived from a service definition.
*
* @see [[Service.methodMap]]
*/
export type ServiceMethodMap<
serviceDefinition extends ModuleRpcCommon.ServiceDefinition,
ResponseContext = any
> = {
[method in ModuleRpcCommon.MethodsFor<
serviceDefinition
>]: serviceDefinition[method] extends {
type: typeof ModuleRpcCommon.ServiceMethodType.serverStream;
}
? ServerStreamMethod<serviceDefinition, method>
: UnaryMethod<serviceDefinition, method>;
} & {
[serviceKey]: Service<serviceDefinition, ResponseContext>;
};
/**
* Get the full service instance from a "method map" service interface.
*
* Implementation detail: The service instance is stored in a "method map" through a
* symbol-named property.
*
* @example ```Typescript
* const service: Service<...> = ...;
* const methodMap = service.methodMap();
* // serviceInstance(methodMap) === service
* ```
*/
export function serviceInstance<
serviceDefinition extends ModuleRpcCommon.ServiceDefinition,
ResponseContext = any
>(methodMap: ServiceMethodMap<serviceDefinition, ResponseContext>) {
return methodMap[serviceKey];
}
/** A unary method typed as part of a "method map" service interface. */
export interface UnaryMethod<
serviceDefinition extends ModuleRpcCommon.ServiceDefinition,
method extends ModuleRpcCommon.MethodsFor<serviceDefinition>
> {
(request: ModuleRpcCommon.RequestFor<serviceDefinition, method>): Promise<
ModuleRpcCommon.ResponseFor<serviceDefinition, method>
>;
}
/** A server-stream method typed as part of a "method map" service interface. */
export interface ServerStreamMethod<
serviceDefinition extends ModuleRpcCommon.ServiceDefinition,
method extends ModuleRpcCommon.MethodsFor<serviceDefinition>
> {
(
request:
| ModuleRpcCommon.RequestFor<serviceDefinition, method>
| (() => ModuleRpcCommon.RequestFor<serviceDefinition, method>),
): Stream<ModuleRpcCommon.ResponseFor<serviceDefinition, method>>;
}
/**
* Wrapper that retries RPCs when they fail and emit service-wide events.
*/
export interface ServiceRetrier<
serviceDefinition extends ModuleRpcCommon.ServiceDefinition,
ResponseContext
> {
/**
* Return the wrapped service. All the methods are retried using the
* agreed-upon strategy.
*
* @see ModuleRpcClient.Service#withRetry()
*/
service(): Service<serviceDefinition, ResponseContext>;
/**
* Register listeners.
*
* Events are:
*
* - `serviceReady`: When a method is ready to process a request.
* - `serviceComplete`: When a method has completed after successfully
* processing a request.
* - `serviceError`: When a method has errored. Parameters:
* - `err`: The error.
* - `retriesSinceLastReady`: The number of retries made since the method
* last emitted a 'ready' event.
* - `abandoned`: Whether as a result of this error event the retrying was
* abandoned (as a consequence, the error `err` has been forwarded to the client).
* - `method`: The method that errored.
* - `request`: The request the method errored on.
*/
on(
event: 'serviceReady' | 'serviceComplete',
callback: <method extends ModuleRpcCommon.MethodsFor<serviceDefinition>>(
method: method,
request: ModuleRpcCommon.RequestFor<serviceDefinition, method>,
) => void,
): this;
on(
event: 'serviceError',
callback: <method extends ModuleRpcCommon.MethodsFor<serviceDefinition>>(
err: Error,
retriesSinceLastReady: number,
abandoned: boolean,
method: method,
request: ModuleRpcCommon.RequestFor<serviceDefinition, method>,
) => void,
): this;
}
class ServiceRetrierImpl<
serviceDefinition extends ModuleRpcCommon.ServiceDefinition,
ResponseContext
> extends events.EventEmitter
implements ServiceRetrier<serviceDefinition, ResponseContext> {
constructor(
private readonly baseService: Service<serviceDefinition, ResponseContext>,
private readonly backoffOptions: Partial<BackoffOptions>,
private readonly shouldRetry: (err: Error) => boolean,
) {
super();
}
service() {
return new Service<serviceDefinition, ResponseContext>(
this.baseService.serviceDefinition,
this.stream,
);
}
private stream: StreamProducer = <
method extends ModuleRpcCommon.MethodsFor<serviceDefinition>
>(
method: method,
request:
| ModuleRpcCommon.RequestFor<serviceDefinition, method>
| (() => ModuleRpcCommon.RequestFor<serviceDefinition, method>),
) => {
return retryStream<ModuleRpcCommon.ResponseFor<serviceDefinition, method>>(
() => this.baseService.stream(method, request),
this.backoffOptions,
this.shouldRetry,
)
.on('ready', () => {
this.emit('serviceReady', method, request);
})
.on('retryingError', (err, retries, abandoned) => {
this.emit('serviceError', err, retries, abandoned, method, request);
})
.on('complete', () => {
this.emit('serviceComplete', method, request);
});
};
} | the_stack |
import * as React from "react";
import pnp from "sp-pnp-js";
import { SortDirection } from "sp-pnp-js";
import * as _ from "lodash";
import DisplayProp from "../../shared/DisplayProp";
import { SearchQuery, SearchResults } from "sp-pnp-js";
import { css } from "office-ui-fabric-react";
//import styles from "./PropertyBagFilteredSiteList.module.scss";
import { IPropertyBagFilteredSiteListProps } from "./IPropertyBagFilteredSiteListProps";
import { Label } from "office-ui-fabric-react/lib/Label";
import { TextField } from "office-ui-fabric-react/lib/TextField";
import { Link } from "office-ui-fabric-react/lib/Link";
import { List } from "office-ui-fabric-react/lib/List";
import { Button, ButtonType } from "office-ui-fabric-react/lib/Button";
import { MessageBar, MessageBarType } from "office-ui-fabric-react/lib/MessageBar";
import * as md from "../../shared/MessageDisplay";
import utils from "../../shared/utils";
import MessageDisplay from "../../shared/MessageDisplay";
import { CommandBar, ICommandBarProps } from "office-ui-fabric-react/lib/CommandBar";
import {
DetailsList, DetailsListLayoutMode, IColumn, IGroupedList, SelectionMode, CheckboxVisibility, IGroup
} from "office-ui-fabric-react/lib/DetailsList";
import {
GroupedList
} from "office-ui-fabric-react/lib/GroupedList";
import {
IViewport
} from "office-ui-fabric-react/lib/utilities/decorators/withViewport";
import {
Panel, PanelType
} from "office-ui-fabric-react/lib/Panel";
import { IContextualMenuItem, } from "office-ui-fabric-react/lib/ContextualMenu";
export interface IPropertyBagFilteredSiteListState {
errorMessages: Array<md.Message>;
sites: Array<Site>;
filteredSites: Array<Site>;
userFilters: Array<UserFilter>;// this is what the user CAN filter on
appliedUserFilters: Array<AppliedUserFilter>;// this is what the user HAS filtered on
}
export class Site {
public constructor(
public title: string,
public description: string,
public url: string,
) { }
}
export class DisplaySite {
constructor(
public Title: string,
public Url: string,
public SiteTemplate: string,
public errorMessages: Array<md.Message>,
public DisplayProps?: Array<DisplayProp>,
public searchableProps?: Array<string>,
public forceCrawl?: boolean,
) { }
}
export class AppliedUserFilter {
/**
* Creates an instance of AppliedUserFilter.
* An AppliedUserFilter is created when a user oerforms a filtering operation
* @param {string} managedPropertyName The property the user filtered on
* @param {string} value The value the user selected for the filter
*
* @memberOf AppliedUserFilter
*/
public constructor(
public managedPropertyName: string,
public value: string)
{ }
}
export class UserFilter {
/**
* A UserFilter lets the use filter the list of displayed sites based on a metadata value.
* The ManagedProperty name is displayed in a CommandBar as a dropdown, with the values as
* dropdown options.
*
* @type {Array<string>}
* @memberOf UserFilter
*/
public values: Array<string>;
public constructor(public managedPropertyName: string) {
this.values = [];
}
}
export default class PropertyBagFilteredSiteList extends React.Component<IPropertyBagFilteredSiteListProps, IPropertyBagFilteredSiteListState> {
public constructor(props) {
console.log(JSON.stringify("in constructor"));
super(props);
this.state = { sites: [], filteredSites: [], errorMessages: [], userFilters: [], appliedUserFilters: [] };
}
/** Utility Functions */
/**
* Removes a message from the MessageDisplay
*
* @param {string} messageId the ID of the message to remove
*
* @memberOf PropertyBagFilteredSiteList
*/
public removeMessage(messageId: string) {
_.remove(this.state.errorMessages, {
Id: messageId
});
this.setState(this.state);
}
/**
* Initializes the list of user filters.
* A user filter is created for each UserFilter name specified in the props.
*
* @param {Array<string>} userFilterNames
*
* @memberOf PropertyBagFilteredSiteList
*/
public setupUserFilters(userFilterNames: Array<string>) {
console.log(JSON.stringify("in extractUserFilterValues"));
this.state.userFilters = [];
for (const userFilterName of userFilterNames) {
this.state.userFilters.push(new UserFilter(userFilterName));
}
}
/**
* Adds values to All the UserFilters for a given SearchResults.
*
* @param {any} r The Searchresult
*
* @memberOf PropertyBagFilteredSiteList
*/
public extractUserFilterValues(r) {
console.log(JSON.stringify("in extractUserFilterValues"));
for (const userFilter of this.state.userFilters) {
const value = r[userFilter.managedPropertyName].trim();
if (_.find(userFilter.values, v => { return v === value; })) {
// already there
}
else {
userFilter.values.push(value);
}
}
}
/**
* Gets the sites to be displayed in the list using the filters passed in from Properies
* Sites are saved in this.state.sites
* @param {Array<string>} siteTemplatesToInclude Site templats (i.e. STS of STS#0, etc,)
* @param {Array<string>} filters Filters to use from PropertyPane
* @param {boolean} showQueryText Whether to display the queryText in the MessageDisplay
* @param {Array<string>} userFilters the list of user filters to be built from the searchresults
* @param {boolean} showSiteDescriptions Include site descroptions in search results
*
* @memberOf PropertyBagFilteredSiteList
*/
public getSites(siteTemplatesToInclude: Array<string>, filters:Array<string>, showQueryText: boolean, userFilters: Array<string>, showSiteDescriptions: boolean) {
console.log(JSON.stringify("in getSites"));
const userFilterNameArray = [];
if (userFilters) {
for (const userFilter of userFilters) {
userFilterNameArray.push(userFilter);
}
}
let querytext = "contentclass:STS_Site ";
if (siteTemplatesToInclude) {
querytext = utils.addSiteTemplatesToSearchQuery(siteTemplatesToInclude, querytext);
}
if (filters) {
querytext = utils.addFiltersToSearchQuery(filters, querytext);
}
if (showQueryText) {
this.state.errorMessages.push(new md.Message("Using Query " + querytext));
}
const selectProperties: Array<string> = ["Title", "SPSiteUrl"];
if (showSiteDescriptions) {
selectProperties.push("Description");
}
for (const userFilter of userFilterNameArray) {
selectProperties.push(userFilter);
}
const q: SearchQuery = {
Querytext: querytext,
SelectProperties: selectProperties,
RowLimit: 999,
TrimDuplicates: false,
// SortList:
// [
// {
// Property: 'Title',
// Direction: SortDirection.Ascending
// }
// ]
};
pnp.sp.search(q).then((results: SearchResults) => {
this.state.sites = [];
debugger;
this.setupUserFilters(userFilterNameArray);
for (const r of results.PrimarySearchResults) {
const index = this.state.sites.push(new Site(r.Title, r.Description, r.SPSiteUrl));
for (const mp of this.props.userFilters) {
this.state.sites[index-1][mp] = r[mp];
}
this.extractUserFilterValues(r);
}
this.filterSites();
this.setState(this.state);
}).catch(err => {
debugger;
this.state.errorMessages.push(new md.Message(err));
this.setState(this.state);
});
}
/** react lifecycle */
/**
* Called whe component loads.
* Gets the sites and builds the userFilters
*
* @memberOf PropertyBagFilteredSiteList
*/
public componentWillMount() {
console.log(JSON.stringify("in componentWillMount"));
this.getSites(this.props.siteTemplatesToInclude, this.props.filters, this.props.showQueryText, this.props.userFilters, this.props.showSiteDescriptions);
}
/**
* Called whe Properties are changed in the PropertyPane
* Gets the sites and builds the userFilters using the new Properties
*
* @param {IPropertyBagFilteredSiteListProps} nextProps
* @param {*} nextContext
*
* @memberOf PropertyBagFilteredSiteList
*/
public componentWillReceiveProps(nextProps: IPropertyBagFilteredSiteListProps, nextContext: any) {
console.log(JSON.stringify("in componentWillReceiveProps"));
this.getSites(nextProps.siteTemplatesToInclude, nextProps.filters, nextProps.showQueryText, nextProps.userFilters, nextProps.showSiteDescriptions);
}
/**
* Called by the Render method.
* Displayes the Site Description if requested in the PropertyPane.
* Otherwise displays an empty Div
*
* @param {Site} site
* @returns
*
* @memberOf PropertyBagFilteredSiteList
*/
public conditionallyRenderDescription(site: Site) {
console.log(JSON.stringify("in conditionallyRenderDescription"));
if (this.props.showSiteDescriptions) {
return (<Label>{site.description}</Label>);
}
else {
return (<div />);
}
}
/**
* Called by the Render Method
* Sets up the ContentualMenuItems based on the FilterData extracted from the SearchResults
*
* @private
* @returns {Array<IContextualMenuItem>}
*
* @memberOf PropertyBagFilteredSiteList
*/
private SetupFilters(): Array<IContextualMenuItem> {
console.log(JSON.stringify("in SetupFilters"));
const items = new Array<IContextualMenuItem>();
for (const uf of this.state.userFilters) {
const item: IContextualMenuItem = {
key: uf.managedPropertyName,
name: uf.managedPropertyName,
title: uf.managedPropertyName,
href:null,
}
item.items = [];
for (const value of uf.values) {
item.items.push({
key: value,
data: {
managedPropertyName: uf.managedPropertyName,
value: value
},
checked: this.AppliedFilterExists(uf.managedPropertyName, value),
name: value,
title: value,
onClick: this.filterOnMetadata.bind(this)
});
}
items.push(item);
}
return items;
}
/**
* Determines if the specified managedProperty and value are currently being filtered on
*
* @param {string} managedPropertyName
* @param {string} value
* @returns {boolean}
*
* @memberOf PropertyBagFilteredSiteList
*/
public AppliedFilterExists(managedPropertyName: string, value: string): boolean {
console.log(JSON.stringify("in AppliedFilterExists"));
const selectedFilter = _.find(this.state.appliedUserFilters, af => {
return (af.managedPropertyName === managedPropertyName && af.value === value);
});
if (selectedFilter) {
return true;
} else {
return false;
}
}
/**
* Togles the userFIlter fpr the managedProperty and value in the specified MenuItem
*
* @param {IContextualMenuItem} item
*
* @memberOf PropertyBagFilteredSiteList
*/
public ToggleAppliedUserFilter(item: IContextualMenuItem) {
console.log(JSON.stringify("in ToggleAppliedUserFilter"));
if (this.AppliedFilterExists(item.data.managedPropertyName, item.data.value)) {
this.state.appliedUserFilters = this.state.appliedUserFilters.filter(af => {
return (af.managedPropertyName !== item.data.managedPropertyName || af.value !== item.data.value);
});
}
else {
this.state.appliedUserFilters.push(new AppliedUserFilter(item.data.managedPropertyName, item.data.value));
}
}
/**
* Filters the sites in this.state.sites using the userFilteres in this.state.appliedUserFilters
* and stores it in this.state.filteredSites.
* this.state.sites holds all sites after filtering based on propertypane filters.
* this.state.filteredSites hods the likst of sites after userFilters are applied and
* is shown in the display
*
* @memberOf PropertyBagFilteredSiteList
*/
public filterSites() {
console.log(JSON.stringify("in filterSites"));
if (this.state.appliedUserFilters.length === 0) {
this.state.filteredSites = this.state.sites;
}
else {
this.state.filteredSites = this.state.sites.filter(site => {
debugger;
for (const auf of this.state.appliedUserFilters) {
if (site[auf.managedPropertyName] !== auf.value) {
return false;
}
}
return true;
});
}
}
/**
* EventHandler called when a user selects one of the filters from the COmmandBar
* Toggles the filter
* Applies the new Filters.
* re-deiplays the list
*
* @param {React.MouseEvent<HTMLElement>} [ev]
* @param {IContextualMenuItem} [item]
*
* @memberOf PropertyBagFilteredSiteList
*/
public filterOnMetadata(ev?: React.MouseEvent<HTMLElement>, item?: IContextualMenuItem) {
console.log(JSON.stringify("in filterOnMetadata"));
this.ToggleAppliedUserFilter(item);
this.filterSites();
this.setState(this.state);
}
public doNothing(ev?: React.MouseEvent<HTMLElement>, item?: IContextualMenuItem) {
console.log(JSON.stringify("in doNothing"));
ev.stopPropagation();
return false;
}
/**
* Renders the list of sites in this.state.filteredSites.
*
* @returns {React.ReactElement<IPropertyBagFilteredSiteListProps>}
*
* @memberOf PropertyBagFilteredSiteList
*/
public render(): React.ReactElement<IPropertyBagFilteredSiteListProps> {
debugger;
const listItems = this.state.filteredSites.map((site) =>
<li >
<a href={site.url} target={this.props.linkTarget}>{site.title}</a>
{this.conditionallyRenderDescription(site)}
</li>
);
const commandItems: Array<IContextualMenuItem> = this.SetupFilters();
console.log(JSON.stringify("commandItems follow"));
console.log(JSON.stringify(commandItems));
return (
<div >
<Label>{this.props.description}</Label>
<CommandBar items={commandItems} />
<MessageDisplay
messages={this.state.errorMessages}
hideMessage={this.removeMessage.bind(this)}
/>
<ul > {listItems}</ul>
{/*<List items={sites} startIndex={0}
onRenderCell={(site, index) => {
return (
<div >
<Link href={site.url}>{site.title}</Link>
<Label>{site.description}</Label>
</div>
);
}}
>
</List>*/}
</div >
);
}
} | the_stack |
import {Destination, DestinationConnectionStatus, DestinationOrigin, DestinationType, DuplexType, GooglePromotedDestinationId, Margins, MarginsType, PrintPreviewModelElement, Size} from 'chrome://print/print_preview.js';
// <if expr="chromeos_ash or chromeos_lacros">
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
// </if>
import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js';
import {getCddTemplate, getCloudDestination, getSaveAsPdfDestination} from './print_preview_test_utils.js';
suite('ModelSettingsAvailabilityTest', function() {
let model: PrintPreviewModelElement;
setup(function() {
document.body.innerHTML = '';
model = document.createElement('print-preview-model');
document.body.appendChild(model);
model.documentSettings = {
hasCssMediaStyles: false,
hasSelection: false,
isFromArc: false,
isModifiable: true,
isScalingDisabled: false,
fitToPageScaling: 100,
pageCount: 3,
title: 'title',
};
model.pageSize = new Size(612, 792);
model.margins = new Margins(72, 72, 72, 72);
// Create a test destination.
model.destination = new Destination(
'FooDevice', DestinationType.LOCAL, DestinationOrigin.LOCAL, 'FooName',
DestinationConnectionStatus.ONLINE);
model.set(
'destination.capabilities',
getCddTemplate(model.destination.id).capabilities);
model.applyStickySettings();
});
// These tests verify that the model correctly updates the settings
// availability based on the destination and document info.
test('copies', function() {
assertTrue(model.settings.copies.available);
// Set max copies to 1.
let caps = getCddTemplate(model.destination.id).capabilities!;
const copiesCap = {max: 1};
caps.printer!.copies = copiesCap;
model.set('destination.capabilities', caps);
assertFalse(model.settings.copies.available);
// Set max copies to 2 (> 1).
caps = getCddTemplate(model.destination.id).capabilities!;
copiesCap.max = 2;
caps.printer!.copies = copiesCap;
model.set('destination.capabilities', caps);
assertTrue(model.settings.copies.available);
// Remove copies capability.
caps = getCddTemplate(model.destination.id).capabilities!;
delete caps.printer!.copies;
model.set('destination.capabilities', caps);
assertFalse(model.settings.copies.available);
// Copies is restored.
caps = getCddTemplate(model.destination.id).capabilities!;
model.set('destination.capabilities', caps);
assertTrue(model.settings.copies.available);
assertFalse(model.settings.copies.setFromUi);
});
test('collate', function() {
assertTrue(model.settings.collate.available);
// Remove collate capability.
let capabilities = getCddTemplate(model.destination.id).capabilities!;
delete capabilities.printer!.collate;
model.set('destination.capabilities', capabilities);
// Copies is no longer available.
assertFalse(model.settings.collate.available);
// Copies is restored.
capabilities = getCddTemplate(model.destination.id).capabilities!;
model.set('destination.capabilities', capabilities);
assertTrue(model.settings.collate.available);
assertFalse(model.settings.collate.setFromUi);
});
test('layout', function() {
// Layout is available since the printer has the capability and the
// document is set to modifiable.
assertTrue(model.settings.layout.available);
// Each of these settings should not show the capability.
[undefined,
{option: [{type: 'PORTRAIT', is_default: true}]},
{option: [{type: 'LANDSCAPE', is_default: true}]},
].forEach(layoutCap => {
const capabilities = getCddTemplate(model.destination.id).capabilities!;
capabilities.printer!.page_orientation = layoutCap;
// Layout section should now be hidden.
model.set('destination.capabilities', capabilities);
assertFalse(model.settings.layout.available);
});
// Reset full capabilities
const capabilities = getCddTemplate(model.destination.id).capabilities!;
model.set('destination.capabilities', capabilities);
assertTrue(model.settings.layout.available);
// Test with PDF - should be hidden.
model.set('documentSettings.isModifiable', false);
assertFalse(model.settings.layout.available);
// Test with ARC - should be available.
model.set('documentSettings.isFromArc', true);
assertTrue(model.settings.layout.available);
model.set('documentSettings.isModifiable', true);
model.set('documentSettings.isFromArc', false);
assertTrue(model.settings.layout.available);
// Unavailable if document has CSS media styles.
model.set('documentSettings.hasCssMediaStyles', true);
assertFalse(model.settings.layout.available);
assertFalse(model.settings.layout.setFromUi);
});
test('color', function() {
// Color is available since the printer has the capability.
assertTrue(model.settings.color.available);
// Each of these settings should make the setting unavailable, with
// |expectedValue| as its unavailableValue.
[{
colorCap: undefined,
expectedValue: false,
},
{
colorCap: {option: [{type: 'STANDARD_COLOR', is_default: true}]},
expectedValue: true,
},
{
colorCap: {
option: [
{type: 'STANDARD_COLOR', is_default: true}, {type: 'CUSTOM_COLOR'}
]
},
expectedValue: true,
},
{
colorCap: {
option: [
{type: 'STANDARD_MONOCHROME', is_default: true},
{type: 'CUSTOM_MONOCHROME'}
]
},
expectedValue: false,
},
{
colorCap: {option: [{type: 'STANDARD_MONOCHROME'}]},
expectedValue: false,
},
{
colorCap: {option: [{type: 'CUSTOM_MONOCHROME', vendor_id: '42'}]},
expectedValue: false,
},
{
colorCap: {option: [{type: 'CUSTOM_COLOR', vendor_id: '42'}]},
expectedValue: true,
}].forEach(capabilityAndValue => {
const capabilities = getCddTemplate(model.destination.id).capabilities!;
capabilities.printer!.color = capabilityAndValue.colorCap;
model.set('destination.capabilities', capabilities);
assertFalse(model.settings.color.available);
assertEquals(
capabilityAndValue.expectedValue,
model.settings.color.unavailableValue as boolean);
});
// Each of these settings should make the setting available, with the
// default value given by expectedValue.
[{
colorCap: {
option: [
{type: 'STANDARD_MONOCHROME', is_default: true},
{type: 'STANDARD_COLOR'}
]
},
expectedValue: false,
},
{
colorCap: {
option: [
{type: 'STANDARD_MONOCHROME'},
{type: 'STANDARD_COLOR', is_default: true}
]
},
expectedValue: true,
},
{
colorCap: {
option: [
{type: 'CUSTOM_MONOCHROME', vendor_id: '42'},
{type: 'CUSTOM_COLOR', is_default: true, vendor_id: '43'}
]
},
expectedValue: true,
}].forEach(capabilityAndValue => {
const capabilities = getCddTemplate(model.destination.id).capabilities!;
capabilities.printer!.color = capabilityAndValue.colorCap;
model.set('destination.capabilities', capabilities);
assertEquals(
capabilityAndValue.expectedValue, model.settings.color.value);
assertTrue(model.settings.color.available);
});
// Google Drive always has an unavailableValue of true when using the cloud
// destination.
model.set(
'destination',
getCloudDestination(
GooglePromotedDestinationId.DOCS, GooglePromotedDestinationId.DOCS,
'foo@chromium.org'));
const capabilities =
getCddTemplate(GooglePromotedDestinationId.DOCS).capabilities!;
delete capabilities.printer!.color;
model.set('destination.capabilities', capabilities);
assertFalse(model.settings.color.available);
assertTrue(model.settings.color.unavailableValue as boolean);
assertFalse(model.settings.color.setFromUi);
});
function setSaveAsPdfDestination() {
const saveAsPdf = getSaveAsPdfDestination();
saveAsPdf.capabilities = getCddTemplate(model.destination.id).capabilities;
model.set('destination', saveAsPdf);
}
test('media size', function() {
// Media size is available since the printer has the capability.
assertTrue(model.settings.mediaSize.available);
// Remove capability.
const capabilities = getCddTemplate(model.destination.id).capabilities!;
delete capabilities.printer!.media_size;
// Section should now be hidden.
model.set('destination.capabilities', capabilities);
assertFalse(model.settings.mediaSize.available);
// Set Save as PDF printer.
setSaveAsPdfDestination();
// Save as PDF printer has media size capability.
assertTrue(model.settings.mediaSize.available);
// PDF to PDF -> media size is unavailable.
model.set('documentSettings.isModifiable', false);
assertFalse(model.settings.mediaSize.available);
// CSS styles to PDF -> media size is unavailable.
model.set('documentSettings.isModfiable', true);
model.set('documentSettings.hasCssMediaStyles', true);
assertFalse(model.settings.mediaSize.available);
assertFalse(model.settings.color.setFromUi);
});
test('margins', function() {
// The settings are available since isModifiable is true.
assertTrue(model.settings.margins.available);
assertTrue(model.settings.customMargins.available);
// No margins settings for ARC.
model.set('documentSettings.isFromArc', true);
assertFalse(model.settings.margins.available);
assertFalse(model.settings.customMargins.available);
assertFalse(model.settings.margins.setFromUi);
assertFalse(model.settings.customMargins.setFromUi);
// No margins settings for PDFs.
model.set('documentSettings.isFromArc', false);
model.set('documentSettings.isModifiable', false);
assertFalse(model.settings.margins.available);
assertFalse(model.settings.customMargins.available);
assertFalse(model.settings.margins.setFromUi);
assertFalse(model.settings.customMargins.setFromUi);
});
test('dpi', function() {
// The settings are available since the printer has multiple DPI options.
assertTrue(model.settings.dpi.available);
// No resolution settings for ARC, but uses the default value.
model.set('documentSettings.isFromArc', true);
let capabilities = getCddTemplate(model.destination.id).capabilities;
model.set('destination.capabilities', capabilities);
assertFalse(model.settings.dpi.available);
assertEquals(200, model.settings.dpi.unavailableValue.horizontal_dpi);
assertEquals(200, model.settings.dpi.unavailableValue.vertical_dpi);
model.set('documentSettings.isFromArc', false);
assertTrue(model.settings.dpi.available);
// Remove capability.
capabilities = getCddTemplate(model.destination.id).capabilities!;
delete capabilities.printer!.dpi;
// Section should now be hidden.
model.set('destination.capabilities', capabilities);
assertFalse(model.settings.dpi.available);
// Does not show up for only 1 option. Unavailable value should be set to
// the only available option.
capabilities = getCddTemplate(model.destination.id).capabilities!;
capabilities.printer!.dpi!.option.pop();
model.set('destination.capabilities', capabilities);
assertFalse(model.settings.dpi.available);
assertEquals(200, model.settings.dpi.unavailableValue.horizontal_dpi);
assertEquals(200, model.settings.dpi.unavailableValue.vertical_dpi);
assertFalse(model.settings.dpi.setFromUi);
});
test('scaling', function() {
// HTML -> printer
assertTrue(model.settings.scaling.available);
// HTML -> Save as PDF
const defaultDestination = model.destination;
setSaveAsPdfDestination();
assertTrue(model.settings.scaling.available);
// PDF -> Save as PDF
model.set('documentSettings.isModifiable', false);
assertFalse(model.settings.scaling.available);
// PDF -> printer
model.set('destination', defaultDestination);
assertTrue(model.settings.scaling.available);
assertFalse(model.settings.scaling.setFromUi);
// ARC -> printer
model.set('destination', defaultDestination);
model.set('documentSettings.isFromArc', true);
assertFalse(model.settings.scaling.available);
// ARC -> Save as PDF
setSaveAsPdfDestination();
assertFalse(model.settings.scaling.available);
});
test('scalingType', function() {
// HTML -> printer
assertTrue(model.settings.scalingType.available);
// HTML -> Save as PDF
const defaultDestination = model.destination;
setSaveAsPdfDestination();
assertTrue(model.settings.scalingType.available);
// PDF -> Save as PDF
model.set('documentSettings.isModifiable', false);
assertFalse(model.settings.scalingType.available);
// PDF -> printer
model.set('destination', defaultDestination);
assertFalse(model.settings.scalingType.available);
// ARC -> printer
model.set('documentSettings.isFromArc', true);
assertFalse(model.settings.scalingType.available);
// ARC -> Save as PDF
setSaveAsPdfDestination();
assertFalse(model.settings.scalingType.available);
});
test('scalingTypePdf', function() {
// HTML -> printer
assertFalse(model.settings.scalingTypePdf.available);
// HTML -> Save as PDF
const defaultDestination = model.destination;
setSaveAsPdfDestination();
assertFalse(model.settings.scalingTypePdf.available);
// PDF -> Save as PDF
model.set('documentSettings.isModifiable', false);
assertFalse(model.settings.scalingTypePdf.available);
// PDF -> printer
model.set('destination', defaultDestination);
assertTrue(model.settings.scalingTypePdf.available);
// ARC -> printer
model.set('documentSettings.isFromArc', true);
assertFalse(model.settings.scalingTypePdf.available);
// ARC -> Save as PDF
setSaveAsPdfDestination();
assertFalse(model.settings.scalingTypePdf.available);
});
test('header footer', function() {
// Default margins + letter paper + HTML page.
assertTrue(model.settings.headerFooter.available);
// Custom margins initializes with customMargins undefined and margins
// values matching the defaults.
model.set('settings.margins.value', MarginsType.CUSTOM);
assertTrue(model.settings.headerFooter.available);
// Set margins to NONE
model.set('settings.margins.value', MarginsType.NO_MARGINS);
assertFalse(model.settings.headerFooter.available);
// Set margins to MINIMUM
model.set('settings.margins.value', MarginsType.MINIMUM);
assertTrue(model.settings.headerFooter.available);
// Custom margins of 0.
model.set('settings.margins.value', MarginsType.CUSTOM);
model.set(
'settings.customMargins.value',
{marginTop: 0, marginLeft: 0, marginRight: 0, marginBottom: 0});
model.set('margins', new Margins(0, 0, 0, 0));
assertFalse(model.settings.headerFooter.available);
// Custom margins of 36 -> header/footer available
model.set(
'settings.customMargins.value',
{marginTop: 36, marginLeft: 36, marginRight: 36, marginBottom: 36});
model.set('margins', new Margins(36, 36, 36, 36));
assertTrue(model.settings.headerFooter.available);
// Zero top and bottom -> header/footer unavailable
model.set(
'settings.customMargins.value',
{marginTop: 0, marginLeft: 36, marginRight: 36, marginBottom: 0});
model.set('margins', new Margins(0, 36, 0, 36));
assertFalse(model.settings.headerFooter.available);
// Zero top and nonzero bottom -> header/footer available
model.set(
'settings.customMargins.value',
{marginTop: 0, marginLeft: 36, marginRight: 36, marginBottom: 36});
model.set('margins', new Margins(0, 36, 36, 36));
assertTrue(model.settings.headerFooter.available);
// Small paper sizes
const capabilities = getCddTemplate(model.destination.id).capabilities!;
capabilities.printer!.media_size = {
'option': [
{
'name': 'SmallLabel',
'width_microns': 38100,
'height_microns': 12700,
'is_default': false
},
{
'name': 'BigLabel',
'width_microns': 50800,
'height_microns': 76200,
'is_default': true
}
]
};
model.set('destination.capabilities', capabilities);
model.set('settings.margins.value', MarginsType.DEFAULT);
// Header/footer should be available for default big label with
// default margins.
assertTrue(model.settings.headerFooter.available);
model.set(
'settings.mediaSize.value', capabilities.printer.media_size.option[0]);
// Header/footer should not be available for small label
assertFalse(model.settings.headerFooter.available);
// Reset to big label.
model.set(
'settings.mediaSize.value', capabilities.printer.media_size.option[1]);
assertTrue(model.settings.headerFooter.available);
// Header/footer is never available for PDFs.
model.set('documentSettings.isModifiable', false);
assertFalse(model.settings.headerFooter.available);
assertFalse(model.settings.headerFooter.setFromUi);
// Header/footer is never available for ARC.
model.set('documentSettings.isFromArc', true);
assertFalse(model.settings.headerFooter.available);
assertFalse(model.settings.headerFooter.setFromUi);
});
test('css background', function() {
// The setting is available since isModifiable is true.
assertTrue(model.settings.cssBackground.available);
// No CSS background setting for PDFs.
model.set('documentSettings.isModifiable', false);
assertFalse(model.settings.cssBackground.available);
assertFalse(model.settings.cssBackground.setFromUi);
// No CSS background setting for ARC.
model.set('documentSettings.isFromArc', true);
assertFalse(model.settings.cssBackground.available);
assertFalse(model.settings.cssBackground.setFromUi);
});
test('duplex', function() {
assertTrue(model.settings.duplex.available);
assertTrue(model.settings.duplexShortEdge.available);
// Remove duplex capability.
let capabilities = getCddTemplate(model.destination.id).capabilities!;
delete capabilities.printer!.duplex;
model.set('destination.capabilities', capabilities);
assertFalse(model.settings.duplex.available);
assertFalse(model.settings.duplexShortEdge.available);
// Set a duplex capability with only 1 type, no duplex.
capabilities = getCddTemplate(model.destination.id).capabilities!;
delete capabilities.printer!.duplex;
capabilities.printer.duplex = {
option: [{type: DuplexType.NO_DUPLEX, is_default: true}]
};
model.set('destination.capabilities', capabilities);
assertFalse(model.settings.duplex.available);
assertFalse(model.settings.duplexShortEdge.available);
// Set a duplex capability with 2 types, long edge and no duplex.
capabilities = getCddTemplate(model.destination.id).capabilities!;
delete capabilities.printer!.duplex;
capabilities.printer.duplex = {
option: [
{type: DuplexType.NO_DUPLEX},
{type: DuplexType.LONG_EDGE, is_default: true}
]
};
model.set('destination.capabilities', capabilities);
assertTrue(model.settings.duplex.available);
assertFalse(model.settings.duplexShortEdge.available);
assertFalse(model.settings.duplex.setFromUi);
assertFalse(model.settings.duplexShortEdge.setFromUi);
});
test('rasterize', function() {
// Availability for PDFs varies depening upon OS.
// Windows and macOS depend on policy - see policy_test.js for their
// testing coverage.
model.set('documentSettings.isModifiable', false);
// <if expr="chromeos_ash or chromeos_lacros or is_linux">
// Always available for PDFs on Linux and ChromeOS
assertTrue(model.settings.rasterize.available);
assertFalse(model.settings.rasterize.setFromUi);
// </if>
// Unavailable for ARC.
model.set('documentSettings.isFromArc', true);
assertFalse(model.settings.rasterize.available);
});
test('selection only', function() {
// Not available with no selection.
assertFalse(model.settings.selectionOnly.available);
model.set('documentSettings.hasSelection', true);
assertTrue(model.settings.selectionOnly.available);
// Not available for PDFs.
model.set('documentSettings.isModifiable', false);
assertFalse(model.settings.selectionOnly.available);
assertFalse(model.settings.selectionOnly.setFromUi);
// Not available for ARC.
model.set('documentSettings.isFromArc', true);
assertFalse(model.settings.selectionOnly.available);
assertFalse(model.settings.selectionOnly.setFromUi);
});
test('pages per sheet', function() {
// Pages per sheet is available everywhere except for ARC.
// With the default settings for Blink content, it is available.
model.set('documentSettings.isModifiable', true);
assertTrue(model.settings.pagesPerSheet.available);
// Still available for PDF content.
model.set('documentSettings.isModifiable', false);
assertTrue(model.settings.pagesPerSheet.available);
// Not available for ARC.
model.set('documentSettings.isFromArc', true);
assertFalse(model.settings.pagesPerSheet.available);
});
// <if expr="chromeos_ash or chromeos_lacros">
test('pin', function() {
// Make device unmanaged.
loadTimeData.overrideValues({isEnterpriseManaged: false});
// Check that pin setting is unavailable on unmanaged devices.
assertFalse(model.settings.pin.available);
// Make device enterprise managed.
loadTimeData.overrideValues({isEnterpriseManaged: true});
// Set capabilities again to update pin availability.
model.set(
'destination.capabilities',
getCddTemplate(model.destination.id).capabilities);
assertTrue(model.settings.pin.available);
// Remove pin capability.
let capabilities = getCddTemplate(model.destination.id).capabilities!;
delete capabilities.printer!.pin;
model.set('destination.capabilities', capabilities);
assertFalse(model.settings.pin.available);
// Set not supported pin capability.
capabilities = getCddTemplate(model.destination.id).capabilities!;
capabilities.printer!.pin!.supported = false;
model.set('destination.capabilities', capabilities);
assertFalse(model.settings.pin.available);
assertFalse(model.settings.pin.setFromUi);
});
test('pinValue', function() {
assertTrue(model.settings.pinValue.available);
// Remove pin capability.
let capabilities = getCddTemplate(model.destination.id).capabilities!;
delete capabilities.printer.pin;
model.set('destination.capabilities', capabilities);
assertFalse(model.settings.pinValue.available);
// Set not supported pin capability.
capabilities = getCddTemplate(model.destination.id).capabilities!;
capabilities.printer.pin!.supported = false;
model.set('destination.capabilities', capabilities);
assertFalse(model.settings.pinValue.available);
assertFalse(model.settings.pinValue.setFromUi);
});
// </if>
}); | the_stack |
import { Block, HeaderData } from '@ethereumjs/block'
import { TransactionFactory, TypedTransaction } from '@ethereumjs/tx'
import { Address, BN, toBuffer, toType, TypeOutput, bufferToHex, intToHex } from 'ethereumjs-util'
import { BaseTrie as Trie } from 'merkle-patricia-tree'
import { encode } from 'rlp'
import { middleware, validators } from '../validation'
import { INTERNAL_ERROR } from '../error-code'
import type VM from '@ethereumjs/vm'
import type EthereumClient from '../../client'
import type { Chain } from '../../blockchain'
import type { Config } from '../../config'
import type { EthereumService } from '../../service'
import type { FullSynchronizer } from '../../sync'
import type { TxPool } from '../../sync/txpool'
enum Status {
VALID = 'VALID',
INVALID = 'INVALID',
SYNCING = 'SYNCING',
}
type ExecutionPayload = {
parentHash: string // DATA, 32 Bytes
coinbase: string // DATA, 20 Bytes
stateRoot: string // DATA, 32 Bytes
receiptRoot: string // DATA, 32 bytes
logsBloom: string // DATA, 256 Bytes
random: string // DATA, 32 Bytes
blockNumber: string // QUANTITY, 64 Bits
gasLimit: string // QUANTITY, 64 Bits
gasUsed: string // QUANTITY, 64 Bits
timestamp: string // QUANTITY, 64 Bits
extraData: string // DATA, 0 to 32 Bytes
baseFeePerGas: string // QUANTITY, 256 Bits
blockHash: string // DATA, 32 Bytes
transactions: string[] // Array of DATA - Array of transaction objects,
// each object is a byte list (DATA) representing
// TransactionType || TransactionPayload or LegacyTransaction
// as defined in EIP-2718.
}
type PreparePayloadParamsObject = {
parentHash: string
timestamp: string
random: string
feeRecipient: string
}
type PayloadCache = {
parentHash: Buffer
timestamp: BN
random: Buffer
feeRecipient: Address
}
const EngineError = {
ActionNotAllowed: {
code: 2,
message: 'Action not allowed',
},
UnknownHeader: {
code: 4,
message: 'Unknown header',
},
UnknownPayload: {
code: 5,
message: 'Unknown payload',
},
}
/**
* Formats a block to {@link ExecutionPayload}.
*/
const blockToExecutionPayload = (block: Block, random: Buffer) => {
const header = block.toJSON().header!
const transactions = block.transactions.map((tx) => bufferToHex(tx.serialize())) ?? []
const payload: ExecutionPayload = {
blockNumber: header.number!,
parentHash: header.parentHash!,
coinbase: header.coinbase!,
stateRoot: header.stateRoot!,
receiptRoot: header.receiptTrie!,
logsBloom: header.logsBloom!,
gasLimit: header.gasLimit!,
gasUsed: header.gasUsed!,
timestamp: header.timestamp!,
extraData: header.extraData!,
baseFeePerGas: header.baseFeePerGas!,
blockHash: bufferToHex(block.hash()),
random: bufferToHex(random),
transactions,
}
return payload
}
/**
* Finds a block in validBlocks or the blockchain, otherwise throws {@link EngineError.UnknownPayload}.
*/
const findBlock = async (
hash: Buffer,
validBlocks: Map<String, Block>,
chain: Chain,
synchronizer: FullSynchronizer
) => {
const parentBlock = validBlocks.get(hash.toString('hex'))
if (parentBlock) {
return parentBlock
} else {
// search in chain
try {
const parentBlock = await chain.getBlock(hash)
return parentBlock
} catch (error) {
// block not found, search network (devp2p)
const peer = synchronizer.best()
const headerResult = await peer?.eth!.getBlockHeaders({ block: hash, max: 1 })
if (headerResult) {
const header = headerResult[1]
const bodiesResult = await peer?.eth!.getBlockBodies({ hashes: [hash] })
if (bodiesResult) {
const blockBody = bodiesResult[1][0]
const block = Block.fromValuesArray([header[0].raw(), ...blockBody], {
common: chain.config.chainCommon,
})
return block
}
}
throw EngineError.UnknownHeader
}
}
}
/**
* Recursively finds parent blocks starting from the parentHash.
*/
const recursivelyFindParents = async (
vmHeadHash: Buffer,
parentHash: Buffer,
validBlocks: Map<String, Block>,
chain: Chain,
synchronizer: FullSynchronizer
) => {
if (parentHash.equals(vmHeadHash)) {
return []
}
const parentBlocks = []
const block = await findBlock(parentHash, validBlocks, chain, synchronizer)
parentBlocks.push(block)
while (!vmHeadHash.equals(parentBlocks[parentBlocks.length - 1].header.parentHash)) {
const block: Block = await findBlock(
parentBlocks[parentBlocks.length - 1].header.parentHash,
validBlocks,
chain,
synchronizer
)
parentBlocks.push(block)
}
return parentBlocks.reverse()
}
/**
* Calculates and returns the transactionsTrie for the block.
*/
const transactionsTrie = async (transactions: TypedTransaction[]) => {
const trie = new Trie()
for (const [i, tx] of transactions.entries()) {
await trie.put(encode(i), tx.serialize())
}
return trie.root
}
/**
* engine_* RPC module
* @memberof module:rpc/modules
*/
export class Engine {
private SECONDS_PER_SLOT = new BN(12) // from beacon chain mainnet config
private client: EthereumClient
private chain: Chain
private config: Config
private synchronizer: FullSynchronizer
private vm: VM
private txPool: TxPool
private pendingPayloads: Map<Number, PayloadCache> // payloadId, payload
private validBlocks: Map<String, Block> // blockHash, block
private nextPayloadId = 0
/**
* Create engine_* RPC module
* @param client Client to which the module binds
*/
constructor(client: EthereumClient) {
this.client = client
const service = client.services.find((s) => s.name === 'eth') as EthereumService
this.chain = service.chain
this.config = this.chain.config
this.synchronizer = service.synchronizer as FullSynchronizer
this.vm = this.synchronizer.execution?.vm
this.txPool = (service.synchronizer as FullSynchronizer).txPool
this.pendingPayloads = new Map()
this.validBlocks = new Map()
this.preparePayload = middleware(this.preparePayload.bind(this), 1, [
[
validators.object({
parentHash: validators.blockHash,
timestamp: validators.hex,
random: validators.hex,
feeRecipient: validators.address,
}),
],
])
this.getPayload = middleware(this.getPayload.bind(this), 1, [[validators.hex]])
this.executePayload = middleware(this.executePayload.bind(this), 1, [
[
validators.object({
parentHash: validators.blockHash,
coinbase: validators.address,
stateRoot: validators.hex,
receiptRoot: validators.hex,
logsBloom: validators.hex,
random: validators.hex,
blockNumber: validators.hex,
gasLimit: validators.hex,
gasUsed: validators.hex,
timestamp: validators.hex,
extraData: validators.hex,
baseFeePerGas: validators.hex,
blockHash: validators.blockHash,
transactions: validators.array(validators.hex),
}),
],
])
this.consensusValidated = middleware(this.consensusValidated.bind(this), 1, [
[
validators.object({
blockHash: validators.blockHash,
status: validators.values(['VALID', 'INVALID']),
}),
],
])
this.forkchoiceUpdated = middleware(this.forkchoiceUpdated.bind(this), 1, [
[
validators.object({
headBlockHash: validators.blockHash,
finalizedBlockHash: validators.blockHash,
}),
],
])
}
/**
* Notifies the client will need to propose a block at some point in the future and
* that the payload will be requested by the corresponding engine_getPayload near
* to that point in time.
*
* @param params An array of one parameter:
* 1. An object
* * parentHash - hash of the parent block
* * timestamp - value for the `timestamp` field of the new payload
* * random - value for the `random` field of the new payload
* * feeRecipient - suggested value for the `coinbase` field of the new payload
* @returns A response object or an error. Response object:
* * payloadId - identifier of the payload building process
*/
async preparePayload(params: [PreparePayloadParamsObject]) {
const { parentHash, timestamp, random, feeRecipient } = params[0]
const payload = {
parentHash: toBuffer(parentHash),
timestamp: toType(timestamp, TypeOutput.BN),
random: toBuffer(random),
feeRecipient: Address.fromString(feeRecipient),
}
const payloadId = this.nextPayloadId.valueOf() // clone with valueOf()
this.pendingPayloads.set(payloadId, payload)
this.nextPayloadId++
return { payloadId: intToHex(payloadId) }
}
/**
* Given payloadId, returns the most recent version of an execution payload
* that is available by the time of the call or responds with an error.
*
* @param params An array of one parameter:
* 1. An object
* * payloadId - identifier of the payload building process
* @returns Instance of {@link ExecutionPayload} or an error
*/
async getPayload(params: [string]) {
if (!this.client.config.synchronized) {
// From spec: Client software SHOULD respond with
// `2: Action not allowed` error if the sync process is in progress.
throw EngineError.ActionNotAllowed
}
let [payloadId]: any = params
payloadId = toType(payloadId, TypeOutput.Number)
const payload = this.pendingPayloads.get(payloadId)
if (!payload) {
throw EngineError.UnknownPayload
}
const { parentHash, timestamp, feeRecipient: coinbase } = payload
// From spec: If timestamp + SECONDS_PER_SLOT has passed, block is no longer valid
if (new BN(Date.now()).divn(1000).gt(timestamp.add(this.SECONDS_PER_SLOT))) {
this.pendingPayloads.delete(payloadId)
throw EngineError.UnknownHeader
}
// Use a copy of the vm to not modify the existing state.
const vmCopy = this.vm.copy()
const vmHead = await vmCopy.blockchain.getLatestBlock()
const parentBlocks = await recursivelyFindParents(
vmHead.hash(),
parentHash,
this.validBlocks,
this.chain,
this.synchronizer
)
for (const parent of parentBlocks) {
try {
const td = await vmCopy.blockchain.getTotalDifficulty(parent.hash())
vmCopy._common.setHardforkByBlockNumber(parent.header.number, td)
await vmCopy.runBlock({ block: parent })
await vmCopy.blockchain.putBlock(parent)
} catch (error: any) {
throw {
code: INTERNAL_ERROR,
message: error.toString(),
}
}
}
const parentBlock = await vmCopy.blockchain.getBlock(parentHash)
const number = parentBlock.header.number.addn(1)
const { gasLimit } = parentBlock.header
const baseFeePerGas = parentBlock.header.calcNextBaseFee()
// Set the state root to ensure the resulting state
// is based on the parent block's state
await vmCopy.stateManager.setStateRoot(parentBlock.header.stateRoot)
const td = await vmCopy.blockchain.getTotalDifficulty(vmHead.hash())
vmCopy._common.setHardforkByBlockNumber(vmHead.header.number, td)
const blockBuilder = await vmCopy.buildBlock({
parentBlock,
headerData: {
timestamp,
number,
gasLimit,
baseFeePerGas,
coinbase,
},
})
const txs = await this.txPool.txsByPriceAndNonce(vmCopy.stateManager, baseFeePerGas)
this.config.logger.info(
`Engine: Assembling block from ${txs.length} eligible txs (baseFee: ${baseFeePerGas})`
)
let index = 0
let blockFull = false
while (index < txs.length && !blockFull) {
try {
await blockBuilder.addTransaction(txs[index])
} catch (error: any) {
if (error.message === 'tx has a higher gas limit than the remaining gas in the block') {
if (blockBuilder.gasUsed.gt(gasLimit.subn(21000))) {
// If block has less than 21000 gas remaining, consider it full
blockFull = true
this.config.logger.info(
`Engine: Assembled block full (gasLeft: ${gasLimit.sub(blockBuilder.gasUsed)})`
)
}
} else {
// If there is an error adding a tx, it will be skipped
const hash = bufferToHex(txs[index].hash())
this.config.logger.debug(
`Skipping tx ${hash}, error encountered when trying to add tx:\n${error}`
)
}
}
index++
}
const block = await blockBuilder.build()
this.pendingPayloads.delete(payloadId)
this.validBlocks.set(block.hash().toString('hex'), block)
return blockToExecutionPayload(block, payload.random)
}
/**
* Verifies the payload according to the execution environment rule set (EIP-3675)
* and returns the status of the verification.
*
* @param params An array of one parameter:
* 1. An object as an instance of {@link ExecutionPayload}
* @returns An object:
* 1. status: String - the result of the payload execution
* VALID - given payload is valid
* INVALID - given payload is invalid
* SYNCING - sync process is in progress
*/
async executePayload(params: [ExecutionPayload]) {
if (!this.config.synchronized) {
return { status: Status.SYNCING }
}
const [payloadData] = params
const transactions = []
for (const [index, serializedTx] of payloadData.transactions.entries()) {
try {
const tx = TransactionFactory.fromSerializedData(toBuffer(serializedTx), {
common: this.config.chainCommon,
})
transactions.push(tx)
} catch (error) {
this.config.logger.error(`Invalid tx at index ${index}: ${error}`)
return { status: Status.INVALID }
}
}
// Format block header
const header: HeaderData = {
...payloadData,
number: payloadData.blockNumber,
receiptTrie: payloadData.receiptRoot,
transactionsTrie: await transactionsTrie(transactions),
}
let block
try {
block = Block.fromBlockData({ header, transactions }, { common: this.config.chainCommon })
} catch (error) {
this.config.logger.debug(`Error verifying block: ${error}`)
return { status: Status.INVALID }
}
const vmCopy = this.vm.copy()
const vmHeadHash = (await vmCopy.blockchain.getLatestHeader()).hash()
const parentBlocks = await recursivelyFindParents(
vmHeadHash,
block.header.parentHash,
this.validBlocks,
this.chain,
this.synchronizer
)
for (const parent of parentBlocks) {
try {
await vmCopy.runBlock({ block: parent })
await vmCopy.blockchain.putBlock(parent)
} catch (error: any) {
throw {
code: INTERNAL_ERROR,
message: error.toString(),
}
}
}
try {
await vmCopy.runBlock({ block })
} catch (error) {
this.config.logger.debug(`Error verifying block: ${error}`)
return { status: Status.INVALID }
}
this.validBlocks.set(block.hash().toString('hex'), block)
return { status: Status.VALID }
}
/**
* Communicates that full consensus validation of an execution payload
* is complete along with its corresponding status.
*
* @param params An array of one parameter:
* 1. An object - Payload validity status with respect to the consensus rules:
* blockHash - block hash value of the payload
* status: String: VALID|INVALID - result of the payload validation with respect to the proof-of-stake consensus rules
* @returns None or an error
*/
async consensusValidated(params: [{ blockHash: string; status: string }]) {
const { blockHash, status }: any = params[0]
const block = this.validBlocks.get(blockHash.slice(2))
if (!block && status === Status.VALID) {
throw EngineError.UnknownHeader
}
if (block && status === Status.INVALID) {
this.validBlocks.delete(block.hash().toString('hex'))
}
return null
}
/**
* Propagates the change in the fork choice to the execution client.
*
* @param params An array of one parameter:
* 1. An object - The state of the fork choice:
* headBlockHash - block hash of the head of the canonical chain
* finalizedBlockHash - block hash of the most recent finalized block
* @returns None or an error
*/
async forkchoiceUpdated(params: [{ headBlockHash: string; finalizedBlockHash: string }]) {
const { headBlockHash, finalizedBlockHash } = params[0]
const headBlock = this.validBlocks.get(headBlockHash.slice(2))
if (!headBlock) {
throw EngineError.UnknownHeader
}
const vmHeadHash = (await this.vm.blockchain.getLatestHeader()).hash()
const parentBlocks = await recursivelyFindParents(
vmHeadHash,
headBlock.header.parentHash,
this.validBlocks,
this.chain,
this.synchronizer
)
await this.chain.putBlocks([...parentBlocks, headBlock], true)
this.synchronizer.syncTargetHeight = headBlock.header.number
if (finalizedBlockHash.slice(2) === '0'.repeat(64)) {
// All zeros means no finalized block yet
} else {
const finalizedBlock = this.validBlocks.get(finalizedBlockHash.slice(2))
if (!finalizedBlock) {
throw EngineError.UnknownHeader
}
if (!this.chain.mergeFirstFinalizedBlock) {
this.chain.mergeFirstFinalizedBlock = finalizedBlock
}
this.chain.mergeLastFinalizedBlock = finalizedBlock
}
return null
}
} | the_stack |
import * as json from "@ts-common/json"
import * as jsonParser from "@ts-common/json-parser"
import * as jsonPointer from "json-pointer"
import { toArray } from "@ts-common/iterator"
import { cloneDeep, Data, FilePosition, getFilePosition } from "@ts-common/source-map"
import * as sm from "@ts-common/string-map"
import { readFileSync, writeFileSync } from "fs"
import * as path from "path"
import { pathToJsonPointer } from "./utils"
/*
* Merges source object into the target object
* @param {object} source The object that needs to be merged
*
* @param {object} target The object to be merged into
*
* @returns {object} target - Returns the merged target object.
*/
export function mergeObjects<T extends sm.MutableStringMap<Data>>(source: T, target: T): T {
const result: sm.MutableStringMap<Data> = target
for (const [key, sourceProperty] of sm.entries(source)) {
if (Array.isArray(sourceProperty)) {
const targetProperty = target[key]
if (!targetProperty) {
result[key] = sourceProperty
} else if (!Array.isArray(targetProperty)) {
throw new Error(
`Cannot merge ${key} from source object into target object because the same property ` +
`in target object is not (of the same type) an Array.`
)
} else {
result[key] = mergeArrays(sourceProperty, targetProperty)
}
} else {
result[key] = cloneDeep(sourceProperty)
}
}
return result as T
}
/*
* Merges source array into the target array
* @param {array} source The array that needs to be merged
*
* @param {array} target The array to be merged into
*
* @returns {array} target - Returns the merged target array.
*/
export function mergeArrays<T extends Data>(source: ReadonlyArray<T>, target: T[]): T[] {
if (!Array.isArray(target) || !Array.isArray(source)) {
return target
}
source.forEach(item => {
target.push(cloneDeep(item))
})
return target
}
function getParamKey(source: any) {
return source.$ref ? source.$ref : source.in + source.name
}
/**
* Get next array index for source object,
* the source object is actually an array but treats as an object, so the its key must be number
* @param source
*/
function getNextKey(source: sm.MutableStringMap<Data>) {
const result = sm.keys(source).reduce((a, b) => (a > b ? a : b))
return (+(result as string) + 1).toString()
}
function mergeParameters<T extends sm.MutableStringMap<Data>>(source: T, target: T): T {
const result: sm.MutableStringMap<Data> = target
for (const sourceProperty of sm.values(source)) {
if (!sm.values(target).some(v => getParamKey(v) === getParamKey(sourceProperty))) {
result[getNextKey(result)] = sourceProperty
}
}
return result as T
}
/**
* This class aimed at process some swagger extensions like x-ms-path and
* you can also resolve some swagger keyword e.g allOf here, then return a
* new json with source location info
*/
export class ResolveSwagger {
public innerSwagger: json.Json | undefined
public file: string
constructor(file: string) {
this.file = path.resolve(file)
}
public resolve(): json.Json | undefined {
const content: string = readFileSync(this.file, { encoding: "utf8" })
this.parse(this.file, content)
this.unifyXMsPaths()
this.ConvertPathLevelParameter()
this.ExpandDefinitions()
this.generateNew()
return this.innerSwagger
}
private unifyXMsPaths() {
if (!this.innerSwagger) {
throw new Error("non swagger object")
}
const swagger = this.innerSwagger as any
const xmsPaths = swagger["x-ms-paths"]
const paths = swagger.paths
if (xmsPaths && xmsPaths instanceof Object && toArray(sm.keys(xmsPaths)).length > 0) {
for (const [property, v] of sm.entries(xmsPaths)) {
paths[property] = v
}
swagger.paths = mergeObjects(xmsPaths, paths)
delete swagger["x-ms-paths"]
}
}
private ConvertPathLevelParameter() {
if (!this.innerSwagger) {
throw new Error("Null swagger object")
}
const swagger = this.innerSwagger as any
const paths = swagger.paths
if (paths && paths instanceof Object && toArray(sm.keys(paths)).length > 0) {
for (const [property, v] of sm.entries(paths)) {
const pathsLevelParameters = (v as any).parameters
if (!pathsLevelParameters) {
continue
}
for (const [key, o] of sm.entries(v as any)) {
// key != parameters indicates an http method
if (key.toLowerCase() !== "parameters") {
const operationParam = (o as any).parameters ? (o as any).parameters : []
paths[property][key].parameters = mergeParameters(pathsLevelParameters, operationParam)
}
}
delete (v as any).parameters
}
}
}
private ExpandDefinitions() {
if (!this.innerSwagger) {
throw new Error("Null swagger object")
}
const swagger = this.innerSwagger as any
const definitions = swagger.definitions
if (definitions && toArray(sm.keys(definitions)).length > 0) {
for (const [property, v] of sm.entries(definitions)) {
const references = (v as any).allOf
if (!references) {
continue
}
this.ExpandAllOf(v)
definitions[property] = v
}
}
}
/**
* @description expands allOf
* @param schema
*/
private ExpandAllOf(schema: any) {
if (!schema || !schema.allOf) {
return
}
this.checkCircularAllOf(schema, undefined, [])
const schemaList = schema.properties ? schema.properties : {}
for (const reference of sm.values(schema.allOf)) {
let allOfSchema = reference as any
if (allOfSchema.$ref) {
allOfSchema = this.dereference(allOfSchema.$ref)
if (!allOfSchema) {
throw new Error("Invalid reference:" + allOfSchema.$ref)
}
}
if (allOfSchema.allOf) {
this.ExpandAllOf(allOfSchema)
}
if (allOfSchema.properties) {
sm.keys(allOfSchema.properties).forEach(key => {
if (sm.keys(schemaList).some(k => k === key)) {
if (!this.isEqual(allOfSchema.properties[key], schemaList[key])) {
throw new Error(`incompatible properties : ${key} `)
}
} else {
schemaList[key] = allOfSchema.properties[key]
}
})
}
if (allOfSchema.required) {
const requiredProperties = schema.required ? schema.required : []
sm.values(allOfSchema.required).forEach(prop => {
if (!sm.values(requiredProperties).some(v => v === prop)) {
requiredProperties.push(prop)
}
})
schema.required = requiredProperties
}
}
schema.properties = schemaList
}
/**
* @description Compare two properties to check if they are equivalent.
* @param parentProperty the property in allOf model.
* @param unwrappedProperty the property in current model.
*/
private isEqual(parentProperty: any, unwrappedProperty: any): boolean {
if (!parentProperty) {
throw new Error("Null parent property.")
}
if (!unwrappedProperty) {
throw new Error("Null unwrapped property.")
}
if ((!parentProperty.type || parentProperty.type === "object") && (!unwrappedProperty.type || unwrappedProperty.type === "object")) {
let parentPropertyToCompare = parentProperty
let unwrappedPropertyToCompare = unwrappedProperty
if (parentProperty.$ref) {
parentPropertyToCompare = this.dereference(parentProperty.$ref)
}
if (unwrappedProperty.$ref) {
unwrappedPropertyToCompare = this.dereference(unwrappedProperty.$ref)
}
if (parentPropertyToCompare === unwrappedPropertyToCompare) {
return true
}
return false
}
if (parentProperty.type === "array" && unwrappedProperty.type === "array") {
return this.isEqual(parentProperty.items, unwrappedProperty.items)
}
return parentProperty.type === unwrappedProperty.type && parentProperty.format === unwrappedProperty.format
}
private checkCircularAllOf(schema: any, visited: any[] | undefined, referenceChain: string[]) {
visited = visited ? visited : []
referenceChain = referenceChain ? referenceChain : []
if (schema) {
if (visited.includes(schema)) {
throw new Error("Found circular allOf reference: " + referenceChain.join("-> "))
}
if (!schema.allOf) {
return
}
visited.push(schema)
sm.values(schema.allOf)
.filter(s => (s as any).$ref)
.forEach(s => {
const ref = (s as any).$ref
referenceChain.push(ref)
const referredSchema = this.dereference(ref)
this.checkCircularAllOf(referredSchema, visited, referenceChain)
referenceChain.pop()
})
visited.pop()
}
}
/**
* Get the definition name from the reference string.
* @param ref a json reference
*/
private getModelName(ref: string) {
const parts = ref.split("/")
if (parts.length === 3 && parts[1] === "definitions") {
return parts[2]
}
return undefined
}
private dereferenceInner(ref: string, visitedRefs: Set<string>): any {
const model = this.getModelName(ref)
if (model) {
if (visitedRefs.has(ref)) {
throw new Error("Circular reference")
}
if (visitedRefs.size > 40) {
throw new Error("Exceeded max(40) reference count.")
}
visitedRefs.add(ref)
const definitions = (this.innerSwagger as any).definitions
if (definitions[model]) {
if (definitions[model].$ref) {
return this.dereferenceInner(definitions[model].$ref, visitedRefs)
} else {
return definitions[model]
}
} else {
throw new Error("Invalid reference:" + ref)
}
}
}
private dereference(ref: string) {
const model = this.getModelName(ref)
if (model) {
const refSet = new Set<string>()
return this.dereferenceInner(ref, refSet)
} else {
throw new Error("Invalid ref: " + ref)
}
}
private stringify(): string {
return json.stringify(this.innerSwagger as json.JsonObject)
}
private generateNew() {
writeFileSync(this.getResolvedPath(), this.stringify())
}
private parse(url: string, data: string) {
try {
this.innerSwagger = jsonParser.parse(url, data)
} catch (e) {
console.log(JSON.stringify(e))
}
}
public getSwaggerFolder(): string {
return this.file.split("/").slice(0, -1).join("/")
}
public getResolvedPath(): string {
return this.file.replace(".json", "-resolved.json")
}
public getLocation(jsonPath: string): FilePosition | undefined {
if (this.innerSwagger) {
try {
const pointer = pathToJsonPointer(jsonPath)
const value = jsonPointer.get(this.innerSwagger as object, pointer)
return getFilePosition(value)
} catch (e) {
console.log(JSON.stringify(e))
}
}
}
} | the_stack |
import { Component } from '@angular/core';
import { from } from 'rxjs';
import {
HMSAccount,
HMSHuaweiIdAuthButton,
HMSAccountAuthManager,
HMSReadSMSManager,
HMSAccountAuthService,
HMSHuaweiIdAuthManager,
HMSHuaweiIdAuthTool,
HMSNetworkTool,
AuthScopeList,
Theme,
ColorPolicy,
CornerRadius,
AuthRequestOption,
AuthParams,
SignInData,
Account,
Cookie,
DomainInfo
} from '@hmscore/ionic-native-hms-account/ngx';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
public accessToken:string;
constructor(private account: HMSAccount,
private smsManager: HMSReadSMSManager,
private authButton: HMSHuaweiIdAuthButton,
private accountAuthService: HMSAccountAuthService,
private authManager: HMSHuaweiIdAuthManager,
private accountAuthManager: HMSAccountAuthManager,
private authTool: HMSHuaweiIdAuthTool,
private tool: HMSNetworkTool) {
}
async signInWithIdToken() {
console.log('signInWithIdToken clicked!');
const signInParam: SignInData = {
"authRequestOption": [AuthRequestOption.SCOPE_ID_TOKEN],
"authParam": AuthParams.DEFAULT_AUTH_REQUEST_PARAM,
"authScopeList": [AuthScopeList.EMAIL, AuthScopeList.PROFILE]
}
try {
const res = await this.account.signIn(signInParam);
console.log(JSON.stringify(res));
alert('signIn -> success' + JSON.stringify(res));
} catch (ex) {
alert('signIn -> Error : ' + JSON.stringify(ex));
}
}
async signInAuthorizationCode() {
console.log('signInAuthorizationCode clicked!');
const signInParam: SignInData = {
"authRequestOption": [AuthRequestOption.SCOPE_AUTHORIZATION_CODE],
"authParam": AuthParams.DEFAULT_AUTH_REQUEST_PARAM_GAME
}
try {
const res = await this.account.signIn(signInParam);
console.log(JSON.stringify(res));
alert('signInAuthorizationCode -> success' + JSON.stringify(res));
} catch (ex) {
alert('signInAuthorizationCode -> Error : ' + JSON.stringify(ex));
}
}
async signOut() {
console.log('signOut clicked!');
try {
await this.account.signOut();
alert('signOut -> success');
} catch (ex) {
alert('signOut -> Error : ' + JSON.stringify(ex));
}
}
async cancelAuthorization() {
console.log('cancelAuthorization clicked!');
try {
await this.account.cancelAuthorization();
alert('cancelAuthorization -> success');
} catch (ex) {
alert('cancelAuthorization -> Error : ' + JSON.stringify(ex));
}
}
async silentSignIn() {
console.log('silentSignIn clicked!');
const huaweiIdAuthParam: AuthParams = AuthParams.DEFAULT_AUTH_REQUEST_PARAM;
try {
const res = await this.account.silentSignIn(huaweiIdAuthParam);
console.log(JSON.stringify(res));
alert('silentSignIn -> success :' + JSON.stringify(res));
} catch (ex) {
alert('silentSignIn -> Error : ' + JSON.stringify(ex));
}
}
async smsVerificationCode() {
console.log('smsVerificationCode clicked!');
try {
const res = await this.smsManager.smsVerificationCode();
alert('smsVerificationCode -> success :' + JSON.stringify(res));
} catch (ex) {
alert('smsVerificationCode -> Error : ' + JSON.stringify(ex));
}
}
async getHashCode() {
console.log('getHashCode clicked!');
try {
const res = await this.smsManager.obtainHashCode();
alert('hashCode -> success :' + JSON.stringify(res));
} catch (ex) {
alert('hashCode -> Error : ' + JSON.stringify(ex));
}
}
async startConsent() {
console.log('startConsent clicked!');
try {
const res = await this.smsManager.startConsent("phoneNumber");
alert('startConsent -> success :' + JSON.stringify(res));
} catch (ex) {
alert('startConsent -> Error : ' + JSON.stringify(ex));
}
}
async getHuaweiIdAuthButton() {
console.log('getHuaweiIdAuthButton clicked!');
const edittedButton = 'btn_auth_button';
this.authButton.getHuaweiIdAuthButton(edittedButton,
Theme.THEME_FULL_TITLE,
ColorPolicy.COLOR_POLICY_RED,
CornerRadius.CORNER_RADIUS_LARGE);
}
async accountSignInWithIdToken() {
console.log('accountSignInWithIdToken clicked!');
const signInParam: SignInData = {
"authRequestOption": [AuthRequestOption.SCOPE_ID_TOKEN,AuthRequestOption.SCOPE_ACCESS_TOKEN,AuthRequestOption.SCOPE_CARRIER_ID],
"authParam": AuthParams.DEFAULT_AUTH_REQUEST_PARAM,
"authScopeList": [AuthScopeList.EMAIL, AuthScopeList.PROFILE]
}
try {
const res = await this.accountAuthService.signIn(signInParam);
console.log(JSON.stringify(res));
this.accessToken = res.accessToken;
alert('signIn -> success' + JSON.stringify(res));
} catch (ex) {
alert('signIn -> Error : ' + JSON.stringify(ex));
}
}
async accountSignOut() {
console.log('signOut clicked!');
try {
await this.accountAuthService.signOut();
alert('signOut -> success');
} catch (ex) {
alert('signOut -> Error : ' + JSON.stringify(ex));
}
}
async accountSilentSignIn() {
console.log('silentSignIn clicked!');
const authParam: AuthParams = AuthParams.DEFAULT_AUTH_REQUEST_PARAM;
try {
const res = await this.accountAuthService.silentSignIn(authParam);
console.log(JSON.stringify(res));
alert('silentSignIn -> success :' + JSON.stringify(res));
} catch (ex) {
alert('silentSignIn -> Error : ' + JSON.stringify(ex));
}
}
async accountCancelAuthorization() {
console.log('cancelAuthorization clicked!');
try {
await this.accountAuthService.cancelAuthorization();
alert('cancelAuthorization -> success');
} catch (ex) {
alert('cancelAuthorization -> Error : ' + JSON.stringify(ex));
}
}
async accountGetChannel() {
console.log('getChannel clicked!');
try {
const res = await this.accountAuthService.getChannel();
alert('getChannel -> success' + JSON.stringify(res.description));
const bitmapData = "data:image/png;base64," + res.icon;
document.getElementById('img_bitmap').setAttribute('src', bitmapData);
} catch (ex) {
alert('getChannel -> Error : ' + JSON.stringify(ex));
}
}
async getIndependentSignIn() {
try {
const res = await this.accountAuthService.getIndependentSignIn(this.accessToken);
alert("getIndependentSignIn -> success :" + JSON.stringify(res));
} catch (ex) {
alert("getIndependentSignIn -> Error : " + JSON.stringify(ex));
}
}
async containScopes() {
console.log('containScopes clicked!');
const authHuaweiId = {
openId: "myOpenId",
uid: "myUid",
photoUriString: "myPhotoUrl",
displayName: "myDisplayName",
accessToken: "myAccessToken",
serviceCountryCode: "myServiceCountryCode",
gender: 0,
status: 2,
unionId: "myUnionId",
serverAuthCode: "myServerAuthCode",
countryCode: "myCountryCode",
grantedScopes: [AuthScopeList.OPENID, AuthScopeList.PROFILE, AuthScopeList.EMAIL],
}
const authScopeList = [AuthScopeList.OPENID, AuthScopeList.PROFILE];
try {
const containScopeRes = await this.authManager.containScopes(authHuaweiId, authScopeList);
alert('containScopes -> success: ' + JSON.stringify(containScopeRes));
} catch (ex) {
alert('containScopes -> Error : ' + JSON.stringify(ex));
}
}
async getAuthResult() {
console.log('getAuthResult clicked!');
try {
const lastAuthResult = await this.authManager.getAuthResult();
alert('getAuthResult -> success: ' + JSON.stringify(lastAuthResult));
} catch (ex) {
alert('getAuthResult -> Error : ' + JSON.stringify(ex));
}
}
async getAuthResultWithScopes() {
console.log('getAuthResultWithScopes clicked!');
const authScopeList = [AuthScopeList.OPENID, AuthScopeList.PROFILE];
try {
const authResultWithScope = await this.authManager.getAuthResultWithScope(authScopeList);
alert('getAuthResultWithScopes -> success: ' + JSON.stringify(authResultWithScope));
} catch (ex) {
alert('getAuthResultWithScopes -> Error : ' + JSON.stringify(ex));
}
}
async addAuthScopes() {
console.log('addAuthScopes clicked!');
const authScopeList = [AuthScopeList.EMAIL];
try {
const authScope = await this.authManager.addAuthScopes(8888, authScopeList);
alert('addAuthScopes -> success: ' + JSON.stringify(authScope));
} catch (ex) {
alert('addAuthScopes -> Error : ' + JSON.stringify(ex));
}
}
async accountContainScopes() {
console.log('containScopes clicked!');
const authHuaweiId = {
openId: "myOpenId",
uid: "myUid",
photoUriString: "myPhotoUrl",
displayName: "myDisplayName",
accessToken: "myAccessToken",
serviceCountryCode: "myServiceCountryCode",
gender: 0,
status: 2,
unionId: "myUnionId",
serverAuthCode: "myServerAuthCode",
countryCode: "myCountryCode",
grantedScopes: [AuthScopeList.OPENID, AuthScopeList.PROFILE, AuthScopeList.EMAIL],
}
const authScopeList = [AuthScopeList.OPENID, AuthScopeList.PROFILE];
try {
const containScopeRes = await this.accountAuthManager.containScopes(authHuaweiId, authScopeList);
alert('containScopes -> success: ' + JSON.stringify(containScopeRes));
} catch (ex) {
alert('containScopes -> Error : ' + JSON.stringify(ex));
}
}
async accountGetAuthResult() {
console.log('getAuthResult clicked!');
try {
const lastAuthResult = await this.accountAuthManager.getAuthResult();
alert('getAuthResult -> success: ' + JSON.stringify(lastAuthResult));
} catch (ex) {
alert('getAuthResult -> Error : ' + JSON.stringify(ex));
}
}
async accountGetAuthResultWithScopes() {
console.log('getAuthResultWithScopes clicked!');
const authScopeList = [AuthScopeList.OPENID, AuthScopeList.PROFILE];
try {
const authResultWithScope = await this.accountAuthManager.getAuthResultWithScope(authScopeList);
alert('getAuthResultWithScopes -> success: ' + JSON.stringify(authResultWithScope));
} catch (ex) {
alert('getAuthResultWithScopes -> Error : ' + JSON.stringify(ex));
}
}
async accountAddAuthScopes() {
console.log('addAuthScopes clicked!');
const authScopeList = [AuthScopeList.EMAIL];
try {
const authScope = await this.accountAuthManager.addAuthScopes(8888, authScopeList);
alert('addAuthScopes -> success: ' + JSON.stringify(authScope));
} catch (ex) {
alert('addAuthScopes -> Error : ' + JSON.stringify(ex));
}
}
async deleteAuthInfo() {
try {
const res = await this.authTool.deleteAuthInfo("accessTokenData");
alert("deleteAuthInfo -> success " + JSON.stringify(res));
} catch (ex) {
alert('deleteAuthInfo -> Error : ' + JSON.stringify(ex));
}
}
async requestUnionId() {
try {
const res = await this.authTool.requestUnionId("test@test.com");
alert("requestUnionId -> success " + JSON.stringify(res));
} catch (ex) {
alert('requestUnionId -> Error : ' + JSON.stringify(ex));
}
}
async requestAccessToken() {
const account: Account =
{
"type": "com.huawei.hwid",
"name": "test@test.com"
}
const scopeList = [AuthScopeList.EMAIL];
try {
const res = await this.authTool.requestAccessToken(account, scopeList);
alert("requestAccessToken -> success " + JSON.stringify(res));
} catch (ex) {
alert('requestAccessToken -> Error : ' + JSON.stringify(ex));
}
}
async buildNetworkURL() {
let domainInfo: DomainInfo = {
"domain": "www.demo.com",
"isUseHttps": true
}
try {
const res = await this.tool.buildNetworkURL(domainInfo);
console.log(JSON.stringify(res));
alert('buildNetworkURL -> success :' + JSON.stringify(res));
} catch (ex) {
alert('buildNetworkURL -> Error : ' + JSON.stringify(ex));
}
}
async buildNetworkCookie() {
const cookieInfo: Cookie = {
"cookieName": "hello",
"cookieValue": "world",
"domain": "www.demo.com",
"path": "/demo",
"isHttpOnly": true,
"isSecure": true,
"maxAge": 10
};
try {
const res = await this.tool.buildNetworkCookie(cookieInfo);
console.log(JSON.stringify(res));
alert('buildNetworkCookie -> success :' + JSON.stringify(res));
} catch (ex) {
alert('buildNetworkCookie -> Error : ' + JSON.stringify(ex));
}
}
} | the_stack |
import * as builder from 'botbuilder';
import * as async from 'async';
import * as Promise from 'promise';
import Consts = require('./Consts');
import zlib = require('zlib');
import { IStorageClient, IHttpResponse } from './IStorageClient';
import { AzureTableClient } from './AzureTableClient';
var azure = require('azure-storage');
export interface IAzureBotStorageOptions {
/** If true the data will be gzipped prior to writing to storage. */
gzipData?: boolean;
}
export class AzureBotStorage implements builder.IBotStorage {
private initializeTableClientPromise: Promise<boolean>;
private storageClientInitialized: boolean;
constructor(private options: IAzureBotStorageOptions, private storageClient?: IStorageClient) { }
public client(storageClient: IStorageClient) : this {
this.storageClient = storageClient;
return this;
}
/** Reads in data from storage. */
public getData(context: builder.IBotStorageContext, callback: (err: Error, data: builder.IBotStorageData) => void): void {
// We initialize on every call, but only block on the first call. The reason for this is that we can't run asynchronous initialization in the class ctor
this.initializeStorageClient().done(() => {
// Build list of read commands
var list: any[] = [];
if (context.userId) {
// Read userData
if (context.persistUserData) {
list.push({
partitionKey: context.userId,
rowKey: Consts.Fields.UserDataField,
field: Consts.Fields.UserDataField
});
}
if (context.conversationId) {
// Read privateConversationData
list.push({
partitionKey: context.conversationId,
rowKey: context.userId,
field: Consts.Fields.PrivateConversationDataField
});
}
}
if (context.persistConversationData && context.conversationId) {
// Read conversationData
list.push({
partitionKey: context.conversationId,
rowKey: Consts.Fields.ConversationDataField,
field: Consts.Fields.ConversationDataField
});
}
// Execute reads in parallel
var data: builder.IBotStorageData = {};
async.each(list, (entry, cb) => {
this.storageClient.retrieve(entry.partitionKey, entry.rowKey, function(error: any, entity: any, response: IHttpResponse){
if (!error) {
if(entity) {
let botData = entity.data || {};
let isCompressed = entity.isCompressed || false;
if (isCompressed) {
// Decompress gzipped data
zlib.gunzip(new Buffer(botData, Consts.base64), (err, result) => {
if (!err) {
try {
var txt = result.toString();
(<any>data)[entry.field + Consts.hash] = txt;
(<any>data)[entry.field] = txt != null ? JSON.parse(txt) : null;
} catch (e) {
err = e;
}
}
cb(err);
});
} else {
try {
(<any>data)[entry.field + Consts.hash] = botData ? JSON.stringify(botData) : null ;
(<any>data)[entry.field] = botData != null ? botData : null;
} catch (e) {
error = e;
}
cb(error);
}
} else {
(<any>data)[entry.field + Consts.hash] = null;
(<any>data)[entry.field] = null;
cb(error);
}
} else {
cb(error);
}
});
}, (err) => {
if (!err) {
callback(null, data);
} else {
var m = err.toString();
callback(err instanceof Error ? err : new Error(m), null);
}
});
}, (err) => callback(err, null));
}
/** Writes out data to storage. */
public saveData(context: builder.IBotStorageContext, data: builder.IBotStorageData, callback?: (err: Error) => void): void {
// We initialize on every call, but only block on the first call. The reason for this is that we can't run asynchronous initialization in the class ctor
let promise = this.initializeStorageClient();
promise.done(() => {
var list: any[] = [];
function addWrite(field: string, partitionKey: string, rowKey: string, botData: any) {
let hashKey = field + Consts.hash;
let hash = JSON.stringify(botData);
if (!(<any>data)[hashKey] || hash !== (<any>data)[hashKey]) {
(<any>data)[hashKey] = hash;
list.push({ field: field, partitionKey: partitionKey, rowKey: rowKey, botData: botData, hash: hash });
}
}
try {
// Build list of write commands
if (context.userId) {
if (context.persistUserData) {
// Write userData
addWrite(Consts.Fields.UserDataField, context.userId, Consts.Fields.UserDataField, data.userData);
}
if (context.conversationId) {
// Write privateConversationData
addWrite(Consts.Fields.PrivateConversationDataField, context.conversationId, context.userId, data.privateConversationData);
}
}
if (context.persistConversationData && context.conversationId) {
// Write conversationData
addWrite(Consts.Fields.ConversationDataField, context.conversationId, Consts.Fields.ConversationDataField, data.conversationData);
}
// Execute writes in parallel
async.each(list, (entry, errorCallback) => {
if (this.options.gzipData) {
zlib.gzip(entry.hash, (err, result) => {
if (!err && result.length > Consts.maxDataLength) {
err = new Error("Data of " + result.length + " bytes gzipped exceeds the " + Consts.maxDataLength + " byte limit. Can't post to: " + entry.url);
(<any>err).code = Consts.ErrorCodes.MessageSize;
}
if (!err) {
//Insert gzipped entry
this.storageClient.insertOrReplace(entry.partitionKey, entry.rowKey, result.toString('base64'), true, function(error: any, eTag: any, response: IHttpResponse){
errorCallback(error);
});
} else {
errorCallback(err);
}
});
} else if (entry.hash.length < Consts.maxDataLength) {
this.storageClient.insertOrReplace(entry.partitionKey, entry.rowKey, entry.botData, false, function(error: any, eTag: any, response: IHttpResponse){
errorCallback(error);
});
} else {
var err = new Error("Data of " + entry.hash.length + " bytes exceeds the " + Consts.maxDataLength + " byte limit. Consider setting connectors gzipData option. Can't post to: " + entry.url);
(<any>err).code = Consts.ErrorCodes.MessageSize;
errorCallback(err);
}
}, (err) => {
if (callback) {
if (!err) {
callback(null);
} else {
var m = err.toString();
callback(err instanceof Error ? err : new Error(m));
}
}
});
} catch (e) {
if (callback) {
var err = e instanceof Error ? e : new Error(e.toString());
(<any>err).code = Consts.ErrorCodes.BadMessage;
callback(err);
}
}
}, (err) => callback(err));
}
private initializeStorageClient(): Promise<boolean>{
if(!this.initializeTableClientPromise)
{
// The first call will trigger the initialization of the table client, which creates the Azure table if it
// does not exist. Subsequent calls will not block.
this.initializeTableClientPromise = new Promise<boolean>((resolve, reject) => {
this.storageClient.initialize(function(error: any){
if(error){
reject(new Error('Failed to initialize azure table client. Error: ' + error.toString()))
}
else{
resolve(true);
}
});
});
}
return this.initializeTableClientPromise;
}
} | the_stack |
import {
Observable,
combineLatest
} from 'rxjs';
import {
switchMap,
map,
shareReplay,
mergeMap,
filter,
tap
} from 'rxjs/operators';
import {
LogicInterface
} from '../../../../src/app/logic-interface.interface';
import {
createDatabase
} from './services/database.service';
import { Collection, Database, Q } from '@nozbe/watermelondb';
import {
Message,
UserWithLastMessage,
User,
AddMessage,
UserPair,
Search
} from '../../../../src/shared/types';
import {
lastOfArray,
sortByNewestFirst
} from 'src/shared/util-server';
import { MessageModel, UserModel } from './models';
export class Logic implements LogicInterface {
private dbPromise: Promise<Database> = createDatabase();
private db: Database;
constructor() {
this.dbPromise.then(db => this.db = db);
}
private get userCollection(): Collection<UserModel> {
return this.db.get<UserModel>('users');
}
private get messageCollection(): Collection<MessageModel> {
return this.db.get<MessageModel>('messages');
}
getUserByName(userName$: Observable<string>): Observable<User> {
return userName$.pipe(
// this is the first usage of this.db, so we have to await the creation
mergeMap((userName) => this.dbPromise.then(() => userName)),
switchMap((userName: string) => {
const query = this.userCollection.query(
Q.where('userId', Q.eq(userName))
);
const obs: Observable<UserModel[]> = query.observe() as any;
return obs.pipe(
map(list => list[0]),
filter(firstDoc => {
if (!firstDoc) {
console.warn('# user document not found ' + userName);
} else {
console.log('# user document found! ' + userName);
}
return !!firstDoc;
})
);
}),
map((doc: UserModel) => {
const ret: User = {
createdAt: doc.createdAt,
id: doc.userId
};
return ret;
}),
filter(doc => !!doc) as any
);
}
getSearchResults(search$: Observable<Search>): Observable<UserWithLastMessage[]> {
return search$.pipe(
switchMap(search => {
const user = search.ownUser;
const query = this.messageCollection.query(
Q.and(
Q.where('text', Q.like('%' + search.searchTerm + '%')),
Q.or(
Q.where('sender', Q.eq(user.id)),
Q.where('reciever', Q.eq(user.id))
)
)
);
const obs: Observable<MessageModel[]> = query.observe() as any;
return obs.pipe(
map(messageModels => messageModels.map(messageModel => messageModelToMessage(messageModel))),
map(messages => {
return {
search,
messages
}
})
);
}),
switchMap(async (searchWithMessages) => {
const search = searchWithMessages.search;
const messages: Message[] = searchWithMessages.messages;
const withUsers = await Promise.all(
messages.map(async (message) => {
let otherUser = message.sender;
if (otherUser === search.ownUser.id) {
otherUser = message.reciever;
}
const userModel = await this.userCollection.query(
Q.where('userId', Q.eq(otherUser))
).fetch();
return {
user: userModelToUser(userModel[0]),
message
};
})
);
return withUsers;
})
);
}
getUsersWithLastMessages(ownUser$: Observable<User>): Observable<UserWithLastMessage[]> {
const usersNotOwn$: Observable<UserModel[]> = ownUser$.pipe(
switchMap((ownUser: User) => {
const query = this.userCollection.query(
Q.where('userId', Q.notEq(ownUser.id))
).observe();
return query as any;
}) as any,
shareReplay(1)
);
const usersWithLastMessage$: Observable<UserWithLastMessage[]> = combineLatest([
ownUser$,
usersNotOwn$
]).pipe(
map(([ownUser, usersNotOwn]) => {
const obs = usersNotOwn.map(user => {
const ret = this.getLastMessageOfUserPair({
user1: ownUser,
user2: userModelToUser(user)
}).pipe(
map(message => ({
user: userModelToUser(user),
message: message ? message : undefined
})),
shareReplay(1)
);
return ret;
});
return obs;
}),
switchMap(usersWithLastMessage => combineLatest(usersWithLastMessage)),
map(usersWithLastMessage => {
return sortByNewestFirst(usersWithLastMessage as any);
})
);
return usersWithLastMessage$;
}
private getLastMessageOfUserPair(
userPair: UserPair
): Observable<Message | null> {
const query = this.messageCollection.query(
Q.or(
Q.and(
Q.where('sender', Q.eq(userPair.user1.id)),
Q.where('reciever', Q.eq(userPair.user2.id))
),
Q.and(
Q.where('sender', Q.eq(userPair.user2.id)),
Q.where('reciever', Q.eq(userPair.user1.id))
)
),
// Q.experimentalSortBy('createdAt', Q.desc)
);
const obs: Observable<MessageModel[]> = query.observe() as any;
return obs.pipe(
map((messageModels: MessageModel[]) => messageModels.map(messageModel => messageModelToMessage(messageModel))),
// experimentalSortBy does not work with lokijs adapter, so we sort by hand
map(messages => sortMessagesByCreatedAt(messages)),
map(messages => lastOfArray(messages))
);
}
getMessagesForUserPair(userPair$: Observable<UserPair>): Observable<Message[]> {
return userPair$.pipe(
switchMap((userPair: any) => {
const query = this.messageCollection.query(
Q.or(
Q.and(
Q.where('sender', Q.eq(userPair.user1.id)),
Q.where('reciever', Q.eq(userPair.user2.id))
),
Q.and(
Q.where('sender', Q.eq(userPair.user2.id)),
Q.where('reciever', Q.eq(userPair.user1.id))
)
),
// Q.experimentalSortBy('createdAt', Q.desc)
);
const obs: Observable<MessageModel[]> = query.observe() as any;
return obs;
}) as any,
map((messageModels: MessageModel[]) => messageModels.map(messageModel => messageModelToMessage(messageModel))),
// experimentalSortBy does not work with lokijs adapter, so we sort by hand
map(messages => sortMessagesByCreatedAt(messages)),
shareReplay()
);
}
async addMessage(message: AddMessage): Promise<any> {
await this.db.write(async () => {
this.messageCollection.create(messageModel => {
messageModel.messageId = message.message.id;
messageModel.text = message.message.text;
messageModel.createdAt = message.message.createdAt;
messageModel.read = message.message.read;
messageModel.sender = message.message.sender;
messageModel.reciever = message.message.reciever;
});
});
}
async addUser(user: User): Promise<any> {
await this.db.write(async () => {
this.userCollection.create(userModel => {
userModel.userId = user.id;
userModel.createdAt = user.createdAt;
});
});
}
async hasData(): Promise<boolean> {
await this.dbPromise;
// TODO limit=1 is not supported with lokijs adapter atm in watermelondb
const users = await this.userCollection.query(
).fetch();
return users.length > 0;
}
}
export function sortMessagesByCreatedAt(
messages: Message[]
): Message[] {
const ret = messages.sort(
(a, b) => {
const messageTimeA = a.createdAt;
const messageTimeB = b.createdAt;
if (messageTimeA === messageTimeB) {
return 0;
}
if (messageTimeA > messageTimeB) {
return 1;
} else {
return -1;
}
}
);
return ret;
}
function messageModelToMessage(messageModel: MessageModel): Message {
return {
id: messageModel.messageId,
read: messageModel.read,
reciever: messageModel.reciever,
sender: messageModel.sender,
text: messageModel.text,
createdAt: messageModel.createdAt
};
}
function userModelToUser(userModel: UserModel): User {
return {
id: userModel.userId,
createdAt: userModel.createdAt
};
} | the_stack |
import * as d3 from "d3";
import { assert } from "chai";
import * as sinon from "sinon";
import * as Plottable from "../../src";
import * as Mocks from "../mocks";
import * as TestMethods from "../testMethods";
describe("Component", () => {
const DIV_WIDTH = 400;
const DIV_HEIGHT = 300;
describe("anchoring", () => {
let c: Plottable.Component;
let div: d3.Selection<HTMLDivElement, any, any, any>;
beforeEach(() => {
c = new Plottable.Component();
div = TestMethods.generateDiv(DIV_WIDTH, DIV_HEIGHT);
});
it("adds itself as a child element of the input selection", () => {
assert.strictEqual(c.anchor(div), c, "setter returns calling object");
assert.strictEqual(<SVGElement> c.rootElement().node(),
div.node(), "component DOM elements are children of div element");
c.destroy();
div.remove();
});
it("adds default selections in the correct order", () => {
c.anchor(div);
assert.isFalse(c.foreground().empty(), "foreground exists in the DOM");
assert.isFalse(c.background().empty(), "background exists in the DOM");
assert.isFalse(c.content().empty(), "content exists in the DOM");
const componentElement = div.select(".component");
const containerNodes = componentElement.selectAll<Element, any>("svg").nodes();
assert.strictEqual(containerNodes[0], c.background().node(), "background at the back");
assert.strictEqual(containerNodes[1], c.content().node(), "content at the middle");
assert.strictEqual(containerNodes[2], c.foreground().node(), "foreground at the front");
c.destroy();
div.remove();
});
it("sets the foreground-container pointer-events to none", () => {
c.anchor(div);
const foreground = c.foreground().node();
const pointerEventForeground = window.getComputedStyle(<Element>foreground).pointerEvents;
assert.strictEqual(pointerEventForeground, "none", "foreground-container's pointer-event is set to none");
c.destroy();
div.remove();
});
it("classes the input with 'plottable' if it is a div", () => {
c.anchor(div);
assert.isTrue(div.classed("plottable"), "<div> was given \"plottable\" CSS class");
c.destroy();
div.remove();
});
it("allows mouse events to operate if the component is visible", () => {
c.anchor(div);
const computedStyle = window.getComputedStyle(<Element>div.node());
assert.strictEqual(computedStyle.pointerEvents.toLowerCase(), "visiblefill",
"\"pointer-events\" style set to \"visiblefill\"");
c.destroy();
div.remove();
});
it("can switch which element it is anchored to", () => {
c.anchor(div);
const div2 = TestMethods.generateDiv(DIV_WIDTH, DIV_HEIGHT);
c.anchor(div2);
assert.notStrictEqual(<SVGElement> c.rootElement().node(),
div.node(), "component DOM elements are not children of div element");
assert.strictEqual(<SVGElement> c.rootElement().node(),
div2.node(), "component DOM elements are children of second div element");
c.destroy();
div2.remove();
div.remove();
});
it("removes DOM elements in previous div when anchoring to a different div", () => {
c.anchor(div);
const div2 = TestMethods.generateDiv(DIV_WIDTH, DIV_HEIGHT);
c.anchor(div2);
assert.isTrue(div.select("svg").empty(), "previous div element should not have any group child nodes");
assert.isFalse(div2.select("svg").empty(), "new div element should have group child nodes");
c.destroy();
div.remove();
div2.remove();
});
it("can undergo set behavior upon anchoring", () => {
let callbackCalled = false;
let passedComponent: Plottable.Component;
const callback = (component: Plottable.Component) => {
callbackCalled = true;
passedComponent = component;
};
assert.strictEqual(c.onAnchor(callback), c, "setter returns calling object");
c.anchor(div);
assert.isTrue(callbackCalled, "callback was called on anchoring");
assert.strictEqual(passedComponent, c, "callback was passed anchored Component");
c.destroy();
div.remove();
});
it("undergoes on-anchor behavior if already anchored", () => {
let callbackCalled = false;
let passedComponent: Plottable.Component;
const callback = (component: Plottable.Component) => {
callbackCalled = true;
passedComponent = component;
};
c.anchor(div);
c.onAnchor(callback);
assert.isTrue(callbackCalled, "callback was immediately if Component was already anchored");
assert.strictEqual(passedComponent, c, "callback was passed the Component that anchored");
c.destroy();
div.remove();
});
it("calls callbacks upon anchoring to different div", () => {
let callbackCalled = false;
let passedComponent: Plottable.Component;
const callback = (component: Plottable.Component) => {
callbackCalled = true;
passedComponent = component;
};
c.onAnchor(callback);
c.anchor(div);
const div2 = TestMethods.generateDiv(DIV_WIDTH, DIV_HEIGHT);
callbackCalled = false;
c.anchor(div2);
assert.isTrue(callbackCalled, "callback was called on anchoring to a new <div>");
assert.strictEqual(passedComponent, c, "callback was passed anchored Component");
c.destroy();
div.remove();
div2.remove();
});
it("can remove set behavior the component would have underwent upon anchoring", () => {
let callbackCalled = false;
const callback = (component: Plottable.Component) => {
callbackCalled = true;
};
c.onAnchor(callback);
assert.strictEqual(c.offAnchor(callback), c, "setter returns calling object");
c.anchor(div);
assert.isFalse(callbackCalled, "removed callback is not called");
c.destroy();
div.remove();
});
it("overflow: visible by default", () => {
c.anchor(div);
const styles = window.getComputedStyle(<Element> c.content().node());
assert.strictEqual(styles.getPropertyValue("overflow"), "visible", "content has overflow: visible");
c.destroy();
div.remove();
});
it("sets overflow: hidden when _overflowHidden is set" ,() => {
(<any> c)._overflowHidden = true;
c.anchor(div);
const styles = window.getComputedStyle(<Element> c.content().node());
assert.strictEqual(styles.getPropertyValue("overflow"), "hidden", "content has overflow: hidden");
c.destroy();
div.remove();
});
});
describe("detaching", () => {
let c: Plottable.Component;
let div: d3.Selection<HTMLDivElement, any, any, any>;
beforeEach(() => {
c = new Plottable.Component();
div = TestMethods.generateDiv(DIV_WIDTH, DIV_HEIGHT);
});
it("can remove its own DOM elements", () => {
c.renderTo(div);
assert.isTrue((<Node> div.node()).hasChildNodes(), "the div has children");
c.detach();
assert.isFalse((<Node> div.node()).hasChildNodes(), "the div has no children");
c.destroy();
div.remove();
});
it("does not error if not already anchored", () => {
assert.doesNotThrow(() => c.detach(), Error, "does not throw error if detach() called before anchor()");
c.destroy();
div.remove();
});
it("sets its parent to null when detaching", () => {
const parent = new Plottable.Components.Group([c]);
c.detach();
assert.isNull(c.parent(), "parent removed upon detaching");
parent.destroy();
c.destroy();
div.remove();
});
it("can undergo set behavior upon detaching", () => {
c.renderTo(div);
let callbackCalled = false;
let passedComponent: Plottable.Component;
const callback = (component: Plottable.Component) => {
callbackCalled = true;
passedComponent = component;
};
assert.strictEqual(c.onDetach(callback), c, "setter returns calling object");
c.detach();
assert.isTrue(callbackCalled, "callback was called when the Component was detached");
assert.strictEqual(passedComponent, c, "callback was passed the Component that detached");
c.destroy();
div.remove();
});
it("calls callbacks upon detaching even if not anchored", () => {
let callbackCalled = false;
let passedComponent: Plottable.Component;
const callback = (component: Plottable.Component) => {
callbackCalled = true;
passedComponent = component;
};
c.onDetach(callback);
c.detach();
assert.isTrue(callbackCalled, "callback still called");
assert.strictEqual(passedComponent, c, "callback passed the Component that detached");
c.destroy();
div.remove();
});
it("can remove callbacks that would have been called upon detaching", () => {
let callbackCalled = false;
const callback = (component: Plottable.Component) => {
callbackCalled = true;
};
c.onDetach(callback);
assert.strictEqual(c.offDetach(callback), c, "setter calls calling object");
c.renderTo(div);
c.detach();
assert.isFalse(callbackCalled, "removed callback is not called");
c.destroy();
div.remove();
});
});
describe("parent container", () => {
let c: Plottable.Component;
let div: d3.Selection<HTMLDivElement, any, any, any>;
beforeEach(() => {
c = new Plottable.Component();
div = TestMethods.generateDiv(DIV_WIDTH, DIV_HEIGHT);
});
it("can set its parent to a container that contains this component", () => {
const acceptingContainer: any = {
has: () => true,
};
assert.strictEqual(c.parent(acceptingContainer), c, "setter returns calling object");
assert.strictEqual(c.parent(), acceptingContainer, "parent set if parent contains component");
c.destroy();
div.remove();
});
it("throws an error when the input parent does not contain this component", () => {
const rejectingContainer: any = {
has: (component: Plottable.Component) => false,
};
// HACKHACK: https://github.com/palantir/plottable/issues/2661 Cannot assert errors being thrown with description
(<any> assert).throws(() => c.parent(rejectingContainer), Error,
"invalid parent", "error thrown for parent not containing child");
c.destroy();
div.remove();
});
});
describe("css classes", () => {
let c: Plottable.Component;
let div: d3.Selection<HTMLDivElement, any, any, any>;
beforeEach(() => {
c = new Plottable.Component();
div = TestMethods.generateDiv(DIV_WIDTH, DIV_HEIGHT);
});
it("can add css classes", () => {
const className = "foo";
assert.strictEqual(c.addClass(className), c, "setter returns calling object");
assert.isTrue(c.hasClass(className), "component has added css class");
c.renderTo(div);
assert.isFalse(div.select(`.${className}`).empty(), "css class added to DOM element");
c.destroy();
div.remove();
});
it("can remove css classes", () => {
const className = "foo";
c.addClass(className);
assert.isTrue(c.hasClass(className), "component has added css class");
c.renderTo(div);
assert.strictEqual(c.removeClass(className), c, "setter returns calling object");
assert.isFalse(c.hasClass(className), "component no longer has css class");
assert.isTrue(div.select(`.${className}`).empty(), "css class removed from DOM element");
c.destroy();
div.remove();
});
});
describe("computing the layout", () => {
let c: Plottable.Component;
let div: d3.Selection<HTMLDivElement, any, any, any>;
beforeEach(() => {
c = new Plottable.Component();
div = TestMethods.generateDiv(DIV_WIDTH, DIV_HEIGHT);
});
it("defaults to take up all space", () => {
assert.isFalse(c.fixedWidth(), "will take all available width");
assert.isFalse(c.fixedHeight(), "will take all available height");
c.anchor(div);
c.computeLayout();
assert.strictEqual(c.width() , DIV_WIDTH, "takes all available width");
assert.strictEqual(c.height(), DIV_HEIGHT, "takes all available height");
const origin = c.origin();
assert.strictEqual(origin.x, 0 , "x origin defaults to leftmost");
assert.strictEqual(origin.y, 0 , "y origin defaults to topmost");
c.destroy();
div.remove();
});
it("does not allow the origin object to be modified", () => {
c.renderTo(div);
const receivedOrigin = c.origin();
const delta = 10;
receivedOrigin.x += delta;
receivedOrigin.y += delta;
assert.notDeepEqual(c.origin(), receivedOrigin, "underlying origin object cannot be modified");
c.destroy();
div.remove();
});
it("recomputes the layout if the environment changes", () => {
c.anchor(div);
c.computeLayout();
assert.strictEqual(c.width() , DIV_WIDTH, "takes all available width");
assert.strictEqual(c.height(), DIV_HEIGHT, "takes all available height");
div.style("width", 2 * DIV_WIDTH + "px").style("height", 2 * DIV_HEIGHT + "px");
c.computeLayout();
assert.strictEqual(c.width() , 2 * DIV_WIDTH, "updated to take new available width");
assert.strictEqual(c.height(), 2 * DIV_HEIGHT, "updated to take new available height");
c.destroy();
div.remove();
});
it("can compute the layout based on CSS", () => {
const parentWidth = 400;
const parentHeight = 200;
// Manually size parent
const parent = d3.select(<Element> div.node().parentNode);
parent.style("width", `${parentWidth}px`);
parent.style("height", `${parentHeight}px`);
// Remove width/height on div directly
div.style("width", null).style("height", null);
c.anchor(div);
c.computeLayout();
assert.strictEqual(c.width(), parentWidth, "defaults to width of parent");
assert.strictEqual(c.height(), parentHeight, "defaults to height of parent");
let origin = c.origin();
assert.strictEqual(origin.x, 0, "xOrigin defaulted to 0");
assert.strictEqual(origin.y, 0, "yOrigin defaulted to 0");
const divWidthPercentage = 50;
const divHeightPercentage = 50;
div.style("width", `${divWidthPercentage}%`).style("height", `${divHeightPercentage}%`);
c.computeLayout();
assert.strictEqual(c.width(), parentWidth * divWidthPercentage / 100, "width computed to be percentage of div width");
assert.strictEqual(c.height(), parentHeight * divHeightPercentage / 100, "height computed to be percentage of div height");
origin = c.origin();
assert.strictEqual(origin.x, 0, "xOrigin defaulted to 0");
assert.strictEqual(origin.y, 0, "yOrigin defaulted to 0");
// reset test page DOM
parent.style("width", "auto");
parent.style("height", "auto");
div.remove();
});
it("throws an error when computing the layout on an unanchored component", () => {
// HACKHACK: https://github.com/palantir/plottable/issues/2661 Cannot assert errors being thrown with description
(<any> assert).throws(() => c.computeLayout(), Error, "anchor() must be called before",
"cannot compute layout on an unanchored component");
div.remove();
});
it("computes the layout of the component based on input", () => {
const origin = {
x: 10,
y: 20,
};
const width = 100;
const height = 200;
c.anchor(div);
c.computeLayout(origin, width, height);
assert.strictEqual(c.origin().x, origin.x, "x origin set");
assert.strictEqual(c.origin().y, origin.y, "y origin set");
assert.strictEqual(c.width() , width, "width set");
assert.strictEqual(c.height(), height, "height set");
const componentElement = c.element();
const translate = [parseFloat(componentElement.style("left")), parseFloat(componentElement.style("top"))];
assert.deepEqual(translate, [origin.x, origin.y], "the element translated appropriately");
c.destroy();
div.remove();
});
it("allows for recomputing the layout and rendering", () => {
c.renderTo(div);
c.computeLayout({x: DIV_WIDTH / 4, y: DIV_HEIGHT / 4}, DIV_WIDTH / 4, DIV_HEIGHT / 4);
c.redraw();
const origin = c.origin();
assert.deepEqual(origin, {x: 0, y: 0}, "origin reset");
const componentElement = div.select(".component");
const translate = [parseFloat(componentElement.style("left")), parseFloat(componentElement.style("top"))];
assert.deepEqual(translate, [origin.x, origin.y], "DOM element rendered at new origin");
c.destroy();
div.remove();
});
it("calls onResize callback if callback is registered", (done) => {
const origin = {
x: 10,
y: 20,
};
const width = 100;
const height = 200;
c.anchor(div);
c.onResize((size: { height: number, width: number }) => {
assert.deepEqual(size, { width, height });
c.destroy();
div.remove();
done();
});
c.computeLayout(origin, width, height);
});
});
describe("computing the layout when of fixed size", () => {
let c: Plottable.Component;
let div: d3.Selection<HTMLDivElement, any, any, any>;
const fixedWidth = 100;
const fixedHeight = 100;
beforeEach(() => {
c = new Mocks.FixedSizeComponent(fixedWidth, fixedHeight);
div = TestMethods.generateDiv(DIV_WIDTH, DIV_HEIGHT);
c.anchor(div);
});
it("gives the component the fixed space if offered more space", () => {
c.computeLayout();
assert.strictEqual(c.width(), fixedWidth, "width bounded to fixed width");
assert.strictEqual(c.height(), fixedHeight, "height bounded to fixed height");
c.destroy();
div.remove();
});
it("gives the component the offered space if it is less than the fixed space", () => {
const restrictedWidth = fixedWidth / 2;
const restrictedHeight = fixedHeight / 2;
c.computeLayout({x: 0, y: 0}, restrictedWidth, restrictedHeight);
assert.strictEqual(c.width(), restrictedWidth, "width bounded to restricted width");
assert.strictEqual(c.height(), restrictedHeight, "height bounded to restricted height");
c.destroy();
div.remove();
});
it("does not translate if more space was requested than offered", () => {
const requestedWidth = DIV_WIDTH * 2;
const requestedHeight = DIV_HEIGHT * 2;
c.destroy();
c = new Mocks.FixedSizeComponent(requestedWidth, requestedHeight);
const t = new Plottable.Components.Table([[c]]);
t.renderTo(div);
const componentElement = div.select(".component");
const translate = [parseFloat(componentElement.style("left")), parseFloat(componentElement.style("top"))];
assert.deepEqual(translate, [0, 0], "the element was not translated");
div.remove();
});
});
describe("aligning", () => {
let c: Plottable.Component;
let div: d3.Selection<HTMLDivElement, any, any, any>;
beforeEach(() => {
c = new Plottable.Component();
div = TestMethods.generateDiv(DIV_WIDTH, DIV_HEIGHT);
});
it("defaults to a top and left alignment", () => {
assert.strictEqual(c.xAlignment(), Plottable.XAlignment.left, "x alignment defaults to \"left\"");
assert.strictEqual(c.yAlignment(), Plottable.YAlignment.top, "y alignment defaults to \"top\"");
c.destroy();
div.remove();
});
it("can set the alignment", () => {
const xAlignment = Plottable.XAlignment.right;
assert.strictEqual(c.xAlignment(xAlignment), c, "returns calling object");
assert.strictEqual(c.xAlignment(), xAlignment, "x alignment has been set");
const yAlignment = Plottable.YAlignment.bottom;
assert.strictEqual(c.yAlignment(yAlignment), c, "returns calling object");
assert.strictEqual(c.yAlignment(), yAlignment, "y alignment has been set");
c.destroy();
div.remove();
});
it("throws errors on bad alignments", () => {
const invalidAlignment = "foo" as any;
// HACKHACK: https://github.com/palantir/plottable/issues/2661 Cannot assert errors being thrown with description
(<any> assert).throws(() => c.xAlignment(invalidAlignment), Error,
"Unsupported alignment", "cannot set an invalid x alignment");
(<any> assert).throws(() => c.yAlignment(invalidAlignment), Error,
"Unsupported alignment", "cannot set an invalid y alignment");
c.destroy();
div.remove();
});
});
describe("aligning when of fixed size", () => {
let c: Plottable.Component;
let div: d3.Selection<HTMLDivElement, any, any, any>;
const fixedWidth = 100;
const fixedHeight = 100;
beforeEach(() => {
c = new Mocks.FixedSizeComponent(fixedWidth, fixedHeight);
div = TestMethods.generateDiv(DIV_WIDTH, DIV_HEIGHT);
c.anchor(div);
});
it("translates the origin in accordance with alignment", () => {
c.xAlignment(Plottable.XAlignment.left)
.yAlignment(Plottable.YAlignment.top);
c.computeLayout();
let expectedOrigin = {x: 0, y: 0};
assert.deepEqual(c.origin(), expectedOrigin, "top-left component aligns correctly");
c.xAlignment(Plottable.XAlignment.center)
.yAlignment(Plottable.YAlignment.center);
c.computeLayout();
expectedOrigin = {x: DIV_WIDTH / 2 - fixedWidth / 2, y: DIV_HEIGHT / 2 - fixedHeight / 2};
assert.deepEqual(c.origin(), expectedOrigin, "center component aligns correctly");
c.xAlignment(Plottable.XAlignment.right)
.yAlignment(Plottable.YAlignment.bottom);
c.computeLayout();
expectedOrigin = {x: DIV_WIDTH - fixedWidth, y: DIV_HEIGHT - fixedHeight};
assert.deepEqual(c.origin(), expectedOrigin, "bottom-right component aligns correctly");
c.destroy();
div.remove();
});
});
describe("calculating the minimum requested space", () => {
let c: Plottable.Component;
let div: d3.Selection<HTMLDivElement, any, any, any>;
beforeEach(() => {
c = new Plottable.Component();
div = TestMethods.generateDiv(DIV_WIDTH, DIV_HEIGHT);
});
it("does not request any space when offered a width and a height", () => {
const offeredWidth = 1;
const offeredHeight = 1;
const layout = c.requestedSpace(offeredWidth, offeredHeight);
assert.strictEqual(layout.minWidth, 0, "requested minWidth defaults to 0");
assert.strictEqual(layout.minHeight, 0, "requested minHeight defaults to 0");
div.remove();
});
});
describe("destroying", () => {
let c: Plottable.Component;
let div: d3.Selection<HTMLDivElement, any, any, any>;
beforeEach(() => {
c = new Plottable.Component();
div = TestMethods.generateDiv(DIV_WIDTH, DIV_HEIGHT);
});
it("cannot reanchor if destroyed", () => {
c.renderTo(div);
c.destroy();
// HACKHACK: https://github.com/palantir/plottable/issues/2661 Cannot assert errors being thrown with description
(<any> assert).throws(() => c.renderTo(div), "reuse", "cannot reanchor a destroyed component");
div.remove();
});
it("performs all of the same operations as detaching", () => {
let detachCalled = false;
c.detach = () => {
detachCalled = true;
return c;
};
c.destroy();
assert.isTrue(detachCalled, "detach called in destroy invocation");
div.remove();
});
});
describe("rendering on the anchored div", () => {
let c: Plottable.Component;
let div: d3.Selection<HTMLDivElement, any, any, any>;
beforeEach(() => {
c = new Plottable.Component();
div = TestMethods.generateDiv(DIV_WIDTH, DIV_HEIGHT);
});
it("performs all of the same operations as renderImmediately()", () => {
let renderFlag = false;
c.renderImmediately = () => {
renderFlag = true;
return c;
};
c.anchor(div);
c.computeLayout();
assert.strictEqual(c.render(), c, "returns calling object");
assert.isTrue(renderFlag, "renderImmediately() called in render invocation");
c.destroy();
div.remove();
});
it("does not render unless allocated space", () => {
let renderFlag = false;
c.renderImmediately = () => {
renderFlag = true;
return c;
};
c.anchor(div);
c.render();
assert.isFalse(renderFlag, "no render until width/height set to nonzero");
const offeredWidth = 10;
let offeredHeight = 0;
c.computeLayout({x: 0, y: 0}, offeredWidth, offeredHeight);
c.render();
assert.isTrue(renderFlag, "render still occurs if one of width/height is zero");
renderFlag = false;
offeredHeight = 10;
c.computeLayout({x: 0, y: 0}, offeredWidth, offeredHeight);
c.render();
assert.isTrue(renderFlag, "render occurs if width and height are positive");
c.destroy();
div.remove();
});
});
describe("rendering to a DOM node", () => {
let c: Plottable.Component;
let div: d3.Selection<HTMLDivElement, any, any, any>;
let renderFlag: boolean;
beforeEach(() => {
renderFlag = false;
c = new Plottable.Component();
div = TestMethods.generateDiv(DIV_WIDTH, DIV_HEIGHT);
c.renderImmediately = () => {
renderFlag = true;
return this;
};
});
afterEach(() => {
Plottable.RenderController.renderPolicy(Plottable.RenderController.Policy.immediate);
});
it("renders to a DOM node involves anchoring, layout computing, and actual rendering", () => {
assert.strictEqual(c.renderTo(div), c, "returns calling object");
assert.isTrue(div.classed("plottable"), "anchored to div");
assert.strictEqual(c.width(), DIV_WIDTH, "component takes up div width");
assert.strictEqual(c.height(), DIV_HEIGHT, "component takes up div height");
assert.isTrue(renderFlag, "component has rendered");
c.destroy();
div.remove();
});
it("only computes layout once", (done) => {
// use async rendering so flushing doesn't happen immediately
Plottable.RenderController.renderPolicy(Plottable.RenderController.Policy.animationFrame);
// set up a bar plot with a color scale
const colorScale = new Plottable.Scales.Color();
const xScale = new Plottable.Scales.Linear();
const yScale = new Plottable.Scales.Linear();
colorScale.autoDomain();
const barPlot = new Plottable.Plots.Bar();
barPlot.addDataset(new Plottable.Dataset([{x: 1, y: 1}]));
barPlot.x((d: any) => d.x, xScale);
barPlot.y((d: any) => d.y, yScale);
// hook up the colorScale to look at data from the bar plot
barPlot.attr("fill", (d) => d.x, colorScale);
// set up a legend to based on the colorScale. Legend will trigger an internal redraw() no the Table
// a second time; this test ensures that second redraw doesn't compute layout twice
const legend = new Plottable.Components.Legend(colorScale);
const table = new Plottable.Components.Table([[barPlot, legend]]);
const computeLayoutSpy = sinon.spy(table, "computeLayout");
table.renderTo(div);
assert.strictEqual(computeLayoutSpy.callCount, 1, "component only computes layout once");
table.destroy();
div.remove();
done();
});
it("renders to a node chosen through D3 selection", () => {
c.renderTo(div);
assert.isTrue(div.classed("plottable"), "anchored to div");
assert.isTrue(renderFlag, "component has rendered");
c.destroy();
div.remove();
});
it("renders to a node chosen through a selector string", () => {
const divId = "foo";
div.attr("id", divId);
c.renderTo(`#${divId}`);
assert.isTrue(div.classed("plottable"), "correct div chosen");
assert.isTrue(renderFlag, "component has rendered");
c.destroy();
div.remove();
});
it("renders to a node chosen through DOM element", () => {
c.renderTo(div.node());
assert.isTrue(div.classed("plottable"), "correct div chosen");
assert.isTrue(renderFlag, "component has rendered");
c.destroy();
div.remove();
});
it("errors on inputs that do not evaluate to an Element", () => {
(<any> assert).throws(() => c.renderTo("#not-an-element"), Error,
"Plottable requires a valid Element to renderTo", "rejects strings that don't correspond to DOM elements");
(<any> assert).throws(() => c.renderTo(d3.select(null) as any), Error,
"Plottable requires a valid Element to renderTo", "rejects empty d3 selections");
c.destroy();
div.remove();
});
it("detaches the component if rendering to a new div", () => {
const divHeight2 = 50;
const div2 = TestMethods.generateDiv(DIV_WIDTH, divHeight2);
c.renderTo(div);
assert.isTrue((<Node> div.node()).hasChildNodes(), "anchored onto div");
assert.strictEqual(c.height(), DIV_HEIGHT, "occupies entire space of div");
c.renderTo(div2);
assert.isFalse((<Node> div.node()).hasChildNodes(), "removed from div");
assert.isTrue((<Node> div2.node()).hasChildNodes(), "anchored onto second div");
assert.strictEqual(c.height(), divHeight2, "occupies entire space of second div");
c.destroy();
div2.remove();
div.remove();
});
});
describe("calculating the origin in relation to the div", () => {
let c: Plottable.Component;
let div: d3.Selection<HTMLDivElement, any, any, any>;
beforeEach(() => {
c = new Plottable.Component();
div = TestMethods.generateDiv(DIV_WIDTH, DIV_HEIGHT);
});
it("returns origin without a parent", () => {
assert.deepEqual(c.originToRoot(), c.origin(), "same as origin with no parent");
c.destroy();
div.remove();
});
it("is offset by the parent's origin", () => {
const parent = new Plottable.Components.Group([c]);
parent.anchor(div);
c.anchor(div);
parent.computeLayout({x: DIV_WIDTH / 4, y: DIV_HEIGHT / 4}, DIV_WIDTH / 2, DIV_HEIGHT / 2);
c.computeLayout({x: DIV_WIDTH / 4, y: DIV_HEIGHT / 4}, DIV_WIDTH / 4, DIV_HEIGHT / 4);
const originToRoot = {
x: parent.origin().x + c.origin().x,
y: parent.origin().y + c.origin().y,
};
assert.deepEqual(c.originToRoot(), originToRoot, "origin offsetted by parents");
parent.destroy();
c.destroy();
div.remove();
});
});
describe("calculating the bounds", () => {
let c: Plottable.Component;
let div: d3.Selection<HTMLDivElement, any, any, any>;
beforeEach(() => {
c = new Plottable.Component();
div = TestMethods.generateDiv(DIV_WIDTH, DIV_HEIGHT);
c.anchor(div);
c.computeLayout();
});
it("calculates the bounds relative to the origin", () => {
assert.deepEqual(c.bounds(), {
topLeft: c.origin(),
bottomRight: { x: DIV_WIDTH, y: DIV_HEIGHT },
});
c.destroy();
div.remove();
});
});
}); | the_stack |
/// <reference path="../typings/tsd.d.ts" />
import assert = require("assert");
import util = require("util");
import StringMap = require("../lib/StringMap");
import bmh = require("../lib/bmh");
import hir = require("./hir");
import OpCode = hir.OpCode;
class DynBuffer
{
buf: Buffer;
length: number = 0;
constructor (hint: number)
{
this.buf = new Buffer(hint);
}
reserve (extra: number, exactly: boolean): void
{
var rlen = this.length + extra;
var newLength: number;
if (!exactly) {
if (rlen <= this.buf.length)
return;
newLength = max(this.buf.length * 2, rlen);
} else {
if (rlen === this.buf.length)
return;
newLength = rlen;
}
var old = this.buf;
this.buf = new Buffer(newLength);
old.copy(this.buf, 0, 0, this.length);
}
addBuffer (s: Buffer, from: number, to: number): void
{
this.reserve(to - from, false);
s.copy(this.buf, this.length, from, to);
this.length += to - from;
}
addASCIIString (s: string): void
{
this.reserve(s.length, false);
var length = this.length;
for ( var i = 0, e = s.length; i < e; ++i )
this.buf[length++] = s.charCodeAt(i);
this.length = length;
}
}
/**
*
* @param s
* @param inComment tells us that we are in a C-style comment, so ["*","/"] must be escaped too
* @param from
* @param to
* @returns {Buffer}
*/
function escapeCStringBuffer (s: Buffer, inComment: boolean, from?: number, to?: number): Buffer
{
if (from === void 0)
from = 0;
if (to === void 0)
to = s.length;
var res: DynBuffer = null;
var lastIndex = from;
var lastByte: number = 0;
for ( var i = from; i < to; ++i ) {
var byte = s[i];
if (byte < 32 || byte > 127 || byte === 34 /*"*/ || byte === 92 /*backslash*/ ||
(byte === 63 /*?*/ && lastByte === 63 /*?*/) || // Trigraphs
(byte === 47 /*/*/ && lastByte === 42 /***/ && inComment) ||
(byte === 42 /***/ && lastByte === 47 /*/*/ && inComment))
{
if (!res)
res = new DynBuffer(to - from + 16);
if (lastIndex < i)
res.addBuffer(s, lastIndex, i);
lastIndex = i + 1;
switch (byte) { // TODO: more escapes
case 9: res.addASCIIString("\\t"); break;
case 10: res.addASCIIString("\\n"); break;
case 13: res.addASCIIString("\\r"); break;
case 34: res.addASCIIString('\\"'); break;
case 63: res.addASCIIString("\\?"); break;
case 92: res.addASCIIString("\\\\"); break;
case 42: res.addASCIIString("\\*"); break;
case 47: res.addASCIIString("\\/"); break;
default: res.addASCIIString(util.format("\\%d%d%d", byte/64&7, byte/8&7, byte&7)); break;
}
}
lastByte = byte;
}
if (res !== null) {
res.reserve(i - lastIndex, true)
if (lastIndex < i)
res.addBuffer(s, lastIndex, i);
return res.buf;
}
else {
if (from !== 0 || to !== s.length)
return s.slice(from, to);
else
return s;
}
}
function escapeCString (s: string, inComment: boolean): string
{
return escapeCStringBuffer(new Buffer(s, "utf8"),inComment).toString("ascii");
}
function bufferIndexOf (haystack: Buffer, haystackLen: number, needle: Buffer, startIndex: number = 0): number
{
// TODO: full Boyer-Moore, etc
// see http://stackoverflow.com/questions/3183582/what-is-the-fastest-substring-search-algorithm
var needleLen = needle.length;
// Utilize Boyer-Moore-Harspool for needles much smaller than the haystack
if (needleLen >= 8 && haystackLen - startIndex - needleLen > 1000)
return bmh.search(haystack, startIndex, haystackLen, needle);
for ( var i = 0, e = haystackLen - needleLen + 1; i < e; ++i ) {
var j: number;
for ( j = 0; j < needleLen && haystack[i+j] === needle[j]; ++j )
{}
if (j === needleLen)
return i;
}
return -1;
}
function max (a: number, b: number): number
{
return a > b ? a : b;
}
function min (a: number, b: number): number
{
return a < b ? a : b;
}
export class OutputSegment
{
private obuf: string[] = [];
public format (...params: any[]): void
{
this.obuf.push(util.format.apply(null, arguments));
}
public push (x: string): void
{
this.obuf.push(x);
}
public dump (out: NodeJS.WritableStream): void
{
for ( var i = 0, e = this.obuf.length; i < e; ++i )
out.write(this.obuf[i]);
}
}
function functionGen (m_backend: CXXBackend, m_fb: hir.FunctionBuilder, m_obuf: OutputSegment)
{
if (m_fb.isBuiltIn)
return;
generateC();
return;
function gen (...params: any[])
{
m_obuf.push(util.format.apply(null, arguments));
}
function strBlock (bb: hir.BasicBlock): string
{
return `b${bb.id}`;
}
function strEnvAccess (envLevel: number): string
{
if (envLevel < 0)
return "NULL";
if (envLevel === m_fb.getEnvLevel())
return "frame.escaped";
var path = "env";
for ( var f: hir.FunctionBuilder = m_fb; f = f.parentBuilder; ) {
if (f.getEnvLevel() === envLevel) {
return path;
} else if (f.getEnvSize() > 0) {
path += "->parent";
}
}
assert(false, util.format("cannot access envLevel %d from envLevel %d (%s)", envLevel, m_fb.getEnvLevel(), m_fb.name));
}
function strEscapingVar (v: hir.Var): string
{
assert(v.escapes, `variable ${v.name} is not marked as escaping`);
return util.format("%s->vars[%d]", strEnvAccess(v.envLevel), v.envIndex);
}
function strMemValue (lv: hir.MemValue): string
{
if (lv instanceof hir.Var) {
if (lv.local)
return strMemValue(lv.local);
else if (lv.param)
return strMemValue(lv.param);
else
return strEscapingVar(lv);
}
else if (lv instanceof hir.Param) {
if (lv.index === 0)
return `argv[${lv.index}]`; // "this" is always available
else
return `(argc > ${lv.index} ? argv[${lv.index}] : JS_UNDEFINED_VALUE)`;
}
else if (lv instanceof hir.ArgSlot) {
return strMemValue(lv.local);
}
else if (lv instanceof hir.Local) {
return `frame.locals[${lv.index}]`;
}
else if (lv instanceof hir.SystemReg) {
switch (lv) {
case hir.frameReg: return "&frame";
case hir.argcReg: return "argc";
case hir.argvReg: return "argv";
case hir.lastThrownValueReg: return "JS_GET_RUNTIME(&frame)->thrownObject";
}
}
assert(false, "unsupported LValue "+ lv);
return "???";
}
function strStringPrim(s: string): string
{
var res = "s_strings["+m_backend.addString(s)+"]";
if (s.length <= 64)
res += "/*\"" + escapeCString(s, true) + "\"*/";
return res;
}
function strNumberImmediate (n: number): string
{
if (isNaN(n))
return "NAN";
else if (!isFinite(n))
return n > 0 ? "INFINITY" : "-INFINITY";
else {
var res = String(n);
if ((n | 0) === n || (n >>> 0) === n) // is it an integer?
return res;
if (res.indexOf(".") < 0) // If there is no decimal point, we must add it
return res + ".0";
else
return res;
}
}
function strRValue (rv: hir.RValue): string
{
if (<any>rv instanceof hir.MemValue)
return strMemValue(<hir.MemValue>rv);
else if (rv === hir.undefinedValue)
return "JS_UNDEFINED_VALUE";
else if (rv === hir.nullValue)
return "JS_NULL_VALUE";
else if (typeof rv === "number")
return util.format("js::makeNumberValue(%s)", strNumberImmediate(rv));
else if (typeof rv === "boolean")
return `js::makeBooleanValue(${rv ? "true":"false"})`;
else if (typeof rv === "string")
return `js::makeStringValue(${strStringPrim(rv)})`;
else
return hir.rv2s(rv);
}
function strDest (v: hir.LValue): string
{
if (v !== hir.nullReg)
return util.format("%s = ", strMemValue(v));
else
return "";
}
function strToNumber (rv: hir.RValue): string
{
if (hir.isImmediate(rv)) {
var folded = hir.foldUnary(OpCode.TO_NUMBER, rv);
if (folded !== null)
return strNumberImmediate(<number>folded);
}
var callerStr: string = "&frame, ";
return util.format("js::toNumber(%s%s)", callerStr, strRValue(rv));
}
function strToInt32 (rv: hir.RValue): string
{
var callerStr: string = "&frame, ";
return hir.isImmediate(rv) ?
util.format("%d", hir.unwrapImmediate(rv)|0) :
util.format("js::toInt32(%s%s)", callerStr, strRValue(rv));
}
function strToUint32 (rv: hir.RValue): string
{
var callerStr: string = "&frame, ";
return hir.isImmediate(rv) ?
util.format("%d", hir.unwrapImmediate(rv)|0) :
util.format("js::toUint32(%s%s)", callerStr, strRValue(rv));
}
function strToString (rv: hir.RValue): string
{
if (hir.isImmediate(rv)) {
var folded = hir.foldUnary(OpCode.TO_STRING, rv);
if (folded !== null)
return strRValue(rv);
}
var callerStr: string = "&frame, ";
return util.format("js::toString(%s%s)", callerStr, strRValue(rv));
}
/**
* Unwrap a value which we know is numeric
* @param rv
*/
function strUnwrapN (rv: hir.RValue): string
{
return hir.isImmediate(rv) ? String(hir.unwrapImmediate(rv)) : util.format("%s.raw.nval", strRValue(rv));
}
function generateC (): void
{
gen("\n// %s\nstatic js::TaggedValue %s (js::StackFrame * caller, js::Env * env, unsigned argc, const js::TaggedValue * argv)\n{\n",
m_fb.name || "<unnamed>", m_backend.strFunc(m_fb)
);
var sourceFile: string = "NULL";
var sourceLine: number = 0;
if (hir.hasSourceLocation(m_fb)) {
sourceFile = '"'+ escapeCString(m_fb.fileName + ":" + (m_fb.name || "<unnamed>"), false) + '"';
sourceLine = m_fb.line;
}
gen(" js::StackFrameN<%d,%d,%d> frame(caller, env, %s, %d);\n",
m_fb.getEnvSize(), m_fb.getLocalsLength(), m_fb.getParamSlotsCount(),
sourceFile, sourceLine
);
for ( var i = 0, e = m_fb.getTryRecordCount(); i < e; ++i )
gen(" js::TryRecord tryRec%d;\n", i );
gen("\n");
// Keep track if the very last thing we generated was a label, so we can add a ';' after i
// at the end
var labelWasLast = false;
for ( var bi = 0, be = m_fb.getBlockListLength(); bi < be; ++bi ) {
var bb = m_fb.getBlock(bi);
labelWasLast = bb.body.length === 0;
gen("%s:\n", strBlock(bb));
for ( var ii = 0, ie = bb.body.length-1; ii < ie; ++ii )
generateInst(bb.body[ii]);
if (ie >= 0)
generateJump(bb.body[ii], bi < be - 1 ? m_fb.getBlock(bi+1) : null);
}
if (labelWasLast)
gen(" ;\n");
gen("}\n");
}
function generateCreate (createOp: hir.UnOp): void
{
var callerStr: string = "&frame, ";
gen(" %sjs::makeObjectValue(js::objectCreate(%s%s));\n",
strDest(createOp.dest), callerStr, strRValue(createOp.src1)
);
}
function generateCreateArguments (createOp: hir.UnOp): void
{
var frameStr = "&frame";
if (createOp.dest === hir.nullReg)
return;
gen(" %s = js::makeObjectValue(new (%s) js::Arguments(JS_GET_RUNTIME(%s)->objectPrototype));\n",
strMemValue(createOp.dest), frameStr, frameStr
);
gen(" ((js::Arguments*)%s.raw.oval)->init(%s, argc-1, argv+1);\n",
strRValue(createOp.dest), frameStr
);
}
function generateLoadSC (loadsc: hir.LoadSCOp): void
{
var src: string;
switch (loadsc.sc) {
case hir.SysConst.RUNTIME_VAR:
src = util.format("js::makeObjectValue(JS_GET_RUNTIME(&frame)->%s)", loadsc.arg);
break;
case hir.SysConst.ARGUMENTS_LEN:
src = "js::makeNumberValue(argc)";
break;
default:
assert(false, "Usupported sysconst "+ loadsc.sc);
return;
}
gen(" %s%s;\n", strDest(loadsc.dest), src);
}
function generateCallerLine(loc: hir.SourceLocation): void
{
if (m_backend.isDebugMode())
gen(" frame.setLine(%d);\n", loc.line);
}
function generateNumericBinop (binop: hir.BinOp, coper: string): void
{
gen(" %sjs::makeNumberValue(%s %s %s);\n", strDest(binop.dest),
strToNumber(binop.src1), coper, strToNumber(binop.src2));
}
function generateIntegerBinop (binop: hir.BinOp, coper: string, lsigned: boolean, rsigned: boolean): void
{
var l = lsigned ? strToInt32(binop.src1): strToUint32(binop.src1);
var r = rsigned ? strToInt32(binop.src2): strToUint32(binop.src2);
gen(" %sjs::makeNumberValue(%s %s %s);\n", strDest(binop.dest), l, coper, r);
}
/**
* A binary operator where we know the operands are numbers
* @param binop
* @param coper
*/
function generateBinop_N (binop: hir.BinOp, coper: string): void
{
gen(" %sjs::makeNumberValue(%s %s %s);\n", strDest(binop.dest),
strUnwrapN(binop.src1), coper, strUnwrapN(binop.src2));
}
function generateNumericUnop (unop: hir.UnOp, coper: string): void
{
gen(" %sjs::makeNumberValue(%s%s);\n", strDest(unop.dest),
coper, strToNumber(unop.src1));
}
function generateIntegerUnop (unop: hir.UnOp, coper: string): void
{
gen(" %sjs::makeNumberValue(%s%s);\n", strDest(unop.dest),
coper, strToInt32(unop.src1));
}
function generateDelete (binop: hir.BinOp): void
{
var callerStr = "&frame, ";
var expr: string = null;
if (hir.isString(binop.src2)) {
var strName: string = <string>hir.unwrapImmediate(binop.src2);
// IMPORTANT: string property names looking like integer numbers must be treated as
// computed properties
if (!hir.isValidArrayIndex(strName)) {
expr = util.format("%s.raw.oval->deleteProperty(%s%s)",
strRValue(binop.src1), callerStr, strStringPrim(strName)
);
}
}
if (expr === null)
expr = util.format("%s.raw.oval->deleteComputed(%s%s)",
strRValue(binop.src1), callerStr, strRValue(binop.src2)
);
gen(" %s%s;\n", strDest(binop.dest), expr);
}
function generateAsm (asm: hir.AsmOp): void
{
gen("{");
for ( var i = 0, e = asm.pat.length; i < e; ++i )
{
var pe = asm.pat[i];
if (typeof pe === "string") {
gen(<string>pe);
} else if (typeof pe === "number") {
gen("(%s)", strRValue(asm.bindings[<number>pe]));
} else
assert(false, "unsupported pattern value "+ pe);
}
gen(";}\n");
}
function generateBinopOutofline (binop: hir.BinOp): void
{
var callerStr: string = "&frame, ";
gen(" %sjs::operator_%s(%s%s, %s);\n",
strDest(binop.dest),
hir.oc2s(binop.op),
callerStr,
strRValue(binop.src1), strRValue(binop.src2)
);
}
function generateBinop (binop: hir.BinOp): void
{
var callerStr = "&frame, ";
switch (binop.op) {
case OpCode.ADD: generateBinopOutofline(binop); break;
case OpCode.ADD_N: generateNumericBinop(binop, "+"); break;
case OpCode.SUB_N: generateNumericBinop(binop, "-"); break;
case OpCode.MUL_N: generateNumericBinop(binop, "*"); break;
case OpCode.DIV_N: generateNumericBinop(binop, "/"); break;
case OpCode.MOD_N:
gen(" %sjs::makeNumberValue(fmod(%s, %s));\n", strDest(binop.dest),
strToNumber(binop.src1), strToNumber(binop.src2));
break;
case OpCode.SHL_N: generateIntegerBinop(binop, "<<", true, false); break;
case OpCode.SHR_N: generateIntegerBinop(binop, ">>", false, false); break;
case OpCode.ASR_N: generateIntegerBinop(binop, ">>", true, false); break;
case OpCode.OR_N: generateIntegerBinop(binop, "|", true, true); break;
case OpCode.XOR_N: generateIntegerBinop(binop, "^", true, true); break;
case OpCode.AND_N: generateIntegerBinop(binop, "&", true, true); break;
case OpCode.ASSERT_OBJECT:
gen(" if (!js::isValueTagObject(%s.tag)) js::throwTypeError(%s\"%%s\", %s.raw.sval->getStr());\n",
strRValue(binop.src1),
callerStr,
strToString(binop.src2)
);
if (binop.dest !== binop.src1 && binop.dest !== hir.nullReg)
gen(" %s%s;\n", strDest(binop.dest), strRValue(binop.src1));
break;
case OpCode.ASSERT_FUNC:
gen(" if (!js::isFunction(%s)) js::throwTypeError(%s\"%%s\", %s.raw.sval->getStr());\n",
strRValue(binop.src1),
callerStr,
strToString(binop.src2)
);
if (binop.dest !== binop.src1 && binop.dest !== hir.nullReg)
gen(" %s%s;\n", strDest(binop.dest), strRValue(binop.src1));
break;
case OpCode.DELETE:
generateDelete(binop);
break;
default:
if (hir.isBinopConditional(binop.op)) {
gen(" %sjs::makeBooleanValue(%s);\n",
strDest(binop.dest),
strIfOpCond(hir.binopToBincond(binop.op), binop.src1, binop.src2)
);
} else {
generateBinopOutofline(binop);
}
break;
}
}
function generateUnop (unop: hir.UnOp): void
{
var callerStr = "&frame, ";
switch (unop.op) {
case OpCode.NEG_N: generateNumericUnop(unop, "-"); break;
case OpCode.LOG_NOT:
gen(" %sjs::makeBooleanValue(!js::toBoolean(%s));\n", strDest(unop.dest), strRValue(unop.src1));
break;
case OpCode.BIN_NOT_N: generateIntegerUnop(unop, "~"); break;
case OpCode.TYPEOF:
gen(" %sjs::makeStringValue(js::operator_TYPEOF(%s%s));\n",
strDest(unop.dest), callerStr, strRValue(unop.src1)
);
break;
case OpCode.TO_NUMBER:
gen(" %sjs::makeNumberValue(%s);\n", strDest(unop.dest), strToNumber(unop.src1));
break;
case OpCode.TO_STRING:
gen(" %s%s;\n", strDest(unop.dest), strToString(unop.src1));
break;
case OpCode.TO_OBJECT:
gen(" %sjs::makeObjectValue(js::toObject(%s%s));\n",
strDest(unop.dest), callerStr, strRValue(unop.src1)
);
break;
default:
assert(false, "Unsupported instruction "+ unop);
break;
}
}
function generateGet (getop: hir.BinOp): void
{
var callerStr = "&frame, ";
if (hir.isString(getop.src2)) {
var strName: string = <string>hir.unwrapImmediate(getop.src2);
// IMPORTANT: string property names looking like integer numbers must be treated as
// computed properties
if (!hir.isValidArrayIndex(strName)) {
gen(" %sjs::get(%s%s, %s);\n",
strDest(getop.dest),
callerStr,
strRValue(getop.src1), strStringPrim(strName)
);
return;
}
}
gen(" %sjs::getComputed(%s%s, %s);\n",
strDest(getop.dest),
callerStr,
strRValue(getop.src1), strRValue(getop.src2)
);
}
function generatePut (putop: hir.PutOp): void
{
var callerStr = "&frame, ";
if (hir.isString(putop.propName)) {
var strName: string = <string>hir.unwrapImmediate(putop.propName);
// IMPORTANT: string property names looking like integer numbers must be treated as
// computed properties
if (!hir.isValidArrayIndex(strName)) {
gen(" js::put(%s%s, %s, %s);\n",
callerStr,
strRValue(putop.obj), strStringPrim(strName), strRValue(putop.src)
);
return;
}
}
gen(" js::putComputed(%s%s, %s, %s);\n",
callerStr,
strRValue(putop.obj), strRValue(putop.propName), strRValue(putop.src)
);
}
function generateInst(inst: hir.Instruction): void
{
switch (inst.op) {
case OpCode.CLOSURE:
var closureop = <hir.ClosureOp>inst;
//outCallerLine();
gen(" %sjs::newFunction(&frame, %s, %s, %d, %s);\n",
strDest(closureop.dest),
strEnvAccess(closureop.funcRef.getLowestEnvAccessed()),
closureop.funcRef.name ? strStringPrim(closureop.funcRef.name) : "NULL",
closureop.funcRef.getParamsLength()-1,
m_backend.strFunc(closureop.funcRef)
);
break;
case OpCode.CREATE: generateCreate(<hir.UnOp>inst); break;
case OpCode.CREATE_ARGUMENTS: generateCreateArguments(<hir.UnOp>inst); break;
case OpCode.LOAD_SC: generateLoadSC(<hir.LoadSCOp>inst); break;
case OpCode.END_TRY:
var endTryOp = <hir.EndTryOp>inst;
gen(" JS_GET_RUNTIME(&frame)->popTry(&tryRec%d);\n", endTryOp.tryId);
break;
case OpCode.ASM: generateAsm(<hir.AsmOp>inst); break;
case OpCode.ASSIGN:
var assignop = <hir.AssignOp>inst;
gen(" %s%s;\n", strDest(assignop.dest), strRValue(assignop.src1));
break;
case OpCode.GET: generateGet(<hir.BinOp>inst); break;
case OpCode.PUT: generatePut(<hir.PutOp>inst); break;
case OpCode.CALL:
// TODO: self tail-recursion optimization
var callop = <hir.CallOp>inst;
generateCallerLine(callop);
gen(" %s%s(&frame, %s, %d, &%s);\n",
strDest(callop.dest),
m_backend.strFunc(callop.fref),
strEnvAccess(callop.fref.getLowestEnvAccessed()),
callop.args.length,
strMemValue(callop.args[0])
);
break;
case OpCode.CALLIND:
var callop = <hir.CallOp>inst;
generateCallerLine(callop);
gen(" %sjs::call(&frame, %s, %d, &%s);\n",
strDest(callop.dest),
strRValue(callop.closure),
callop.args.length,
strMemValue(callop.args[0])
);
break;
case OpCode.CALLCONS:
var callop = <hir.CallOp>inst;
generateCallerLine(callop);
gen(" %sjs::callCons(&frame, %s, %d, &%s);\n",
strDest(callop.dest),
strRValue(callop.closure),
callop.args.length,
strMemValue(callop.args[0])
);
break;
default:
if (inst.op >= OpCode._BINOP_FIRST && inst.op <= OpCode._BINOP_LAST) {
generateBinop(<hir.BinOp>inst);
} else if (inst.op >= OpCode._UNOP_FIRST && inst.op <= OpCode._UNOP_LAST) {
generateUnop(<hir.UnOp>inst);
}
else {
assert(false, "Unsupported instruction "+ inst);
}
break;
}
}
function strIfIn (src1: hir.RValue, src2: hir.RValue): string
{
var callerStr = "&frame, ";
if (hir.isString(src1)) {
var strName: string = <string>hir.unwrapImmediate(src1);
// IMPORTANT: string property names looking like integer numbers must be treated as
// computed properties, but if not, we can go the faster way
if (!hir.isValidArrayIndex(strName)) {
return util.format("%s.raw.oval->hasProperty(%s)",
strRValue(src2), strStringPrim(strName)
);
}
}
return util.format("(%s.raw.oval->hasComputed(%s%s) != 0)",
strRValue(src2), callerStr, strRValue(src1)
);
}
function strIfOpCond (op: OpCode, src1: hir.RValue, src2: hir.RValue): string
{
var callerStr: string = "&frame, ";
var cond: string;
assert(op >= OpCode._IF_FIRST && op <= OpCode._IF_LAST);
switch (op) {
case OpCode.IF_TRUE:
cond = util.format("js::toBoolean(%s)", strRValue(src1));
break;
case OpCode.IF_IS_OBJECT:
cond = util.format("js::isValueTagObject(%s.tag)", strRValue(src1));
break;
case OpCode.IF_STRICT_EQ:
cond = util.format("operator_%s(%s, %s)",
hir.oc2s(op), strRValue(src1), strRValue(src2)
);
break;
case OpCode.IF_STRICT_NE:
cond = util.format("!operator_%s(%s, %s)",
hir.oc2s(OpCode.IF_STRICT_EQ), strRValue(src1), strRValue(src2)
);
break;
case OpCode.IF_LOOSE_EQ:
cond = util.format("operator_%s(%s%s, %s)",
hir.oc2s(op), callerStr, strRValue(src1), strRValue(src2)
);
break;
case OpCode.IF_LOOSE_NE:
cond = util.format("!operator_%s(%s%s, %s)",
hir.oc2s(OpCode.IF_LOOSE_EQ), callerStr, strRValue(src1), strRValue(src2)
);
break;
case OpCode.IF_IN:
cond = strIfIn(src1, src2);
break;
case OpCode.IF_INSTANCEOF:
cond = util.format("operator_IF_INSTANCEOF(%s%s, %s.raw.fval)",
callerStr, strRValue(src1), strRValue(src2)
);
break;
default:
if (op >= OpCode._BINCOND_FIRST && op <= OpCode._BINCOND_LAST) {
cond = util.format("operator_%s(%s%s, %s)",
hir.oc2s(op), callerStr, strRValue(src1), strRValue(src2)
);
} else {
cond = util.format("operator_%s(%s)", hir.oc2s(op), strRValue(src1));
}
break;
}
return cond;
}
/**
* Generate a jump instruction, taking care of the fall-through case.
* @param inst
* @param nextBB
*/
function generateJump (inst: hir.Instruction, nextBB: hir.BasicBlock): void
{
var callerStr: string = "&frame, ";
assert(inst instanceof hir.JumpInstruction);
var jump = <hir.JumpInstruction>inst;
var bb1 = jump.label1 && jump.label1.bb;
var bb2 = jump.label2 && jump.label2.bb;
switch (jump.op) {
case OpCode.RET:
var retop = <hir.RetOp>jump;
gen(" return %s;\n", strRValue(retop.src));
break;
case OpCode.THROW:
var throwOp = <hir.ThrowOp>jump;
gen(" js::throwValue(%s%s);\n", callerStr, strRValue(throwOp.src));
break;
case OpCode.GOTO:
if (bb1 !== nextBB)
gen(" goto %s;\n", strBlock(bb1));
break;
case OpCode.BEGIN_TRY:
var beginTryOp = <hir.BeginTryOp>jump;
gen(" JS_GET_RUNTIME(&frame)->pushTry(&tryRec%d);\n", beginTryOp.tryId);
gen(" if (::setjmp(tryRec%d.jbuf) == 0) goto %s; else goto %s;\n",
beginTryOp.tryId, strBlock(bb1), strBlock(bb2)
);
break;
case OpCode.SWITCH:
var switchOp = <hir.SwitchOp>jump;
gen(" switch ((int32_t)%s.raw.nval) {", strRValue(switchOp.selector));
for ( var i = 0; i < switchOp.values.length; ++i )
gen(" case %d: goto %s;", switchOp.values[i], strBlock(switchOp.targets[i].bb));
if (switchOp.label2)
if (bb2 !== nextBB)
gen(" default: goto %s;", strBlock(bb2));
gen(" };\n");
break;
default:
if (jump.op >= OpCode._IF_FIRST && jump.op <= OpCode._IF_LAST) {
var ifop = <hir.IfOp>jump;
var cond = strIfOpCond(ifop.op, ifop.src1, ifop.src2);
if (bb2 === nextBB)
gen(" if (%s) goto %s;\n", cond, strBlock(bb1));
else if (bb1 === nextBB)
gen(" if (!%s) goto %s;\n", cond, strBlock(bb2));
else
gen(" if (%s) goto %s; else goto %s;\n", cond, strBlock(bb1), strBlock(bb2));
} else {
assert(false, "unknown instructiopn "+ jump);
}
}
}
}
export class CXXBackend
{
private topLevel: hir.FunctionBuilder;
private asmHeaders : string[];
private debugMode: boolean;
private strings : string[] = [];
private stringMap = new StringMap<number>();
private codeSeg = new OutputSegment();
constructor (topLevel: hir.FunctionBuilder, asmHeaders: string[], debugMode: boolean)
{
this.topLevel = topLevel;
this.asmHeaders = asmHeaders;
this.debugMode = debugMode;
}
isDebugMode (): boolean
{
return this.debugMode;
}
addString (s: string): number {
var n: number;
if ( (n = this.stringMap.get(s)) === void 0) {
n = this.strings.length;
this.strings.push(s);
this.stringMap.set(s, n);
}
return n;
}
strFunc (fref: hir.FunctionBuilder): string
{
return fref.mangledName;
}
private gen (...params: any[])
{
this.codeSeg.push(util.format.apply(null, arguments));
}
private outputStringStorage (out: NodeJS.WritableStream): void
{
if (!this.strings.length)
return;
/* TODO: to generalized suffix tree mapping.
Something like this?
- sort strings in decreasing length
- start with an empty string buffer
- for each string
- if found in the string buffer use that position
- append to the string buffer
*/
var index: number[] = new Array<number>(this.strings.length);
var offsets: number[] = new Array<number>(this.strings.length);
var lengths: number[] = new Array<number>(this.strings.length);
// Sort the strings in decreasing length
var e = this.strings.length;
var i : number;
var totalLength = 0; // the combined length of all strings as initial guess for our buffer
for ( i = 0; i < e; ++i ) {
index[i] = i;
totalLength += this.strings[i].length;
}
index.sort( (a: number, b:number) => this.strings[b].length - this.strings[a].length);
var buf = new DynBuffer(totalLength);
for ( i = 0; i < e; ++i ) {
var ii = index[i];
var s = this.strings[ii];
var encoded = new Buffer(s, "utf8");
var pos: number = bufferIndexOf(buf.buf, buf.length, encoded);
if (pos < 0) { // Append to the buffer
pos = buf.length;
buf.addBuffer(encoded, 0, encoded.length);
}
offsets[ii] = pos;
lengths[ii] = encoded.length;
}
out.write(util.format("static const js::StringPrim * s_strings[%d];\n", this.strings.length));
out.write("static const char s_strconst[] =\n");
var line: string;
var margin = 72;
for ( var ofs = 0; ofs < buf.length; )
{
var to = min(buf.length, ofs + margin);
line = " \"" + escapeCStringBuffer(buf.buf, false, ofs, to) + "\"";
if (to === buf.length)
line += ";";
line += "\n";
out.write(line);
ofs = to;
}
line = util.format("static const unsigned s_strofs[%d] = {", this.strings.length*2);
for ( var i = 0; i < this.strings.length; ++i ) {
var t = util.format("%d,%d", offsets[i], lengths[i]);
if (line.length + t.length + 1 > margin) {
out.write(line += i > 0 ? ",\n" : "\n");
line = " "+t;
} else {
line += i > 0 ? "," + t : t;
}
}
line += "};\n\n";
out.write(line);
}
generateC (out: NodeJS.WritableStream, strictMode: boolean): void
{
var forEachFunc = (m_fb: hir.FunctionBuilder, cb: (m_fb: hir.FunctionBuilder)=>void) => {
if (m_fb !== this.topLevel)
cb(m_fb);
m_fb.closures.forEach((m_fb) => forEachFunc(m_fb, cb));
};
forEachFunc(this.topLevel, (m_fb) => {
if (!m_fb.isBuiltIn)
this.gen("static js::TaggedValue %s (js::StackFrame*, js::Env*, unsigned, const js::TaggedValue*); // %s\n",
this.strFunc(m_fb), m_fb.name || "<unnamed>"
);
});
this.gen("\n");
forEachFunc(this.topLevel, (m_fb) => functionGen(this, m_fb, this.codeSeg));
this.gen(
`
int main(int argc, const char ** argv)
{
js::g_runtime = new js::Runtime(${strictMode}, argc, argv);
js::StackFrameN<0, 1, 0> frame(NULL, NULL, __FILE__ ":main", __LINE__);
`
);
if (this.strings.length > 0) {
this.gen(util.format(
" JS_GET_RUNTIME(&frame)->initStrings(&frame, s_strings, s_strconst, s_strofs, %d);",
this.strings.length
));
}
this.gen(
`
frame.setLine(__LINE__+1);
frame.locals[0] = js::makeObjectValue(new(&frame) js::Object(JS_GET_RUNTIME(&frame)->objectPrototype));
frame.setLine(__LINE__+1);
${this.topLevel.closures[0].mangledName}(&frame, JS_GET_RUNTIME(&frame)->env, 1, frame.locals);
if (JS_GET_RUNTIME(&frame)->diagFlags & (js::Runtime::DIAG_HEAP_GC | js::Runtime::DIAG_FORCE_GC))
js::forceGC(&frame);
return 0;
}`
);
out.write(util.format("#include <jsc/jsruntime.h>\n"));
// Generate the headers added with __asmh__
this.asmHeaders.forEach((h: string) => out.write(util.format("%s\n", h)));
out.write("\n");
this.outputStringStorage(out);
this.codeSeg.dump(out);
}
} | the_stack |
import StateMachine from '../../src/app/app'
import StateMachineHistory from '../../src/plugins/history'
import LifecycleLogger from '../helpers/lifecycle_logger'
//-------------------------------------------------------------------------------------------------
test('history', () => {
const fsm = new StateMachine({
init: 'solid',
transitions: [
{ name: 'melt', from: 'solid', to: 'liquid' },
{ name: 'freeze', from: 'liquid', to: 'solid' },
{ name: 'vaporize', from: 'liquid', to: 'gas' },
{ name: 'condense', from: 'gas', to: 'liquid' }
],
plugins: [
StateMachineHistory
]
})
expect(fsm.state).toBe('solid'); expect(fsm.history).toEqual([ 'solid' ]);
fsm.melt(); expect(fsm.state).toBe('liquid'); expect(fsm.history).toEqual([ 'solid', 'liquid' ])
fsm.vaporize(); expect(fsm.state).toBe('gas'); expect(fsm.history).toEqual([ 'solid', 'liquid', 'gas' ])
fsm.condense(); expect(fsm.state).toBe('liquid'); expect(fsm.history).toEqual([ 'solid', 'liquid', 'gas', 'liquid' ]);
})
//-------------------------------------------------------------------------------------------------
test('history can be cleared', () => {
const fsm = new StateMachine({
transitions: [
{ name: 'init', from: 'none', to: 'A' },
{ name: 'step', from: 'A', to: 'B' },
{ name: 'step', from: 'B', to: 'C' },
{ name: 'step', from: 'C', to: 'A' }
],
plugins: [
StateMachineHistory
]
})
fsm.init()
fsm.step()
expect(fsm.state).toBe('B');
expect(fsm.history).toEqual(['A', 'B']);
fsm.clearHistory()
expect(fsm.state).toBe('B');
expect(fsm.history).toEqual([]);
})
//-------------------------------------------------------------------------------------------------
test('history does not record no-op transitions', () => {
const fsm = new StateMachine({
init: 'solid',
transitions: [
{ name: 'melt', from: 'solid', to: 'liquid' },
{ name: 'freeze', from: 'liquid', to: 'solid' },
{ name: 'vaporize', from: 'liquid', to: 'gas' },
{ name: 'condense', from: 'gas', to: 'liquid' },
{ name: 'noop', from: '*', to: '*' }
],
plugins: [
StateMachineHistory
]
})
expect(fsm.state).toBe('solid'); expect(fsm.history).toEqual([ 'solid' ]);
fsm.noop(); expect(fsm.state).toBe('solid'); expect(fsm.history).toEqual([ 'solid' ])
fsm.melt(); expect(fsm.state).toBe('liquid'); expect(fsm.history).toEqual([ 'solid', 'liquid' ])
fsm.noop(); expect(fsm.state).toBe('liquid'); expect(fsm.history).toEqual([ 'solid', 'liquid' ])
fsm.vaporize(); expect(fsm.state).toBe('gas'); expect(fsm.history).toEqual([ 'solid', 'liquid', 'gas' ])
fsm.noop(); expect(fsm.state).toBe('gas'); expect(fsm.history).toEqual([ 'solid', 'liquid', 'gas' ])
})
//-------------------------------------------------------------------------------------------------
test('history with configurable names', () => {
const fsm = new StateMachine({
init: 'solid',
transitions: [
{ name: 'melt', from: 'solid', to: 'liquid' },
{ name: 'freeze', from: 'liquid', to: 'solid' },
{ name: 'vaporize', from: 'liquid', to: 'gas' },
{ name: 'condense', from: 'gas', to: 'liquid' }
],
plugins: [
// @ts-ignore
new StateMachineHistory({ name: 'memory', future: 'yonder' })
]
})
expect(fsm.state).toBe('solid'); expect(fsm.memory).toEqual([ 'solid' ]);
fsm.melt(); expect(fsm.state).toBe('liquid'); expect(fsm.memory).toEqual([ 'solid', 'liquid' ])
fsm.vaporize(); expect(fsm.state).toBe('gas'); expect(fsm.memory).toEqual([ 'solid', 'liquid', 'gas' ])
fsm.condense(); expect(fsm.state).toBe('liquid'); expect(fsm.memory).toEqual([ 'solid', 'liquid', 'gas', 'liquid' ])
expect(fsm.canMemoryBack).toBe(true)
expect(fsm.canMemoryForward).toBe(false)
expect(fsm.yonder).toEqual([ ])
fsm.memoryBack()
expect(fsm.state).toBe('gas')
expect(fsm.memory).toEqual([ 'solid', 'liquid', 'gas' ])
expect(fsm.yonder).toEqual([ 'liquid' ])
fsm.clearMemory()
expect(fsm.memory).toEqual([])
expect(fsm.yonder).toEqual([])
})
//-------------------------------------------------------------------------------------------------
test('history, by default, just keeps growing', () => {
const fsm = new StateMachine({
init: 'solid',
transitions: [
{ name: 'melt', from: 'solid', to: 'liquid' },
{ name: 'freeze', from: 'liquid', to: 'solid' },
{ name: 'vaporize', from: 'liquid', to: 'gas' },
{ name: 'condense', from: 'gas', to: 'liquid' }
],
plugins: [
// @ts-ignore
new StateMachineHistory()
]
})
expect(fsm.state).toBe('solid')
expect(fsm.history).toEqual([ 'solid' ])
fsm.melt(); expect(fsm.history).toEqual([ 'solid', 'liquid' ])
fsm.vaporize(); expect(fsm.history).toEqual([ 'solid', 'liquid', 'gas' ])
fsm.condense(); expect(fsm.history).toEqual([ 'solid', 'liquid', 'gas', 'liquid' ])
fsm.freeze(); expect(fsm.history).toEqual([ 'solid', 'liquid', 'gas', 'liquid', 'solid' ])
fsm.melt(); expect(fsm.history).toEqual([ 'solid', 'liquid', 'gas', 'liquid', 'solid', 'liquid' ])
fsm.vaporize(); expect(fsm.history).toEqual([ 'solid', 'liquid', 'gas', 'liquid', 'solid', 'liquid', 'gas' ])
})
//-------------------------------------------------------------------------------------------------
test('history can be limited to N entries', () => {
const fsm = new StateMachine({
init: 'solid',
transitions: [
{ name: 'melt', from: 'solid', to: 'liquid' },
{ name: 'freeze', from: 'liquid', to: 'solid' },
{ name: 'vaporize', from: 'liquid', to: 'gas' },
{ name: 'condense', from: 'gas', to: 'liquid' }
],
plugins: [
// @ts-ignore
new StateMachineHistory({ max: 3 })
]
})
expect(fsm.state).toBe('solid')
expect(fsm.history).toEqual([ 'solid' ])
fsm.melt(); expect(fsm.history).toEqual([ 'solid', 'liquid' ])
fsm.vaporize(); expect(fsm.history).toEqual([ 'solid', 'liquid', 'gas' ])
fsm.condense(); expect(fsm.history).toEqual([ 'liquid', 'gas', 'liquid' ])
fsm.freeze(); expect(fsm.history).toEqual([ 'gas', 'liquid', 'solid' ])
fsm.melt(); expect(fsm.history).toEqual([ 'liquid', 'solid', 'liquid' ])
fsm.vaporize(); expect(fsm.history).toEqual([ 'solid', 'liquid', 'gas' ])
})
//-------------------------------------------------------------------------------------------------
test('history back and forward', () => {
const fsm = new StateMachine({
init: 'A',
transitions: [
{ name: 'step', from: 'A', to: 'B' },
{ name: 'step', from: 'B', to: 'C' },
{ name: 'step', from: 'C', to: 'D' }
],
plugins: [
StateMachineHistory
]
})
expect(fsm.state).toBe('A')
expect(fsm.canHistoryBack).toBe(false)
expect(fsm.history).toEqual([ 'A' ])
expect(fsm.future).toEqual([ ])
try {
fsm.historyBack()
} catch (e) {
expect(e.message).toBe('no history')
}
fsm.step()
fsm.step()
fsm.step()
expect(fsm.state).toBe('D')
expect(fsm.canHistoryBack).toBe(true)
expect(fsm.canHistoryForward).toBe(false)
expect(fsm.history).toEqual([ 'A', 'B', 'C', 'D' ])
expect(fsm.future).toEqual([])
fsm.historyBack()
expect(fsm.state).toBe('C')
expect(fsm.history).toEqual([ 'A', 'B', 'C' ])
expect(fsm.future).toEqual([ 'D' ])
expect(fsm.canHistoryBack).toBe(true)
expect(fsm.canHistoryForward).toBe(true)
fsm.historyBack()
expect(fsm.state).toBe('B')
expect(fsm.history).toEqual([ 'A', 'B' ])
expect(fsm.future).toEqual([ 'D', 'C' ])
expect(fsm.canHistoryBack).toBe(true)
expect(fsm.canHistoryForward).toBe(true)
fsm.historyBack()
expect(fsm.state).toBe('A')
expect(fsm.history).toEqual([ 'A' ])
expect(fsm.future).toEqual([ 'D', 'C', 'B' ])
expect(fsm.canHistoryBack).toBe(false)
expect(fsm.canHistoryForward).toBe(true)
fsm.historyForward()
expect(fsm.state).toBe('B')
expect(fsm.history).toEqual([ 'A', 'B' ])
expect(fsm.future).toEqual([ 'D', 'C' ])
expect(fsm.canHistoryBack).toBe(true)
expect(fsm.canHistoryForward).toBe(true)
fsm.historyForward()
expect(fsm.state).toBe('C')
expect(fsm.history).toEqual([ 'A', 'B', 'C' ])
expect(fsm.future).toEqual([ 'D' ])
expect(fsm.canHistoryBack).toBe(true)
expect(fsm.canHistoryForward).toBe(true)
fsm.step()
expect(fsm.state).toBe('D')
expect(fsm.history).toEqual([ 'A', 'B', 'C', 'D' ])
expect(fsm.future).toEqual([ ])
expect(fsm.canHistoryBack).toBe(true)
expect(fsm.canHistoryForward).toBe(false)
try {
fsm.historyForward()
} catch (e) {
expect(e.message).toBe('no history');
}
})
//-------------------------------------------------------------------------------------------------
test('history back and forward lifecycle events', () => {
// @ts-ignore
const logger = new LifecycleLogger(),
fsm = new StateMachine({
init: 'A',
transitions: [
{ name: 'step', from: 'A', to: 'B' },
{ name: 'step', from: 'B', to: 'C' },
{ name: 'step', from: 'C', to: 'D' }
],
methods: {
onBeforeTransition: logger,
onBeforeStep: logger,
onBeforeHistoryBack: logger,
onBeforeHistoryForward: logger,
onLeaveState: logger,
onLeaveA: logger,
onLeaveB: logger,
onLeaveC: logger,
onLeaveD: logger,
onTransition: logger,
onEnterState: logger,
onEnterA: logger,
onEnterB: logger,
onEnterC: logger,
onEnterD: logger,
onAfterTransition: logger,
onAfterStep: logger,
onAfterHistoryBack: logger,
onAfterHistoryForward: logger
},
plugins: [
StateMachineHistory
]
})
fsm.step()
fsm.step()
fsm.step()
logger.clear()
expect(fsm.state).toBe('D')
expect(fsm.history).toEqual([ 'A', 'B', 'C', 'D' ])
expect(fsm.future).toEqual([ ])
fsm.historyBack()
expect(fsm.state).toBe('C')
expect(fsm.history).toEqual([ 'A', 'B', 'C' ])
expect(fsm.future).toEqual([ 'D' ])
// console.log(logger.log);
expect(logger.log).toEqual([
{ event: 'onBeforeTransition', transition: 'historyBack', from: 'D', to: 'C', current: 'D' },
{ event: 'onBeforeHistoryBack', transition: 'historyBack', from: 'D', to: 'C', current: 'D' },
{ event: 'onLeaveState', transition: 'historyBack', from: 'D', to: 'C', current: 'D' },
{ event: 'onLeaveD', transition: 'historyBack', from: 'D', to: 'C', current: 'D' },
{ event: 'onTransition', transition: 'historyBack', from: 'D', to: 'C', current: 'D' },
{ event: 'onEnterState', transition: 'historyBack', from: 'D', to: 'C', current: 'C' },
{ event: 'onEnterC', transition: 'historyBack', from: 'D', to: 'C', current: 'C' },
{ event: 'onAfterTransition', transition: 'historyBack', from: 'D', to: 'C', current: 'C' },
{ event: 'onAfterHistoryBack', transition: 'historyBack', from: 'D', to: 'C', current: 'C' }
]);
logger.clear()
fsm.historyForward()
expect(fsm.state).toBe('D')
expect(fsm.history).toEqual([ 'A', 'B', 'C', 'D' ])
expect(fsm.future).toEqual([ ])
expect(logger.log).toEqual([
{ event: 'onBeforeTransition', transition: 'historyForward', from: 'C', to: 'D', current: 'C' },
{ event: 'onBeforeHistoryForward', transition: 'historyForward', from: 'C', to: 'D', current: 'C' },
{ event: 'onLeaveState', transition: 'historyForward', from: 'C', to: 'D', current: 'C' },
{ event: 'onLeaveC', transition: 'historyForward', from: 'C', to: 'D', current: 'C' },
{ event: 'onTransition', transition: 'historyForward', from: 'C', to: 'D', current: 'C' },
{ event: 'onEnterState', transition: 'historyForward', from: 'C', to: 'D', current: 'D' },
{ event: 'onEnterD', transition: 'historyForward', from: 'C', to: 'D', current: 'D' },
{ event: 'onAfterTransition', transition: 'historyForward', from: 'C', to: 'D', current: 'D' },
{ event: 'onAfterHistoryForward', transition: 'historyForward', from: 'C', to: 'D', current: 'D' }
])
})
//-------------------------------------------------------------------------------------------------
test('history can be used with a state machine factory', () => {
const FSM = StateMachine.factory({
init: 'solid',
transitions: [
{ name: 'melt', from: 'solid', to: 'liquid' },
{ name: 'freeze', from: 'liquid', to: 'solid' },
{ name: 'vaporize', from: 'liquid', to: 'gas' },
{ name: 'condense', from: 'gas', to: 'liquid' }
],
plugins: [
StateMachineHistory
]
})
const a = new FSM(),
b = new FSM();
expect(a.state).toBe('solid')
expect(b.state).toBe('solid')
expect(a.history).toEqual([ 'solid' ])
expect(b.history).toEqual([ 'solid' ])
a.melt()
a.vaporize()
a.condense()
a.freeze()
expect(a.state).toBe('solid')
expect(b.state).toBe('solid')
expect(a.history).toEqual([ 'solid', 'liquid', 'gas', 'liquid', 'solid' ])
expect(b.history).toEqual([ 'solid' ])
b.melt()
b.freeze()
expect(a.state).toBe('solid')
expect(b.state).toBe('solid')
expect(a.history).toEqual([ 'solid', 'liquid', 'gas', 'liquid', 'solid' ])
expect(b.history).toEqual([ 'solid', 'liquid', 'solid' ])
})
//-------------------------------------------------------------------------------------------------
test('history can be used with a singleton state machine applied to existing object', () => {
let fsm = {
name: 'jake'
}
// @ts-ignore
fsm = StateMachine.apply(fsm, {
init: 'solid',
transitions: [
{ name: 'melt', from: 'solid', to: 'liquid' },
{ name: 'freeze', from: 'liquid', to: 'solid' },
{ name: 'vaporize', from: 'liquid', to: 'gas' },
{ name: 'condense', from: 'gas', to: 'liquid' }
],
plugins: [
StateMachineHistory
]
})
expect(fsm.name).toBe('jake')
// @ts-ignore
expect(fsm.state).toBe('solid')
// @ts-ignore
expect(fsm.history).toEqual([ 'solid' ])
// @ts-ignore
fsm.melt();
// @ts-ignore
expect(fsm.state).toBe('liquid')
// @ts-ignore
expect(fsm.history).toEqual([ 'solid', 'liquid' ])
// @ts-ignore
fsm.vaporize();
// @ts-ignore
expect(fsm.state).toBe('gas')
// @ts-ignore
expect(fsm.history).toEqual([ 'solid', 'liquid', 'gas' ])
// @ts-ignore
fsm.condense()
// @ts-ignore
expect(fsm.state).toBe('liquid')
// @ts-ignore
expect(fsm.history).toEqual([ 'solid', 'liquid', 'gas', 'liquid' ])
})
//-------------------------------------------------------------------------------------------------
test('history can be used with a state machine factory applied to existing class', () => {
function FSM(this, name) {
this.name = name
// this._fsm()
}
const FSM2 = StateMachine.factory(FSM, {
init: 'solid',
transitions: [
{ name: 'melt', from: 'solid', to: 'liquid' },
{ name: 'freeze', from: 'liquid', to: 'solid' },
{ name: 'vaporize', from: 'liquid', to: 'gas' },
{ name: 'condense', from: 'gas', to: 'liquid' }
],
plugins: [
StateMachineHistory
]
})
const a = new FSM2('A'),
b = new FSM2('B');
expect(a.name).toBe('A')
expect(b.name).toBe('B')
expect(a.state).toBe('solid')
expect(b.state).toBe('solid')
expect(a.history).toEqual([ 'solid' ])
expect(b.history).toEqual([ 'solid' ])
a.melt()
a.vaporize()
a.condense()
a.freeze()
expect(a.state).toBe('solid')
expect(b.state).toBe('solid')
expect(a.history).toEqual([ 'solid', 'liquid', 'gas', 'liquid', 'solid' ])
expect(b.history).toEqual([ 'solid' ])
b.melt()
b.freeze()
expect(a.state).toBe('solid')
expect(b.state).toBe('solid')
expect(a.history).toEqual([ 'solid', 'liquid', 'gas', 'liquid', 'solid' ])
expect(b.history).toEqual([ 'solid', 'liquid', 'solid' ])
}) | the_stack |
import { Logger } from "@adpt/utils";
import stringify from "json-stable-stringify";
import { InternalError } from "../error";
import {
AdaptElement,
AdaptElementOrNull,
AnyProps,
isMountedElement,
} from "../jsx";
import {
Action,
ActionInfo,
ChangeType,
Plugin,
PluginOptions,
} from "./deploy_types";
export interface WidgetPair<E extends AdaptElement, O extends object> {
queryDomainKey: QueryDomainKey;
actionInfo: ActionInfo;
element?: E;
observed?: O;
}
type WidgetActions<E extends AdaptElement, O extends object> =
Record<ChangeType, WidgetPair<E, O>[]>;
export interface QueryDomain<Id, Secret> {
id: Id;
secret: Secret;
}
type QueryDomainKey = string;
export type WidgetId = string;
export interface WidgetChange<E extends AdaptElement> {
id: WidgetId;
from?: E;
to?: E;
}
interface Expected<E extends AdaptElement> {
[ queryDomainKey: string ]: WidgetChange<E>[];
}
export interface Observed<O extends object> {
[ queryDomainKey: string ]: O[];
}
type GetId<T extends object> = (o: T) => WidgetId;
type ComputeChanges<E extends AdaptElement, O extends object> =
(e: WidgetChange<E>, o: O | undefined) => ActionInfo;
type TranslateAction<
QD extends QueryDomain<any, any>,
E extends AdaptElement,
O extends object
> = (d: QD, p: WidgetPair<E, O>) => void | Promise<void>;
export abstract class WidgetPlugin<
WidgetElem extends AdaptElement,
WidgetObs extends object,
QDomain extends QueryDomain<any, any>,
> implements Plugin<Observed<WidgetObs>> {
deployID_?: string;
log_?: Logger;
dataDir_?: string;
queryDomains = new Map<QueryDomainKey, QDomain>();
/*
* Methods that each subclass is required to implement
*/
findElems: (dom: AdaptElementOrNull) => WidgetElem[];
getElemQueryDomain: (el: WidgetElem) => QDomain;
getWidgetTypeFromElem: (el: WidgetElem) => string;
getWidgetTypeFromObs: (obs: WidgetObs) => string;
getWidgetIdFromElem: (el: WidgetElem) => WidgetId;
getWidgetIdFromObs: (obs: WidgetObs) => WidgetId;
computeChanges: ComputeChanges<WidgetElem, WidgetObs>;
getObservations: (
domain: QDomain,
deployID: string,
elemsInQDomain: WidgetChange<WidgetElem>[]) => Promise<WidgetObs[]>;
createWidget: (
domain: QDomain, deployID: string,
resource: WidgetPair<WidgetElem, WidgetObs>) => Promise<void>;
destroyWidget: (
domain: QDomain, deployID: string,
resource: WidgetPair<WidgetElem, WidgetObs>) => Promise<void>;
modifyWidget: (
domain: QDomain, deployID: string,
resource: WidgetPair<WidgetElem, WidgetObs>) => Promise<void>;
/*
* Methods that implement the Plugin interface
*/
async start(options: PluginOptions) {
this.deployID_ = options.deployID;
this.log_ = options.log;
this.dataDir_ = options.dataDir;
}
createExpected(
oldDom: AdaptElementOrNull,
newDom: AdaptElementOrNull,
createQueryDomains = false): Expected<WidgetElem> {
const ret: Expected<WidgetElem> = {};
const changes = new Map<WidgetId, WidgetChange<WidgetElem>>();
const addElems = (dom: AdaptElementOrNull, type: "from" | "to") => {
this.findElems(dom).forEach((el) => {
const id = this.getWidgetIdFromElem(el);
let change = changes.get(id);
if (change) {
change[type] = el;
return;
}
change = { id, [type]: el };
changes.set(id, change);
const domain = this.getElemQueryDomain(el);
const qdKey = makeQueryDomainKey(domain);
const qdChangeList = ret[qdKey] || [];
ret[qdKey] = qdChangeList;
qdChangeList.push(change);
if (createQueryDomains && this.queryDomains.get(qdKey) == null) {
this.queryDomains.set(qdKey, domain);
}
});
};
addElems(oldDom, "from");
addElems(newDom, "to");
return ret;
}
async observe(oldDom: AdaptElementOrNull, dom: AdaptElementOrNull): Promise<Observed<WidgetObs>> {
const elemsInQDomain = this.createExpected(oldDom, dom, true);
const obs: Observed<WidgetObs> = {};
for (const [ key, domain ] of this.queryDomains.entries()) {
obs[key] = await this.getObservations(domain, this.deployID,
elemsInQDomain[key]);
}
return obs;
}
analyze(oldDom: AdaptElementOrNull, dom: AdaptElementOrNull, obs: Observed<WidgetObs>): Action[] {
const deployID = this.deployID;
const expected = this.createExpected(oldDom, dom);
const actions = diffObservations<WidgetElem, WidgetObs>(
expected,
obs,
(o) => this.getWidgetIdFromObs(o),
(el, o) => this.computeChanges(el, o)
);
const ret: Action[] = [];
this.translatePairs(ret, actions.create, "Creating",
(d, p) => this.createWidget(d, deployID, p));
this.translatePairs(ret, actions.modify, "Modifying",
(d, p) => this.modifyWidget(d, deployID, p));
this.translatePairs(ret, actions.replace, "Replacing",
async (d, p) => {
await this.destroyWidget(d, deployID, p);
await this.createWidget(d, deployID, p);
});
this.translatePairs(ret, actions.delete, "Destroying",
(d, p) => this.destroyWidget(d, deployID, p));
this.translatePairs(ret, actions.none, "Not modifying", () => {/**/});
return ret;
}
async finish() {
this.log_ = undefined;
}
/*
* Additional class methods
*/
get deployID(): string {
if (this.deployID_ == null) {
throw new InternalError(`deployID not initialized yet`);
}
return this.deployID_;
}
get dataDir(): string {
if (this.dataDir_ == null) {
throw new Error(`Internal error: dataDir not initialized yet`);
}
return this.dataDir_;
}
log = (arg: any, ...args: any[]): void => {
if (this.log_) this.log_(arg, ...args);
}
queryDomain(key: QueryDomainKey) {
return this.queryDomains.get(key);
}
widgetInfo(pair: WidgetPair<WidgetElem, WidgetObs>) {
let type: string;
let id: WidgetId;
let key: string | undefined;
const el = pair.element;
if (el != null) {
if (!isMountedElement(el)) throw new InternalError(`element not mounted`);
type = this.getWidgetTypeFromElem(el);
id = this.getWidgetIdFromElem(el);
key = el.props.key;
} else if (pair.observed !== undefined) {
type = this.getWidgetTypeFromObs(pair.observed);
id = this.getWidgetIdFromObs(pair.observed);
} else {
throw new InternalError(`WidgetPair with no content`);
}
return { type, id, key };
}
/**
* Translate WidgetPairs into plugin Actions
*/
translatePairs(
actions: Action[],
pairs: WidgetPair<WidgetElem, WidgetObs>[],
actionType: string,
action: TranslateAction<QDomain, WidgetElem, WidgetObs>
) {
for (const p of pairs) {
const { type, id, key } = this.widgetInfo(p);
const k = key ? ` '${key}'` : "";
const description = `${actionType} ${type}${k} (id=${id})`;
const domain = this.queryDomain(p.queryDomainKey);
if (domain == null) throw new InternalError(`domain null`);
actions.push({
...p.actionInfo,
act: async () => {
try {
await action(domain, p);
} catch (err) {
const path = p.element ? getPath(p.element) : "";
throw new Error(
`An error occurred while ${description}` +
`${path}: ${err.message || err}`);
}
}
});
}
}
}
function getPath(el: AdaptElement<AnyProps>): string {
if (isMountedElement(el)) return ` [${el.path}]`;
return "";
}
function makeQueryDomainKey(queryDomain: QueryDomain<any, any>): QueryDomainKey {
return stringify(queryDomain.id);
}
function diffArrays<E extends AdaptElement, O extends object>(
queryDomainKey: QueryDomainKey,
expected: WidgetChange<E>[],
observed: O[],
observedId: GetId<O>,
computeChanges: ComputeChanges<E, O>,
actions: WidgetActions<E, O>,
): void {
const obsMap = new Map(observed.map((o) => [observedId(o), o] as [string, O]));
let actionInfo: ActionInfo;
for (const e of expected) {
const o = obsMap.get(e.id);
if (o !== undefined) obsMap.delete(e.id);
actionInfo = computeChanges(e, o);
const pair = { queryDomainKey, actionInfo };
const actionList = actions[actionInfo.type];
switch (actionInfo.type) {
case ChangeType.create:
actionList.push({...pair, element: e.to});
break;
case ChangeType.none:
const element = e.to || e.from;
if (element == null) throw new InternalError(`WidgetChange with no 'from' or 'to' properties`);
actionList.push({...pair, element });
break;
case ChangeType.delete:
if (o == null) {
throw new Error(
`Error in deployment plugin. Plugin computeChanges ` +
`method returned ChangeType.delete for Element type ` +
`${e.from!.componentName} but no corresponding ` +
`object was observed in the environment.`);
}
actionList.push({...pair, observed: o});
break;
case ChangeType.modify:
case ChangeType.replace:
actionList.push({...pair, element: e.to, observed: o});
break;
}
}
for (const [id, o] of obsMap) {
actionInfo = computeChanges({id}, o);
actions.delete.push({queryDomainKey, actionInfo, observed: o});
}
}
function diffObservations<E extends AdaptElement, O extends object>(
expected: Expected<E>,
observed: Observed<O>,
observedId: GetId<O>,
computeChanges: ComputeChanges<E, O>,
): WidgetActions<E, O> {
const actions: WidgetActions<E, O> = {
create: [],
delete: [],
modify: [],
none: [],
replace: [],
};
// Clone so we can modify
observed = {...observed};
for (const key of Object.keys(expected)) {
diffArrays(key, expected[key], observed[key] || [],
observedId, computeChanges, actions);
delete observed[key];
}
for (const key of Object.keys(observed)) {
diffArrays(key, [], observed[key],
observedId, computeChanges, actions);
}
return actions;
} | the_stack |
import fs from "fs";
import protos from "google-ads-node/build/protos/protos.json";
import pluralize from "pluralize";
import { ServiceName } from "../src/protos";
import { toCamelCase } from "../src/utils";
import { googleAdsVersion } from "../src/version";
import { FILES } from "./path";
const VERSION = googleAdsVersion;
const IGNORED_SERVICES = ["GoogleAdsService", "GoogleAdsFieldService"];
const GOOGLE_ADS_DOCS_URL =
"https://developers.google.com/google-ads/api/reference";
const allServices =
protos.nested.google.nested.ads.nested.googleads.nested[VERSION].nested
.services.nested;
interface ProtoDefinition {
options?: Record<string, string>;
methods?: {
[methodName: string]: MethodDefinition;
};
fields?: {
[fieldName: string]: {
type: string;
id: number;
options?: Record<string, string | boolean>;
};
};
}
interface MethodDefinition {
requestType: string;
responseType: string;
options: Record<string, string>;
}
type MutateMethod = "create" | "update" | "remove";
interface MutateOptions {
hasOptions: boolean;
type: string;
}
export async function compileServices(): Promise<void> {
// Output file
const stream = fs.createWriteStream(FILES.services);
// TODO: This isn't ideal, maybe some kind of template instead?
stream.write(`
/* Autogenerated File! Do Not Edit */
import { ClientOptions } from "../../client";
import { CustomerOptions } from "../../types";
import { Service } from "../../service";
import { resources, services, protobuf, longrunning } from "../index";
import {
BaseMutationHookArgs,
HookedCancellation,
HookedResolution,
Hooks,
} from "../../hooks";
export default class ServiceFactory extends Service {
constructor(
clientOptions: ClientOptions,
customerOptions: CustomerOptions,
hooks?: Hooks
) {
super(clientOptions, customerOptions, hooks ?? {});
}
`);
for (const [name, service] of Object.entries<ProtoDefinition>(allServices)) {
// We only care about services, not request or response types
if (!name.endsWith("Service") || IGNORED_SERVICES.includes(name)) {
continue;
}
// Compiled service methods
const compiledMethods: string[] = [];
// Compiled inline types for a service
const serviceTypes: string[] = [];
// Give up if the service doesn't have any methods defined
if (!service.methods) {
continue;
}
for (const [methodName, methodDef] of Object.entries<MethodDefinition>(
service.methods
)) {
if (methodName.startsWith("Get")) {
const getMethod = compileGetMethod(methodName, methodDef);
compiledMethods.push(getMethod);
continue;
}
if (methodName.startsWith("Mutate")) {
const { mutateMethods, mutateOptions } = compileMutateMethods(
name,
methodName,
methodDef
);
compiledMethods.push(...mutateMethods);
if (mutateOptions.hasOptions) {
serviceTypes.push(mutateOptions.type);
} else {
serviceTypes.push("type MutateOptions = never");
}
continue;
}
const specialMethod = compileSpecialMethod(name, methodName, methodDef);
compiledMethods.push(specialMethod);
}
if (compiledMethods.length === 0) {
console.log(`No service methods compiled for "${name}"`);
continue;
}
const resourceName = name.replace("Service", "");
const pluralServiceName = pluralize(toCamelCase(resourceName));
const serviceInit = buildServiceInit(
`${name}Client` as ServiceName,
`services.${name}`
);
stream.write(`
/**
* @link ${GOOGLE_ADS_DOCS_URL}/rpc/${VERSION}/${name}
*/
public get ${pluralServiceName}() {
${serviceInit}
${serviceTypes.length > 0 ? serviceTypes.join("\n") : ""}
return {
${compiledMethods.join("\n,")}
}
}
`);
console.log(`Compiled service "${name}" → customer.${pluralServiceName}`);
}
stream.write("\n}");
}
function compileSpecialMethod(
serviceName: string,
methodName: string,
methodDef: MethodDefinition
): string {
const serviceMethod = toCamelCase(methodName);
const requestType = `services.${methodDef.requestType}`;
// Some special methods use types such as google.longrunning.Operation
const responseType = methodDef.responseType.includes("google.")
? methodDef.responseType.split("google.")[1]
: `services.${methodDef.responseType}`;
return `
/**
* @link ${GOOGLE_ADS_DOCS_URL}/rpc/${VERSION}/${serviceName}#${methodName.toLowerCase()}
*/
${serviceMethod}: async (request: ${requestType}): Promise<${responseType}> => {
try {
// @ts-expect-error Response is an array type
const [response] = await service.${serviceMethod}(request, {
// @ts-expect-error This arg doesn't exist in the type definitions
otherArgs: {
headers: this.callHeaders,
},
});
return response;
} catch (err) {
throw this.getGoogleAdsError(err);
}
}
`;
}
function compileGetMethod(
methodName: string,
methodDef: MethodDefinition
): string {
const serviceMethod = toCamelCase(methodName);
const requestType = `services.${methodDef.requestType}`;
const responseType = methodDef.responseType.split(`${VERSION}.`)[1];
return `
/**
* @description Retrieve a ${responseType} in full detail
* @warning Don't use get in production!
* @returns ${responseType}
*/
get: async (resourceName: string): Promise<${responseType}> => {
const request = new ${requestType}({
resource_name: resourceName,
});
try {
// @ts-expect-error Response is an array type
const [response] = await service.${serviceMethod}(request, {
// @ts-expect-error This arg doesn't exist in the type definitions
otherArgs: {
headers: this.callHeaders,
},
});
return response;
} catch (err) {
throw this.getGoogleAdsError(err);
}
}
`;
}
function compileMutateMethods(
serviceName: string,
methodName: string,
methodDef: MethodDefinition
): { mutateMethods: string[]; mutateOptions: MutateOptions } {
const mutateMethods: string[] = [];
const { requestType } = methodDef;
const req = (allServices as any)[requestType];
const opType = req.fields.operation ?? req.fields.operations;
const op = (allServices as any)[opType.type];
const methods = Object.keys(op.fields).filter((o) =>
["create", "update", "remove"].includes(o)
);
const serviceMethod = toCamelCase(methodName);
const resourceName = serviceName.replace("Service", "");
const argName = pluralize(toCamelCase(resourceName));
const types = {
resource: `resources.I${resourceName}`,
request: `services.I${methodDef.requestType}`,
requestClass: `resources.${resourceName}`,
operation: `services.${opType.type}`,
response: `services.${methodDef.responseType}`,
};
const options = Object.keys(req.fields).filter(
(k) => !["customer_id", "operations", "operation"].includes(k)
);
const mutateOptions = buildMutationOptions(types.request, options);
// create & update service methods
for (const method of methods) {
if (["create", "update"].includes(method)) {
mutateMethods.push(
buildMutateMethod(
serviceName,
method as MutateMethod,
argName,
types.resource,
types.request,
types.requestClass,
types.operation,
types.response,
serviceMethod,
options
)
);
}
}
// delete service method
if (methods.includes("remove")) {
mutateMethods.push(
buildMutateMethod(
serviceName,
"remove",
argName,
"string",
types.request,
types.requestClass,
types.operation,
types.response,
serviceMethod,
options
)
);
}
return { mutateMethods, mutateOptions };
}
function buildServiceInit(name: ServiceName, type: string): string {
return `const service = this.loadService<${type}>("${name}")`;
}
function buildMutationOptions(
requestType: string,
fields: string[]
): MutateOptions {
if (fields.length === 0) {
return {
hasOptions: false,
type: "",
};
}
const pickKeys = fields.map((f) => `"${f}"`).join("|");
return {
hasOptions: true,
type: `type MutateOptions = Partial<Pick<${requestType}, ${pickKeys}>>`,
};
}
function buildMutateMethod(
serviceName: string,
mutation: MutateMethod,
argName: string,
resourceType: string,
requestType: string,
requestClass: string,
operationType: string,
responseType: string,
methodName: string,
mutationOptions: string[]
): string {
const isUpdate = mutation === "update";
const updateMaskMessageArg = isUpdate ? `, ${requestClass}` : "";
return `
/**
* @description ${mutation} resources of type ${resourceType}
* @returns ${responseType}
*/
${mutation}: async (
${argName}: ${
mutation === "remove"
? `${resourceType}[]`
: `(${resourceType} | ${requestClass})[]`
} ,
options?: MutateOptions
): Promise<${responseType} > => {
const ops = this.buildOperations<
${operationType},
${resourceType}
>(
"${mutation}",
${argName}
${isUpdate ? "// @ts-expect-error Static class type here is fine" : ""}
${updateMaskMessageArg}
);
const request = this.buildRequest<
${operationType},
${requestType},
MutateOptions
>(ops, options);
${buildMutateHookStart(serviceName, methodName)}
try {
// @ts-expect-error Response is an array type
const [response] = await service.${methodName}(request, {
// @ts-expect-error This arg doesn't exist in the type definitions
otherArgs: {
headers: this.callHeaders,
},
});
${buildMutateHookEnd(
mutationOptions?.includes("partial_failure")
? `response: this.decodePartialFailureError(response)`
: "response"
)}
${
mutationOptions?.includes("partial_failure")
? `return this.decodePartialFailureError(response);`
: "return response;"
}
} catch (err) {
${buildMutateHookError()}
}
}
`;
}
function buildMutateHookStart(serviceName: string, methodName: string): string {
return `const baseHookArguments: BaseMutationHookArgs = {
credentials: this.credentials,
method: "${serviceName}.${methodName}",
mutation: request,
isServiceCall: true,
};
if (this.hooks.onMutationStart) {
const mutationCancellation: HookedCancellation = { cancelled: false };
await this.hooks.onMutationStart({
...baseHookArguments,
cancel: (res) => {
mutationCancellation.cancelled = true;
mutationCancellation.res = res;
},
editOptions: (options) => {
Object.entries(options).forEach(([key, val]) => {
// @ts-expect-error Index with key type is fine
request[key] = val;
});
},
});
if (mutationCancellation.cancelled) {
return mutationCancellation.res;
}
}`;
}
function buildMutateHookEnd(response: string) {
return `if (this.hooks.onMutationEnd) {
const mutationResolution: HookedResolution = { resolved: false };
await this.hooks.onMutationEnd({
...baseHookArguments,
${response},
resolve: (res) => {
mutationResolution.resolved = true;
mutationResolution.res = res;
},
});
if (mutationResolution.resolved) {
return mutationResolution.res;
}
}`;
}
function buildMutateHookError() {
return `const googleAdsError = this.getGoogleAdsError(err);
if (this.hooks.onMutationError) {
await this.hooks.onMutationError({
...baseHookArguments,
error: googleAdsError,
});
}
throw googleAdsError;`;
} | the_stack |
import { DataSet } from '@/lib/dataset';
import {
addLocalUniquesToDataset,
iterateRecords,
updateLocalUniquesFromDatabase,
} from '@/lib/dataset/helpers';
import {
_guessType,
inferTypeFromDataset,
MongoResults,
mongoResultsToDataset,
} from '@/lib/dataset/mongo';
/**
* helper functions to sort a dataset so that we can test output in a predictible way.
*
* @param dataset input dataset
* @return the sorted dataset
*/
function _sortDataset(dataset: DataSet): DataSet {
const sortedColumns = Array.from(dataset.headers).sort((col1, col2) =>
col1.name.localeCompare(col2.name),
);
const reorderMap = sortedColumns.map(colname => dataset.headers.indexOf(colname));
const sortedData = [];
for (const row of dataset.data) {
sortedData.push(reorderMap.map(newidx => row[newidx]));
}
return {
headers: sortedColumns,
data: sortedData,
paginationContext: dataset.paginationContext,
};
}
describe('_sortDataset tests', () => {
it('should be able to leave as is sorted results', () => {
const dataset: DataSet = {
headers: [{ name: 'col1' }, { name: 'col2' }, { name: 'col3' }],
data: [
[1, 2, 3],
[4, 5, 6],
],
paginationContext: { pageno: 1, pagesize: 50, totalCount: 2 },
};
const sorted = _sortDataset(dataset);
expect(sorted.headers).toEqual([{ name: 'col1' }, { name: 'col2' }, { name: 'col3' }]);
expect(sorted.data).toEqual([
[1, 2, 3],
[4, 5, 6],
]);
});
it('should be able to sort results', () => {
const dataset: DataSet = {
headers: [{ name: 'col3' }, { name: 'col1' }, { name: 'col4' }, { name: 'col2' }],
data: [
[1, 2, 3, 4],
[5, 6, 7, 8],
],
paginationContext: { pageno: 1, pagesize: 50, totalCount: 2 },
};
const sorted = _sortDataset(dataset);
expect(sorted.headers).toEqual([
{ name: 'col1' },
{ name: 'col2' },
{ name: 'col3' },
{ name: 'col4' },
]);
expect(sorted.data).toEqual([
[2, 4, 1, 3],
[6, 8, 5, 7],
]);
});
});
describe('Dataset helper tests', () => {
it('should be able to handle empty mongo results', () => {
const mongoResults: MongoResults = [];
const dataset = mongoResultsToDataset(mongoResults);
expect(dataset.headers).toEqual([]);
expect(dataset.data).toEqual([]);
});
it('should be able to convert homegeneous mongo results', () => {
const mongoResults: MongoResults = [
{ col1: 'foo', col2: 42, col3: true },
{ col1: 'bar', col2: 7, col3: false },
];
const dataset = _sortDataset(mongoResultsToDataset(mongoResults));
expect(dataset.headers).toEqual([{ name: 'col1' }, { name: 'col2' }, { name: 'col3' }]);
expect(dataset.data).toEqual([
['foo', 42, true],
['bar', 7, false],
]);
});
it('should be able to convert heterogeneous mongo results', () => {
const mongoResults: MongoResults = [
{ col1: 'foo', col3: true },
{ col1: 'bar', col2: 7, col4: '?' },
];
const dataset = _sortDataset(mongoResultsToDataset(mongoResults));
expect(dataset.headers).toEqual([
{ name: 'col1' },
{ name: 'col2' },
{ name: 'col3' },
{ name: 'col4' },
]);
expect(dataset.data).toEqual([
['foo', null, true, null],
['bar', 7, null, '?'],
]);
});
});
describe('_guessType', () => {
it('should return float', () => {
const val = _guessType(42.34);
expect(val).toEqual('float');
});
it('should return integer', () => {
const val = _guessType(42);
expect(val).toEqual('integer');
});
it('should return string', () => {
const val = _guessType('value');
expect(val).toEqual('string');
});
it('should return boolean', () => {
const val = _guessType(false);
expect(val).toEqual('boolean');
});
it('should return date', () => {
const val = _guessType(new Date());
expect(val).toEqual('date');
});
it('should return object', () => {
const val = _guessType({ value: 'my_value' });
expect(val).toEqual('object');
});
it('should return null when value is null', () => {
const val = _guessType(null);
expect(val).toEqual(null);
});
it('should return null when value is undefined', () => {
const val = _guessType(undefined);
expect(val).toEqual(null);
});
it('should return null when value is Symbol', () => {
const val = _guessType(Symbol());
expect(val).toEqual(null);
});
it('should return null when value is function', () => {
const val = _guessType(() => {});
expect(val).toEqual(null);
});
});
describe('inferTypeFromDataset', () => {
it('should guess the right type of the columns', () => {
const dataset: DataSet = {
headers: [{ name: 'city' }, { name: 'population' }, { name: 'isCapitalCity' }],
data: [
['Paris', 10000000, true],
['Marseille', 3000000, false],
['Berlin', 1300000, true],
['Avignon', 100000, false],
['La Souterraine', 0, false],
['New York City', 10000000, false],
['Rio de Janeiro', 4000000, false],
],
paginationContext: { pageno: 1, pagesize: 50, totalCount: 7 },
};
const datasetWithInferredType = inferTypeFromDataset(dataset);
expect(datasetWithInferredType.headers).toEqual([
{ name: 'city', type: 'string' },
{ name: 'population', type: 'integer' },
{ name: 'isCapitalCity', type: 'boolean' },
]);
});
it('should infer type even with mixed values if we set maxRows low enough', () => {
const dataset: DataSet = {
headers: [{ name: 'city' }, { name: 'population' }, { name: 'isCapitalCity' }],
data: [
['Paris', 10000000, true],
['Marseille', 3000000, false],
['Berlin', 1300000, true],
['Avignon', 100000, false],
['La Souterraine', 0, false],
['New York City', 10000000, false],
['Rio de Janeiro', 4000000, false],
[undefined, null, 10],
],
paginationContext: { pageno: 1, pagesize: 50, totalCount: 7 },
};
const datasetWithInferredType = inferTypeFromDataset(dataset, 7);
expect(datasetWithInferredType.headers).toEqual([
{ name: 'city', type: 'string' },
{ name: 'population', type: 'integer' },
{ name: 'isCapitalCity', type: 'boolean' },
]);
});
it('should not infer type with mixed values', () => {
const dataset: DataSet = {
headers: [{ name: 'city' }, { name: 'population' }, { name: 'isCapitalCity' }],
data: [
['Paris', 10000000, true],
['Marseille', 3000000, false],
['Berlin', 1300000, true],
['Avignon', 100000, false],
['La Souterraine', 0, false],
['New York City', 10000000, false],
['Rio de Janeiro', 4000000, false],
[undefined, false, 10],
],
paginationContext: { pageno: 1, pagesize: 50, totalCount: 8 },
};
const datasetWithInferredType = inferTypeFromDataset(dataset);
expect(datasetWithInferredType.headers).toEqual([
{ name: 'city' },
{ name: 'population' },
{ name: 'isCapitalCity' },
]);
});
it('should not infer type on column with undefined values', () => {
const dataset: DataSet = {
headers: [{ name: 'city' }, { name: 'population' }, { name: 'isCapitalCity' }],
data: [['Paris', 10000000, undefined]],
paginationContext: { pageno: 1, pagesize: 50, totalCount: 1 },
};
const datasetWithInferredType = inferTypeFromDataset(dataset, 1);
expect(datasetWithInferredType.headers).toEqual([
{ name: 'city', type: 'string' },
{ name: 'population', type: 'integer' },
{ name: 'isCapitalCity' },
]);
});
it('should not infer type on column with null values', () => {
const dataset: DataSet = {
headers: [{ name: 'city' }, { name: 'population' }, { name: 'isCapitalCity' }],
data: [['Paris', 10000000, null]],
paginationContext: { pageno: 1, pagesize: 50, totalCount: 1 },
};
const datasetWithInferredType = inferTypeFromDataset(dataset, 1);
expect(datasetWithInferredType.headers).toEqual([
{ name: 'city', type: 'string' },
{ name: 'population', type: 'integer' },
{ name: 'isCapitalCity' },
]);
});
it("should infer type on column with null values if there's other values in the column", () => {
const dataset: DataSet = {
headers: [{ name: 'city' }, { name: 'population' }, { name: 'isCapitalCity' }],
data: [
['Paris', 10000000, null],
['Paris', 10000000, false],
],
paginationContext: { pageno: 1, pagesize: 50, totalCount: 2 },
};
const datasetWithInferredType = inferTypeFromDataset(dataset);
expect(datasetWithInferredType.headers).toEqual([
{ name: 'city', type: 'string' },
{ name: 'population', type: 'integer' },
{ name: 'isCapitalCity', type: 'boolean' },
]);
});
it('should not infer type on column with symbol values', () => {
const dataset: DataSet = {
headers: [{ name: 'city' }, { name: 'population' }, { name: 'isCapitalCity' }],
data: [['Paris', 10000000, Symbol()]],
paginationContext: { pageno: 1, pagesize: 50, totalCount: 1 },
};
const datasetWithInferredType = inferTypeFromDataset(dataset, 1);
expect(datasetWithInferredType.headers).toEqual([
{ name: 'city', type: 'string' },
{ name: 'population', type: 'integer' },
{ name: 'isCapitalCity' },
]);
});
it('should not infer type on column with function values', () => {
const dataset: DataSet = {
headers: [{ name: 'city' }, { name: 'population' }, { name: 'isCapitalCity' }],
data: [['Paris', 10000000, () => {}]],
paginationContext: { pageno: 1, pagesize: 50, totalCount: 1 },
};
const datasetWithInferredType = inferTypeFromDataset(dataset, 1);
expect(datasetWithInferredType.headers).toEqual([
{ name: 'city', type: 'string' },
{ name: 'population', type: 'integer' },
{ name: 'isCapitalCity' },
]);
});
it('should not infer a float type for mixed integer and float values', () => {
const dataset: DataSet = {
headers: [{ name: 'city' }, { name: 'density' }, { name: 'isCapitalCity' }],
data: [
['Paris', 61.7, true],
['Marseille', 40, false],
['Berlin', 41.5, true],
],
paginationContext: { pageno: 1, pagesize: 50, totalCount: 1 },
};
const datasetWithInferredType = inferTypeFromDataset(dataset);
expect(datasetWithInferredType.headers).toEqual([
{ name: 'city', type: 'string' },
{ name: 'density', type: 'float' },
{ name: 'isCapitalCity', type: 'boolean' },
]);
});
});
describe('dataset records iteration', () => {
it('should handle empty datasets', () => {
const dataset: DataSet = { headers: [], data: [] };
expect(Array.from(iterateRecords(dataset))).toEqual([]);
});
it('should iterate on dataset records', () => {
const dataset: DataSet = {
headers: [{ name: 'city' }, { name: 'density' }, { name: 'isCapitalCity' }],
data: [
['Paris', 61.7, true],
['Marseille', 40, false],
['Berlin', 41.5, true],
],
};
expect(Array.from(iterateRecords(dataset))).toEqual([
{ city: 'Paris', density: 61.7, isCapitalCity: true },
{ city: 'Marseille', density: 40, isCapitalCity: false },
{ city: 'Berlin', density: 41.5, isCapitalCity: true },
]);
});
});
describe('dataset local uniques computation', () => {
it('should handle empty datasets with no columns', () => {
const dataset: DataSet = { headers: [], data: [] };
const extendedDataset = addLocalUniquesToDataset(dataset);
expect(dataset).toEqual({ headers: [], data: [] });
expect(extendedDataset).toEqual({
headers: [],
data: [],
});
});
it('should handle empty datasets with columns', () => {
const dataset: DataSet = { headers: [{ name: 'city' }, { name: 'density' }], data: [] };
const extendedDataset = addLocalUniquesToDataset(dataset);
expect(dataset).toEqual({ headers: [{ name: 'city' }, { name: 'density' }], data: [] });
expect(extendedDataset).toEqual({
headers: [
{ name: 'city', uniques: { values: [], loaded: true } },
{ name: 'density', uniques: { values: [], loaded: true } },
],
data: [],
});
});
it('should handle datasets with pagesize > totalCount', () => {
const dataset: DataSet = {
headers: [
{ name: 'city' },
{ name: 'density' },
{ name: 'isCapitalCity' },
{ name: 'population' },
],
data: [
['Paris', 61.7, true, { population: 9 }],
['Marseille', 40, false, { population: 4 }],
['Berlin', 41.5, true, { population: 3 }],
['Paris', 2, true, { population: 9 }],
],
paginationContext: {
pageno: 1,
totalCount: 10,
pagesize: 10,
},
};
const extendedDataset = addLocalUniquesToDataset(dataset);
expect(dataset).toEqual({
headers: [
{ name: 'city' },
{ name: 'density' },
{ name: 'isCapitalCity' },
{ name: 'population' },
],
data: [
['Paris', 61.7, true, { population: 9 }],
['Marseille', 40, false, { population: 4 }],
['Berlin', 41.5, true, { population: 3 }],
['Paris', 2, true, { population: 9 }],
],
paginationContext: {
pageno: 1,
totalCount: 10,
pagesize: 10,
},
});
expect(extendedDataset).toEqual({
headers: [
{
name: 'city',
uniques: {
values: [
{ value: 'Berlin', count: 1 },
{ value: 'Marseille', count: 1 },
{ value: 'Paris', count: 2 },
],
loaded: true,
},
},
{
name: 'density',
uniques: {
values: [
{ value: 2, count: 1 }, // result order depends on the other columns because they have all the same count
{ value: 40, count: 1 },
{ value: 41.5, count: 1 },
{ value: 61.7, count: 1 },
],
loaded: true,
},
},
{
name: 'isCapitalCity',
uniques: {
values: [
{ value: false, count: 1 },
{ value: true, count: 3 },
],
loaded: true,
},
},
{
name: 'population',
uniques: {
values: [
{ value: { population: 3 }, count: 1 },
{ value: { population: 4 }, count: 1 },
{ value: { population: 9 }, count: 2 },
],
loaded: true,
},
},
],
data: [
['Paris', 61.7, true, { population: 9 }],
['Marseille', 40, false, { population: 4 }],
['Berlin', 41.5, true, { population: 3 }],
['Paris', 2, true, { population: 9 }],
],
paginationContext: {
pageno: 1,
totalCount: 10,
pagesize: 10,
},
});
});
it('should handle datasets', () => {
const dataset: DataSet = {
headers: [
{ name: 'city' },
{ name: 'density' },
{ name: 'isCapitalCity' },
{ name: 'population' },
],
data: [
['Paris', 61.7, true, { population: 9 }],
['Marseille', 4, false, { population: 4 }],
['marseille', 35, false, { population: 4 }],
['Berlin', 41.5, true, { population: 3 }],
['Paris', 1, true, { population: 9 }],
['paris', 10, true, { population: 9 }],
],
paginationContext: {
pageno: 1,
totalCount: 100,
pagesize: 50,
},
};
const extendedDataset = addLocalUniquesToDataset(dataset);
expect(dataset).toEqual({
headers: [
{ name: 'city' },
{ name: 'density' },
{ name: 'isCapitalCity' },
{ name: 'population' },
],
data: [
['Paris', 61.7, true, { population: 9 }],
['Marseille', 4, false, { population: 4 }],
['marseille', 35, false, { population: 4 }],
['Berlin', 41.5, true, { population: 3 }],
['Paris', 1, true, { population: 9 }],
['paris', 10, true, { population: 9 }],
],
paginationContext: {
pageno: 1,
totalCount: 100,
pagesize: 50,
},
});
expect(extendedDataset).toEqual({
headers: [
{
name: 'city',
uniques: {
values: [
{ value: 'Berlin', count: 1 },
{ value: 'marseille', count: 1 },
{ value: 'Marseille', count: 1 },
{ value: 'paris', count: 1 },
{ value: 'Paris', count: 2 },
],
loaded: false,
},
},
{
name: 'density',
uniques: {
values: [
{ value: 1, count: 1 },
{ value: 4, count: 1 },
{ value: 10, count: 1 },
{ value: 35, count: 1 },
{ value: 41.5, count: 1 },
{ value: 61.7, count: 1 },
],
loaded: false,
},
},
{
name: 'isCapitalCity',
uniques: {
values: [
{ value: false, count: 2 },
{ value: true, count: 4 },
],
loaded: false,
},
},
{
name: 'population',
uniques: {
values: [
{ value: { population: 3 }, count: 1 },
{ value: { population: 4 }, count: 2 },
{ value: { population: 9 }, count: 3 },
],
loaded: false,
},
},
],
data: [
['Paris', 61.7, true, { population: 9 }],
['Marseille', 4, false, { population: 4 }],
['marseille', 35, false, { population: 4 }],
['Berlin', 41.5, true, { population: 3 }],
['Paris', 1, true, { population: 9 }],
['paris', 10, true, { population: 9 }],
],
paginationContext: {
pageno: 1,
totalCount: 100,
pagesize: 50,
},
});
});
});
describe('dataset update local Uniques', () => {
it('should update header of dataset', () => {
const datasetToUpdate = {
headers: [
{
name: 'city',
uniques: {
values: [
{ value: 'Paris', count: 2 },
{ value: 'Marseille', count: 1 },
{ value: 'Berlin', count: 1 },
],
loaded: false,
},
},
{
name: 'density',
uniques: {
values: [
{ value: 2, count: 1 },
{ value: 40, count: 1 },
{ value: 41.5, count: 1 },
{ value: 61.7, count: 1 },
],
loaded: false,
},
},
{
name: 'isCapitalCity',
uniques: {
values: [
{ value: true, count: 3 },
{ value: false, count: 1 },
],
loaded: false,
},
},
],
data: [
['Paris', 61.7, true],
['Marseille', 40, false],
['Berlin', 41.5, true],
['Paris', 2, true],
],
};
expect(
updateLocalUniquesFromDatabase(datasetToUpdate, {
headers: [{ name: 'city' }, { name: '__vqb_count__' }],
data: [
['Paris', 4],
['Marseille', 5],
['Berlin', 10],
['Washington', 2],
],
}),
).toEqual({
headers: [
{
name: 'city',
uniques: {
values: [
{ value: 'Berlin', count: 10 },
{ value: 'Marseille', count: 5 },
{ value: 'Paris', count: 4 },
{ value: 'Washington', count: 2 },
],
loaded: true,
},
},
{
name: 'density',
uniques: {
values: [
{ value: 2, count: 1 },
{ value: 40, count: 1 },
{ value: 41.5, count: 1 },
{ value: 61.7, count: 1 },
],
loaded: false,
},
},
{
name: 'isCapitalCity',
uniques: {
values: [
{ value: true, count: 3 },
{ value: false, count: 1 },
],
loaded: false,
},
},
],
data: [
['Paris', 61.7, true],
['Marseille', 40, false],
['Berlin', 41.5, true],
['Paris', 2, true],
],
});
});
it('should update dataset', () => {
const datasetToUpdate = {
headers: [
{
name: 'city',
uniques: {
values: [
{ value: 'Paris', count: 2 },
{ value: 'Marseille', count: 1 },
{ value: 'Berlin', count: 1 },
],
loaded: false,
},
},
{
name: 'density',
uniques: {
values: [
{ value: 2, count: 1 },
{ value: 40, count: 1 },
{ value: 41.5, count: 1 },
{ value: 61.7, count: 1 },
],
loaded: false,
},
},
{
name: 'isCapitalCity',
uniques: {
values: [
{ value: true, count: 3 },
{ value: false, count: 1 },
],
loaded: false,
},
},
],
data: [
['Paris', 61.7, true],
['Marseille', 40, false],
['Berlin', 41.5, true],
['Paris', 2, true],
],
};
expect(
updateLocalUniquesFromDatabase(datasetToUpdate, {
headers: [{ name: 'isCapitalCity' }, { name: '__vqb_count__' }],
data: [
[true, 16],
[false, 5],
],
}),
).toEqual({
headers: [
{
name: 'city',
uniques: {
values: [
{ value: 'Paris', count: 2 },
{ value: 'Marseille', count: 1 },
{ value: 'Berlin', count: 1 },
],
loaded: false,
},
},
{
name: 'density',
uniques: {
values: [
{ value: 2, count: 1 },
{ value: 40, count: 1 },
{ value: 41.5, count: 1 },
{ value: 61.7, count: 1 },
],
loaded: false,
},
},
{
name: 'isCapitalCity',
uniques: {
values: [
{ value: false, count: 5 },
{ value: true, count: 16 },
],
loaded: true,
},
},
],
data: [
['Paris', 61.7, true],
['Marseille', 40, false],
['Berlin', 41.5, true],
['Paris', 2, true],
],
});
});
}); | the_stack |
import * as fs from 'fs'
import * as path from 'path'
// ------------------------------------------------------------------------
// Error
// ------------------------------------------------------------------------
export class OptionsError extends Error {
constructor(public readonly option: string, public readonly reason: string) {
super(`${option}: ${reason}`)
}
}
// ------------------------------------------------------------------------
// Options
// ------------------------------------------------------------------------
export interface HelpOptions {
type: 'help'
message?: string
}
export interface VersionOptions {
type: 'version'
version: string
}
export interface BuildOptions {
type: 'build'
sourcePaths: string[]
target: string[]
dist: string
esm: boolean
platform: 'browser' | 'node'
minify: boolean
sourcemap: boolean
external: string[]
}
export interface WatchOptions {
type: 'watch'
sourcePaths: string[]
target: string[]
dist: string
esm: boolean
platform: 'browser' | 'node'
minify: boolean
sourcemap: boolean
external: string[]
}
export interface RunOptions {
type: 'start'
sourcePath: string
entryPath: string
args: string[]
dist: string
esm: boolean
target: string[]
minify: boolean
sourcemap: boolean
external: string[]
}
export interface ServeOptions {
type: 'serve'
sourcePaths: string[]
port: number
dist: string
esm: boolean
target: string[]
minify: boolean
sourcemap: boolean
external: string[]
}
export interface MonitorOptions {
type: 'monitor'
sourcePaths: string[]
arguments: string[]
}
export interface TaskOptions {
type: 'task'
sourcePath: string
name: string
arguments: string[]
}
export type Options =
| HelpOptions
| VersionOptions
| BuildOptions
| WatchOptions
| RunOptions
| ServeOptions
| MonitorOptions
| TaskOptions
// ------------------------------------------------------------------------
// Defaults
// ------------------------------------------------------------------------
function defaultHelpOptions(message?: string): HelpOptions {
return { type: 'help', message }
}
function defaultVersionOptions(): VersionOptions {
return { type: 'version', version: 'resolve from package.json' }
}
function defaultBuildOptions(): BuildOptions {
return {
type: 'build',
dist: path.join(process.cwd(), 'dist'),
esm: false,
minify: false,
platform: 'browser',
sourcePaths: [],
sourcemap: false,
target: ['esnext'],
external: []
}
}
function defaultWatchOptions(): WatchOptions {
return {
type: 'watch',
dist: path.join(process.cwd(), 'dist'),
esm: false,
minify: false,
platform: 'browser',
sourcePaths: [],
sourcemap: false,
target: ['esnext'],
external: []
}
}
function defaultServeOptions(): ServeOptions {
return {
type: 'serve',
sourcePaths: [],
dist: path.join(process.cwd(), 'dist'),
esm: false,
target: ['esnext'],
port: 5000,
sourcemap: false,
minify: false,
external: []
}
}
function defaultRunOptions(): RunOptions {
return {
type: 'start',
sourcePath: 'index.ts',
entryPath: path.join(process.cwd(), 'dist', 'index.js'),
args: [],
dist: path.join(process.cwd(), 'dist'),
esm: false,
target: ['esnext'],
sourcemap: false,
minify: false,
external: []
}
}
function defaultMonitorOptions(): MonitorOptions {
return {
type: 'monitor',
sourcePaths: [],
arguments: []
}
}
function defaultTaskOptions(): TaskOptions {
return {
type: 'task',
sourcePath: path.join(process.cwd(), 'hammer.mjs'),
name: '',
arguments: []
}
}
// ------------------------------------------------------------------------
// Preparation
// ------------------------------------------------------------------------
function prepareArguments(args: string[]): string[] {
let open = false
const result = []
const temp = []
while (args.length > 0) {
const next = args.shift()!
if(!open && next.indexOf('"') === 0 && next.lastIndexOf('"') !== next.length - 1) {
temp.push(next.slice(1))
open = true
} else if (open && next.indexOf('"') === next.length - 1) {
temp.push(next.slice(0, next.length - 1))
result.push(temp.join(' '))
while(temp.length > 0) temp.shift()
open = false
} else if(open) {
temp.push(next)
} else {
result.push(next)
}
}
return result
}
// ------------------------------------------------------------------------
// Field Parsers
// ------------------------------------------------------------------------
function* parseSourcePaths(params: string[]): Generator<string> {
if(params.length === 0) throw new OptionsError('paths', 'Expected one or more paths.')
const next = params.shift()!
for(const partialPath of next.split(' ')) {
const sourcePath = path.resolve(process.cwd(), partialPath)
if (!fs.existsSync(sourcePath)) throw new OptionsError('paths', `Cannot find source path '${sourcePath} does not exists.'`)
yield sourcePath
}
}
function parseSourcePathAndArguments(params: string[]): [sourcePath: string, args: string[]] {
if(params.length === 0) throw new OptionsError('run', 'Expected entry path.')
const next = params.shift()!
const split = next.split(' ')
const partialPath = split.shift()!
const entryPath = path.join(process.cwd(), partialPath)
const extname = path.extname(entryPath)
if(!['.ts', '.tsx', '.js'].includes(extname)) throw new OptionsError('run', `Entry path not a TypeScript or JavaScript file. Got '${entryPath}'`)
if(!fs.existsSync(entryPath)) throw new OptionsError('run', `Entry path '${entryPath}' does not exist.`)
return [entryPath, split]
}
function parseDist(params: string[]): string {
if (params.length === 0) throw new OptionsError('dist', "Expected directory path.")
return path.join(process.cwd(), params.shift()!)
}
function parsePlatform(params: string[]): 'browser' | 'node' {
if (params.length === 0) throw new OptionsError('platform', "Expected profile option.")
const next = params.shift()!
if (next === 'browser' || next === 'node') return next
throw new OptionsError('platform', `Expected 'node' or 'browser'. Got '${next}'`)
}
function parseExternal(params: string[]): string[] {
if (params.length === 0) throw new OptionsError('external', "Expected external option.")
let next = params.shift()!
if(next.indexOf('"') === 0) next = next.slice(1, next.length - 1)
if(next.lastIndexOf('"') === next.length - 1) next = next.slice(0, next.length - 1)
const external = next.split(' ').map(x => x.trim())
return external
}
function parsePort(params: string[]): number {
if (params.length === 0) throw new OptionsError('port', "Expected port number")
const next = params.shift()!
const port = parseInt(next)
if(Number.isNaN(port)) throw new OptionsError('port', `Expected port number. Received '${port}'`)
if(port < 0 || port > 65535) throw new OptionsError('port', `Invalid port number. Received '${port}'`)
return port
}
function* parseTarget(params: string[]): Generator<string> {
if (params.length === 0) throw new OptionsError('target', "Expected target option")
while (params.length > 0) {
const next = params.shift()!
if (next.includes('--')) {
params.unshift(next)
return
}
yield next
}
}
// ------------------------------------------------------------------------
// Parsers
// ------------------------------------------------------------------------
export function parseBuildOptions(params: string[]): BuildOptions {
const options = defaultBuildOptions()
options.sourcePaths = [...parseSourcePaths(params)]
if (options.sourcePaths.length === 0) throw new OptionsError('build', `Expected at least one source path.`)
while (params.length > 0) {
const next = params.shift()!
switch (next) {
case '--platform': options.platform = parsePlatform(params); break;
case '--target': options.target = [...parseTarget(params)]; break;
case '--dist': options.dist = parseDist(params); break;
case '--esm': options.esm = true; break;
case '--external': options.external = parseExternal(params); break;
case '--sourcemap': options.sourcemap = true; break;
case '--minify': options.minify = true; break;
}
}
return options
}
export function parseWatchOptions(params: string[]): WatchOptions {
const options = defaultWatchOptions()
options.sourcePaths = [...parseSourcePaths(params)]
if (options.sourcePaths.length === 0) throw new OptionsError('build', `Expected at least one source path.`)
while (params.length > 0) {
const next = params.shift()!
switch (next) {
case '--platform': options.platform = parsePlatform(params); break;
case '--target': options.target = [...parseTarget(params)]; break;
case '--dist': options.dist = parseDist(params); break;
case '--esm': options.esm = true; break;
case '--external': options.external = parseExternal(params); break;
case '--sourcemap': options.sourcemap = true; break;
case '--minify': options.minify = true; break;
}
}
return options
}
export function parseRunOptions(params: string[]): RunOptions {
const options = defaultRunOptions()
const [sourcePath, args] = parseSourcePathAndArguments(params)
options.sourcePath = sourcePath
options.args = args
while (params.length > 0) {
const next = params.shift()
switch (next) {
case '--dist': options.dist = parseDist(params); break;
case '--esm': options.esm = true; break;
case '--external': options.external = parseExternal(params); break;
case '--target': options.target = [...parseTarget(params)]; break;
case '--sourcemap': options.sourcemap = true; break;
case '--minify': options.minify = true; break;
}
}
const extension = path.extname(options.sourcePath)
options.entryPath = path.join(options.dist, [path.basename(options.sourcePath, extension), '.js'].join(''))
return options
}
export function parseServeOptions(params: string[]): ServeOptions {
const options = defaultServeOptions()
options.sourcePaths = [...parseSourcePaths(params)]
while (params.length > 0) {
const next = params.shift()
switch (next) {
case '--dist': options.dist = parseDist(params); break;
case '--esm': options.esm = true; break;
case '--external': options.external = parseExternal(params); break;
case '--minify': options.minify = true; break;
case '--sourcemap': options.sourcemap = true; break;
case '--target': options.target = [...parseTarget(params)]; break;
case '--port': options.port = parsePort(params); break;
}
}
return options
}
export function parseMonitorOptions(params: string[]): MonitorOptions {
const options = defaultMonitorOptions()
options.sourcePaths = [...parseSourcePaths(params)]
options.arguments = params
return options
}
function resolveHammerTaskFile(): string {
if(fs.existsSync(path.join(process.cwd(), 'hammer.mjs'))) {
return path.join(process.cwd(), 'hammer.mjs')
} else {
throw Error(`No task file found. Expected 'hammer.mjs' in current directory.`)
}
}
export function parseTaskOptions(params: string[]): TaskOptions {
const options = defaultTaskOptions()
options.sourcePath = resolveHammerTaskFile()
if (params.length === 0) return options
options.name = params.shift()!
options.arguments = params
return options
}
export function parse(args: string[]) {
try {
const params = prepareArguments(args).slice(2)
if(params.length === 0) return defaultHelpOptions()
const command = params.shift()
switch (command) {
case 'build': return parseBuildOptions(params)
case 'watch': return parseWatchOptions(params)
case 'serve': return parseServeOptions(params)
case 'run': return parseRunOptions(params)
case 'monitor': return parseMonitorOptions(params)
case 'task': return parseTaskOptions(params)
case 'help': return defaultHelpOptions()
case 'version': return defaultVersionOptions()
default: return defaultHelpOptions(`Unknown command '${command}'`)
}
} catch (error) {
return defaultHelpOptions(error.message)
}
} | the_stack |
import { ipcRenderer } from "electron";
import { platform } from "os";
import { join, dirname, extname, basename } from "path";
import { readdir, readJSON, writeJSON, stat, copyFile } from "fs-extra";
import { Nullable, IStringDictionary } from "../../../shared/types";
import { IPCRequests, IPCResponses } from "../../../shared/ipc";
import { Editor } from "../editor";
import { ConsoleLayer } from "../components/console";
import { Tools } from "../tools/tools";
import { ExecTools, IExecProcess } from "../tools/exec";
import { Overlay } from "../gui/overlay";
import { IWorkSpace } from "./typings";
export class WorkSpace {
/**
* Defines the absolute path of the workspace file.
*/
public static Path: Nullable<string> = null;
/**
* Defines the absolute path of the workspace folder.
*/
public static DirPath: Nullable<string> = null;
/**
* Defines the list of all available projects in the workspace.
*/
public static AvailableProjects: string[] = [];
/**
* Defines the current project datas.
*/
public static Workspace: Nullable<IWorkSpace> = null;
/**
* Defines the port of the server used when testing the game.
*/
public static ServerPort: Nullable<number> = null;
private static _WatchProjectProgram: Nullable<IExecProcess> = null;
private static _WatchTypescriptProgram: Nullable<IExecProcess> = null;
private static _BuildingProject: boolean = false;
/**
* Returns wether or not the editor has a workspace opened.
*/
public static HasWorkspace(): boolean {
return this.Path !== null;
}
/**
* Returns the workspace path set when opened the editor from the OS file system.
*/
public static GetOpeningWorkspace(): Promise<Nullable<string>> {
return new Promise<Nullable<string>>((resolve) => {
ipcRenderer.once(IPCResponses.GetWorkspacePath, (_, path) => resolve(path));
ipcRenderer.send(IPCRequests.GetWorkspacePath);
});
}
/**
* Sets the new project path of the project.
* @param path the new path of the project.
*/
public static SetOpeningWorkspace(path: string): Promise<void> {
return new Promise<void>((resolve) => {
ipcRenderer.once(IPCResponses.SetWorkspacePath, () => resolve());
ipcRenderer.send(IPCRequests.SetWorkspacePath, path);
});
}
/**
* Reads the workspace file and configures the workspace class.
* @param path the absolute path of the workspace file.
*/
public static async ReadWorkSpaceFile(path: string): Promise<Nullable<IWorkSpace>> {
const json = await readJSON(path, { encoding: "utf-8" });
this.Path = path;
this.DirPath = join(dirname(path), "/");
this.Workspace = json;
return json;
}
/**
* Writes the workspace file.
* @param projectPath the absolute path of the saved project.
*/
public static WriteWorkspaceFile(projectPath: string): Promise<void> {
if (!this.DirPath || !this.Path) { return Promise.resolve(); }
// Get all plugin prefernces
const pluginsPreferences: IStringDictionary<any> = { };
for (const p in Editor.LoadedExternalPlugins) {
const plugin = Editor.LoadedExternalPlugins[p];
if (!plugin.getWorkspacePreferences) { continue; }
try {
const preferences = plugin.getWorkspacePreferences();
JSON.stringify(preferences);
pluginsPreferences[p] = preferences;
} catch (e) {
console.error(e);
}
}
return writeJSON(this.Path, {
lastOpenedScene: projectPath.replace(this.DirPath!, ""),
serverPort: this.Workspace!.serverPort,
generateSceneOnSave: this.Workspace!.generateSceneOnSave,
useIncrementalLoading: this.Workspace!.useIncrementalLoading,
firstLoad: this.Workspace!.firstLoad,
watchProject: this.Workspace!.watchProject,
physicsEngine: this.Workspace!.physicsEngine,
pluginsPreferences,
playProjectInIFrame: this.Workspace!.playProjectInIFrame,
https: this.Workspace!.https ?? {
enabled: false,
},
ktx2CompressedTextures: {
enabled: this.Workspace!.ktx2CompressedTextures?.enabled ?? false,
pvrTexToolCliPath: this.Workspace!.ktx2CompressedTextures?.pvrTexToolCliPath ?? "",
forcedFormat: this.Workspace!.ktx2CompressedTextures?.forcedFormat ?? "automatic",
enabledInPreview: this.Workspace!.ktx2CompressedTextures?.enabledInPreview ?? false,
astcOptions: this.Workspace!.ktx2CompressedTextures?.astcOptions ?? {
quality: "astcveryfast",
},
pvrtcOptions: this.Workspace!.ktx2CompressedTextures?.pvrtcOptions ?? {
quality: "pvrtcfastest",
},
ect1Options: this.Workspace!.ktx2CompressedTextures?.ect1Options ?? {
enabled: false,
quality: "etcfast",
},
ect2Options: this.Workspace!.ktx2CompressedTextures?.ect2Options ?? {
enabled: false,
quality: "etcfast",
},
},
} as IWorkSpace, {
encoding: "utf-8",
spaces: "\t",
});
}
/**
* Refreshes the list of available projects in the workspace.
*/
public static async RefreshAvailableProjects(): Promise<void> {
if (!this.DirPath) { return; }
const projectsFolder = join(this.DirPath, "projects");
const files = await readdir(projectsFolder);
this.AvailableProjects = [];
for (const f of files) {
const infos = await stat(join(projectsFolder, f));
if (infos.isDirectory()) { this.AvailableProjects.push(f); }
}
}
/**
* Returns the path of the latest opened project.
*/
public static GetProjectPath(): string {
return join(this.DirPath!, this.Workspace!.lastOpenedScene);
}
/**
* Returns the name of the project.
*/
public static GetProjectName(): string {
return basename(dirname(this.GetProjectPath()));
}
/**
* Opens the file dialog and loads the selected project.
*/
public static async Browse(): Promise<void> {
const file = await Tools.ShowOpenFileDialog("Please select the workspace to open.");
if (!file || extname(file).toLowerCase() !== ".editorworkspace") { return; }
Overlay.Show("Preparing...", true);
await this.SetOpeningWorkspace(file);
window.location.reload();
}
/**
* Installs and builds the project.
* @param editor the editor reference.
*/
public static async InstallAndBuild(editor: Editor): Promise<void> {
if (!this.Workspace) { return; }
const task = editor.addTaskFeedback(0, "Installing dependencies. Please wait...", 0);
try {
await ExecTools.Exec(editor, "npm install", WorkSpace.DirPath!, false, ConsoleLayer.TypeScript);
editor.updateTaskFeedback(task, 50, "Building project...");
await ExecTools.Exec(editor, "npm run build -- --progress", WorkSpace.DirPath!, false, ConsoleLayer.WebPack);
editor.updateTaskFeedback(task, 100, "Done!");
} catch (e) {
editor.updateTaskFeedback(task, 0, "Failed");
}
this.Workspace.firstLoad = false;
editor.closeTaskFeedback(task, 1000);
}
/**
* Builds the project.
* @param editor the editor reference.
*/
public static async BuildProject(editor: Editor): Promise<void> {
if (!this.Workspace || this._BuildingProject) { return; }
this._BuildingProject = true;
const task = editor.addTaskFeedback(50, "Building project...");
try {
editor.console.setActiveTab("webpack");
await ExecTools.Exec(editor, "npm run build -- --progress", WorkSpace.DirPath!, false, ConsoleLayer.WebPack);
editor.updateTaskFeedback(task, 100, "Done!");
} catch (e) {
editor.updateTaskFeedback(task, 0, "Failed");
}
this._BuildingProject = false;
editor.closeTaskFeedback(task, 1000);
}
/**
* Watchs the project using webpack.
* @param editor the editor reference.
*/
public static async WatchProject(editor: Editor): Promise<void> {
if (this._WatchProjectProgram) { return; }
// Get command
const packageJson = await readJSON(join(this.DirPath!, "package.json"));
const isWin32 = platform() === "win32";
const watchScript = join("node_modules", ".bin", isWin32 ? packageJson.scripts.watch.replace("webpack", "webpack.cmd") : packageJson.scripts.watch);
this._WatchProjectProgram = ExecTools.ExecAndGetProgram(editor, `./${watchScript}`, this.DirPath!, false, ConsoleLayer.WebPack);
}
/**
* Returns wether or not the project is being watched using webpack.
*/
public static get IsWatchingProject(): boolean {
return this._WatchProjectProgram !== null;
}
/**
* Stops watching the project using webpack.
*/
public static StopWatchingProject(): void {
if (this._WatchProjectProgram) {
this._WatchProjectProgram.process.kill();
}
this._WatchProjectProgram = null;
}
/**
* Watchs the project's typescript using tsc. This is used to safely watch attached scripts on nodes.
* @param editor the editor reference.
*/
public static async WatchTypeScript(editor: Editor): Promise<void> {
if (this._WatchTypescriptProgram) { return; }
// Update the tsconfig file
await copyFile(join(Tools.GetAppPath(), "assets", "scripts", "editor.tsconfig.json"), join(this.DirPath!, "editor.tsconfig.json"));
// Get command
const isWin32 = platform() === "win32";
const watchScript = join("node_modules", ".bin", isWin32 ? "tsc.cmd" : "tsc");
this._WatchTypescriptProgram = ExecTools.ExecAndGetProgram(editor, `./${watchScript} -p ./editor.tsconfig.json --watch`, this.DirPath!, false, ConsoleLayer.TypeScript);
}
/**
* Returns wether or not the typescript project is being watched.
*/
public static get IsWatchingTypeScript(): boolean {
return this._WatchTypescriptProgram !== null;
}
/**
* Stops watching the TypeScript project.
*/
public static StopWatchingTypeScript(): void {
if (this._WatchTypescriptProgram) {
try {
this._WatchTypescriptProgram.process.kill();
} catch (e) {
// Catch silently.
}
}
this._WatchTypescriptProgram = null;
}
/**
* Restarts the TypeScript watcher in case it goes in error.
* @param editor defines the editor reference.
*/
public static RestartTypeScriptWatcher(editor: Editor): Promise<void> {
this.StopWatchingTypeScript();
return this.WatchTypeScript(editor);
}
/**
* Kills all the existing programs.
*/
public static KillAllProcesses(): void {
this.StopWatchingProject();
this.StopWatchingTypeScript();
}
} | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type FairExhibitorRailTestsQueryVariables = {
showID: string;
};
export type FairExhibitorRailTestsQueryResponse = {
readonly show: {
readonly " $fragmentRefs": FragmentRefs<"FairExhibitorRail_show">;
} | null;
};
export type FairExhibitorRailTestsQuery = {
readonly response: FairExhibitorRailTestsQueryResponse;
readonly variables: FairExhibitorRailTestsQueryVariables;
};
/*
query FairExhibitorRailTestsQuery(
$showID: String!
) {
show(id: $showID) {
...FairExhibitorRail_show
id
}
}
fragment FairExhibitorRail_show on Show {
internalID
slug
href
partner {
__typename
... on Partner {
name
}
... on ExternalPartner {
name
id
}
... on Node {
__isNode: __typename
id
}
}
counts {
artworks
}
fair {
internalID
slug
id
}
artworks: artworksConnection(first: 20) {
edges {
node {
href
artistNames
id
image {
imageURL
aspectRatio
}
saleMessage
saleArtwork {
openingBid {
display
}
highestBid {
display
}
currentBid {
display
}
counts {
bidderPositions
}
id
}
sale {
isClosed
isAuction
endAt
id
}
title
internalID
slug
}
}
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = [
{
"defaultValue": null,
"kind": "LocalArgument",
"name": "showID"
}
],
v1 = [
{
"kind": "Variable",
"name": "id",
"variableName": "showID"
}
],
v2 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "internalID",
"storageKey": null
},
v3 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "slug",
"storageKey": null
},
v4 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "href",
"storageKey": null
},
v5 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
v6 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v7 = [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "display",
"storageKey": null
}
],
v8 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "String"
},
v9 = {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "ID"
},
v10 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Boolean"
},
v11 = {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "String"
};
return {
"fragment": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Fragment",
"metadata": null,
"name": "FairExhibitorRailTestsQuery",
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "Show",
"kind": "LinkedField",
"name": "show",
"plural": false,
"selections": [
{
"args": null,
"kind": "FragmentSpread",
"name": "FairExhibitorRail_show"
}
],
"storageKey": null
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Operation",
"name": "FairExhibitorRailTestsQuery",
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "Show",
"kind": "LinkedField",
"name": "show",
"plural": false,
"selections": [
(v2/*: any*/),
(v3/*: any*/),
(v4/*: any*/),
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "partner",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
{
"kind": "InlineFragment",
"selections": [
(v5/*: any*/)
],
"type": "Partner",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": [
(v5/*: any*/),
(v6/*: any*/)
],
"type": "ExternalPartner",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": [
(v6/*: any*/)
],
"type": "Node",
"abstractKey": "__isNode"
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ShowCounts",
"kind": "LinkedField",
"name": "counts",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "artworks",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Fair",
"kind": "LinkedField",
"name": "fair",
"plural": false,
"selections": [
(v2/*: any*/),
(v3/*: any*/),
(v6/*: any*/)
],
"storageKey": null
},
{
"alias": "artworks",
"args": [
{
"kind": "Literal",
"name": "first",
"value": 20
}
],
"concreteType": "ArtworkConnection",
"kind": "LinkedField",
"name": "artworksConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "ArtworkEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v4/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "artistNames",
"storageKey": null
},
(v6/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "image",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "imageURL",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "aspectRatio",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "saleMessage",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "SaleArtwork",
"kind": "LinkedField",
"name": "saleArtwork",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "SaleArtworkOpeningBid",
"kind": "LinkedField",
"name": "openingBid",
"plural": false,
"selections": (v7/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "SaleArtworkHighestBid",
"kind": "LinkedField",
"name": "highestBid",
"plural": false,
"selections": (v7/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "SaleArtworkCurrentBid",
"kind": "LinkedField",
"name": "currentBid",
"plural": false,
"selections": (v7/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "SaleArtworkCounts",
"kind": "LinkedField",
"name": "counts",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "bidderPositions",
"storageKey": null
}
],
"storageKey": null
},
(v6/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Sale",
"kind": "LinkedField",
"name": "sale",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isClosed",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isAuction",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "endAt",
"storageKey": null
},
(v6/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "title",
"storageKey": null
},
(v2/*: any*/),
(v3/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "artworksConnection(first:20)"
},
(v6/*: any*/)
],
"storageKey": null
}
]
},
"params": {
"id": "2085d54ec10a066039cdab7c7be5fb9c",
"metadata": {
"relayTestingSelectionTypeInfo": {
"show": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Show"
},
"show.artworks": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "ArtworkConnection"
},
"show.artworks.edges": {
"enumValues": null,
"nullable": true,
"plural": true,
"type": "ArtworkEdge"
},
"show.artworks.edges.node": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Artwork"
},
"show.artworks.edges.node.artistNames": (v8/*: any*/),
"show.artworks.edges.node.href": (v8/*: any*/),
"show.artworks.edges.node.id": (v9/*: any*/),
"show.artworks.edges.node.image": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Image"
},
"show.artworks.edges.node.image.aspectRatio": {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "Float"
},
"show.artworks.edges.node.image.imageURL": (v8/*: any*/),
"show.artworks.edges.node.internalID": (v9/*: any*/),
"show.artworks.edges.node.sale": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Sale"
},
"show.artworks.edges.node.sale.endAt": (v8/*: any*/),
"show.artworks.edges.node.sale.id": (v9/*: any*/),
"show.artworks.edges.node.sale.isAuction": (v10/*: any*/),
"show.artworks.edges.node.sale.isClosed": (v10/*: any*/),
"show.artworks.edges.node.saleArtwork": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "SaleArtwork"
},
"show.artworks.edges.node.saleArtwork.counts": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "SaleArtworkCounts"
},
"show.artworks.edges.node.saleArtwork.counts.bidderPositions": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "FormattedNumber"
},
"show.artworks.edges.node.saleArtwork.currentBid": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "SaleArtworkCurrentBid"
},
"show.artworks.edges.node.saleArtwork.currentBid.display": (v8/*: any*/),
"show.artworks.edges.node.saleArtwork.highestBid": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "SaleArtworkHighestBid"
},
"show.artworks.edges.node.saleArtwork.highestBid.display": (v8/*: any*/),
"show.artworks.edges.node.saleArtwork.id": (v9/*: any*/),
"show.artworks.edges.node.saleArtwork.openingBid": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "SaleArtworkOpeningBid"
},
"show.artworks.edges.node.saleArtwork.openingBid.display": (v8/*: any*/),
"show.artworks.edges.node.saleMessage": (v8/*: any*/),
"show.artworks.edges.node.slug": (v9/*: any*/),
"show.artworks.edges.node.title": (v8/*: any*/),
"show.counts": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "ShowCounts"
},
"show.counts.artworks": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Int"
},
"show.fair": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Fair"
},
"show.fair.id": (v9/*: any*/),
"show.fair.internalID": (v9/*: any*/),
"show.fair.slug": (v9/*: any*/),
"show.href": (v8/*: any*/),
"show.id": (v9/*: any*/),
"show.internalID": (v9/*: any*/),
"show.partner": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "PartnerTypes"
},
"show.partner.__isNode": (v11/*: any*/),
"show.partner.__typename": (v11/*: any*/),
"show.partner.id": (v9/*: any*/),
"show.partner.name": (v8/*: any*/),
"show.slug": (v9/*: any*/)
}
},
"name": "FairExhibitorRailTestsQuery",
"operationKind": "query",
"text": null
}
};
})();
(node as any).hash = 'f55097d013da8f10a1b1141b5afa43e0';
export default node; | the_stack |
import { Workbook, SheetModel, CellModel, getSheet, getColumn, ColumnModel, isHiddenRow, getCell, setCell, getSheetIndex } from '../base/index';
import { cellValidation, applyCellFormat, isValidation, addHighlight, getCellAddress, validationHighlight, getSwapRange, getSheetIndexFromAddress, getSplittedAddressForColumn } from '../common/index';
import { removeHighlight, InsertDeleteEventArgs, checkIsFormula, checkCellValid } from '../common/index';
import { getRangeIndexes, getUpdatedFormulaOnInsertDelete, InsertDeleteModelArgs } from '../common/index';
import { CellFormatArgs, ValidationType, ValidationOperator, ValidationModel, updateCell, beforeInsert, beforeDelete } from '../common/index';
import { extend, isNullOrUndefined } from '@syncfusion/ej2-base';
/**
* The `WorkbookHyperlink` module is used to handle Hyperlink action in Spreadsheet.
*/
export class WorkbookDataValidation {
private parent: Workbook;
/**
* Constructor for WorkbookSort module.
*
* @param {Workbook} parent - Specifies the parent element.
*/
constructor(parent: Workbook) {
this.parent = parent;
this.addEventListener();
}
/**
* To destroy the sort module.
*
* @returns {void}
*/
protected destroy(): void {
this.removeEventListener();
this.parent = null;
}
private addEventListener(): void {
this.parent.on(cellValidation, this.validationHandler, this);
this.parent.on(addHighlight, this.addHighlightHandler, this);
this.parent.on(removeHighlight, this.removeHighlightHandler, this);
this.parent.on(beforeInsert, this.beforeInsertDeleteHandler, this);
this.parent.on(beforeDelete, this.beforeInsertDeleteHandler, this);
}
private removeEventListener(): void {
if (!this.parent.isDestroyed) {
this.parent.off(cellValidation, this.validationHandler);
this.parent.off(addHighlight, this.addHighlightHandler);
this.parent.off(removeHighlight, this.removeHighlightHandler);
this.parent.off(beforeInsert, this.beforeInsertDeleteHandler);
this.parent.off(beforeDelete, this.beforeInsertDeleteHandler);
}
}
private validationHandler(args: { range: string, rules?: ValidationModel, isRemoveValidation?: boolean, cancel?: boolean }): void {
let onlyRange: string = args.range;
let sheetName: string = '';
let column: ColumnModel;
if (args.range.indexOf('!') > -1) {
onlyRange = args.range.split('!')[1];
sheetName = args.range.split('!')[0];
}
const sheet: SheetModel = getSheet(this.parent, sheetName ? getSheetIndex(this.parent, sheetName) : this.parent.activeSheetIndex);
this.parent.dataValidationRange = (this.parent.dataValidationRange.indexOf('!') > -1 ? '' : sheet.name + '!') + this.parent.dataValidationRange + onlyRange + ',';
let isfullCol: boolean = false;
const maxRowCount: number = sheet.rowCount;
const rangeArr: string[] = onlyRange.split(':');
if (onlyRange.match(/\D/g) && !onlyRange.match(/[0-9]/g)) {
rangeArr[0] += 1;
rangeArr[1] += maxRowCount;
onlyRange = rangeArr[0] + ':' + rangeArr[1];
isfullCol = true;
} else if (!onlyRange.match(/\D/g) && onlyRange.match(/[0-9]/g)) {
rangeArr[0] = 'A' + rangeArr[0];
rangeArr[1] = getCellAddress(0, sheet.colCount - 1).replace(/[0-9]/g, '') + rangeArr[1];
onlyRange = rangeArr[0] + ':' + rangeArr[1];
}
if (!isNullOrUndefined(sheetName)) {
args.range = sheetName + '!' + onlyRange;
}
args.range = args.range || sheet.selectedRange;
const indexes: number[] = getSwapRange(getRangeIndexes(args.range));
if (isfullCol) {
for (let colIdx: number = indexes[1]; colIdx <= indexes[3]; colIdx++) {
column = getColumn(sheet, colIdx);
isfullCol = isfullCol && args.isRemoveValidation && column && !column.validation ? false : true;
}
}
if (isfullCol) {
for (let colIdx: number = indexes[1]; colIdx <= indexes[3]; colIdx++) {
column = getColumn(sheet, colIdx);
if (args.isRemoveValidation && column && column.validation) {
delete (sheet.columns[colIdx].validation);
} else {
if (!args.isRemoveValidation) {
if (isNullOrUndefined(column)) {
sheet.columns[colIdx] = getColumn(sheet, colIdx);
}
sheet.columns[colIdx].validation = {
operator: args.rules.operator as ValidationOperator,
type: args.rules.type as ValidationType,
value1: args.rules.value1 as string,
value2: args.rules.value2 as string,
inCellDropDown: args.rules.inCellDropDown,
ignoreBlank: args.rules.ignoreBlank
};
}
}
}
} else {
let cell: CellModel;
for (let rowIdx: number = indexes[0]; rowIdx <= indexes[2]; rowIdx++) {
for (let colIdx: number = indexes[1]; colIdx <= indexes[3]; colIdx++) {
if (args.isRemoveValidation) {
if (rowIdx === indexes[2]) {
column = getColumn(sheet, colIdx);
if (column && column.validation) {
column.validation.address = getSplittedAddressForColumn(column.validation.address,
[indexes[0], colIdx, indexes[2], colIdx], colIdx);
}
}
cell = getCell(rowIdx, colIdx, sheet);
if (cell && cell.validation &&
!updateCell(this.parent, sheet, { cell: { validation: {} }, rowIdx: rowIdx, colIdx: colIdx })) {
delete (cell.validation);
this.parent.notify(
applyCellFormat, <CellFormatArgs>{ rowIdx: rowIdx, colIdx: colIdx, style:
this.parent.getCellStyleValue(['backgroundColor', 'color'], [rowIdx, colIdx]) });
}
} else {
cell = { validation: Object.assign({}, args.rules) };
updateCell(this.parent, sheet, { cell: cell, rowIdx: rowIdx, colIdx: colIdx });
}
}
}
}
}
private addHighlightHandler(args: { range: string, td? : HTMLElement, isclearFormat?: boolean }): void {
this.InvalidDataHandler(args.range, false, args.td, args.isclearFormat);
}
private removeHighlightHandler(args: { range: string }): void {
this.InvalidDataHandler(args.range, true);
}
private getRange(range: string): string {
const indexes: number[] = getRangeIndexes(range);
const sheet: SheetModel = this.parent.getActiveSheet();
const maxColCount: number = sheet.colCount;
const maxRowCount: number = sheet.rowCount;
if (indexes[2] === maxRowCount - 1 && indexes[0] === 0) {
range = range.replace(/[0-9]/g, '');
} else if (indexes[3] === maxColCount - 1 && indexes[2] === 0) {
range = range.replace(/\D/g, '');
}
return range;
}
private InvalidDataHandler(range: string, isRemoveHighlightedData: boolean, td?: HTMLElement, isclearFormat?: boolean): void {
const isCell: boolean = false;
let cell: CellModel;
let value: string;
const sheetIdx: number = range ? getSheetIndexFromAddress(this.parent, range) : this.parent.activeSheetIndex;
const sheet: SheetModel = getSheet(this.parent, sheetIdx);
range = range || sheet.selectedRange;
const indexes: number[] = range ? getSwapRange(getRangeIndexes(range)) : [];
range = this.getRange(range);
let isfullCol: boolean = false;
if (range.match(/\D/g) && !range.match(/[0-9]/g)) {
isfullCol = true;
}
let rowIdx: number = range ? indexes[0] : 0;
const lastRowIdx: number = range ? indexes[2] : sheet.rows.length;
for (rowIdx; rowIdx <= lastRowIdx; rowIdx++) {
if (sheet.rows[rowIdx]) {
let colIdx: number = range ? indexes[1] : 0;
const lastColIdx: number = range ? indexes[3] : sheet.rows[rowIdx].cells.length;
for (colIdx; colIdx <= lastColIdx; colIdx++) {
let validation: ValidationModel;
if (sheet.rows[rowIdx].cells && sheet.rows[rowIdx].cells[colIdx]) {
const column: ColumnModel = getColumn(sheet, colIdx);
cell = sheet.rows[rowIdx].cells[colIdx];
if (cell && cell.validation) {
validation = cell.validation;
if (isclearFormat && !validation.isHighlighted) {
return;
}
if (isRemoveHighlightedData) {
if (validation.isHighlighted) {
cell.validation.isHighlighted = false;
}
} else {
cell.validation.isHighlighted = true;
}
} else if (column && column.validation) {
validation = column.validation;
if (isclearFormat && !validation.isHighlighted) {
return;
}
if (isRemoveHighlightedData && isfullCol) {
if (validation.isHighlighted) {
column.validation.isHighlighted = false;
}
} else if (isfullCol) {
column.validation.isHighlighted = true;
}
}
value = cell.value ? cell.value : '';
const range: number[] = [rowIdx, colIdx];
if (validation && this.parent.allowDataValidation) {
let validEventArgs: checkCellValid = { value, range, sheetIdx, isCell, td: td, isValid: true };
this.parent.notify(isValidation, validEventArgs);
const isValid: boolean = validEventArgs.isValid;
if (!isValid) {
if (!isHiddenRow(sheet, rowIdx) && sheetIdx === this.parent.activeSheetIndex){
this.parent.notify(validationHighlight, {
isRemoveHighlightedData: isRemoveHighlightedData, rowIdx: rowIdx, colIdx: colIdx, td: td
});
}}
}
}
}
}
}
}
private beforeInsertDeleteHandler(args: InsertDeleteEventArgs): void {
if (args.modelType === 'Sheet') {
return;
}
let cell: CellModel;
let sheet: SheetModel
for (let i: number = 0, sheetLen = this.parent.sheets.length; i < sheetLen; i++) {
sheet = this.parent.sheets[i];
for (let j: number = 0, rowLen = sheet.rows.length; j < rowLen; j++) {
if (sheet.rows[j] && sheet.rows[j].cells) {
for (let k: number = 0, cellLen = sheet.rows[j].cells.length; k < cellLen; k++) {
cell = sheet.rows[j].cells[k];
if (cell && cell.validation) {
const isInsert: boolean = (args as { name: string }).name === 'beforeInsert';
const endIndex: number = args.index + (args.model.length - 1);
const isNewlyInsertedModel: boolean = args.modelType === 'Row' ? (j >= args.index && j <= endIndex) : (k >= args.index && k <= endIndex);
let eventArgs: { insertDeleteArgs: InsertDeleteEventArgs, cell?: CellModel, row: number, col: number };
if (isInsert) {
eventArgs = { insertDeleteArgs: { startIndex: args.index, endIndex: args.index + args.model.length - 1, modelType: args.modelType, isInsert: true, sheet: getSheet(this.parent, args.activeSheetIndex) }, row: j, col: k };
} else {
eventArgs = { insertDeleteArgs: { startIndex: (args as InsertDeleteModelArgs).start as number, endIndex: (args as InsertDeleteModelArgs).end, modelType: args.modelType, sheet: args.model as SheetModel }, row: j, col: k };
}
if (checkIsFormula(cell.validation.value1) && !isNewlyInsertedModel) {
eventArgs.cell = { formula: cell.validation.value1 };
this.parent.notify(getUpdatedFormulaOnInsertDelete, eventArgs);
cell.validation.value1 = eventArgs.cell.formula;
}
if (checkIsFormula(cell.validation.value2) && !isNewlyInsertedModel) {
eventArgs.cell = { formula: cell.validation.value2 };
this.parent.notify(getUpdatedFormulaOnInsertDelete, eventArgs);
cell.validation.value2 = eventArgs.cell.formula;
}
if (args.activeSheetIndex === i && isInsert) {
this.updateValidationForInsertedModel(args, sheet, j, k, cell.validation);
}
}
}
}
}
}
}
private updateValidationForInsertedModel(args: InsertDeleteEventArgs, sheet: SheetModel, rowIndex: number, colIndex: number, validation: ValidationModel): void {
const endIndex: number = args.index + (args.model.length - 1);
if (args.modelType === 'Column') {
if ((args.insertType === 'before' && endIndex === colIndex - 1) || (args.insertType === 'after' && args.index - 1 === colIndex)) {
for (let l: number = args.index; l <= endIndex; l++) {
setCell(rowIndex, l, sheet, { validation: extend({}, validation) }, true);
}
}
} else if (args.modelType === 'Row') {
if ((args.insertType === 'above' && endIndex === rowIndex - 1) || (args.insertType === 'below' && args.index - 1 === rowIndex)) {
for (let l: number = args.index; l <= endIndex; l++) {
setCell(l, colIndex, sheet, { validation: extend({}, validation) }, true);
}
}
}
}
/**
* Gets the module name.
*
* @returns {string} string
*/
protected getModuleName(): string {
return 'workbookDataValidation';
}
} | the_stack |
import { assert } from "chai";
import { document } from "xmlcreate";
import { Absent, parse, parseToExistingElement } from "../../lib/main";
import { IOptions, ITypeHandlers, IWrapHandlers } from "../../lib/options";
import { isSet } from "../../lib/utils";
const simpleOptions: IOptions = {
declaration: {
include: false,
},
format: {
pretty: false,
},
};
describe("parser", () => {
describe("#parse", () => {
it("primitives", () => {
assert.strictEqual(
parse("root", "string", simpleOptions),
"<root>string</root>",
);
assert.strictEqual(
parse("root", 3, simpleOptions),
"<root>3</root>",
);
assert.strictEqual(
parse("root", true, simpleOptions),
"<root>true</root>",
);
assert.strictEqual(
parse("root", undefined, simpleOptions),
"<root>undefined</root>",
);
assert.strictEqual(
parse("root", null, simpleOptions),
"<root>null</root>",
);
});
it("object versions of primitives", () => {
// noinspection JSPrimitiveTypeWrapperUsage
assert.strictEqual(
parse("root", new String("string"), simpleOptions),
"<root>string</root>",
);
// noinspection JSPrimitiveTypeWrapperUsage
assert.strictEqual(
parse("root", new Number(3), simpleOptions),
"<root>3</root>",
);
// noinspection JSPrimitiveTypeWrapperUsage
assert.strictEqual(
parse("root", new Boolean(true), simpleOptions),
"<root>true</root>",
);
});
it("simple objects and maps", () => {
assert.strictEqual(parse("root", {}, simpleOptions), "<root/>");
assert.strictEqual(
parse("root", { test: "123" }, simpleOptions),
"<root><test>123</test></root>",
);
assert.strictEqual(
parse("root", { test: "123", test2: "456" }, simpleOptions),
"<root><test>123</test><test2>456</test2>" + "</root>",
);
assert.strictEqual(
parse("root", new Map(), simpleOptions),
"<root/>",
);
assert.strictEqual(
parse("root", new Map([["test", "123"]]), simpleOptions),
"<root><test>123</test></root>",
);
assert.strictEqual(
parse(
"root",
new Map([
["test", "123"],
["test2", "456"],
]),
simpleOptions,
),
"<root><test>123</test><test2>456</test2></root>",
);
});
it("simple arrays and sets", () => {
assert.strictEqual(parse("root", [], simpleOptions), "<root/>");
assert.strictEqual(
parse("root", ["test", "123"], simpleOptions),
"<root><root>test</root><root>123</root>" + "</root>",
);
assert.strictEqual(
parse("root", new Set(), simpleOptions),
"<root/>",
);
assert.strictEqual(
parse("root", new Set(["test", "123"]), simpleOptions),
"<root><root>test</root><root>123</root>" + "</root>",
);
});
it("functions and regular expressions", () => {
assert.strictEqual(
parse("root", () => "test", simpleOptions),
'<root>function () { return "test"; }' + "</root>",
);
assert.strictEqual(
parse("root", /test/, simpleOptions),
"<root>/test/</root>",
);
});
it("primitives in objects and maps", () => {
// noinspection JSPrimitiveTypeWrapperUsage
assert.strictEqual(
parse(
"root",
{
test: "str",
test2: 3,
test3: true,
test4: undefined,
test5: null,
test6: new String("str2"),
test7: new Number(6),
test8: new Boolean(false),
},
simpleOptions,
),
"<root><test>str</test><test2>3</test2><test3>true</test3>" +
"<test4>undefined</test4><test5>null</test5><test6>str2" +
"</test6><test7>6</test7><test8>false</test8></root>",
);
// noinspection JSPrimitiveTypeWrapperUsage
assert.strictEqual(
parse(
"root",
new Map<string, unknown>([
["test", "str"],
["test2", 3],
["test3", true],
["test4", undefined],
["test5", null],
["test6", new String("str2")],
["test7", new Number(6)],
["test8", new Boolean(false)],
]),
simpleOptions,
),
"<root><test>str</test><test2>3</test2><test3>true</test3>" +
"<test4>undefined</test4><test5>null</test5><test6>str2" +
"</test6><test7>6</test7><test8>false</test8></root>",
);
// noinspection JSPrimitiveTypeWrapperUsage
assert.strictEqual(
parse(
"root",
new Map([
[false, "str1"],
[undefined, "str2"],
[null, "str3"],
]),
simpleOptions,
),
"<root><false>str1</false><undefined>str2</undefined>" +
"<null>str3</null></root>",
);
});
it("primitives in arrays and sets", () => {
// noinspection JSPrimitiveTypeWrapperUsage
assert.strictEqual(
parse(
"root",
[
"test",
3,
false,
undefined,
null,
new String("str1"),
new Number(5),
new Boolean(false),
],
simpleOptions,
),
"<root><root>test</root><root>3</root><root>false</root>" +
"<root>undefined</root><root>null</root><root>str1" +
"</root><root>5</root><root>false</root></root>",
);
// noinspection JSPrimitiveTypeWrapperUsage
assert.strictEqual(
parse(
"root",
new Set([
"test",
3,
false,
undefined,
null,
new String("str1"),
new Number(5),
new Boolean(false),
]),
simpleOptions,
),
"<root><root>test</root><root>3</root><root>false</root>" +
"<root>undefined</root><root>null</root><root>str1" +
"</root><root>5</root><root>false</root></root>",
);
});
it("nested objects and maps", () => {
assert.strictEqual(
parse(
"root",
{
test: {
test15: "test16",
test17: {
test18: "test19",
test20: "test21",
},
test2: new Map<string, unknown>([
["test3", "test4"],
[
"test5",
{
test6: "test7",
test8: "test9",
},
],
[
"test10",
new Map([
["test11", "test12"],
["test13", "test14"],
]),
],
]),
},
},
simpleOptions,
),
"<root><test><test15>test16</test15><test17>" +
"<test18>test19</test18><test20>test21</test20>" +
"</test17><test2><test3>test4</test3><test5><test6>" +
"test7</test6><test8>test9</test8></test5><test10>" +
"<test11>test12</test11><test13>test14</test13>" +
"</test10></test2></test></root>",
);
});
it("nested arrays and sets", () => {
assert.strictEqual(
parse(
"root",
[
["a", "b", "c", ["d", "e"]],
new Set([
"f",
"g",
"h",
new Set(["i", "j"]),
["k", "l"],
]),
],
simpleOptions,
),
"<root><root>a</root><root>b</root><root>c</root><root>" +
"d</root><root>e</root><root>f</root><root>g</root>" +
"<root>h</root><root>i</root><root>j</root><root>k" +
"</root><root>l</root></root>",
);
});
it("complex combinations of objects, maps, arrays, and sets", () => {
assert.strictEqual(
parse(
"root",
{
test1: {
test12: new Set([
"test13",
{
test14: "test15",
test16: "test17",
},
new Map([
["test18", "test19"],
["test20", "test21"],
]),
]),
test2: [
"test3",
{
test4: "test5",
test6: "test7",
},
new Map([
["test8", "test9"],
["test10", "test11"],
]),
],
test43: "test44",
},
test22: new Map<string, unknown>([
["test45", "test46"],
[
"test23",
[
"test24",
{
test25: "test26",
test27: "test28",
},
new Map([
["test29", "test30"],
["test31", "test32"],
]),
],
],
[
"test33",
new Set([
"test34",
{
test35: "test36",
test37: "test38",
},
new Map([
["test39", "test40"],
["test41", "test42"],
]),
]),
],
]),
},
simpleOptions,
),
"<root><test1><test12>test13</test12><test12><test14>" +
"test15</test14><test16>test17</test16></test12>" +
"<test12><test18>test19</test18><test20>test21</test20>" +
"</test12><test2>test3</test2><test2><test4>test5" +
"</test4><test6>test7</test6></test2><test2><test8>" +
"test9</test8><test10>test11</test10></test2><test43>" +
"test44</test43></test1><test22><test45>test46</test45>" +
"<test23>test24</test23><test23><test25>test26</test25>" +
"<test27>test28</test27></test23><test23><test29>test30" +
"</test29><test31>test32</test31></test23><test33>test34" +
"</test33><test33><test35>test36</test35><test37>test38" +
"</test37></test33><test33><test39>test40</test39>" +
"<test41>test42</test41></test33></test22></root>",
);
});
describe("options", () => {
it("aliasString", () => {
const aliasStringOptions: IOptions = {
aliasString: "_customAliasString",
declaration: {
include: false,
},
format: {
pretty: false,
},
};
assert.strictEqual(
parse(
"root",
{
"=": "testRoot",
"test1": "test2",
"test3": "test4",
},
simpleOptions,
),
"<testRoot><test1>test2</test1>" +
"<test3>test4</test3></testRoot>",
);
assert.strictEqual(
parse(
"root",
new Map([
["=", "testRoot"],
["test1", "test2"],
["test3", "test4"],
]),
simpleOptions,
),
"<testRoot><test1>test2</test1>" +
"<test3>test4</test3></testRoot>",
);
assert.strictEqual(
parse(
"root",
{
test1: "test2",
test3: {
"=": "test4",
"test5": "test6",
},
test7: new Map([
["=", "test8"],
["test9", "test10"],
]),
},
simpleOptions,
),
"<root><test1>test2</test1><test4><test5>test6</test5>" +
"</test4><test8><test9>test10</test9></test8>" +
"</root>",
);
assert.strictEqual(
parse(
"root",
new Map<string, unknown>([
["test1", "test2"],
[
"test3",
{
"=": "test4",
"test5": "test6",
},
],
[
"test7",
new Map([
["=", "test8"],
["test9", "test10"],
]),
],
]),
simpleOptions,
),
"<root><test1>test2</test1><test4><test5>test6</test5>" +
"</test4><test8><test9>test10</test9></test8>" +
"</root>",
);
assert.strictEqual(
parse(
"root",
[
{
"=": "test1",
"test2": "test3",
},
new Map([
["=", "test4"],
["test5", "test6"],
]),
{
test7: "test8",
test9: [
{
"=": "test10",
"test11": "test12",
},
new Map([
["=", "test13"],
["test14", "test15"],
]),
],
},
],
simpleOptions,
),
"<root><test1><test2>test3</test2></test1><test4>" +
"<test5>test6</test5></test4><root><test7>test8" +
"</test7><test10><test11>test12</test11></test10>" +
"<test13><test14>test15</test14></test13></root>" +
"</root>",
);
assert.strictEqual(
parse(
"root",
new Set([
{
"=": "test1",
"test2": "test3",
},
new Map([
["=", "test4"],
["test5", "test6"],
]),
{
test7: "test8",
test9: new Set([
{
"=": "test10",
"test11": "test12",
},
new Map([
["=", "test13"],
["test14", "test15"],
]),
]),
},
]),
simpleOptions,
),
"<root><test1><test2>test3</test2></test1><test4>" +
"<test5>test6</test5></test4><root><test7>test8" +
"</test7><test10><test11>test12</test11></test10>" +
"<test13><test14>test15</test14></test13></root>" +
"</root>",
);
assert.strictEqual(
parse(
"root",
{
_customAliasString: "test1",
test2: "test3",
test4: {
_customAliasString: "test5",
test6: "test7",
},
},
aliasStringOptions,
),
"<test1><test2>test3</test2><test5><test6>test7" +
"</test6></test5></test1>",
);
});
it("attributeString", () => {
const attributeStringOptions: IOptions = {
attributeString: "attributeString",
declaration: {
include: false,
},
format: {
pretty: false,
},
};
// noinspection HtmlUnknownAttribute
assert.strictEqual(
parse(
"root",
{
"@": {
test1: "test2",
test3: "test4",
test5: 3,
test6: null,
test7: undefined,
test8: true,
},
},
simpleOptions,
),
"<root test1='test2' test3='test4' test5='3' " +
"test6='null' test7='undefined' test8='true'/>",
);
assert.strictEqual(
parse(
"root",
{
test5: {
"@": {
test1: "test2",
test3: "test4",
},
"test6": "test7",
},
},
simpleOptions,
),
"<root><test5 test1='test2' test3='test4'><test6>" +
"test7</test6></test5></root>",
);
assert.throws(() => {
parse(
"root",
{
attributeString: {
test1: "test2",
test3: "test4",
},
test5: {
"@": {
test1: "test2",
test3: "test4",
},
},
},
attributeStringOptions,
);
});
});
it("cdataInvalidChars", () => {
const cdataInvalidCharsOptions: IOptions = {
cdataInvalidChars: true,
declaration: {
include: false,
},
format: {
pretty: false,
},
};
assert.strictEqual(
parse(
"root",
{
test1: "a&b",
test2: "c<d",
test3: "a&b<c]]>d&e<f",
},
simpleOptions,
),
"<root><test1>a&b</test1><test2>c<d</test2>" +
"<test3>a&b<c]]>d&e<f</test3></root>",
);
assert.strictEqual(
parse(
"root",
{
test1: "a&b",
test2: "c<d",
test3: "a&b<c]]>d&e<f]]>cdata_not_required",
},
cdataInvalidCharsOptions,
),
"<root><test1><![CDATA[a&b]]></test1><test2>" +
"<![CDATA[c<d]]></test2><test3><![CDATA[a&b<c]]>" +
"]]><![CDATA[d&e<f]]>]]>cdata_not_required" +
"</test3></root>",
);
});
it("cdataKeys", () => {
const cdataKeysOptions: IOptions = {
cdataKeys: ["test1"],
declaration: {
include: false,
},
format: {
pretty: false,
},
};
const cdataKeysWildcardOptions: IOptions = {
cdataKeys: ["test1", "*"],
declaration: {
include: false,
},
format: {
pretty: false,
},
};
assert.strictEqual(
parse(
"root",
{
test1: "ab",
test2: {
test1: "ab&",
},
test3: "ab&",
test4: "cd",
test5: {
test1: "ab&]]>no_cdata_required",
},
},
cdataKeysOptions,
),
"<root><test1><![CDATA[ab]]></test1><test2><test1>" +
"<![CDATA[ab&]]></test1></test2><test3>ab&" +
"</test3><test4>cd</test4><test5><test1>" +
"<![CDATA[ab&]]>]]><![CDATA[no_cdata_required]]>" +
"</test1></test5></root>",
);
assert.strictEqual(
parse(
"root",
{
test1: "ab",
test2: {
test1: "ab&",
},
test3: "ab&",
test4: "cd",
test5: {
test1: "ab&]]>no_cdata_required",
},
},
cdataKeysWildcardOptions,
),
"<root><test1><![CDATA[ab]]></test1><test2><test1>" +
"<![CDATA[ab&]]></test1></test2><test3>" +
"<![CDATA[ab&]]></test3><test4><![CDATA[cd]]>" +
"</test4><test5><test1><![CDATA[ab&]]>]]>" +
"<![CDATA[no_cdata_required]]></test1></test5></root>",
);
});
it("declaration", () => {
const declOptions: IOptions = {
declaration: {
encoding: "UTF-8",
include: true,
standalone: "yes",
version: "1.0",
},
format: {
pretty: false,
},
};
assert.strictEqual(
parse(
"root",
{
test1: "test2",
},
declOptions,
),
"<?xml version='1.0' encoding='UTF-8'" +
" standalone='yes'?><root><test1>test2</test1></root>",
);
});
it("dtd", () => {
const dtdOptions: IOptions = {
declaration: {
include: false,
},
dtd: {
include: true,
name: "a",
pubId: "c",
sysId: "b",
},
format: {
pretty: false,
},
};
assert.strictEqual(
parse(
"root",
{
test1: "test2",
},
dtdOptions,
),
"<!DOCTYPE a PUBLIC 'c' 'b'><root><test1>test2" +
"</test1></root>",
);
});
it("format", () => {
const formatOptions: IOptions = {
declaration: {
include: false,
},
format: {
doubleQuotes: true,
indent: "\t",
newline: "\r\n",
pretty: true,
},
};
assert.strictEqual(
parse(
"root",
{
test1: "test2",
test3: "test4\ntest5",
},
formatOptions,
),
"<root>\r\n\t<test1>test2</test1>\r\n\t<test3>" +
"test4\ntest5</test3>\r\n</root>",
);
});
it("replaceInvalidChars", () => {
const replaceInvalidCharsOptions: IOptions = {
declaration: {
include: false,
},
format: {
pretty: false,
},
replaceInvalidChars: true,
};
assert.strictEqual(
parse(
"root",
{
test1: "test2\u0001",
},
replaceInvalidCharsOptions,
),
"<root><test1>test2\uFFFD</test1></root>",
);
});
it("typeHandlers", () => {
const typeHandlers: ITypeHandlers = {
"[object Null]": () => Absent.instance,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
"[object Number]": (val: any) => val + 17,
};
const typeHandlersOptions: IOptions = {
declaration: {
include: false,
},
format: {
pretty: false,
},
typeHandlers,
};
const typeHandlersWildcard: ITypeHandlers = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
"*": (val: any) => {
if (typeof val === "string") {
return val + "abc";
} else {
return val;
}
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
"[object Number]": (val: any) => val + 17,
};
const typeHandlersWildcardOptions: IOptions = {
declaration: {
include: false,
},
format: {
pretty: false,
},
typeHandlers: typeHandlersWildcard,
};
assert.strictEqual(
parse(
"root",
{
test1: 3,
test2: "test3",
test4: null,
},
typeHandlersOptions,
),
"<root><test1>20</test1><test2>test3</test2></root>",
);
assert.strictEqual(
parse(
"root",
{
test1: 3,
test2: "test3",
test4: null,
},
typeHandlersWildcardOptions,
),
"<root><test1>20</test1><test2>test3abc</test2>" +
"<test4>null</test4></root>",
);
});
it("useSelfClosingTagIfEmpty", () => {
const useSelfClosingTagIfEmptyOptions: IOptions = {
declaration: {
include: false,
},
format: {
pretty: false,
},
useSelfClosingTagIfEmpty: false,
};
assert.strictEqual(
parse(
"root",
{
test1: "",
},
useSelfClosingTagIfEmptyOptions,
),
"<root><test1></test1></root>",
);
assert.strictEqual(
parse(
"root",
{
test1: "",
},
simpleOptions,
),
"<root><test1/></root>",
);
});
it("validation", () => {
const validationOptions: IOptions = {
declaration: {
include: false,
},
format: {
pretty: false,
},
validation: false,
};
assert.strictEqual(
parse(
"root",
{
test1: "\u0001",
},
validationOptions,
),
"<root><test1>\u0001</test1></root>",
);
assert.throws(() =>
parse(
"root",
{
test1: "\u0001",
},
simpleOptions,
),
);
});
it("valueString", () => {
const valueStringOptions: IOptions = {
declaration: {
include: false,
},
format: {
pretty: false,
},
valueString: "valueString",
};
assert.strictEqual(
parse(
"root",
{
test1: {
"#": "test6",
"test2": "test3",
"test4": "test5",
},
test13: {
"#": 3,
},
test14: {
"#": true,
},
test15: {
"#": null,
},
test16: {
"#": undefined,
},
test7: new Map([
["test8", "test9"],
["#", "test10"],
["test11", "test12"],
]),
},
simpleOptions,
),
"<root><test1>test6<test2>test3</test2><test4>test5" +
"</test4></test1><test13>3</test13><test14>true" +
"</test14><test15>null</test15><test16>undefined" +
"</test16><test7><test8>test9</test8>test10<test11>" +
"test12</test11></test7></root>",
);
assert.strictEqual(
parse(
"root",
{
test1: {
test2: "test3",
test4: "test5",
valueString: "test6",
},
},
valueStringOptions,
),
"<root><test1><test2>test3</test2><test4>test5" +
"</test4>test6</test1></root>",
);
});
it("wrapHandlers", () => {
const wrapHandlers: IWrapHandlers = {
test1: () => "test2",
test17: () => null,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
test3: (key: string, value: any) =>
"test4" +
key +
(isSet(value) ? value.values().next().value : value[0]),
};
const wrapHandlersOptions: IOptions = {
declaration: {
include: false,
},
format: {
pretty: false,
},
wrapHandlers,
};
const wrapHandlersWildcard: IWrapHandlers = {
"*": () => "test5",
"test1": () => "test2",
// eslint-disable-next-line @typescript-eslint/no-explicit-any
"test3": (key: string, value: any) =>
"test4" +
key +
(isSet(value) ? value.values().next().value : value[0]),
};
const wrapHandlersWildcardOptions: IOptions = {
declaration: {
include: false,
},
format: {
pretty: false,
},
wrapHandlers: wrapHandlersWildcard,
};
assert.strictEqual(
parse(
"root",
{
test1: ["test6", "test7"],
test10: new Map<string, unknown>([
["test1", ["test11", "test12"]],
["test3", new Set(["test13", "test14"])],
]),
test17: ["test18", "test19"],
test3: new Set(["test8", "test9"]),
},
wrapHandlersOptions,
),
"<root><test1><test2>test6</test2><test2>test7" +
"</test2></test1><test10><test1><test2>test11" +
"</test2><test2>test12</test2></test1><test3>" +
"<test4test3test13>test13</test4test3test13>" +
"<test4test3test13>test14</test4test3test13>" +
"</test3></test10><test17>test18</test17>" +
"<test17>test19</test17><test3><test4test3test8>" +
"test8</test4test3test8><test4test3test8>test9" +
"</test4test3test8></test3></root>",
);
assert.strictEqual(
parse(
"root",
{
test1: ["test6", "test7"],
test10: new Map<string, unknown>([
["test1", ["test11", "test12"]],
["test3", new Set(["test13", "test14"])],
]),
test17: ["test18", "test19"],
test3: new Set(["test8", "test9"]),
},
wrapHandlersWildcardOptions,
),
"<root><test1><test2>test6</test2><test2>test7</test2>" +
"</test1><test10><test1><test2>test11</test2><test2>" +
"test12</test2></test1><test3><test4test3test13>" +
"test13</test4test3test13><test4test3test13>test14" +
"</test4test3test13></test3></test10><test17><test5>" +
"test18</test5><test5>test19</test5></test17><test3>" +
"<test4test3test8>test8</test4test3test8>" +
"<test4test3test8>test9</test4test3test8></test3>" +
"</root>",
);
});
});
});
it("#parseToExistingElement", () => {
const d = document();
d.procInst({ target: "test4" });
const e = d.element({ name: "test" });
parseToExistingElement(e, { test2: "test3" }, simpleOptions);
assert.strictEqual(
d.toString({ pretty: false }),
"<?test4?><test><test2>test3</test2></test>",
);
});
}); | the_stack |
if ((typeof global !== "undefined") && !(global as any).document) {
(global as any).document = {};
}
import _sodium from "libsodium-wrappers";
import * as Argon2 from "argon2-webworker";
import * as Constants from "./Constants";
import { numToUint8Array, symmetricNonceSize } from "./Helpers";
import { Rollsum } from "./Chunker";
import type rnsodiumType from "react-native-sodium";
import { ProgrammingError } from "./Exceptions";
const sodium = _sodium;
let rnsodium: typeof rnsodiumType;
export function _setRnSodium(rnsodium_: any) {
rnsodium = rnsodium_;
}
export const ready = (async () => {
await sodium.ready;
})();
export function concatArrayBuffers(buffer1: Uint8Array, buffer2: Uint8Array): Uint8Array {
const ret = new Uint8Array(buffer1.length + buffer2.length);
ret.set(buffer1, 0);
ret.set(buffer2, buffer1.length);
return ret;
}
export function concatArrayBuffersArrays(buffers: Uint8Array[]): Uint8Array {
const length = buffers.reduce((x, y) => x + y.length, 0);
const ret = new Uint8Array(length);
let pos = 0;
for (const buffer of buffers) {
ret.set(buffer, pos);
pos += buffer.length;
}
return ret;
}
export enum KeyDerivationDifficulty {
Hard = 90,
Medium = 50,
Easy = 10,
}
export async function deriveKey(salt: Uint8Array, password: string, difficulty = KeyDerivationDifficulty.Hard): Promise<Uint8Array> {
salt = salt.subarray(0, sodium.crypto_pwhash_SALTBYTES);
let opslimit: number;
switch (difficulty) {
case KeyDerivationDifficulty.Hard:
opslimit = sodium.crypto_pwhash_OPSLIMIT_SENSITIVE;
break;
case KeyDerivationDifficulty.Medium:
opslimit = sodium.crypto_pwhash_OPSLIMIT_MODERATE;
break;
case KeyDerivationDifficulty.Easy:
opslimit = sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE;
break;
default:
throw new ProgrammingError("Passed invalid difficulty.");
}
try {
const ret = await Argon2.hash({
hashLen: 32,
pass: password,
salt,
time: opslimit,
mem: sodium.crypto_pwhash_MEMLIMIT_MODERATE / 1024,
parallelism: 1,
type: Argon2.ArgonType.Argon2id,
});
return ret.hash;
} catch (e) {
if (typeof(Worker) !== "undefined") {
// Web worker failed
console.warn("Failed loading web worker!", e);
}
}
if (rnsodium) {
const ret = await rnsodium.crypto_pwhash(
32,
sodium.to_base64(sodium.from_string(password), sodium.base64_variants.ORIGINAL),
sodium.to_base64(salt, sodium.base64_variants.ORIGINAL),
opslimit,
sodium.crypto_pwhash_MEMLIMIT_MODERATE,
sodium.crypto_pwhash_ALG_DEFAULT
);
return sodium.from_base64(ret, sodium.base64_variants.ORIGINAL);
}
return sodium.crypto_pwhash(
32,
sodium.from_string(password),
salt,
opslimit,
sodium.crypto_pwhash_MEMLIMIT_MODERATE,
sodium.crypto_pwhash_ALG_DEFAULT
);
}
export class CryptoManager {
protected version: number;
protected cipherKey: Uint8Array;
protected macKey: Uint8Array;
protected asymKeySeed: Uint8Array;
protected subDerivationKey: Uint8Array;
protected determinsticEncryptionKey: Uint8Array;
constructor(key: Uint8Array, keyContext: string, version: number = Constants.CURRENT_VERSION) {
keyContext = keyContext.padEnd(8);
this.version = version;
this.cipherKey = sodium.crypto_kdf_derive_from_key(32, 1, keyContext, key);
this.macKey = sodium.crypto_kdf_derive_from_key(32, 2, keyContext, key);
this.asymKeySeed = sodium.crypto_kdf_derive_from_key(32, 3, keyContext, key);
this.subDerivationKey = sodium.crypto_kdf_derive_from_key(32, 4, keyContext, key);
this.determinsticEncryptionKey = sodium.crypto_kdf_derive_from_key(32, 5, keyContext, key);
}
public encrypt(message: Uint8Array, additionalData: Uint8Array | null = null): Uint8Array {
const nonce = sodium.randombytes_buf(symmetricNonceSize);
return concatArrayBuffers(nonce,
sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(message, additionalData, null, nonce, this.cipherKey));
}
public decrypt(nonceCiphertext: Uint8Array, additionalData: Uint8Array | null = null): Uint8Array {
const nonce = nonceCiphertext.subarray(0, symmetricNonceSize);
const ciphertext = nonceCiphertext.subarray(symmetricNonceSize);
return sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(null, ciphertext, additionalData, nonce, this.cipherKey);
}
public encryptDetached(message: Uint8Array, additionalData: Uint8Array | null = null): [Uint8Array, Uint8Array] {
const nonce = sodium.randombytes_buf(symmetricNonceSize);
const ret = sodium.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(message, additionalData, null, nonce, this.cipherKey);
return [ret.mac, concatArrayBuffers(nonce, ret.ciphertext)];
}
public decryptDetached(nonceCiphertext: Uint8Array, mac: Uint8Array, additionalData: Uint8Array | null = null): Uint8Array {
const nonce = nonceCiphertext.subarray(0, symmetricNonceSize);
const ciphertext = nonceCiphertext.subarray(symmetricNonceSize);
return sodium.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(null, ciphertext, mac, additionalData, nonce, this.cipherKey);
}
public verify(nonceCiphertext: Uint8Array, mac: Uint8Array, additionalData: Uint8Array | null = null): boolean {
const nonce = nonceCiphertext.subarray(0, symmetricNonceSize);
const ciphertext = nonceCiphertext.subarray(symmetricNonceSize);
sodium.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(null, ciphertext, mac, additionalData, nonce, this.cipherKey, null);
return true;
}
public deterministicEncrypt(message: Uint8Array, additionalData: Uint8Array | null = null): Uint8Array {
// FIXME: we could me slightly more efficient (save 8 bytes) and use crypto_stream_xchacha20_xor directly, and
// just have the mac be used to verify. Though that function is not exposed in libsodium.js (the slimmer version),
// and it's easier to get wrong, so we are just using the full xchacha20poly1305 we already use anyway.
const nonce = this.calculateMac(message).subarray(0, symmetricNonceSize);
return concatArrayBuffers(nonce,
sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(message, additionalData, null, nonce, this.determinsticEncryptionKey));
}
public deterministicDecrypt(nonceCiphertext: Uint8Array, additionalData: Uint8Array | null = null): Uint8Array {
const nonce = nonceCiphertext.subarray(0, symmetricNonceSize);
const ciphertext = nonceCiphertext.subarray(symmetricNonceSize);
return sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(null, ciphertext, additionalData, nonce, this.determinsticEncryptionKey);
}
public deriveSubkey(salt: Uint8Array): Uint8Array {
return sodium.crypto_generichash(32, this.subDerivationKey, salt);
}
public getCryptoMac(withKey = true) {
const key = (withKey) ? this.macKey : null;
return new CryptoMac(key);
}
public calculateMac(message: Uint8Array, withKey = true) {
const key = (withKey) ? this.macKey : null;
return sodium.crypto_generichash(32, message, key);
}
public getChunker() {
return new Rollsum();
}
}
export class LoginCryptoManager {
private keypair: _sodium.KeyPair;
private constructor(keypair: _sodium.KeyPair) {
this.keypair = keypair;
}
public static keygen(seed: Uint8Array) {
return new this(sodium.crypto_sign_seed_keypair(seed));
}
public signDetached(message: Uint8Array): Uint8Array {
return sodium.crypto_sign_detached(message, this.keypair.privateKey);
}
public static verifyDetached(message: Uint8Array, signature: Uint8Array, pubkey: Uint8Array): boolean {
return sodium.crypto_sign_verify_detached(signature, message, pubkey);
}
public get pubkey() {
return this.keypair.publicKey;
}
}
export class BoxCryptoManager {
private keypair: _sodium.KeyPair;
private constructor(keypair: _sodium.KeyPair) {
this.keypair = keypair;
}
public static keygen(seed?: Uint8Array) {
if (seed) {
return new this(sodium.crypto_box_seed_keypair(seed));
} else {
return new this(sodium.crypto_box_keypair());
}
}
public static fromPrivkey(privkey: Uint8Array) {
return new this({
keyType: "x25519",
privateKey: privkey,
publicKey: sodium.crypto_scalarmult_base(privkey),
});
}
public encrypt(message: Uint8Array, pubkey: Uint8Array): Uint8Array {
const nonce = sodium.randombytes_buf(sodium.crypto_box_NONCEBYTES);
const ret = sodium.crypto_box_easy(message, nonce, pubkey, this.keypair.privateKey);
return concatArrayBuffers(nonce, ret);
}
public decrypt(nonceCiphertext: Uint8Array, pubkey: Uint8Array): Uint8Array {
const nonceSize = sodium.crypto_box_NONCEBYTES;
const nonce = nonceCiphertext.subarray(0, nonceSize);
const ciphertext = nonceCiphertext.subarray(nonceSize);
return sodium.crypto_box_open_easy(ciphertext, nonce, pubkey, this.keypair.privateKey);
}
public get pubkey() {
return this.keypair.publicKey;
}
public get privkey() {
return this.keypair.privateKey;
}
}
export class CryptoMac {
private state: _sodium.StateAddress;
private length: number;
constructor(key: Uint8Array | null, length = 32) {
this.length = length;
this.state = sodium.crypto_generichash_init(key, length);
}
public updateWithLenPrefix(messageChunk: Uint8Array) {
sodium.crypto_generichash_update(this.state, numToUint8Array(messageChunk.length));
sodium.crypto_generichash_update(this.state, messageChunk);
}
public update(messageChunk: Uint8Array) {
sodium.crypto_generichash_update(this.state, messageChunk);
}
public finalize() {
return sodium.crypto_generichash_final(this.state, this.length);
}
}
function getEncodedChunk(content: Uint8Array, offset: number) {
const num = ((content[offset] << 16) +
(content[offset + 1] << 8) +
content[offset + 2]) % 100000;
return num.toString().padStart(5, "0");
}
export function getPrettyFingerprint(content: Uint8Array, delimiter = " ") {
const fingerprint = sodium.crypto_generichash(32, content);
/* We use 3 bytes each time to generate a 5 digit number - this means 10 pairs for bytes 0-29
* We then use bytes 29-31 for another number, and then the 3 most significant bits of each first byte for the last.
*/
let ret = "";
let lastNum = 0;
for (let i = 0 ; i < 10 ; i++) {
const suffix = (i % 4 === 3) ? "\n" : delimiter;
ret += getEncodedChunk(fingerprint, i * 3) + suffix;
lastNum = (lastNum << 3) | ((fingerprint[i] & 0xE0) >>> 5);
}
ret += getEncodedChunk(fingerprint, 29) + delimiter;
ret += (lastNum % 100000).toString().padStart(5, "0");
return ret;
} | the_stack |
import "./helpers/dotenv_helper";
import { getTestId, getState, dispatch } from "./helpers/test_helper";
import { query } from "@api_shared/db";
import { acceptDeviceGrant } from "./helpers/device_grants_helper";
import * as R from "ramda";
import { registerWithEmail, loadAccount } from "./helpers/auth_helper";
import { createApp } from "./helpers/apps_helper";
import { createBlock } from "./helpers/blocks_helper";
import { getAuth, getEnvWithMeta } from "@core/lib/client";
import { Client, Api } from "@core/types";
import { graphTypes } from "@core/lib/graph";
import { acceptInvite } from "./helpers/invites_helper";
import {
updateEnvs,
updateLocals,
getEnvironments,
} from "./helpers/envs_helper";
import waitForExpect from "wait-for-expect";
describe("devices", () => {
let email: string, orgId: string, ownerId: string;
beforeEach(async () => {
email = `success+${getTestId()}@simulator.amazonses.com`;
({ orgId, userId: ownerId } = await registerWithEmail(email));
});
describe("managing access", () => {
let appId: string, blockId: string, granteeId: string, granteeEmail: string;
beforeEach(async () => {
let state = getState(ownerId);
const { orgRoles } = graphTypes(state.graph),
orgAdminRole = R.indexBy(R.prop("name"), orgRoles)["Org Admin"];
[{ id: appId }, { id: blockId }] = [
await createApp(ownerId),
await createBlock(ownerId),
];
await updateEnvs(ownerId, appId);
await updateLocals(ownerId, appId);
await updateEnvs(ownerId, blockId);
await updateLocals(ownerId, blockId);
await dispatch(
{
type: Client.ActionType.INVITE_USERS,
payload: [
{
user: {
firstName: "Admin",
lastName: "Test",
email: `success+grantee-${getTestId()}@simulator.amazonses.com`,
provider: <const>"email",
uid: `success+grantee-${getTestId()}@simulator.amazonses.com`,
orgRoleId: orgAdminRole.id,
},
},
],
},
ownerId
);
state = getState(ownerId);
const invite = state.generatedInvites[0];
({ id: granteeId, email: granteeEmail } = invite.user);
await acceptInvite(invite);
state = getState(granteeId);
await dispatch(
{
type: Client.ActionType.FORGET_DEVICE,
payload: {
accountId: granteeId,
},
},
granteeId
);
// force refresh owner graph
await loadAccount(ownerId);
});
test("generate, load, and accept a device grant, then revoke device", async () => {
let state = getState(ownerId);
await dispatch(
{ type: Client.ActionType.CLEAR_GENERATED_DEVICE_GRANTS },
ownerId
);
const approveDeviceParams = [{ granteeId }],
approveDevicesPromise = dispatch(
{
type: Client.ActionType.APPROVE_DEVICES,
payload: approveDeviceParams,
},
ownerId
);
await waitForExpect(() => {
state = getState(ownerId);
expect(Object.values(state.generatingDeviceGrants)[0]).toEqual(
approveDeviceParams
);
});
const approveRes = await approveDevicesPromise;
expect(approveRes.success).toBeTrue();
await waitForExpect(() => {
state = getState(ownerId);
expect(state.generatingDeviceGrants).toEqual({});
expect(state.generatedDeviceGrants.length).toBe(1);
});
const generatedDeviceGrant = state.generatedDeviceGrants[0];
// test envs update with active device grant
for (let envParentId of [appId, blockId]) {
const environments = getEnvironments(ownerId, envParentId),
[development] = environments;
dispatch(
{
type: Client.ActionType.CREATE_ENTRY_ROW,
payload: {
envParentId: envParentId,
entryKey: "GRANT_KEY",
vals: {
[development.id]: { val: "grant-val" },
},
},
},
ownerId
);
dispatch(
{
type: Client.ActionType.CREATE_ENTRY,
payload: {
envParentId: envParentId,
environmentId: [envParentId, ownerId].join("|"),
entryKey: "GRANT_KEY",
val: { val: "grant-val" },
},
},
ownerId
);
}
await dispatch(
{
type: Client.ActionType.COMMIT_ENVS,
payload: { message: "commit message" },
},
ownerId
);
state = getState(ownerId);
await acceptDeviceGrant(granteeId, generatedDeviceGrant);
state = getState(granteeId);
const granteeDeviceId = getAuth<Client.ClientUserAuth>(
state,
granteeId
)!.deviceId;
await dispatch(
{
type: Client.ActionType.GET_SESSION,
},
granteeId
);
await dispatch(
{
type: Client.ActionType.FETCH_ENVS,
payload: {
byEnvParentId: [appId, blockId].reduce(
(agg, id) => ({ ...agg, [id]: { envs: true, changesets: true } }),
{}
),
},
},
granteeId
);
state = getState(granteeId);
for (let envParentId of [appId, blockId]) {
const environments = getEnvironments(granteeId, envParentId),
[development, staging, production] = environments;
expect(
getEnvWithMeta(state, {
envParentId,
environmentId: development.id,
})
).toEqual({
inherits: {},
variables: {
KEY2: { isUndefined: true },
KEY3: { val: "key3-val" },
GRANT_KEY: { val: "grant-val" },
IMPORTED_KEY1: { val: "imported-val" },
IMPORTED_KEY2: { val: "imported-val" },
},
});
expect(
getEnvWithMeta(state, {
envParentId,
environmentId: staging.id,
})
).toEqual({
inherits: {},
variables: {
KEY2: { isEmpty: true, val: "" },
KEY3: { val: "key3-val" },
},
});
expect(
getEnvWithMeta(state, {
envParentId,
environmentId: production.id,
})
).toEqual({
inherits: {},
variables: { KEY2: { val: "val3" }, KEY3: { val: "key3-val" } },
});
expect(
getEnvWithMeta(state, {
envParentId,
environmentId: [envParentId, ownerId].join("|"),
})
).toEqual({
inherits: {},
variables: {
KEY2: { isUndefined: true },
KEY3: { val: "key3-locals-val" },
GRANT_KEY: { val: "grant-val" },
IMPORTED_KEY1: { val: "imported-val" },
IMPORTED_KEY2: { val: "imported-val" },
},
});
}
expect(Object.values(state.changesets)).toEqual(
expect.arrayContaining([
expect.objectContaining({
key: expect.toBeString(),
changesets: expect.arrayContaining([
expect.objectContaining({
message: "commit message",
actions: expect.arrayContaining([
expect.objectContaining({
type: expect.toBeString(),
payload: expect.toBeObject(),
meta: expect.toBeObject(),
}),
]),
}),
]),
}),
])
);
// revoke device
const promise = dispatch(
{
type: Api.ActionType.REVOKE_DEVICE,
payload: { id: granteeDeviceId },
},
ownerId
);
await waitForExpect(() => {
state = getState(ownerId);
expect(state.isRemoving[granteeDeviceId]).toBeTrue();
});
const revokeRes = await promise;
expect(revokeRes.success).toBeTrue();
state = getState(ownerId);
expect(state.isRemoving[granteeDeviceId]).toBeUndefined();
// ensure revoked device can't authenticate
const authRes = await dispatch(
{
type: Client.ActionType.GET_SESSION,
},
granteeId
);
expect(authRes.success).toBeFalse();
// ensure revoked device can't be revoked again
const shouldFailRes = await dispatch(
{
type: Api.ActionType.REVOKE_DEVICE,
payload: { id: granteeDeviceId },
},
ownerId
);
expect(shouldFailRes.success).toBeFalse();
});
test("revoke device grant", async () => {
await dispatch(
{
type: Client.ActionType.APPROVE_DEVICES,
payload: [{ granteeId }],
},
ownerId
);
let state = getState(ownerId);
const generatedDeviceGrant = state.generatedDeviceGrants.slice(-1)[0];
const deviceGrant = graphTypes(state.graph).deviceGrants.find(
R.propEq("createdAt", state.graphUpdatedAt)
)!,
promise = dispatch(
{
type: Api.ActionType.REVOKE_DEVICE_GRANT,
payload: { id: deviceGrant.id },
},
ownerId
);
state = getState(ownerId);
expect(state.isRemoving[deviceGrant.id]).toBeTrue();
const res = await promise;
expect(res.success).toBeTrue();
state = getState(ownerId);
expect(state.isRemoving[deviceGrant.id]).toBeUndefined();
// ensure revoked device grant can't be loaded
const [{ skey: emailToken }] = await query<Api.Db.DeviceGrantPointer>({
pkey: ["deviceGrant", generatedDeviceGrant.identityHash].join("|"),
transactionConn: undefined,
}),
loadRes = await dispatch<
Client.Action.ClientActions["LoadDeviceGrant"]
>(
{
type: Client.ActionType.LOAD_DEVICE_GRANT,
payload: {
emailToken,
encryptionToken: [
generatedDeviceGrant.identityHash,
generatedDeviceGrant.encryptionKey,
].join("_"),
},
},
undefined
);
expect(loadRes.success).toBeFalse();
});
});
}); | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/disasterRecoveryConfigsMappers";
import * as Parameters from "../models/parameters";
import { EventHubManagementClientContext } from "../eventHubManagementClientContext";
/** Class representing a DisasterRecoveryConfigs. */
export class DisasterRecoveryConfigs {
private readonly client: EventHubManagementClientContext;
/**
* Create a DisasterRecoveryConfigs.
* @param {EventHubManagementClientContext} client Reference to the service client.
*/
constructor(client: EventHubManagementClientContext) {
this.client = client;
}
/**
* Gets a list of authorization rules for a Namespace.
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param namespaceName The Namespace name
* @param alias The Disaster Recovery configuration name
* @param [options] The optional parameters
* @returns Promise<Models.DisasterRecoveryConfigsListAuthorizationRulesResponse>
*/
listAuthorizationRules(resourceGroupName: string, namespaceName: string, alias: string, options?: msRest.RequestOptionsBase): Promise<Models.DisasterRecoveryConfigsListAuthorizationRulesResponse>;
/**
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param namespaceName The Namespace name
* @param alias The Disaster Recovery configuration name
* @param callback The callback
*/
listAuthorizationRules(resourceGroupName: string, namespaceName: string, alias: string, callback: msRest.ServiceCallback<Models.AuthorizationRuleListResult>): void;
/**
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param namespaceName The Namespace name
* @param alias The Disaster Recovery configuration name
* @param options The optional parameters
* @param callback The callback
*/
listAuthorizationRules(resourceGroupName: string, namespaceName: string, alias: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AuthorizationRuleListResult>): void;
listAuthorizationRules(resourceGroupName: string, namespaceName: string, alias: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AuthorizationRuleListResult>, callback?: msRest.ServiceCallback<Models.AuthorizationRuleListResult>): Promise<Models.DisasterRecoveryConfigsListAuthorizationRulesResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
namespaceName,
alias,
options
},
listAuthorizationRulesOperationSpec,
callback) as Promise<Models.DisasterRecoveryConfigsListAuthorizationRulesResponse>;
}
/**
* Gets an AuthorizationRule for a Namespace by rule name.
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param namespaceName The Namespace name
* @param alias The Disaster Recovery configuration name
* @param authorizationRuleName The authorization rule name.
* @param [options] The optional parameters
* @returns Promise<Models.DisasterRecoveryConfigsGetAuthorizationRuleResponse>
*/
getAuthorizationRule(resourceGroupName: string, namespaceName: string, alias: string, authorizationRuleName: string, options?: msRest.RequestOptionsBase): Promise<Models.DisasterRecoveryConfigsGetAuthorizationRuleResponse>;
/**
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param namespaceName The Namespace name
* @param alias The Disaster Recovery configuration name
* @param authorizationRuleName The authorization rule name.
* @param callback The callback
*/
getAuthorizationRule(resourceGroupName: string, namespaceName: string, alias: string, authorizationRuleName: string, callback: msRest.ServiceCallback<Models.AuthorizationRule>): void;
/**
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param namespaceName The Namespace name
* @param alias The Disaster Recovery configuration name
* @param authorizationRuleName The authorization rule name.
* @param options The optional parameters
* @param callback The callback
*/
getAuthorizationRule(resourceGroupName: string, namespaceName: string, alias: string, authorizationRuleName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AuthorizationRule>): void;
getAuthorizationRule(resourceGroupName: string, namespaceName: string, alias: string, authorizationRuleName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AuthorizationRule>, callback?: msRest.ServiceCallback<Models.AuthorizationRule>): Promise<Models.DisasterRecoveryConfigsGetAuthorizationRuleResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
namespaceName,
alias,
authorizationRuleName,
options
},
getAuthorizationRuleOperationSpec,
callback) as Promise<Models.DisasterRecoveryConfigsGetAuthorizationRuleResponse>;
}
/**
* Gets the primary and secondary connection strings for the Namespace.
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param namespaceName The Namespace name
* @param alias The Disaster Recovery configuration name
* @param authorizationRuleName The authorization rule name.
* @param [options] The optional parameters
* @returns Promise<Models.DisasterRecoveryConfigsListKeysResponse>
*/
listKeys(resourceGroupName: string, namespaceName: string, alias: string, authorizationRuleName: string, options?: msRest.RequestOptionsBase): Promise<Models.DisasterRecoveryConfigsListKeysResponse>;
/**
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param namespaceName The Namespace name
* @param alias The Disaster Recovery configuration name
* @param authorizationRuleName The authorization rule name.
* @param callback The callback
*/
listKeys(resourceGroupName: string, namespaceName: string, alias: string, authorizationRuleName: string, callback: msRest.ServiceCallback<Models.AccessKeys>): void;
/**
* @param resourceGroupName Name of the resource group within the azure subscription.
* @param namespaceName The Namespace name
* @param alias The Disaster Recovery configuration name
* @param authorizationRuleName The authorization rule name.
* @param options The optional parameters
* @param callback The callback
*/
listKeys(resourceGroupName: string, namespaceName: string, alias: string, authorizationRuleName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AccessKeys>): void;
listKeys(resourceGroupName: string, namespaceName: string, alias: string, authorizationRuleName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AccessKeys>, callback?: msRest.ServiceCallback<Models.AccessKeys>): Promise<Models.DisasterRecoveryConfigsListKeysResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
namespaceName,
alias,
authorizationRuleName,
options
},
listKeysOperationSpec,
callback) as Promise<Models.DisasterRecoveryConfigsListKeysResponse>;
}
/**
* Gets a list of authorization rules for a Namespace.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.DisasterRecoveryConfigsListAuthorizationRulesNextResponse>
*/
listAuthorizationRulesNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.DisasterRecoveryConfigsListAuthorizationRulesNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listAuthorizationRulesNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.AuthorizationRuleListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listAuthorizationRulesNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AuthorizationRuleListResult>): void;
listAuthorizationRulesNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AuthorizationRuleListResult>, callback?: msRest.ServiceCallback<Models.AuthorizationRuleListResult>): Promise<Models.DisasterRecoveryConfigsListAuthorizationRulesNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listAuthorizationRulesNextOperationSpec,
callback) as Promise<Models.DisasterRecoveryConfigsListAuthorizationRulesNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listAuthorizationRulesOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}/authorizationRules",
urlParameters: [
Parameters.resourceGroupName,
Parameters.namespaceName,
Parameters.alias,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion1
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AuthorizationRuleListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const getAuthorizationRuleOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}/authorizationRules/{authorizationRuleName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.namespaceName,
Parameters.alias,
Parameters.authorizationRuleName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion1
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AuthorizationRule
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listKeysOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}/authorizationRules/{authorizationRuleName}/listKeys",
urlParameters: [
Parameters.resourceGroupName,
Parameters.namespaceName,
Parameters.alias,
Parameters.authorizationRuleName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion1
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AccessKeys
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listAuthorizationRulesNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AuthorizationRuleListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
}; | the_stack |
import * as React from 'react';
import * as ClickOutHandler from 'react-onclickout';
import { Icon } from "office-ui-fabric-react/lib/Icon";
import { MessageBar, MessageBarType } from "office-ui-fabric-react/lib/MessageBar";
import { SearchBox } from "office-ui-fabric-react/lib/SearchBox";
import IGlobalNavigationProps from './IGlobalNavigationProps';
import IGlobalNavigationState from './IGlobalNavigationState';
import NavigationElement, { INavigationElementProps } from './NavigationElement';
import styles from './GlobalNavigation.module.scss';
import * as Breakpoints from "./Breakpoints";
export default class GlobalNavigation extends React.PureComponent<IGlobalNavigationProps, IGlobalNavigationState> {
constructor(props: IGlobalNavigationProps) {
super(props);
this.state = { isExpanded: false, items: [], isXtraLarge: this.isLargerThanLarge(), isLoading: true };
this._onToggle = this._onToggle.bind(this);
this._onWindowResize = this._onWindowResize.bind(this);
}
public componentWillUnmount() {
window.removeEventListener("resize", _ => this._onWindowResize());
this._onWindowResize();
}
public async componentDidMount() {
try {
let data = await this.getData();
this.setState(data);
window.addEventListener("resize", _ => this._onWindowResize());
} catch (error) {
this.setState({ error: error });
}
}
public render() {
if (this.state.error) {
return (
<div className={styles.globalNavigation}>
<MessageBar messageBarType={MessageBarType.severeWarning}>{this.props.errorText}</MessageBar>
</div>
);
} else if (!this.state.isLoading) {
const HomeButton = this.renderHomeButton;
const FocusButton = this.renderFocusButton;
const HelpButton = this.renderHelpButton;
const NavSearchBox = this.renderSearchBox;
const settings = this.props.settings ? this.props.settings : {};
const textColor = settings.navToggleTextColor ? settings.navToggleTextColor : '';
const backgroundColor = settings.navToggleBackgroundColor ? settings.navToggleBackgroundColor : '';
const linkTextColor = settings.linkTextColor ? settings.linkTextColor : '';
const navContentBackgroundColor = settings.navContentBackgroundColor ? settings.navContentBackgroundColor : '';
return (
<ClickOutHandler onClickOut={e => this._onToggle(e, false)}>
<div className={`${styles.globalNavigation} ${this.state.isFocusToggled ? ' isFocusToggled' : ''}`}>
<div className={`${styles.toggleNavRow}`} style={{ color: textColor, backgroundColor: backgroundColor }} >
{settings.homeButtonFloatLeft ? <HomeButton /> : ''}
<div className={`${styles.toggleNavColumn}`} onClick={this._onToggle}>
<div className={styles.toggleNav}>
<span className={styles.toggleNavText}>{settings.navToggleText ? settings.navToggleText : 'Menu'}</span>
<Icon className={styles.toggleNavIcon} iconName={this.state.isExpanded ? "ChevronUp" : "ChevronDown"} />
</div>
</div>
<NavSearchBox />
<FocusButton />
{settings.homeButtonFloatLeft ? '' : <HomeButton />}
<HelpButton />
</div>
<div className={styles.navRowsContainer} style={{ color: linkTextColor, backgroundColor: navContentBackgroundColor }}>
{this.state.isExpanded ? this.renderRows() : null}
</div>
</div>
</ClickOutHandler>
);
} else {
return null;
}
}
/**
*
*
* @memberof GlobalNavigation
*/
public closeDialog() {
setTimeout(() => {
this.setState({ isExpanded: false });
}, 200);
}
private async getData(): Promise<Partial<IGlobalNavigationState>> {
let navigationElements;
let errorCount = 2;
while (errorCount > 0) {
try {
navigationElements = await this.props.dataFetch.fetch();
break;
} catch (error) {
errorCount--;
if (errorCount == 0) throw error;
}
}
navigationElements = navigationElements.filter(element => element.order > -1);
return ({
items: navigationElements,
isLoading: false,
});
}
/**
* Renders a row for every X columns
*/
private renderRows() {
const settings = this.props.settings ? this.props.settings : {};
const linkTextColor = settings.linkTextColor ? settings.linkTextColor : '';
const navHeaderTextColor = settings.navHeaderTextColor ? settings.navHeaderTextColor : '';
const navContentBackgroundColor = settings.navContentBackgroundColor ? settings.navContentBackgroundColor : '';
const navColumns = settings.navColumns ? +settings.navColumns : 5;
const elementsWithItems = this.state.items.filter(item => item.links.length > 0);
const rows = [];
const flexDirection = this.state.isXtraLarge ? styles.isLarge : styles.isSmall;
let numberOfColumns = navColumns;
if (!numberOfColumns || numberOfColumns < 0) {
numberOfColumns = 5;
}
for (let i = 0; i < elementsWithItems.length; i += numberOfColumns) {
const row = (
<div className={[styles.navElementsRow, flexDirection].join(" ")} style={{ color: linkTextColor, backgroundColor: navContentBackgroundColor }}>
{[].concat(elementsWithItems).slice(i, i + numberOfColumns).map(item => {
const props: INavigationElementProps = {
...item,
navHeaderTextColor: navHeaderTextColor,
linkTextColor: linkTextColor
};
return <NavigationElement {...props} />;
})}
</div>
);
rows.push(row);
}
return rows;
}
private _onToggle(e, isExpanded?: boolean) {
if (typeof isExpanded !== 'undefined') {
// hide id clicked outside the menu
this.setState({ isExpanded: false });
} else {
this.setState(prevState => ({ isExpanded: !prevState.isExpanded }));
}
}
/**
* On window resize
*
* @param {boolean} initial True if initial call from constructor()
*/
private _onWindowResize() {
let isXtraLarge = this.isLargerThanLarge();
this.setState({ isXtraLarge: isXtraLarge });
}
private isLargerThanLarge(): boolean {
const deviceWidthStr = Breakpoints.GetCurrentBreakpoint();
let isXtraLarge;
switch (deviceWidthStr) {
case "sm": case "md": case "lg": isXtraLarge = false;
break;
default: isXtraLarge = true;
}
return isXtraLarge;
}
private renderHomeButton = () => {
const settings = this.props.settings ? this.props.settings : {};
const textColor = settings.homeButtonTextColor ? settings.homeButtonTextColor : '#ffffff';
const backgroundColor = settings.homeButtonColor ? settings.homeButtonColor : '';
const homeButtonUrl = settings.homeButtonUrl ? settings.homeButtonUrl : '';
const isHidden = (settings.homeButtonEnabled === 'false' || (settings.homeButtonMobileOnly === 'true' && !this.state.isXtraLarge));
return (
<div className={`${styles.homeButtonContainer}`} style={{ color: textColor, backgroundColor: backgroundColor }} hidden={isHidden}>
<a href={homeButtonUrl} title={settings.homeButtonText ? settings.homeButtonText : ''}>
<Icon style={{ color: textColor }} iconName={settings.homeButtonIcon ? settings.homeButtonIcon : 'Home'} />
</a>
</div>
);
}
private toggleFocus() {
const toggleFocusSelectors = [
"div.od-SuiteNav",
"div.commandBarWrapper",
"#SuiteNavPlaceHolder",
"div[role='banner']",
"div.sp-pageLayout-sideNav div[class^='spNav_']",
"div.sp-App--hasLeftNav .Files-leftNav"
];
toggleFocusSelectors.forEach(selector => {
this.toggleElement(selector);
});
}
private toggleElement(selector) {
let element = document.querySelector(selector);
element ?
element.style.display == "none" ?
element.style.display = "block" :
element.style.display = "none" :
console.log(`Pzl.Megamenu.FocusOnContent: element ${selector} not found.`);
}
private renderFocusButton = () => {
const settings = this.props.settings ? this.props.settings : {};
const textColor = settings.focusButtonTextColor ? settings.focusButtonTextColor : '#ffffff';
const backgroundColor = settings.focusButtonColor ? settings.focusButtonColor : '';
const backgroundColorWhenActive = settings.focusButtonActiveColor ? settings.focusButtonActiveColor : '#000000';
const isHidden = settings.focusButtonEnabled !== 'true';
return (
<div className={`${styles.focusButtonContainer}`} style={{ color: textColor, backgroundColor: this.state.isFocusToggled ? backgroundColorWhenActive : backgroundColor }} hidden={isHidden}>
<Icon onClick={() => {
this.setState({ isFocusToggled: !this.state.isFocusToggled });
this.toggleFocus();
}} title={settings.focusButtonText ? settings.focusButtonText : 'Focus on content'} style={{ color: textColor, backgroundColor: this.state.isFocusToggled ? backgroundColorWhenActive : backgroundColor }} iconName={settings.focusButtonIcon ? settings.focusButtonIcon : 'ZoomToFit'} />
</div>
);
}
private renderHelpButton = () => {
const settings = this.props.settings ? this.props.settings : {};
const textColor = settings.helpButtonTextColor ? settings.helpButtonTextColor : '#ffffff';
const backgroundColor = settings.helpButtonColor ? settings.helpButtonColor : 'ff0000';
const buttonText = settings.helpButtonText ? settings.helpButtonText : '';
const helpButtonUrl = settings.helpButtonUrl ? settings.helpButtonUrl : '';
return (
<div className={`${styles.supportLinkContainer}`} style={{ backgroundColor: backgroundColor }} hidden={!(settings.helpButtonEnabled === 'true')}>
<a href={helpButtonUrl} style={{ color: textColor }} target="_blank" >
<Icon iconName={settings.helpButtonIcon ? settings.helpButtonIcon : 'Home'} />
<span>{this.state.isXtraLarge ? <span className={styles.supportLinkText}>{buttonText}</span> : null}</span>
</a>
</div>
);
}
private renderSearchBox = () => {
const settings = this.props.settings ? this.props.settings : {};
return (
<div className={`${styles.searchBoxContainer}`} hidden={settings.searchBarEnabled !== 'true' || !this.state.isXtraLarge}>
<SearchBox className={styles.searchBox} onSearch={(query) => this.onSearch(query, settings.searchBarUrlParam)} placeholder={settings.searchBarPlaceholder ? settings.searchBarPlaceholder : 'Search'} />
</div>
);
}
private onSearch(searchValue, queryParam?: string) {
const safeQueryParam = (queryParam && queryParam.length > 0) ? queryParam : 'q';
const searchUrl = this.props.settings && this.props.settings.searchBarSearchUrl ? this.props.settings.searchBarSearchUrl : `${this.props.currentSiteUrl}/_layouts/15/search.aspx`;
const searchUrlWithParams = searchUrl.indexOf('?') > -1 ? searchUrl : `${searchUrl}?${safeQueryParam}=`;
location.href = `${searchUrlWithParams}${searchValue}`;
}
}
export {
IGlobalNavigationProps,
IGlobalNavigationState,
}; | the_stack |
import { CrossEditSuspiciousPatternsInfo, Revision } from './interface';
import {
DecisionLogProps,
DecisionLogDoc,
} from '~/shared/models/decision-log.model';
export class CrossEditSuspiciousPatterns implements Revision {
// Enum of Operating Mode of the CrossEditSuspiciousPatterns Detection Mechanism.
// Two Possibilities: "author" for author-based detection and "article" for article-based detection.
mode:string;
// Configurable Parameters
// These are set upon creation and are fixed during analysis process
url:string;
windowSize:number;
baseline:number;
percentage:number;
margin:number;
warningTimeframe:number; // Timeframe to get previous warnings to determine blocks, in days
warningThreshold:number;
revID:string;
axiosClient:any;
db;
// Adding additional fields because the instance's execution will be suspended awaiting the reviewer's decision
// Hence the instance has to be able to store intermediate results.
title: string;
author: string;
windowStart: number;
windowEnd: number;
avg: number;
diff: number;
timestamp: string;
editsList;
type: string;
recipient: string;
previousRevisionInfos;
constructor(info: CrossEditSuspiciousPatternsInfo) {
this.mode = info.mode;
this.url = info.url;
this.windowSize = info.windowSize;
this.baseline = info.baseline;
this.percentage = info.percentage;
this.margin = info.margin;
this.warningTimeframe = info.warningTimeframe; // Timeframe to get previous warnings to determine blocks, in days
this.warningThreshold = info.warningThreshold;
this.revID = info.revID.replace(/[^0-9]/g, '');
this.axiosClient = info.axiosClient;
this.db = {};
this.type = '';
this.recipient = '';
this.previousRevisionInfos = [];
}
async sleep(milliseconds: number) {
return await new Promise((resolve) => setTimeout(resolve, milliseconds));
}
public resetDecisionLog() {
// Simulating a real database in demo
this.db = {};
}
/*
Queries the MediaWiki API to get the article title and author ID from revision ID.
*/
async getUserAndTitle() {
let thisUrl = this.url;
const params = {
action: 'query',
format: 'json',
prop: 'info|revisions',
revids: this.revID,
};
Object.keys(params).forEach(function(key) {thisUrl += '&' + key + '=' + params[key];});
const response = await fetch(thisUrl, { headers: { 'User-Agent': 'WikiLoop DoubleCheck Team' } });
const responseJson = await response.json();
const pagesObject = responseJson.query.pages;
let pageObject;
for (const v in pagesObject) {
pageObject = pagesObject[v];
}
const title = pageObject.title;
const author = pageObject.revisions[0].user;
const timestamp = pageObject.revisions[0].timestamp;
this.title = title;
this.author = author;
this.timestamp = timestamp;
console.log('Loaded metadata for revision ID: ' + this.revID);
}
async findEditHistoryAuthor() {
const title = this.title;
const author = this.author;
const timestamp = this.timestamp;
console.log('Timestamp in findEditHistoryAuthor is: ' + timestamp);
let thisUrl = this.url;
const params = {
action: 'query',
format: 'json',
list: 'allrevisions',
arvuser: author,
arvstart: timestamp,
arvdir: 'older',
arvlimit: this.windowSize,
arvprop: 'oresscores|timestamp|ids',
};
Object.keys(params).forEach(function(key) {thisUrl += '&' + key + '=' + params[key];});
const response = await fetch(thisUrl, { headers: { 'User-Agent': 'WikiLoop DoubleCheck Team' } });
console.log(response);
const responseJson = await response.json();
console.log(responseJson);
const editsByArticle = responseJson.query.allrevisions;
const editsList = [];
for (const page in editsByArticle) {
editsList.push(editsByArticle[page].revisions[0]);
editsList[editsList.length - 1].title = editsByArticle[page].title;
}
this.editsList = editsList;
console.log('Retrieved past ' + editsList.length + ' edits for author ' + author);
}
async findEditHistoryArticle() {
const title = this.title;
const author = this.author;
const timestamp = this.timestamp;
console.log('Timestamp in findEditHistoryArticle is: ' + timestamp);
let thisUrl = this.url;
const params = {
action: 'query',
rvdir: 'older',
rvstart: timestamp,
rvlimit: this.windowSize,
prop: 'revisions',
titles: title,
rvprop: 'timestamp|user|oresscores|ids',
rvslots: 'main',
formatversion: '2',
format: 'json',
};
Object.keys(params).forEach(function(key) {thisUrl += '&' + key + '=' + params[key];});
const response = await fetch(thisUrl, { headers: { 'User-Agent': 'WikiLoop DoubleCheck Team' } });
console.log(response);
const responseJson = await response.json();
console.log(responseJson);
const editsByArticle = responseJson.query.pages['0'].revisions;
const editsList = [];
for (const key in editsByArticle) {
editsList.push(editsByArticle[key]);
}
this.editsList = editsList;
console.log('Retrieved past ' + editsList.length + ' edits for author ' + author);
}
displayWarningChoice() {
// Returns whether the reviewer agrees on issuing a warning
console.log('Choice displayed to reviewer on whether to warn ' + this.author);
return true;
}
displayBlockChoice() {
// Returns whether the reviewer agrees on issuing a block
console.log('Choice displayed to reviewer on whether to block ' + this.author);
return true;
}
displayEventChoice() {
// Returns whether the reviewer agrees on logging the event for future protects
console.log('Choice displayed to reviewer on whether to log event for ' + this.title);
return true;
}
displayProtectChoice(userID: string) {
// Returns whether the reviewer agrees on issuing a block
console.log('Choice displayed to reviewer on whether to protect ' + this.title);
return true;
}
sendWarningMessage(recipient: string) {
console.log('Warning message sent to ' + recipient);
}
sendBlockMessage(recipient: string) {
console.log('Block message sent to ' + recipient);
}
sendProtectMessage(recipient: string) {
console.log('Protect message sent to ' + recipient);
}
getRecipientForBlock() {
return 'BlockRecipientPlaceholder';
}
getRecipientForProtect() {
return 'ProtectRecipientPlaceholder';
}
async getPreviousWarningsAuthor(
userId: string,
endTimestamp: number,
) {
let url = '/api/decisionLog/author/';
url = url + userId + '/' + endTimestamp + '/' + this.warningTimeframe + '/' + this.warningThreshold;
console.log(url);
const events = await this.axiosClient.$get(url);
console.log('Get ' + events.length + ' past events for ' + userId);
console.log(events);
return events;
}
async getPreviousWarningsArticle(
title: string,
endTimestamp: number,
) {
let url = '/api/decisionLog/article/';
url = url + title + '/' + endTimestamp + '/' + this.warningTimeframe + '/' + this.warningThreshold;
console.log(url);
const events = await this.axiosClient.$get(url);
console.log('Get ' + events.length + ' past events for ' + title);
console.log(events);
return events;
}
async writeNewDecisionAuthor(
userId: string,
title: string,
type: string,
timestamp: Date,
recipientId: string,
startWindow: Date,
avgScore: number,
) {
const decisionObject = {
userId,
title,
type,
timestamp,
recipientId,
startWindow,
avgScore,
};
await this.axiosClient.$post('/api/decisionLog/author', decisionObject);
console.log('Suspicious event of type ' + type + ' logged for author ' + userId + ' at ' + timestamp);
}
async writeNewDecisionArticle(
userId: string,
title: string,
type: string,
timestamp: Date,
recipientId: string,
startWindow: Date,
avgScore: number,
) {
const decisionObject = {
userId,
title,
type,
timestamp,
recipientId,
startWindow,
avgScore,
};
await this.axiosClient.$post('/api/decisionLog/article', decisionObject);
console.log('Suspicious event of type ' + type + ' logged for article ' + title + ' at ' + timestamp);
}
// Used for both "author" mode and "article" mode
async getScoreAndProcess() {
const title = this.title;
const author = this.author;
const editsList = this.editsList;
const scores = new Array(Math.min(this.windowSize, editsList.length));
const previousRevisionInfos = new Array(Math.min(this.windowSize, editsList.length));
for (let i = 0; i < scores.length; i++) {
// Only take ORES_DAMAGING score
// If ORES Scores are missing, skip this edit entirely.
if (editsList[i].oresscores.damaging === undefined) {
let missingScoreString = '';
missingScoreString += 'Title: ' + title + ' Author: ' + author + '\n';
missingScoreString += 'ORES Scores are missing. Hence no detection is performed. \n';
missingScoreString += 'Timestamp: ' + editsList[0].timestamp + '\n';
console.log(missingScoreString);
const decisionInfo = {
mode: this.mode,
type: this.type,
author: this.author,
recipient: this.recipient,
percentage: (this.avg * 100).toFixed(0),
previousRevisionInfos: this.previousRevisionInfos,
};
return decisionInfo;
}
scores[i] = editsList[i].oresscores.damaging.true;
let editInfo = null;
if (this.mode === 'author') {
editInfo = {
author: this.author,
title: String(editsList[i].title),
score: (scores[i] * 100).toFixed(0),
timestamp: editsList[i].timestamp,
parentid: editsList[i].parentid,
};
} else if (this.mode === 'article') {
editInfo = {
author: String(editsList[i].user),
title: this.title,
score: (scores[i] * 100).toFixed(0),
timestamp: editsList[i].timestamp,
parentid: editsList[i].parentid,
};
}
previousRevisionInfos[i] = editInfo;
}
const windowStart: number = editsList[editsList.length - 1].timestamp;
const windowEnd: number = editsList[0].timestamp;
const windowStartDate: Date = new Date(windowStart);
const windowEndDate: Date = new Date(windowEnd);
const avg: number = scores.reduce((acc, e) => acc + e, 0) / scores.length;
const diff: number = avg - this.baseline;
this.windowStart = windowStart;
this.windowEnd = windowEnd;
this.avg = avg;
this.diff = diff;
this.previousRevisionInfos = previousRevisionInfos;
if (diff > this.margin) {
if (this.mode === 'author') {
const warnings = await this.getPreviousWarningsAuthor(author, windowEnd);
if (warnings.length > this.warningThreshold) {
this.type = 'block';
this.recipient = await this.getRecipientForBlock();
} else {
this.type = 'warning';
this.recipient = author;
}
this.writeNewDecisionAuthor(author, title, this.type, windowEndDate, this.recipient, windowStartDate, avg);
} else if (this.mode === 'article') {
const warnings = await this.getPreviousWarningsArticle(title, windowEnd);
if (warnings.length > this.warningThreshold) {
this.type = 'protect';
this.recipient = await this.getRecipientForProtect();
} else {
this.type = 'articleLogEvent';
this.recipient = '';
}
this.writeNewDecisionArticle(author, title, this.type, windowEndDate, this.recipient, windowStartDate, avg);
}
} else if (this.mode === 'author') {
console.log('Author ' + author + 'is not engaged in suspicious behavior.');
} else if (this.mode === 'article') {
console.log('Article ' + title + 'is not affected by suspicious activity.');
}
// Display on prototype.html
let resultString = '';
resultString += 'Title: ' + title + ' Author: ' + author + '\n';
resultString += 'Detection Type: ' + this.mode + '\n';
resultString += 'Avg ORES Damaging score is: ' + avg.toFixed(2) + '\n';
resultString += 'Difference from baseline score is: ' + diff.toFixed(2) + '\n';
resultString += 'Starting time of window is: ' + windowStart + '\n';
resultString += 'Ending time of window is: ' + windowEnd + '\n';
console.log(resultString);
const decisionInfo = {
mode: this.mode,
type: this.type,
author: this.author,
recipient: this.recipient,
percentage: (this.avg * 100).toFixed(0),
previousRevisionInfos: this.previousRevisionInfos,
};
return decisionInfo;
}
public executeDecision() {
if (this.mode === 'author') {
if (this.type === 'block') {
this.sendBlockMessage(this.recipient);
}
if (this.type === 'warning') {
this.sendWarningMessage(this.recipient);
}
} else if (this.mode === 'article') {
if (this.type === 'protect') {
this.sendProtectMessage(this.recipient);
}
}
}
public async analyze() {
await this.getUserAndTitle();
if (this.mode === 'author') {
await this.findEditHistoryAuthor();
} else if (this.mode === 'article') {
await this.findEditHistoryArticle();
}
const decisionInfo = await this.getScoreAndProcess();
console.log('Executed test for revision ID: ' + this.revID + decisionInfo);
return decisionInfo;
}
} | the_stack |
import { basename, dirname, extname, join, relative, sep } from 'path';
import { readdirSync, existsSync, writeFileSync, openSync, closeSync } from 'fs';
import { Logger } from '../logger/logger';
import { toUnixPath } from '../util/helpers';
import * as Constants from '../util/constants';
import * as GeneratorConstants from './constants';
import { camelCase, constantCase, getStringPropertyValue, mkDirpAsync, paramCase, pascalCase, readFileAsync, replaceAll, sentenceCase, upperCaseFirst, writeFileAsync } from '../util/helpers';
import { BuildContext } from '../util/interfaces';
import { globAll, GlobResult } from '../util/glob-util';
import { changeExtension, ensureSuffix, removeSuffix } from '../util/helpers';
import { appendNgModuleDeclaration, appendNgModuleExports, appendNgModuleProvider, insertNamedImportIfNeeded } from '../util/typescript-utils';
export function hydrateRequest(context: BuildContext, request: GeneratorRequest) {
const hydrated = request as HydratedGeneratorRequest;
const suffix = getSuffixFromGeneratorType(context, request.type);
hydrated.className = ensureSuffix(pascalCase(request.name), upperCaseFirst(suffix));
hydrated.fileName = removeSuffix(paramCase(request.name), `-${paramCase(suffix)}`);
if (request.type === 'pipe') hydrated.pipeName = camelCase(request.name);
if (!!hydrated.includeNgModule) {
if (hydrated.type === 'tabs') {
hydrated.importStatement = `import { IonicPage, NavController } from 'ionic-angular';`;
} else {
hydrated.importStatement = `import { IonicPage, NavController, NavParams } from 'ionic-angular';`;
}
hydrated.ionicPage = '\n@IonicPage()';
} else {
hydrated.ionicPage = null;
hydrated.importStatement = `import { NavController, NavParams } from 'ionic-angular';`;
}
hydrated.dirToRead = join(getStringPropertyValue(Constants.ENV_VAR_IONIC_ANGULAR_TEMPLATE_DIR), request.type);
const baseDir = getDirToWriteToByType(context, request.type);
hydrated.dirToWrite = join(baseDir, hydrated.fileName);
return hydrated;
}
export function createCommonModule(envVar: string, requestType: string) {
let className = requestType.charAt(0).toUpperCase() + requestType.slice(1) + 's';
let tmplt = `import { NgModule } from '@angular/core';\n@NgModule({\n\tdeclarations: [],\n\timports: [],\n\texports: []\n})\nexport class ${className}Module {}\n`;
writeFileSync(envVar, tmplt);
}
export function hydrateTabRequest(context: BuildContext, request: GeneratorTabRequest) {
const h = hydrateRequest(context, request);
const hydrated = Object.assign({
tabs: request.tabs,
tabContent: '',
tabVariables: '',
tabsImportStatement: '',
}, h) as HydratedGeneratorRequest;
if (hydrated.includeNgModule) {
hydrated.tabsImportStatement += `import { IonicPage, NavController } from 'ionic-angular';`;
} else {
hydrated.tabsImportStatement += `import { NavController } from 'ionic-angular';`;
}
for (let i = 0; i < request.tabs.length; i++) {
const tabVar = `${camelCase(request.tabs[i].name)}Root`;
if (hydrated.includeNgModule) {
hydrated.tabVariables += ` ${tabVar} = '${request.tabs[i].className}'\n`;
} else {
hydrated.tabVariables += ` ${tabVar} = ${request.tabs[i].className}\n`;
}
// If this is the last ion-tab to insert
// then we do not want a new line
if (i === request.tabs.length - 1) {
hydrated.tabContent += ` <ion-tab [root]="${tabVar}" tabTitle="${sentenceCase(request.tabs[i].name)}" tabIcon="information-circle"></ion-tab>`;
} else {
hydrated.tabContent += ` <ion-tab [root]="${tabVar}" tabTitle="${sentenceCase(request.tabs[i].name)}" tabIcon="information-circle"></ion-tab>\n`;
}
}
return hydrated;
}
export function readTemplates(pathToRead: string): Promise<Map<string, string>> {
const fileNames = readdirSync(pathToRead);
const absolutePaths = fileNames.map(fileName => {
return join(pathToRead, fileName);
});
const filePathToContent = new Map<string, string>();
const promises = absolutePaths.map(absolutePath => {
const promise = readFileAsync(absolutePath);
promise.then((fileContent: string) => {
filePathToContent.set(absolutePath, fileContent);
});
return promise;
});
return Promise.all(promises).then(() => {
return filePathToContent;
});
}
export function filterOutTemplates(request: HydratedGeneratorRequest, templates: Map<string, string>) {
const templatesToUseMap = new Map<string, string>();
templates.forEach((fileContent: string, filePath: string) => {
const newFileExtension = basename(filePath, GeneratorConstants.KNOWN_FILE_EXTENSION);
const shouldSkip = (!request.includeNgModule && newFileExtension === GeneratorConstants.NG_MODULE_FILE_EXTENSION) || (!request.includeSpec && newFileExtension === GeneratorConstants.SPEC_FILE_EXTENSION);
if (!shouldSkip) {
templatesToUseMap.set(filePath, fileContent);
}
});
return templatesToUseMap;
}
export function applyTemplates(request: HydratedGeneratorRequest, templates: Map<string, string>) {
const appliedTemplateMap = new Map<string, string>();
templates.forEach((fileContent: string, filePath: string) => {
fileContent = replaceAll(fileContent, GeneratorConstants.CLASSNAME_VARIABLE, request.className);
fileContent = replaceAll(fileContent, GeneratorConstants.PIPENAME_VARIABLE, request.pipeName);
fileContent = replaceAll(fileContent, GeneratorConstants.IMPORTSTATEMENT_VARIABLE, request.importStatement);
fileContent = replaceAll(fileContent, GeneratorConstants.IONICPAGE_VARIABLE, request.ionicPage);
fileContent = replaceAll(fileContent, GeneratorConstants.FILENAME_VARIABLE, request.fileName);
fileContent = replaceAll(fileContent, GeneratorConstants.SUPPLIEDNAME_VARIABLE, request.name);
fileContent = replaceAll(fileContent, GeneratorConstants.TAB_CONTENT_VARIABLE, request.tabContent);
fileContent = replaceAll(fileContent, GeneratorConstants.TAB_VARIABLES_VARIABLE, request.tabVariables);
fileContent = replaceAll(fileContent, GeneratorConstants.TABS_IMPORTSTATEMENT_VARIABLE, request.tabsImportStatement);
appliedTemplateMap.set(filePath, fileContent);
});
return appliedTemplateMap;
}
export function writeGeneratedFiles(request: HydratedGeneratorRequest, processedTemplates: Map<string, string>): Promise<string[]> {
const promises: Promise<any>[] = [];
const createdFileList: string[] = [];
processedTemplates.forEach((fileContent: string, filePath: string) => {
const newFileExtension = basename(filePath, GeneratorConstants.KNOWN_FILE_EXTENSION);
const newFileName = `${request.fileName}.${newFileExtension}`;
const fileToWrite = join(request.dirToWrite, newFileName);
createdFileList.push(fileToWrite);
promises.push(createDirAndWriteFile(fileToWrite, fileContent));
});
return Promise.all(promises).then(() => {
return createdFileList;
});
}
function createDirAndWriteFile(filePath: string, fileContent: string) {
const directory = dirname(filePath);
return mkDirpAsync(directory).then(() => {
return writeFileAsync(filePath, fileContent);
});
}
export function getNgModules(context: BuildContext, types: string[]): Promise<GlobResult[]> {
const ngModuleSuffix = getStringPropertyValue(Constants.ENV_NG_MODULE_FILE_NAME_SUFFIX);
const patterns = types.map((type) => join(getDirToWriteToByType(context, type), '**', `*${ngModuleSuffix}`));
return globAll(patterns);
}
function getSuffixFromGeneratorType(context: BuildContext, type: string) {
if (type === Constants.COMPONENT) {
return 'Component';
} else if (type === Constants.DIRECTIVE) {
return 'Directive';
} else if (type === Constants.PAGE || type === Constants.TABS) {
return 'Page';
} else if (type === Constants.PIPE) {
return 'Pipe';
} else if (type === Constants.PROVIDER) {
return 'Provider';
}
throw new Error(`Unknown Generator Type: ${type}`);
}
export function getDirToWriteToByType(context: BuildContext, type: string) {
if (type === Constants.COMPONENT) {
return context.componentsDir;
} else if (type === Constants.DIRECTIVE) {
return context.directivesDir;
} else if (type === Constants.PAGE || type === Constants.TABS) {
return context.pagesDir;
} else if (type === Constants.PIPE) {
return context.pipesDir;
} else if (type === Constants.PROVIDER) {
return context.providersDir;
}
throw new Error(`Unknown Generator Type: ${type}`);
}
export async function nonPageFileManipulation(context: BuildContext, name: string, ngModulePath: string, type: string) {
const hydratedRequest = hydrateRequest(context, { type, name });
const envVar = getStringPropertyValue(`IONIC_${hydratedRequest.type.toUpperCase()}S_NG_MODULE_PATH`);
let importPath;
let fileContent: string;
let templatesArray: string[] = await generateTemplates(context, hydratedRequest, false);
if (hydratedRequest.type === 'pipe' || hydratedRequest.type === 'component' || hydratedRequest.type === 'directive') {
if (!existsSync(envVar)) createCommonModule(envVar, hydratedRequest.type);
}
const typescriptFilePath = changeExtension(templatesArray.filter(path => extname(path) === '.ts')[0], '');
readFileAsync(ngModulePath).then((content) => {
importPath = type === 'pipe' || type === 'component' || type === 'directive'
// Insert `./` if it's a pipe component or directive
// Since these will go in a common module.
? toUnixPath(`./${relative(dirname(ngModulePath), hydratedRequest.dirToWrite)}${sep}${hydratedRequest.fileName}`)
: toUnixPath(`${relative(dirname(ngModulePath), hydratedRequest.dirToWrite)}${sep}${hydratedRequest.fileName}`);
content = insertNamedImportIfNeeded(ngModulePath, content, hydratedRequest.className, importPath);
if (type === 'pipe' || type === 'component' || type === 'directive') {
content = appendNgModuleDeclaration(ngModulePath, content, hydratedRequest.className);
content = appendNgModuleExports(ngModulePath, content, hydratedRequest.className);
}
if (type === 'provider') {
content = appendNgModuleProvider(ngModulePath, content, hydratedRequest.className);
}
return writeFileAsync(ngModulePath, content);
});
}
export function tabsModuleManipulation(tabs: string[][], hydratedRequest: HydratedGeneratorRequest, tabHydratedRequests: HydratedGeneratorRequest[]): Promise<any> {
tabHydratedRequests.forEach((tabRequest, index) => {
tabRequest.generatedFileNames = tabs[index];
});
const ngModulePath = tabs[0].find((element: any): boolean => element.indexOf('module') !== -1);
if (!ngModulePath) {
// Static imports
const tabsPath = join(hydratedRequest.dirToWrite, `${hydratedRequest.fileName}.ts`);
let modifiedContent: string = null;
return readFileAsync(tabsPath).then(content => {
tabHydratedRequests.forEach((tabRequest) => {
const typescriptFilePath = changeExtension(tabRequest.generatedFileNames.filter(path => extname(path) === '.ts')[0], '');
const importPath = toUnixPath(relative(dirname(tabsPath), typescriptFilePath));
modifiedContent = insertNamedImportIfNeeded(tabsPath, content, tabRequest.className, importPath);
content = modifiedContent;
});
return writeFileAsync(tabsPath, modifiedContent);
});
}
}
export function generateTemplates(context: BuildContext, request: HydratedGeneratorRequest, includePageConstants?: boolean): Promise<string[]> {
Logger.debug('[Generators] generateTemplates: Reading templates ...');
let pageConstantFile = join(context.pagesDir, 'pages.constants.ts');
if (includePageConstants && !existsSync(pageConstantFile)) createPageConstants(context);
return readTemplates(request.dirToRead).then((map: Map<string, string>) => {
Logger.debug('[Generators] generateTemplates: Filtering out NgModule and Specs if needed ...');
return filterOutTemplates(request, map);
}).then((filteredMap: Map<string, string>) => {
Logger.debug('[Generators] generateTemplates: Applying templates ...');
const appliedTemplateMap = applyTemplates(request, filteredMap);
Logger.debug('[Generators] generateTemplates: Writing generated files to disk ...');
// Adding const to gets some type completion
if (includePageConstants) createConstStatments(pageConstantFile, request);
return writeGeneratedFiles(request, appliedTemplateMap);
});
}
export function createConstStatments(pageConstantFile: string, request: HydratedGeneratorRequest) {
readFileAsync(pageConstantFile).then((content) => {
content += `\nexport const ${constantCase(request.className)} = '${request.className}';`;
writeFileAsync(pageConstantFile, content);
});
}
export function createPageConstants(context: BuildContext) {
let pageConstantFile = join(context.pagesDir, 'pages.constants.ts');
writeFileAsync(pageConstantFile, '//Constants for getting type references');
}
export interface GeneratorOption {
type: string;
multiple: boolean;
}
export interface GeneratorRequest {
type?: string;
name?: string;
includeSpec?: boolean;
includeNgModule?: boolean;
}
export interface GeneratorTabRequest extends GeneratorRequest {
tabs?: HydratedGeneratorRequest[];
}
export interface HydratedGeneratorRequest extends GeneratorRequest {
fileName?: string;
importStatement?: string;
ionicPage?: string;
className?: string;
tabContent?: string;
tabVariables?: string;
tabsImportStatement?: string;
dirToRead?: string;
dirToWrite?: string;
generatedFileNames?: string[];
pipeName?: string;
} | the_stack |
import {expectErroneousCode, expectTranslate} from './test_support';
describe('variables', () => {
it('should print variable declaration with initializer', () => {
expectTranslate('var a:number = 1;').to.equal(`@JS()
external num get a;
@JS()
external set a(num v);`);
});
it('should print variable declaration', () => {
expectTranslate('var a:number;').to.equal(`@JS()
external num get a;
@JS()
external set a(num v);`);
expectTranslate('var a;').to.equal(`@JS()
external get a;
@JS()
external set a(v);`);
expectTranslate('var a:any;').to.equal(`@JS()
external dynamic get a;
@JS()
external set a(dynamic v);`);
});
it('should transpile variable declaration lists', () => {
expectTranslate('var a: A;').to.equal(`@JS()
external A get a;
@JS()
external set a(A v);`);
expectTranslate('var a, b;').to.equal(`@JS()
external get a;
@JS()
external set a(v);
@JS()
external get b;
@JS()
external set b(v);`);
});
it('should transpile variable declaration lists with initializers', () => {
expectTranslate('var a = 0;').to.equal(`@JS()
external get a;
@JS()
external set a(v);`);
expectTranslate('var a, b = 0;').to.equal(`@JS()
external get a;
@JS()
external set a(v);
@JS()
external get b;
@JS()
external set b(v);`);
expectTranslate('var a = 1, b = 0;').to.equal(`@JS()
external get a;
@JS()
external set a(v);
@JS()
external get b;
@JS()
external set b(v);`);
});
it('support vardecls containing more than one type (implicit or explicit)', () => {
expectTranslate('var a: A, untyped;').to.equal(`@JS()
external A get a;
@JS()
external set a(A v);
@JS()
external get untyped;
@JS()
external set untyped(v);`);
expectTranslate('var untyped, b: B;').to.equal(`@JS()
external get untyped;
@JS()
external set untyped(v);
@JS()
external B get b;
@JS()
external set b(B v);`);
expectTranslate('var n: number, s: string;').to.equal(`@JS()
external num get n;
@JS()
external set n(num v);
@JS()
external String get s;
@JS()
external set s(String v);`);
expectTranslate('var untyped, n: number, s: string;').to.equal(`@JS()
external get untyped;
@JS()
external set untyped(v);
@JS()
external num get n;
@JS()
external set n(num v);
@JS()
external String get s;
@JS()
external set s(String v);`);
});
it('supports const', () => {
// Arbitrary expressions essentially translate const ==> final
// but Dart doesn't allow external fields so we use getters instead.
expectTranslate('const A = 1 + 2;').to.equal(`@JS()
external get A;`);
// ... but literals are special cased to be deep const.
expectTranslate('const A = 1, B = 2;').to.equal(`@JS()
external get A;
@JS()
external get B;`);
expectTranslate('const A: number = 1;').to.equal(`@JS()
external num get A;`);
});
});
describe('classes', () => {
it('should translate classes', () => {
expectTranslate('class X {}').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
}`);
});
it('should support extends', () => {
expectTranslate('class X extends Y {}').to.equal(`@JS()
class X extends Y {
// @Ignore
X.fakeConstructor$() : super.fakeConstructor$();
}`);
});
it('should support implements', () => {
expectTranslate('class X implements Y, Z {}').to.equal(`@JS()
class X implements Y, Z {
// @Ignore
X.fakeConstructor$();
}`);
});
it('should support implements', () => {
expectTranslate('class X extends Y implements Z {}').to.equal(`@JS()
class X extends Y implements Z {
// @Ignore
X.fakeConstructor$() : super.fakeConstructor$();
}`);
});
it('should support abstract', () => {
expectTranslate('abstract class X {}').to.equal(`@JS()
abstract class X {
// @Ignore
X.fakeConstructor$();
}`);
});
describe('members', () => {
it('supports empty declarations', () => {
expectTranslate('class X { ; }').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
}`);
});
it('supports fields', () => {
expectTranslate('class X { x: number; y: string; }').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external num get x;
external set x(num v);
external String get y;
external set y(String v);
}`);
expectTranslate('class X { x; }').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external get x;
external set x(v);
}`);
});
it('supports function typed fields', () => {
expectTranslate(
'interface FnDef {(y: number): string;}\n' +
'class X { x: FnDef; }')
.to.equal(`typedef String FnDef(num y);
@JS()
class X {
// @Ignore
X.fakeConstructor$();
external FnDef get x;
external set x(FnDef v);
}`);
});
it('supports field initializers', () => {
expectTranslate('class X { x: number = 42; }').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external num get x;
external set x(num v);
}`);
});
// TODO(martinprobst): Re-enable once Angular is migrated to TS.
it('supports visibility modifiers', () => {
expectTranslate('class X { private _x; x; }').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external get JS$_x;
external set JS$_x(v);
external get x;
external set x(v);
}`);
expectTranslate('class X { private x; }').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external get x;
external set x(v);
}`);
expectTranslate('class X { constructor (private x) {} }').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external get x;
external set x(v);
external factory X(x);
}`);
expectTranslate('class X { _x; }').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external get JS$_x;
external set JS$_x(v);
}`);
});
it('allow protected', () => {
expectTranslate('class X { protected x; }').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external get x;
external set x(v);
}`);
});
it('supports static fields', () => {
expectTranslate('class X { static x: number = 42; }').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external static num get x;
external static set x(num v);
}`);
});
it('supports methods', () => {
expectTranslate('class X { x() { return 42; } }').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external x();
}`);
});
it('should emit extension methods to return Futures from methods that return Promises', () => {
expectTranslate(`declare class MyMath {
randomInRange(start: number, end: number): Promise<number>;
}`).to.equal(`import "package:js/js_util.dart" show promiseToFuture;
@JS()
class MyMath {
// @Ignore
MyMath.fakeConstructor$();
}
@JS("MyMath")
abstract class _MyMath {
external Promise<num> randomInRange(num start, num end);
}
extension MyMathExtensions on MyMath {
Future<num> randomInRange(num start, num end) {
final Object t = this;
final _MyMath tt = t;
return promiseToFuture(tt.randomInRange(start, end));
}
}
@JS()
abstract class Promise<T> {
external factory Promise(
void executor(void resolve(T result), Function reject));
external Promise then(void onFulfilled(T result), [Function onRejected]);
}`);
expectTranslate(`declare class X<T> {
f(a: T): Promise<T>;
}`).to.equal(`import "package:js/js_util.dart" show promiseToFuture;
@JS()
class X<T> {
// @Ignore
X.fakeConstructor$();
}
@JS("X")
abstract class _X<T> {
external Promise<T> f(T a);
}
extension XExtensions<T> on X<T> {
Future<T> f(T a) {
final Object t = this;
final _X<T> tt = t;
return promiseToFuture(tt.f(a));
}
}
@JS()
abstract class Promise<T> {
external factory Promise(
void executor(void resolve(T result), Function reject));
external Promise then(void onFulfilled(T result), [Function onRejected]);
}`);
expectTranslate(`declare class Y {
a: number;
}
declare class Z extends Y {
f(): Promise<string>;
}`).to.equal(`import "package:js/js_util.dart" show promiseToFuture;
@JS()
class Y {
// @Ignore
Y.fakeConstructor$();
external num get a;
external set a(num v);
}
@JS()
class Z extends Y {
// @Ignore
Z.fakeConstructor$() : super.fakeConstructor$();
}
@JS("Z")
abstract class _Z {
external Promise<String> f();
}
extension ZExtensions on Z {
Future<String> f() {
final Object t = this;
final _Z tt = t;
return promiseToFuture(tt.f());
}
}
@JS()
abstract class Promise<T> {
external factory Promise(
void executor(void resolve(T result), Function reject));
external Promise then(void onFulfilled(T result), [Function onRejected]);
}`);
expectTranslate(`declare class X {
f(a: string): Promise<number>;
f(a: string, b: number): Promise<number>;
}`).to.equal(`import "package:js/js_util.dart" show promiseToFuture;
@JS()
class X {
// @Ignore
X.fakeConstructor$();
}
@JS("X")
abstract class _X {
/*external Promise<num> f(String a);*/
/*external Promise<num> f(String a, num b);*/
external Promise<num> f(String a, [num b]);
}
extension XExtensions on X {
Future<num> f(String a, [num b]) {
final Object t = this;
final _X tt = t;
if (b == null) {
return promiseToFuture(tt.f(a));
}
return promiseToFuture(tt.f(a, b));
}
}
@JS()
abstract class Promise<T> {
external factory Promise(
void executor(void resolve(T result), Function reject));
external Promise then(void onFulfilled(T result), [Function onRejected]);
}`);
expectTranslate(`declare class X {
f(a: string): Promise<number>;
f(a: number, b: number): Promise<number>;
f(c: number[]): Promise<number>;
}`).to.equal(`import "package:js/js_util.dart" show promiseToFuture;
@JS()
class X {
// @Ignore
X.fakeConstructor$();
}
@JS("X")
abstract class _X {
/*external Promise<num> f(String a);*/
/*external Promise<num> f(num a, num b);*/
/*external Promise<num> f(List<num> c);*/
external Promise<num> f(dynamic /*String|num|List<num>*/ a_c, [num b]);
}
extension XExtensions on X {
Future<num> f(dynamic /*String|num|List<num>*/ a_c, [num b]) {
final Object t = this;
final _X tt = t;
if (b == null) {
return promiseToFuture(tt.f(a_c));
}
return promiseToFuture(tt.f(a_c, b));
}
}
@JS()
abstract class Promise<T> {
external factory Promise(
void executor(void resolve(T result), Function reject));
external Promise then(void onFulfilled(T result), [Function onRejected]);
}`);
});
it('supports abstract methods', () => {
expectTranslate('abstract class X { abstract x(); }').to.equal(`@JS()
abstract class X {
// @Ignore
X.fakeConstructor$();
external x();
}`);
});
it('supports method return types', () => {
expectTranslate('class X { x(): number { return 42; } }').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external num x();
}`);
});
it('supports method params', () => {
expectTranslate('class X { x(a, b) { return 42; } }').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external x(a, b);
}`);
});
it('supports method return types', () => {
expectTranslate('class X { x( a : number, b : string ) { return 42; } }').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external x(num a, String b);
}`);
});
it('supports get methods', () => {
expectTranslate('class X { get y(): number {} }').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external num get y;
}`);
expectTranslate('class X { static get Y(): number {} }').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external static num get Y;
}`);
});
it('supports set methods', () => {
expectTranslate('class X { set y(n: number) {} }').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external set y(num n);
}`);
expectTranslate('class X { static get Y(): number {} }').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external static num get Y;
}`);
});
it('supports constructors', () => {
expectTranslate('class X { constructor() {} }').to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external factory X();
}`);
});
it('supports parameter properties', () => {
expectTranslate(
'class X { c: number; \n' +
' constructor(private _bar: B, ' +
'public foo: string = "hello", ' +
'private _goggles: boolean = true) {} }')
.to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external B get JS$_bar;
external set JS$_bar(B v);
external String get foo;
external set foo(String v);
external bool get JS$_goggles;
external set JS$_goggles(bool v);
external num get c;
external set c(num v);
external factory X(B JS$_bar, [String foo, bool JS$_goggles]);
}`);
expectTranslate(
'@CONST class X { ' +
'constructor(public foo: string, b: number, private _marbles: boolean = true) {} }')
.to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external String get foo;
external set foo(String v);
external bool get JS$_marbles;
external set JS$_marbles(bool v);
external factory X(String foo, num b, [bool JS$_marbles]);
}`);
});
it('should emit extension getters/setters that expose Futures in place of Promises', () => {
expectTranslate(`declare class MyMath {
readonly two: Promise<num>;
three: Promise<num>;
}`).to.equal(`import "package:js/js_util.dart" show promiseToFuture;
@JS()
class MyMath {
// @Ignore
MyMath.fakeConstructor$();
}
@JS("MyMath")
abstract class _MyMath {
external Promise<num> get two;
external Promise<num> get three;
external set three(Promise<num> v);
}
extension MyMathExtensions on MyMath {
Future<num> get two {
final Object t = this;
final _MyMath tt = t;
return promiseToFuture(tt.two);
}
Future<num> get three {
final Object t = this;
final _MyMath tt = t;
return promiseToFuture(tt.three);
}
set three(Future<num> v) {
final Object t = this;
final _MyMath tt = t;
tt.three = Promise<num>(allowInterop((resolve, reject) {
v.then(resolve, onError: reject);
}));
}
}
@JS()
abstract class Promise<T> {
external factory Promise(
void executor(void resolve(T result), Function reject));
external Promise then(void onFulfilled(T result), [Function onRejected]);
}`);
expectTranslate(`declare class X<T> {
aPromise: Promise<T>;
}`).to.equal(`import "package:js/js_util.dart" show promiseToFuture;
@JS()
class X<T> {
// @Ignore
X.fakeConstructor$();
}
@JS("X")
abstract class _X<T> {
external Promise<T> get aPromise;
external set aPromise(Promise<T> v);
}
extension XExtensions<T> on X<T> {
Future<T> get aPromise {
final Object t = this;
final _X<T> tt = t;
return promiseToFuture(tt.aPromise);
}
set aPromise(Future<T> v) {
final Object t = this;
final _X<T> tt = t;
tt.aPromise = Promise<T>(allowInterop((resolve, reject) {
v.then(resolve, onError: reject);
}));
}
}
@JS()
abstract class Promise<T> {
external factory Promise(
void executor(void resolve(T result), Function reject));
external Promise then(void onFulfilled(T result), [Function onRejected]);
}`);
});
});
});
describe('interfaces', () => {
it('translates interfaces to abstract classes', () => {
expectTranslate('interface X {}').to.equal(`@anonymous
@JS()
abstract class X {}`);
});
it('translates interface extends to class implements', () => {
expectTranslate('interface X extends Y, Z {}').to.equal(`@anonymous
@JS()
abstract class X implements Y, Z {}`);
});
it('supports abstract methods', () => {
expectTranslate('interface X { x(); }').to.equal(`@anonymous
@JS()
abstract class X {
external x();
}`);
});
it('supports interface properties', () => {
expectTranslate('interface X { x: string; y; }').to.equal(`@anonymous
@JS()
abstract class X {
external String get x;
external set x(String v);
external get y;
external set y(v);
external factory X({String x, y});
}`);
});
it('should emit extension methods to return Futures from methods that return Promises',
() => {
expectTranslate(`declare interface X<T> {
f(a: T): Promise<T>;
}`).to.equal(`import "package:js/js_util.dart" show promiseToFuture;
@anonymous
@JS()
abstract class X<T> {}
@anonymous
@JS()
abstract class _X<T> {
external Promise<T> f(T a);
}
extension XExtensions<T> on X<T> {
Future<T> f(T a) {
final Object t = this;
final _X<T> tt = t;
return promiseToFuture(tt.f(a));
}
}
@JS()
abstract class Promise<T> {
external factory Promise(
void executor(void resolve(T result), Function reject));
external Promise then(void onFulfilled(T result), [Function onRejected]);
}`);
expectTranslate(`declare interface Y {
a: number;
}
declare interface Z extends Y {
f(): Promise<string>;
}`).to.equal(`import "package:js/js_util.dart" show promiseToFuture;
@anonymous
@JS()
abstract class Y {
external num get a;
external set a(num v);
external factory Y({num a});
}
@anonymous
@JS()
abstract class Z implements Y {}
@anonymous
@JS()
abstract class _Z {
external Promise<String> f();
}
extension ZExtensions on Z {
Future<String> f() {
final Object t = this;
final _Z tt = t;
return promiseToFuture(tt.f());
}
}
@JS()
abstract class Promise<T> {
external factory Promise(
void executor(void resolve(T result), Function reject));
external Promise then(void onFulfilled(T result), [Function onRejected]);
}`);
});
it('handles interface properties with names that are invalid in Dart ', () => {
expectTranslate(`interface X { '!@#$%^&*': string; }`).to.equal(`@anonymous
@JS()
abstract class X {
/*external String get !@#$%^&*;*/
/*external set !@#$%^&*(String v);*/
external factory X();
}`);
expectTranslate(`interface X { '5abcde': string; }`).to.equal(`@anonymous
@JS()
abstract class X {
external String get JS$5abcde;
external set JS$5abcde(String v);
external factory X();
}`);
expectTranslate(`interface X { '_wxyz': string; }`).to.equal(`@anonymous
@JS()
abstract class X {
external String get JS$_wxyz;
external set JS$_wxyz(String v);
external factory X();
}`);
expectTranslate(`interface X { 'foo_34_81$': string; }`).to.equal(`@anonymous
@JS()
abstract class X {
external String get foo_34_81$;
external set foo_34_81$(String v);
external factory X({String foo_34_81$});
}`);
});
});
describe('types with constructors', () => {
describe('supports type literals with constructors', () => {
it('simple', () => {
expectTranslate(`
declare interface XType {
a: string;
b: number;
c(): boolean;
}
declare var X: {
prototype: XType,
new(a: string, b: number): XType
};`).to.equal(`@anonymous
@JS()
abstract class XType {
external String get a;
external set a(String v);
external num get b;
external set b(num v);
external bool c();
}
@JS()
abstract class X {
external String get a;
external set a(String v);
external num get b;
external set b(num v);
external bool c();
external factory X(String a, num b);
}`);
});
it('should make members of the literal type static ', () => {
expectTranslate(`
declare interface XType {
a: string;
b: number;
c(): boolean;
}
declare var X: {
b: number;
prototype: XType,
new(a: string, b: number): XType
};`).to.equal(`@anonymous
@JS()
abstract class XType {
external String get a;
external set a(String v);
external num get b;
external set b(num v);
external bool c();
}
@JS()
abstract class X {
external String get a;
external set a(String v);
external static num get b;
external static set b(num v);
external bool c();
external factory X(String a, num b);
}`);
expectTranslate(`
interface C {
oncached: (ev: Event) => any;
}
declare var C: {new(): C; CHECKING: number; }`)
.to.equal(`import "dart:html" show Event;
@JS()
abstract class C {
external dynamic Function(Event) get oncached;
external set oncached(dynamic Function(Event) v);
external factory C();
external static num get CHECKING;
external static set CHECKING(num v);
}`);
});
it('when possible, should merge the variable with an existing type of the same name', () => {
expectTranslate(`
declare interface X {
a: string;
b: number;
c(): boolean;
}
declare var X: {
prototype: X,
new(a: string, b: number): X
};`).to.equal(`@JS()
abstract class X {
external String get a;
external set a(String v);
external num get b;
external set b(num v);
external bool c();
external factory X(String a, num b);
}`);
expectTranslate(`
declare interface X {
a: string;
b: number;
c(): boolean;
}
declare var X: {
b: number;
prototype: X,
new(a: string, b: number): X
};`).to.equal(`@JS()
abstract class X {
external String get a;
external set a(String v);
external static num get b;
external static set b(num v);
external bool c();
external factory X(String a, num b);
}`);
expectTranslate(`
interface X { a: number; }
interface Y { c: number; }
declare var X: {prototype: X, new (): X, b: string};
declare var Y: {prototype: Y, new (): Y, d: string};
`).to.equal(`@JS()
abstract class X {
external num get a;
external set a(num v);
external factory X();
external static String get b;
external static set b(String v);
}
@JS()
abstract class Y {
external num get c;
external set c(num v);
external factory Y();
external static String get d;
external static set d(String v);
}`);
});
it('should support named type aliases of literals', () => {
expectTranslate(`
declare interface XType {
a: string;
b: number;
c(): boolean;
}
declare type Y = {
prototype: XType,
new(a: string, b: number): XType
}
declare var X: Y;
`).to.equal(`@anonymous
@JS()
abstract class XType {
external String get a;
external set a(String v);
external num get b;
external set b(num v);
external bool c();
}
@anonymous
@JS()
abstract class Y {
// Skipping constructor from aliased type.
/*new(String a, num b);*/
}
@JS()
abstract class X {
external String get a;
external set a(String v);
external num get b;
external set b(num v);
external bool c();
external factory X(String a, num b);
}`);
});
it('supports declarations within namespaces', () => {
expectTranslate(`
declare interface XType {
a: string;
b: number;
c(): boolean;
}
declare module m1 {
declare var X: {
prototype: XType,
new(a: string, b: number): XType
}
};`).to.equal(`@anonymous
@JS()
abstract class XType {
external String get a;
external set a(String v);
external num get b;
external set b(num v);
external bool c();
}
// Module m1
@JS("m1.X")
abstract class X {
external String get a;
external set a(String v);
external num get b;
external set b(num v);
external bool c();
external factory X(String a, num b);
}
// End module m1`);
});
});
describe('supports interfaces with constructors', () => {
it('simple', () => {
expectTranslate(`
declare interface XType {
a: string;
b: number;
c(): boolean;
}
declare interface X {
new(a: string, b: number): XType;
}
declare var X: X;
`).to.equal(`@anonymous
@JS()
abstract class XType {
external String get a;
external set a(String v);
external num get b;
external set b(num v);
external bool c();
}
@JS()
abstract class X {
external String get a;
external set a(String v);
external num get b;
external set b(num v);
external bool c();
external factory X(String a, num b);
}`);
});
it('should make members declared on the interface static ', () => {
expectTranslate(`
declare interface XType {
a: string;
b: number;
c(): boolean;
}
declare interface X {
b: number;
new(a: string, b: number): XType;
}
declare var X: X;
`).to.equal(`@anonymous
@JS()
abstract class XType {
external String get a;
external set a(String v);
external num get b;
external set b(num v);
external bool c();
}
@JS()
abstract class X {
external String get a;
external set a(String v);
external static num get b;
external static set b(num v);
external bool c();
external factory X(String a, num b);
}`);
});
it('should support type aliases', () => {
expectTranslate(`
declare interface XType {
a: string;
b: number;
c(): boolean;
}
declare type YType = XType;
declare interface X {
new(a: string, b: number): YType;
}
declare var Y: X;
`).to.equal(`@anonymous
@JS()
abstract class XType {
external String get a;
external set a(String v);
external num get b;
external set b(num v);
external bool c();
}
/*declare type YType = XType;*/
@anonymous
@JS()
abstract class X {
// Constructors on anonymous interfaces are not yet supported.
/*external factory X(String a, num b);*/
}
@JS()
abstract class Y {
external String get a;
external set a(String v);
external num get b;
external set b(num v);
external bool c();
external factory Y(String a, num b);
}`);
});
it('supports being declared within a namespace', () => {
expectTranslate(`
declare interface XType {
a: string;
b: number;
c(): boolean;
}
declare module m1 {
declare var X: {
prototype: XType,
new(a: string, b: number): XType
}
};`).to.equal(`@anonymous
@JS()
abstract class XType {
external String get a;
external set a(String v);
external num get b;
external set b(num v);
external bool c();
}
// Module m1
@JS("m1.X")
abstract class X {
external String get a;
external set a(String v);
external num get b;
external set b(num v);
external bool c();
external factory X(String a, num b);
}
// End module m1`);
});
});
describe('cases where a type and a variable cannot be merged', () => {
it('should handle cases where an interface has no matching variable', () => {
// Case where we cannot find a variable matching the interface so it is unsafe to give the
// interface a constructor.
expectTranslate(`
interface X {
new (a: string|boolean, b: number): XType;
}`).to.equal(`@anonymous
@JS()
abstract class X {
// Constructors on anonymous interfaces are not yet supported.
/*external factory X(String|bool a, num b);*/
}`);
});
});
it('should merge variables and interfaces with the same name by default', () => {
expectTranslate(`
interface X {
a: string;
b: number;
c(): boolean;
}
declare var X: { d: number[] };
declare var x: X;
`).to.equal(`@anonymous
@JS()
abstract class X {
external String get a;
external set a(String v);
external num get b;
external set b(num v);
external bool c();
external static List<num> get d;
external static set d(List<num> v);
}
@JS()
external X get x;
@JS()
external set x(X v);`);
});
});
describe('flags', () => {
// If the lib.dom.d.ts file is compiled, it creates conflicting interface definitions which causes
// a problem for variable declarations that we have merged into classes. The main problem was that
// when the declaration transpiler performed the notSimpleBagOfProperties check, it was checking
// the lib.dom.d.ts definition of the interface, which made it think the class didn't have a
// constructor defined when in reality it did.
it('does not compile DOM library files when the --generate-html flag is set', () => {
const generateHTMLOpts = {failFast: true, generateHTML: true};
expectTranslate(
`declare var AbstractRange: {prototype: AbstractRange; new (): AbstractRange;};
declare interface AbstractRange {
readonly collapsed: boolean;
readonly endOffset: number;
readonly startOffset: number;
}`,
generateHTMLOpts)
.to.equal(`@JS()
abstract class AbstractRange {
external bool get collapsed;
external num get endOffset;
external num get startOffset;
external factory AbstractRange();
}`);
});
describe('emitting properties of top level variables with anonymous types as static', () => {
it('performs this by default', () => {
expectTranslate(`
declare interface CacheBase {
readonly CHECKING: number;
readonly DOWNLOADING: number;
readonly IDLE: number;
}
declare interface MyCache extends CacheBase {}
declare var MyCache: {
prototype: MyCache;
new (): MyCache;
readonly CHECKING: number;
readonly DOWNLOADING: number;
readonly IDLE: number;
};`).to.equal(`@anonymous
@JS()
abstract class CacheBase {
external static num get CHECKING;
external static num get DOWNLOADING;
external static num get IDLE;
}
@JS()
abstract class MyCache implements CacheBase {
external factory MyCache();
external static num get CHECKING;
external static num get DOWNLOADING;
external static num get IDLE;
}`);
});
it('but not when the --explicit-static flag is set', () => {
const explicitStaticOpts = {failFast: true, explicitStatic: true};
expectTranslate(
`
declare interface CacheBase {
readonly CHECKING: number;
readonly DOWNLOADING: number;
readonly IDLE: number;
}
declare interface MyCache extends CacheBase {}
declare var MyCache: {
prototype: MyCache;
new (): MyCache;
readonly CHECKING: number;
readonly DOWNLOADING: number;
readonly IDLE: number;
};`,
explicitStaticOpts)
.to.equal(`@anonymous
@JS()
abstract class CacheBase {
external num get CHECKING;
external num get DOWNLOADING;
external num get IDLE;
external factory CacheBase({num CHECKING, num DOWNLOADING, num IDLE});
}
@JS()
abstract class MyCache implements CacheBase {
external factory MyCache();
external num get CHECKING;
external num get DOWNLOADING;
external num get IDLE;
}`);
});
});
describe('--trust-js-types', () => {
const trustJSTypesOpts = {failFast: true, trustJSTypes: true};
it('makes classes that have neither constructors nor static members anonymous when set', () => {
expectTranslate(
`declare class X {
a: number;
b: string;
}`,
trustJSTypesOpts)
.to.equal(`@anonymous
@JS()
class X {
// @Ignore
X.fakeConstructor$();
external num get a;
external set a(num v);
external String get b;
external set b(String v);
}`);
expectTranslate(
`declare class X {
constructor();
a: number;
b: string;
}`,
trustJSTypesOpts)
.to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external factory X();
external num get a;
external set a(num v);
external String get b;
external set b(String v);
}`);
});
expectTranslate(
`declare class X {
static a: number;
static b: string;
}`,
trustJSTypesOpts)
.to.equal(`@JS()
class X {
// @Ignore
X.fakeConstructor$();
external static num get a;
external static set a(num v);
external static String get b;
external static set b(String v);
}`);
});
describe('--rename-conflicting-types', () => {
it('should merge variables and interfaces with the same name by default', () => {
expectTranslate(`
interface X {
a: string;
b: number;
c(): boolean;
}
declare var X: { d: number[] };
declare var x: X;
`).to.equal(`@anonymous
@JS()
abstract class X {
external String get a;
external set a(String v);
external num get b;
external set b(num v);
external bool c();
external static List<num> get d;
external static set d(List<num> v);
}
@JS()
external X get x;
@JS()
external set x(X v);`);
});
it('should rename types that conflict with unrelated variables when the flag is set', () => {
const renameConflictingTypesOpts = {failFast: true, renameConflictingTypes: true};
expectTranslate(
`interface X {
a: string;
b: number;
c(): boolean;
}
declare var X: { a: number[], b: number[], c: number[] };
declare var x: X;`,
renameConflictingTypesOpts)
.to.equal(`@anonymous
@JS()
abstract class XType {
external String get a;
external set a(String v);
external num get b;
external set b(num v);
external bool c();
}
@JS()
external dynamic /*{ a: number[], b: number[], c: number[] }*/ get X;
@JS()
external set X(dynamic /*{ a: number[], b: number[], c: number[] }*/ v);
@JS()
external XType get x;
@JS()
external set x(XType v);`);
});
});
});
describe('single call signature interfaces', () => {
it('should support declaration', () => {
expectTranslate('interface F { (n: number): boolean; }').to.equal('typedef bool F(num n);');
});
it('should support generics', () => {
expectTranslate('interface F<A, B> { (a: A): B; }').to.equal('typedef B F<A, B>(A a);');
});
});
describe('enums', () => {
it('should support basic enum declaration', () => {
expectTranslate('enum Color { Red, Green, Blue }').to.equal(`@JS()
class Color {
external static num get Red;
external static num get Green;
external static num get Blue;
}`);
});
it('allow empty enum', () => {
expectTranslate('enum Empty {}').to.equal(`@JS()
class Empty {}`);
});
it('enum with initializer', () => {
expectTranslate('enum Color { Red = 1, Green, Blue = 4 }').to.equal(`@JS()
class Color {
external static num get Red;
external static num get Green;
external static num get Blue;
}`);
});
it('should ingore switch', () => {
expectTranslate('switch(c) { case Color.Red: break; default: break; }').to.equal('');
});
it('does not support const enum', () => {
expectErroneousCode('const enum Color { Red }').to.throw('const enums are not supported');
});
}); | the_stack |
import { TestBed, fakeAsync, tick, flush, ComponentFixture } from '@angular/core/testing';
import { FormsModule, NgModel } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { Component, ViewChild } from '@angular/core';
import { MdcIconButtonDirective, MdcIconToggleDirective, MdcIconDirective, MdcFormsIconButtonDirective } from './mdc.icon-button.directive';
import { hasRipple } from '../../testutils/page.test';
describe('mdcIconButton', () => {
@Component({
template: `
<button mdcIconButton class="material-icons" [disabled]="disabled" (click)="action()"></button>
`
})
class TestComponent {
disabled: any;
clickCount = 0;
action() {
++this.clickCount;
}
}
function setup() {
const fixture = TestBed.configureTestingModule({
declarations: [MdcIconButtonDirective, TestComponent]
}).createComponent(TestComponent);
fixture.detectChanges();
return { fixture };
}
it('should render the icon button with icon and ripple styles', fakeAsync(() => {
const { fixture } = setup();
const iconButton = fixture.nativeElement.querySelector('button');
expect(iconButton.classList).toContain('mdc-icon-button');
expect(hasRipple(iconButton)).toBe(true);
}));
it('should be styled differently when disabled', (() => {
const { fixture } = setup();
const iconButton = fixture.nativeElement.querySelector('button');
const testComponent = fixture.debugElement.injector.get(TestComponent);
expect(iconButton.disabled).toBe(false);
testComponent.disabled = true;
fixture.detectChanges();
expect(iconButton.disabled).toBe(true);
}));
it('should act on clicks', (() => {
const { fixture } = setup();
const iconButton = fixture.nativeElement.querySelector('button');
const testComponent = fixture.debugElement.injector.get(TestComponent);
expect(testComponent.clickCount).toBe(0);
iconButton.click();
expect(testComponent.clickCount).toBe(1);
}));
});
describe('mdcIconToggle', () => {
@Component({
template: `
<button mdcIconToggle (onChange)="changeValue($event)" (click)="action()" [disabled]="disabled" [on]="favorite"
label="Add to favorites">
<i mdcIcon="on" class="material-icons">favorite</i>
<i mdcIcon class="material-icons">favorite_border</i>
</button>
`
})
class TestComponent {
disabled: any;
favorite: any;
changes = [];
actions = [];
changeValue(val: any) {
this.changes.push(val);
this.favorite = val;
}
action() {
this.actions.push(this.favorite);
}
}
function setup(testComponentType: any = TestComponent) {
const fixture = TestBed.configureTestingModule({
declarations: [MdcIconToggleDirective, MdcIconDirective, testComponentType]
}).createComponent(testComponentType);
fixture.detectChanges();
const iconToggle = fixture.debugElement.query(By.directive(MdcIconToggleDirective)).injector.get(MdcIconToggleDirective);
const element: HTMLButtonElement = fixture.nativeElement.querySelector('.mdc-icon-button');
const testComponent = fixture.debugElement.injector.get(testComponentType);
return { fixture, iconToggle, element, testComponent };
}
it('should render the icon toggles with icon and ripple styles', fakeAsync(() => {
const { element } = setup();
expect(element.classList).toContain('mdc-icon-button');
expect(hasRipple(element)).toBe(true);
}));
it('should be styled differently when disabled', (() => {
const { fixture, iconToggle, testComponent } = setup();
expect(iconToggle.disabled).toBe(false);
testComponent.disabled = true;
fixture.detectChanges();
expect(iconToggle.disabled).toBe(true);
}));
it('should toggle state when clicked', (() => {
const { iconToggle, testComponent, element } = setup();
expect(iconToggle.on).toBe(false); // initial value from 'favorite' property
expect(testComponent.favorite).toBeUndefined(); // not yet initialized, so undefined (coerced to false on button)
expect(element.classList).not.toContain('mdc-icon-button--on');
clickAndCheck(true);
clickAndCheck(false);
clickAndCheck(true);
function clickAndCheck(expected) {
element.click();
expect(iconToggle.on).toBe(expected);
expect(testComponent.favorite).toBe(expected);
if (expected)
expect(element.classList).toContain('mdc-icon-button--on');
else
expect(element.classList).not.toContain('mdc-icon-button--on');
}
}));
it('aria-pressed should reflect state of toggle', (() => {
const { fixture, testComponent, element } = setup();
expect(testComponent.favorite).toBeUndefined(); // not yet initialized, so undefined (coerced to false on button)
expect(element.getAttribute('aria-pressed')).toBe('false');
element.click(); // user change
expect(element.getAttribute('aria-pressed')).toBe('true');
testComponent.favorite = false; //programmatic change
fixture.detectChanges();
expect(element.getAttribute('aria-pressed')).toBe('false');
}));
it('label is reflected as aria-label', (() => {
const { element } = setup();
expect(element.getAttribute('aria-label')).toBe('Add to favorites');
}));
it('labelOn and labelOff are reflected as aria-label', (() => {
const { fixture, element, testComponent } = setup(TestLabelOnOffComponent);
expect(element.getAttribute('aria-label')).toBe('Add to favorites');
testComponent.favorite = true;
fixture.detectChanges();
expect(element.getAttribute('aria-label')).toBe('Remove from favorites');
}));
it('should toggle state when clicked', (() => {
const { iconToggle, testComponent, element } = setup();
expect(iconToggle.on).toBe(false); // initial value from 'favorite' property
expect(testComponent.favorite).toBeUndefined(); // not yet initialized, so undefined (coerced to false on button)
expect(element.classList).not.toContain('mdc-icon-button--on');
clickAndCheck(true);
clickAndCheck(false);
clickAndCheck(true);
function clickAndCheck(expected) {
element.click();
expect(iconToggle.on).toBe(expected);
expect(testComponent.favorite).toBe(expected);
if (expected)
expect(element.classList).toContain('mdc-icon-button--on');
else
expect(element.classList).not.toContain('mdc-icon-button--on');
}
}));
it('value changes must be emitted via onChange', (() => {
const { fixture, iconToggle, testComponent } = setup();
iconToggle._elm.nativeElement.click(); fixture.detectChanges();
expect(testComponent.changes).toEqual([true]);
iconToggle._elm.nativeElement.click(); fixture.detectChanges();
expect(testComponent.changes).toEqual([true, false]);
}));
it("programmatic value changes must be emitted via onChange", (() => {
const { fixture, testComponent } = setup();
testComponent.favorite = true; fixture.detectChanges();
testComponent.favorite = false; fixture.detectChanges();
testComponent.favorite = true; fixture.detectChanges();
expect(testComponent.changes).toEqual([true, false, true]);
}));
@Component({
template: `
<button mdcIconToggle (onChange)="changeValue($event)" (click)="action()" [disabled]="disabled" [on]="favorite">
<i mdcIcon="on" class="fa fa-heart"></i>
<i mdcIcon class="fa fa-heart-o"></i>
</button>`
})
class TestIconIsClassComponent {
}
it("iconIsClass property", fakeAsync(() => {
const { element } = setup(TestIconIsClassComponent);
expect(element.classList).toContain('mdc-icon-button');
expect(hasRipple(element)).toBe(true);
}));
@Component({
template: `
<button mdcIconToggle [on]="favorite"
labelOff="Add to favorites"
labelOn="Remove from favorites">
<i mdcIcon="on" class="material-icons">favorite</i>
<i mdcIcon class="material-icons">favorite_border</i>
</button>
`
})
class TestLabelOnOffComponent {
favorite = false;
}
});
describe('mdcIconToggle with FormsModule', () => {
@Component({
template: `
<button mdcIconToggle #ngModel="ngModel" [ngModel]="favorite" (ngModelChange)="changeValue($event)"
(click)="action()" [disabled]="disabled">
<i mdcIcon="on" class="material-icons">favorite</i>
<i mdcIcon class="material-icons">favorite_border</i>
</button>
`
})
class TestComponent {
@ViewChild('ngModel') ngModel: NgModel;
favorite: any;
disabled = false;
changes = [];
actions = [];
changeValue(val: any) {
this.changes.push(val);
this.favorite = val;
}
action() {
this.actions.push(this.favorite);
}
}
function setup() {
const fixture = TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [MdcIconToggleDirective, MdcIconDirective, MdcFormsIconButtonDirective, TestComponent]
}).createComponent(TestComponent);
fixture.detectChanges();
const iconToggle = fixture.debugElement.query(By.directive(MdcIconToggleDirective)).injector.get(MdcIconToggleDirective);
const testComponent = fixture.debugElement.injector.get(TestComponent);
return { fixture, iconToggle, testComponent };
}
it('value changes must be emitted via ngModelChange', (() => {
const { fixture, iconToggle, testComponent } = setup();
iconToggle._elm.nativeElement.click(); fixture.detectChanges();
expect(testComponent.changes).toEqual([true]);
iconToggle._elm.nativeElement.click(); fixture.detectChanges();
expect(testComponent.changes).toEqual([true, false]);
}));
it("programmatic changes of 'ngModel don't trigger ngModelChange events", fakeAsync(() => {
const { fixture, testComponent } = setup();
testComponent.favorite = true; fixture.detectChanges(); flush();
testComponent.favorite = false; fixture.detectChanges(); flush();
testComponent.favorite = true; fixture.detectChanges(); flush();
expect(testComponent.changes).toEqual([]);
}));
it("the disabled property should disable the button", fakeAsync(() => {
const { fixture } = setup();
const iconToggle = fixture.debugElement.query(By.directive(MdcIconToggleDirective)).injector.get(MdcIconToggleDirective);
const testComponent = fixture.debugElement.injector.get(TestComponent);
tick();
expect(iconToggle._elm.nativeElement.disabled).toBe(false);
expect(testComponent.ngModel.disabled).toBe(false);
testComponent.disabled = true;
fixture.detectChanges();
tick();
expect(iconToggle._elm.nativeElement.disabled).toBe(true);
expect(testComponent.ngModel.disabled).toBe(true);
}));
}); | the_stack |
import Service from './service';
import {statusCodes} from './TLV/values';
export type ValueFormat = 'bool' | 'uint8' | 'uint16' | 'uint32' | 'int' | 'float' | 'string' | 'tlv8' | 'data';
export type ValueUnit = 'celsius' | 'percentage' | 'arcdegrees' | 'lux' | 'seconds';
export type OnWrite = (value: any, callback: (status: statusCodes) => void, authData?: Buffer) => void;
const defaultRanges: { [index: string]: number[] } = {
int: [-2147483648, 2147483647],
uint8: [0, 255],
uint32: [0, 4294967295],
uint64: [0, 18446744073709551615]
};
export default class Characteristic {
/**
* @property ID of this characteristic / must be unique at service level
* @private
*/
private ID: number;
/**
* @property Characteristic Type
* @private
*/
private type: string;
/**
* @property Characteristic Value
* @private
*/
private value?: any;
/**
* @property Characteristic Value Format
* @private
*/
private valueFormat: ValueFormat;
/**
* @property Characteristic Value Unit
* @private
*/
private valueUnit?: ValueUnit;
/**
* @property Characteristic Min. Value
* @private
*/
private minValue?: number;
/**
* @property Characteristic Max. Value
* @private
*/
private maxValue?: number;
/**
* @property Characteristic Step Value
* @private
*/
private stepValue?: number;
/**
* @property Characteristic Value Max. Length
* @private
*/
private maxLength?: number;
/**
* @property Characteristic Valid Values
* @private
*/
private validValues?: number[];
/**
* @property Characteristic Valid Range Values
* @private
*/
private validRangeValues?: number[];
/**
* @property Whether or not this is a hidden characteristic
* @private
*/
private isHidden?: boolean;
/**
* @property Whether or not this characteristic supports notifications
* @private
*/
private hasNotifications?: boolean;
/**
* @property Whether or not this characteristic notifications are silent
* @private
*/
private silentNotifications?: boolean;
/**
* @property Whether or not this characteristic has a value
* @private
*/
private hasValue?: boolean;
/**
* @property Whether or not this characteristic is readonly
* @private
*/
private isReadonly?: boolean;
/**
* @property Whether or not this characteristic needs additional authorization
* @private
*/
private additionalAuthorization?: boolean;
/**
* @property An instance to this characteristic's service
* @private
*/
private service?: Service;
/**
* @property Characteristic Description
* @private
*/
private description?: string;
/**
* @property Subscribers for Notifications
* @private
*/
private subscribers: string[] = [];
/**
* @property Write handler for this characteristic
* @public
*/
public onWrite: OnWrite;
constructor(ID: number, type: string, valueFormat: ValueFormat, isHidden?: boolean, hasNotifications?: boolean, hasValue?: boolean, isReadonly?: boolean, additionalAuthorization?: boolean, valueUnit?: ValueUnit, description?: string, minValue?: number, maxValue?: number, stepValue?: number, maxLength?: number, validValues?: number[], validRangeValues?: number[], silentNotifications?: boolean) {
this.ID = ID;
this.type = type;
this.valueFormat = valueFormat;
this.valueUnit = valueUnit;
this.description = description;
if (this.isNumeric()) {
this.minValue = minValue;
this.maxValue = maxValue;
this.stepValue = stepValue;
this.validValues = validValues;
this.validRangeValues = validRangeValues;
}
if (this.hasLength())
this.maxLength = maxLength;
if (this.isSet(this.maxLength) && this.maxLength! > 256 && !this.isBuffer())
this.maxLength = 256;
this.isHidden = isHidden;
this.hasNotifications = hasNotifications;
this.hasValue = hasValue;
this.isReadonly = isReadonly;
this.additionalAuthorization = additionalAuthorization;
this.silentNotifications = silentNotifications;
}
/**
* @method Returns ID of this characteristic
* @returns {number}
*/
public getID(): number {
return this.ID;
}
/**
* @method Returns type of this characteristic
* @returns {string}
*/
public getType(): string {
return this.type;
}
/**
* @method Returns hasValue
* @returns {string}
*/
public getHasValue(): boolean {
return this.hasValue as boolean;
}
/**
* @method Returns hasNotifications
* @returns {string}
*/
public getHasNotifications(): boolean {
return this.hasNotifications as boolean;
}
/**
* @method Returns isReadonly
* @returns {string}
*/
public getIsReadonly(): boolean {
return this.isReadonly as boolean;
}
/**
* @method Whether or not this is a numeric characteristic
* @returns {boolean}
*/
private isNumeric(): boolean {
if (!this.valueFormat)
return false;
return ['uint8', 'uint16', 'uint32', 'int', 'float'].indexOf(this.valueFormat as string) > -1;
}
/**
* @method Whether or not this characteristic's value has a length
* @returns {boolean}
*/
private hasLength(): boolean {
if (!this.valueFormat)
return false;
return ['string', 'tlv8', 'data'].indexOf(this.valueFormat as string) > -1;
}
/**
* @method Whether or not this characteristic's value is a buffer
* @returns {boolean}
*/
private isBuffer(): boolean {
if (!this.valueFormat)
return false;
return ['tlv8', 'data'].indexOf(this.valueFormat as string) > -1;
}
/**
* @method Sets the value of this characteristic
* @param value
* @param {boolean} checkValue
* @returns {boolean}
*/
public setValue(value: any, checkValue: boolean = true): boolean {
if (!this.hasValue)
return false;
if (value === this.value)
return true;
if (!checkValue || this.isValid(value)) {
value = this.prepareValue(value);
this.value = value;
if (this.hasNotifications && this.subscribers.length && this.service && this.service.getAccessory() && this.service.getAccessory().getServer()) {
this.subscribers = this.service.getAccessory().getServer().TCPServer.sendNotification(this.subscribers, JSON.stringify({
characteristics: [{
aid: this.service.getAccessory().getID(),
iid: this.service.getAccessory().getIID(this.service.getID(), this.ID),
value: this.getValue()
}]
}));
}
return true;
} else {
console.error('Invalid Value', value);
return false;
}
}
/**
* @method Returns the value of this characteristic
* @param {boolean} parse
* @returns {any}
*/
public getValue(parse: boolean = true): any {
if (!parse)
return this.value;
let value;
if (this.hasValue) {
if (this.isNumeric())
value = this.valueFormat == 'float' ? this.getIntDefaultValue(parseFloat(this.value)) : this.getIntDefaultValue(parseInt(this.value));
else if (this.valueFormat == 'bool')
value = this.value >= 1;
else if (this.isBuffer())
value = this.value ? this.value.toString('base64') : '';
else
value = (this.value || '').toString();
} else
value = null;
return value;
}
/**
* @method Sets the service which is related to this characteristic
* @param service
*/
public setService(service: Service) {
if (this.service)
throw new Error('Service is already set.');
this.service = service;
}
/**
* @method Subscribes a TCP socket to this characteristic events
* @param socketID
*/
public subscribe(socketID: string) {
if (!this.hasNotifications)
return;
if (this.subscribers.indexOf(socketID) <= -1)
this.subscribers.push(socketID);
}
/**
* @method Unsubscribes a TCP socket for this characteristic events
* @param socketID
*/
public unsubscribe(socketID: string) {
if (!this.hasNotifications)
return;
this.subscribers.splice(this.subscribers.indexOf(socketID), 1);
}
/**
* @method Checks whether the provided value is valid or not
* @param value
* @returns {boolean}
*/
public isValid(value: any): boolean {
if (!this.isSet(value))
return false;
if (this.isNumeric()) {
if (isNaN(value))
return false;
if (this.isSet(this.minValue) && value < this.minValue!)
return false;
if (this.isSet(this.maxValue) && value > this.maxValue!)
return false;
if (this.validValues && this.validValues.indexOf(value) <= -1)
return false;
const range = this.validRangeValues || defaultRanges[this.valueFormat];
if (range && (value < range[0] || value > range[1]))
return false;
if (this.isSet(this.stepValue) && this.floatSafeRemainder(value, this.stepValue!) !== 0)
return false;
} else {
if (this.isBuffer() && !Buffer.isBuffer(value))
return false;
if (this.isSet(this.maxLength) && value.length > this.maxLength!)
return false;
}
return true;
}
/**
* @method Calculates remainder
* @param {number} value
* @param {number} step
* @returns {number}
*/
// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript
private floatSafeRemainder(value: any, step: number): number {
value = parseFloat(value);
if (isNaN(value))
return 1;
const valDecCount = (value.toString().split('.')[1] || '').length;
const stepDecCount = (step.toString().split('.')[1] || '').length;
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
const valInt = parseInt(value.toFixed(decCount).replace('.', ''));
const stepInt = parseInt(step.toFixed(decCount).replace('.', ''));
return (valInt % stepInt) / Math.pow(10, decCount);
}
/**
* @method Returns default value for integers if required
* @param {number} value
* @returns {number}
*/
private getIntDefaultValue(value: number): number {
if (this.isSet(value) && !isNaN(value))
return value;
let defaultValue = 0;
if (this.isSet(this.minValue))
defaultValue = this.minValue!;
else if (this.validValues)
defaultValue = this.validValues[0];
else if (this.validRangeValues)
defaultValue = this.validRangeValues[0];
return defaultValue;
}
/**
* @method Prepares a value to be stored
* @param value
* @returns {any}
*/
private prepareValue(value: any): any {
if (!this.isSet(value))
return value;
let finalValue;
if (this.isNumeric())
finalValue = this.getIntDefaultValue(parseFloat(value));
else if (this.valueFormat == 'bool')
finalValue = value >= 1;
else if (this.isBuffer())
finalValue = Buffer.isBuffer(value) ? value : Buffer.from(value || '', 'base64');
else
finalValue = (value || '').toString();
return finalValue;
}
/**
* @method Writes value of this characteristic
* @param value
* @returns {Promise<T>}
*/
public writeValue(value: any, authData: string): Promise<number> {
return new Promise((resolve, reject) => {
value = this.prepareValue(value);
if (this.isValid(value)) {
if (this.isReadonly) {
reject(statusCodes.isReadonly);
return;
}
if (this.onWrite) {
const timeout = setTimeout(function () {
reject(statusCodes.timedout);
}, 10000);
this.onWrite(value, (status) => {
clearTimeout(timeout);
if (status == statusCodes.OK) {
if (this.hasValue)
this.setValue(value, false);
resolve(statusCodes.OK);
} else
reject(status);
}, this.additionalAuthorization ? Buffer.from(authData, 'base64') : undefined);
} else {
if (this.hasValue) {
this.setValue(value, false);
resolve(statusCodes.OK);
} else
reject(statusCodes.communicationError);
}
} else
reject(statusCodes.invalidValue);
});
}
/**
* @method Returns array of permissions of this characteristic
* @returns {string[]}
*/
public getPermissions(): string[] {
const permissions: string[] = [];
if (this.hasValue)
permissions.push('pr');
if (!this.isReadonly)
permissions.push('pw');
if (this.hasNotifications)
permissions.push('ev');
if (this.additionalAuthorization)
permissions.push('aa');
if (this.isHidden)
permissions.push('hd');
return permissions;
}
/**
* @method Returns metadata of this characteristic
* @returns {{[p: string]: any}}
*/
public getMetadata(): { [index: string]: any } {
const object: { [index: string]: any } = {};
object['format'] = this.valueFormat;
if (this.valueUnit)
object['unit'] = this.valueUnit;
if (this.isSet(this.minValue))
object['minValue'] = this.minValue;
if (this.isSet(this.maxValue))
object['maxValue'] = this.maxValue;
if (this.isSet(this.stepValue))
object['minStep'] = this.stepValue;
if (this.isSet(this.maxLength))
object[this.isBuffer() ? 'maxDataLen' : 'maxLen'] = this.maxLength;
if (this.validValues)
object['valid-values'] = this.validValues;
if (this.validRangeValues)
object['valid-values-range'] = this.validRangeValues;
return object;
}
/**
* @method Adds metadata to a characteristic object
* @param object
*/
public addMetadata(object: any) {
const metadata = this.getMetadata();
for (const index in metadata)
object[index] = metadata[index];
}
/**
* @method Returns an object which represents this characteristic
* @returns {{[p: string]: any}}
*/
public toJSON(): {} {
const value = this.getValue();
const object: { [index: string]: any } = {
type: this.type,
iid: this.ID,
perms: this.getPermissions(),
};
if (this.isSet(value))
object['value'] = value;
if (this.hasNotifications && !this.silentNotifications)
object['ev'] = true;
if (this.description)
object['description'] = this.description;
this.addMetadata(object);
return object;
}
/**
* @method Checks if a variable is set or not
* @param value
* @returns {boolean}
*/
private isSet(value: any): boolean {
return value !== null && value !== undefined;
}
} | the_stack |
import Debug = require('debug'); const debug = Debug('modbus-client')
import * as Stream from 'stream'
import {
ReadCoilsRequestBody,
ReadDiscreteInputsRequestBody,
ReadHoldingRegistersRequestBody,
ReadInputRegistersRequestBody,
WriteMultipleCoilsRequestBody,
WriteMultipleRegistersRequestBody,
WriteSingleCoilRequestBody,
WriteSingleRegisterRequestBody
} from './request'
import ModbusAbstractRequest from './abstract-request.js'
import ModbusAbstractResponse from './abstract-response.js'
import MBClientRequestHandler from './client-request-handler.js'
import MBClientResponseHandler from './client-response-handler.js'
import { UserRequestError } from './errors'
import { CastRequestBody } from './request-response-map'
import { WriteMultipleCoilsResponseBody } from './response'
import { PromiseUserRequest } from './user-request.js'
/** Common Modbus Client
* @abstract
*/
export default abstract class MBClient<S extends Stream.Duplex, Req extends ModbusAbstractRequest> {
public abstract get slaveId (): number;
public abstract get unitId (): number;
/**
* Connection state of the client. Either online or offline.
*/
public get connectionState () {
return this._requestHandler.state
}
public get socket () {
return this._socket
}
/**
* The current number of requests
* in the handler cue
*/
public get requestCount (): number {
return this._requestHandler.requestCount
}
protected _socket: S
protected abstract readonly _requestHandler: MBClientRequestHandler<S, Req>
protected abstract readonly _responseHandler: MBClientResponseHandler
/** Creates a new Modbus client object.
* @param {Socket} socket A socket object
* @throws {NoSocketException}
*/
constructor (socket: S) {
if (new.target === MBClient) {
throw new TypeError('Cannot instantiate ModbusClient directly.')
}
this._socket = socket
if (!socket) {
throw new Error('NoSocketException.')
}
this._socket.on('data', this._onData.bind(this))
}
/** Execute ReadCoils Request (Function Code 0x01)
* @param {number} start Start Address.
* @param {number} count Coil Quantity.
* @returns {Promise}
* @example
* client.readCoils(0, 10).then(function (res) {
* console.log(res.response, res.request)
* }).catch(function (err) {
* ...
* })
*/
public readCoils (start: number, count: number) {
debug('issuing new read coils request')
let request
try {
request = new ReadCoilsRequestBody(start, count)
} catch (e) {
debug('unknown request error occurred')
return Promise.reject(e)
}
return this._requestHandler.register(request)
}
/** Execute ReadDiscreteInputs Request (Function Code 0x02)
* @param {number} start Start Address.
* @param {number} count Coil Quantity.
* @example
* client.readDiscreteInputs(0, 10).then(function (res) {
* console.log(res.response, res.request)
* }).catch(function (err) {
* ...
* })
*/
public readDiscreteInputs (start: number, count: number) {
debug('issuing new read discrete inputs request')
let request
try {
request = new ReadDiscreteInputsRequestBody(start, count)
} catch (e) {
debug('unknown request error occurred')
return Promise.reject(e)
}
return this._requestHandler.register(request)
}
/** Execute ReadHoldingRegisters Request (Function Code 0x03)
* @param {number} start Start Address.
* @param {number} count Coil Quantity.
* @example
* client.readHoldingRegisters(0, 10).then(function (res) {
* console.log(res.response, res.request)
* }).catch(function (err) {
* ...
* })
*/
public readHoldingRegisters (start: number, count: number) {
debug('issuing new read holding registers request')
let request
try {
request = new ReadHoldingRegistersRequestBody(start, count)
} catch (e) {
debug('unknown request error occurred')
return Promise.reject(e)
}
return this._requestHandler.register(request)
}
/** Execute ReadInputRegisters Request (Function Code 0x04)
* @param {number} start Start Address.
* @param {number} count Coil Quantity.
* @example
* client.readInputRegisters(0, 10).then(function (res) {
* console.log(res.response, res.request)
* }).catch(function (err) {
* ...
* })
*/
public readInputRegisters (start: number, count: number) {
debug('issuing new read input registers request')
let request
try {
request = new ReadInputRegistersRequestBody(start, count)
} catch (e) {
debug('unknown request error occurred')
return Promise.reject(e)
}
return this._requestHandler.register(request)
}
/** Execute WriteSingleCoil Request (Function Code 0x05)
* @param {number} address Address.
* @param {boolean | 0 | 1} value Value.
* @example
* client.writeSingleCoil(10, true).then(function (res) {
* console.log(res.response, res.request)
* }).catch(function (err) {
* ...
* })
*/
public writeSingleCoil (address: number, value: boolean | 0 | 1) {
debug('issuing new write single coil request')
let request
try {
request = new WriteSingleCoilRequestBody(address, value)
} catch (e) {
debug('unknown request error occurred')
return Promise.reject(e)
}
return this._requestHandler.register(request)
}
/** Execute WriteSingleRegister Request (Function Code 0x06)
* @param {number} address Address.
* @param {number} value Value.
* @example
* client.writeSingleRegister(10, 1234).then(function (res) {
* console.log(res.response, res.request)
* }).catch(function (err) {
* ...
* })
*/
public writeSingleRegister (address: number, value: number) {
debug('issuing new write single register request')
let request
try {
request = new WriteSingleRegisterRequestBody(address, value)
} catch (e) {
debug('unknown request error occurred')
return Promise.reject(e)
}
return this._requestHandler.register(request)
}
/** Execute WriteMultipleCoils Request (Function Code 0x0F)
* @param {number} address Address.
* @param {boolean[]} values Values either as an Array[Boolean] or a Buffer.
* @returns {PromiseUserRequest<ReqType, ResType>}
* @example
* client.writeMultipleCoils(10, [true, false, true, false, true]).then(function (res) {
* console.log(res.response, res.request)
* }).catch(function (err) {
* ...
* })
*/
public writeMultipleCoils (start: number, values: boolean[]):
PromiseUserRequest<CastRequestBody<Req, WriteMultipleCoilsRequestBody>>
/** Execute WriteMultipleCoils Request (Function Code 0x0F)
* @param {Number} address Address.
* @param { Buffer} values Values either as an Array[Boolean] or a Buffer.
* @param {Number} [quantity] If you choose to use the Buffer for the values then you have to
* specify the quantity of bytes.
* @returns {PromiseUserRequest<ReqType, ResType>}
* @example
* client.writeMultipleCoils(10, Buffer.from([0xdd]), 7).then(function (res) {
* console.log(res.response, res.request)
* }).catch(function (err) {
* ...
* })
*/
public writeMultipleCoils (start: number, values: Buffer, quantity: number):
PromiseUserRequest<CastRequestBody<Req, WriteMultipleCoilsRequestBody>>
public writeMultipleCoils (start: number, values: boolean[] | Buffer, quantity: number = 0) {
debug('issuing new write multiple coils request')
let request
try {
if (values instanceof Buffer) {
request = new WriteMultipleCoilsRequestBody(start, values, quantity)
} else {
request = new WriteMultipleCoilsRequestBody(start, values)
}
} catch (e) {
debug('unknown request error occurred')
return Promise.reject(e)
}
return this._requestHandler.register(request)
}
/** Execute WriteMultipleRegisters Request (Function Code 0x10)
* @param {Number} address Address.
* @param {Array|Buffer} values Values either as an Array[UInt16] or a Buffer.
* @returns {Promise}
* @example
* client.writeMultipleRegisters(10, [0x1234, 0x5678, 0x9ABC, 0xDEF0]).then(function (res) {
* console.log(res.response, res.request)
* }).catch(function (err) {
* ...
* })
* @example
* const buff = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0]);
* client.writeMultipleRegisters(10, buff).then(function (res) {
* console.log(res.response, res.request)
* }).catch(function (err) {
* ...
* })
*/
public writeMultipleRegisters (start: number, values: number[] | Buffer) {
debug('issuing new write multiple registers request')
let request
try {
request = new WriteMultipleRegistersRequestBody(start, values)
} catch (e) {
debug('unknown request error occurred')
return Promise.reject(e)
}
return this._requestHandler.register(request)
}
/**
* Manually Reject a specified number of requests
*/
public manuallyClearRequests (numRequests: number): void {
return this._requestHandler.manuallyRejectRequests(numRequests)
}
/**
* Manually reject the first request in the cue
*/
public manuallyRejectCurrentRequest (): void {
return this._requestHandler.manuallyRejectCurrentRequest()
}
/**
* Reject current request with a custom error
*/
public customErrorRequest (err: UserRequestError<any>) {
return this._requestHandler.customErrorRequest(err)
}
private _onData (data: Buffer) {
debug('received data')
this._responseHandler.handleData(data)
/* get latest message from message handler */
do {
const response = this._responseHandler.shift()
/* no message was parsed by now, come back later */
if (!response) {
return
}
/* process the response in the request handler if unitId is a match */
if (this.unitId === response.unitId) {
this._requestHandler.handle(response) // TODO: Find a better way than overwriting the type as any
}
} while (1)
}
} | the_stack |
"use strict";
declare var zip: any;
declare var cordova: Cordova;
import LocalPackage = require("./localPackage");
import RemotePackage = require("./remotePackage");
import CodePushUtil = require("./codePushUtil");
import NativeAppInfo = require("./nativeAppInfo");
import Sdk = require("./sdk");
import SyncStatus = require("./syncStatus");
/**
* This is the entry point to Cordova CodePush SDK.
* It provides the following features to the app developer:
* - polling the server for new versions of the app
* - notifying the plugin that the application loaded successfully after an update
* - getting information about the currently deployed package
*/
class CodePush implements CodePushCordovaPlugin {
/**
* The default options for the sync command.
*/
private static DefaultSyncOptions: SyncOptions;
/**
* Notifies the plugin that the update operation succeeded and that the application is ready.
* Calling this function is required if a rollbackTimeout parameter is used for your LocalPackage.apply() call.
* If apply() is used without a rollbackTimeout, calling this function is a noop.
*
* @param notifySucceeded Optional callback invoked if the plugin was successfully notified.
* @param notifyFailed Optional callback invoked in case of an error during notifying the plugin.
*/
public notifyApplicationReady(notifySucceeded?: SuccessCallback<void>, notifyFailed?: ErrorCallback): void {
cordova.exec(notifySucceeded, notifyFailed, "CodePush", "updateSuccess", []);
}
/**
* Get the current package information.
*
* @param packageSuccess Callback invoked with the currently deployed package information.
* @param packageError Optional callback invoked in case of an error.
*/
public getCurrentPackage(packageSuccess: SuccessCallback<LocalPackage>, packageError?: ErrorCallback): void {
return LocalPackage.getPackageInfoOrNull(LocalPackage.PackageInfoFile, packageSuccess, packageError);
}
/**
* Checks with the CodePush server if an update package is available for download.
*
* @param querySuccess Callback invoked in case of a successful response from the server.
* The callback takes one RemotePackage parameter. A non-null package is a valid update.
* A null package means the application is up to date for the current native application version.
* @param queryError Optional callback invoked in case of an error.
*/
public checkForUpdate(querySuccess: SuccessCallback<RemotePackage>, queryError?: ErrorCallback): void {
try {
var callback: Callback<RemotePackage | NativeUpdateNotification> = (error: Error, remotePackageOrUpdateNotification: IRemotePackage | NativeUpdateNotification) => {
if (error) {
CodePushUtil.invokeErrorCallback(error, queryError);
}
else {
var appUpToDate = () => {
CodePushUtil.logMessage("The application is up to date.");
querySuccess && querySuccess(null);
};
if (remotePackageOrUpdateNotification) {
if ((<NativeUpdateNotification>remotePackageOrUpdateNotification).updateAppVersion) {
/* There is an update available for a different version. In the current version of the plugin, we treat that as no update. */
appUpToDate();
} else {
/* There is an update available for the current version. */
var remotePackage: RemotePackage = <RemotePackage>remotePackageOrUpdateNotification;
NativeAppInfo.isFailedUpdate(remotePackage.packageHash, (applyFailed: boolean) => {
var result: RemotePackage = new RemotePackage();
result.appVersion = remotePackage.appVersion;
result.deploymentKey = remotePackage.deploymentKey;
result.description = remotePackage.description;
result.downloadUrl = remotePackage.downloadUrl;
result.isMandatory = remotePackage.isMandatory;
result.label = remotePackage.label;
result.packageHash = remotePackage.packageHash;
result.packageSize = remotePackage.packageSize;
result.failedApply = applyFailed;
CodePushUtil.logMessage("An update is available. " + JSON.stringify(result));
querySuccess && querySuccess(result);
});
}
}
else {
appUpToDate();
}
}
};
Sdk.getAcquisitionManager((initError: Error, acquisitionManager: AcquisitionManager) => {
if (initError) {
CodePushUtil.invokeErrorCallback(initError, queryError);
} else {
LocalPackage.getCurrentOrDefaultPackage((localPackage: LocalPackage) => {
acquisitionManager.queryUpdateWithCurrentPackage(localPackage, callback);
}, (error: Error) => {
CodePushUtil.invokeErrorCallback(error, queryError);
});
}
});
} catch (e) {
CodePushUtil.invokeErrorCallback(new Error("An error occurred while querying for updates." + CodePushUtil.getErrorMessage(e)), queryError);
}
}
/**
* Convenience method for installing updates in one method call.
* This method is provided for simplicity, and its behavior can be replicated by using window.codePush.checkForUpdate(), RemotePackage's download() and LocalPackage's apply() methods.
*
* The algorithm of this method is the following:
* - Checks for an update on the CodePush server.
* - If an update is available
* - If the update is mandatory and the alertMessage is set in options, the user will be informed that the application will be updated to the latest version.
* The update package will then be downloaded and applied.
* - If the update is not mandatory and the confirmMessage is set in options, the user will be asked if they want to update to the latest version.
* If they decline, the syncCallback will be invoked with SyncStatus.UPDATE_IGNORED.
* - Otherwise, the update package will be downloaded and applied with no user interaction.
* - If no update is available on the server, the syncCallback will be invoked with the SyncStatus.UP_TO_DATE.
* - If an error occurs during checking for update, downloading or applying it, the syncCallback will be invoked with the SyncStatus.ERROR.
*
* @param syncCallback Optional callback to be called with the status of the sync operation.
* The callback will be called only once, and the possible statuses are defined by the SyncStatus enum.
* @param syncOptions Optional SyncOptions parameter configuring the behavior of the sync operation.
*
*/
public sync(syncCallback?: SuccessCallback<any>, syncOptions?: SyncOptions): void {
/* No options were specified, use default */
if (!syncOptions) {
syncOptions = this.getDefaultSyncOptions();
}
/* Some options were specified */
if (syncOptions.mandatoryUpdateMessage) {
syncOptions.mandatoryContinueButtonLabel = syncOptions.mandatoryContinueButtonLabel || this.getDefaultSyncOptions().mandatoryContinueButtonLabel;
syncOptions.updateTitle = syncOptions.updateTitle || this.getDefaultSyncOptions().updateTitle;
}
if (syncOptions.optionalUpdateMessage) {
syncOptions.optionalInstallButtonLabel = syncOptions.optionalInstallButtonLabel || this.getDefaultSyncOptions().optionalInstallButtonLabel;
syncOptions.optionalIgnoreButtonLabel = syncOptions.optionalIgnoreButtonLabel || this.getDefaultSyncOptions().optionalIgnoreButtonLabel;
syncOptions.updateTitle = syncOptions.updateTitle || this.getDefaultSyncOptions().updateTitle;
}
if (typeof syncOptions.ignoreFailedUpdates !== typeof true) {
/* Ignoring failed updates by default. */
syncOptions.ignoreFailedUpdates = true;
}
if (syncOptions.appendReleaseDescription && !syncOptions.descriptionPrefix) {
syncOptions.descriptionPrefix = this.getDefaultSyncOptions().descriptionPrefix;
}
window.codePush.notifyApplicationReady();
var onError = (error: Error) => {
CodePushUtil.logError("An error occurred during sync.", error);
syncCallback && syncCallback(SyncStatus.ERROR);
};
var onApplySuccess = () => {
syncCallback && syncCallback(SyncStatus.APPLY_SUCCESS);
};
var onDownloadSuccess = (localPackage: ILocalPackage) => {
localPackage.apply(onApplySuccess, onError, syncOptions.rollbackTimeout);
};
var downloadAndInstallUpdate = (remotePackage: RemotePackage) => {
remotePackage.download(onDownloadSuccess, onError);
};
var onUpdate = (remotePackage: RemotePackage) => {
if (!remotePackage || (remotePackage.failedApply && syncOptions.ignoreFailedUpdates)) {
syncCallback && syncCallback(SyncStatus.UP_TO_DATE);
} else {
if (remotePackage.isMandatory && syncOptions.mandatoryUpdateMessage) {
/* Alert user */
var message = syncOptions.appendReleaseDescription ? syncOptions.mandatoryUpdateMessage + syncOptions.descriptionPrefix + remotePackage.description : syncOptions.mandatoryUpdateMessage;
navigator.notification.alert(message, () => { downloadAndInstallUpdate(remotePackage); }, syncOptions.updateTitle, syncOptions.mandatoryContinueButtonLabel);
} else if (!remotePackage.isMandatory && syncOptions.optionalUpdateMessage) {
/* Confirm update with user */
var optionalUpdateCallback = (buttonIndex: number) => {
switch (buttonIndex) {
case 1:
/* Install */
downloadAndInstallUpdate(remotePackage);
break;
case 2:
default:
/* Cancel */
syncCallback && syncCallback(SyncStatus.UPDATE_IGNORED);
break;
}
};
var message = syncOptions.appendReleaseDescription ? syncOptions.optionalUpdateMessage + syncOptions.descriptionPrefix + remotePackage.description : syncOptions.optionalUpdateMessage;
navigator.notification.confirm(message, optionalUpdateCallback, syncOptions.updateTitle, [syncOptions.optionalInstallButtonLabel, syncOptions.optionalIgnoreButtonLabel]);
} else {
/* No user interaction */
downloadAndInstallUpdate(remotePackage);
}
}
};
window.codePush.checkForUpdate(onUpdate, onError);
}
/**
* Returns the default options for the CodePush sync operation.
* If the options are not defined yet, the static DefaultSyncOptions member will be instantiated.
*/
private getDefaultSyncOptions(): SyncOptions {
if (!CodePush.DefaultSyncOptions) {
CodePush.DefaultSyncOptions = {
updateTitle: "Update",
mandatoryUpdateMessage: "You will be updated to the latest version.",
mandatoryContinueButtonLabel: "Continue",
optionalUpdateMessage: "An update is available. Would you like to install it?",
optionalInstallButtonLabel: "Install",
optionalIgnoreButtonLabel: "Ignore",
rollbackTimeout: 0,
ignoreFailedUpdates: true,
appendReleaseDescription: false,
descriptionPrefix: " Description: "
};
}
return CodePush.DefaultSyncOptions;
}
}
var instance = new CodePush();
export = instance; | the_stack |
import { moment, normalizePath, Notice, TFile, TFolder } from 'obsidian';
import { getAllDailyNotes, getDateFromFile } from 'obsidian-daily-notes-interface';
import appStore from '../stores/appStore';
import {
CommentOnMemos,
CommentsInOriginalNotes,
DefaultMemoComposition,
DeleteFileName,
FetchMemosFromNote,
FetchMemosMark,
ProcessEntriesBelow,
QueryFileName,
} from '../memos';
import { getAPI } from 'obsidian-dataview';
import { t } from '../translations/helper';
import { getDailyNotePath } from '../helpers/utils';
export class DailyNotesFolderMissingError extends Error {}
interface allKindsofMemos {
memos: Model.Memo[];
commentMemos: Model.Memo[];
}
const getTaskType = (memoTaskType: string): string => {
let memoType;
if (memoTaskType === ' ') {
memoType = 'TASK-TODO';
return memoType;
} else if (memoTaskType === 'x' || memoTaskType === 'X') {
memoType = 'TASK-DONE';
return memoType;
} else {
memoType = 'TASK-' + memoTaskType;
return memoType;
}
};
export async function getRemainingMemos(note: TFile): Promise<number> {
if (!note) {
return 0;
}
const { vault } = appStore.getState().dailyNotesState.app;
let fileContents = await vault.read(note);
let regexMatch;
if (
DefaultMemoComposition != '' &&
/{TIME}/g.test(DefaultMemoComposition) &&
/{CONTENT}/g.test(DefaultMemoComposition)
) {
//eslint-disable-next-line
regexMatch =
'(-|\\*) (\\[(.{1})\\]\\s)?' +
DefaultMemoComposition.replace(/{TIME}/g, '((\\<time\\>)?\\d{1,2}:\\d{2})?').replace(/ {CONTENT}/g, '');
} else {
//eslint-disable-next-line
regexMatch = '(-|\\*) (\\[(.{1})\\]\\s)?((\\<time\\>)?\\d{1,2}\\:\\d{2})?';
}
const regexMatchRe = new RegExp(regexMatch, 'g');
//eslint-disable-next-line
const matchLength = (fileContents.match(regexMatchRe) || []).length;
// const matchLength = (fileContents.match(/(-|\*) (\[ \]\s)?((\<time\>)?\d{1,2}\:\d{2})?/g) || []).length;
const re = new RegExp(ProcessEntriesBelow.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'), 'g');
const processEntriesHeader = (fileContents.match(re) || []).length;
fileContents = null;
if (processEntriesHeader) {
return matchLength;
}
return 0;
}
export async function getCommentMemosFromDailyNote(dailyNote: TFile | null, commentMemos: any[]): Promise<any[]> {
if (!dailyNote) {
return commentMemos;
}
}
export async function getMemosFromDailyNote(
dailyNote: TFile | null,
allMemos: any[],
commentMemos: any[],
): Promise<any[]> {
if (!dailyNote) {
return [];
}
const { vault } = appStore.getState().dailyNotesState.app;
const Memos = await getRemainingMemos(dailyNote);
let underComments;
if (Memos === 0) return;
// console.log(getAPI().version.compare('>=', '0.5.9'));
// Get Comments Near the Original Memos. Maybe use Dataview to fetch all memos in the near future.
if (CommentOnMemos && CommentsInOriginalNotes && getAPI().version.compare('>=', '0.5.9') === true) {
const dataviewAPI = getAPI();
if (dataviewAPI !== undefined && ProcessEntriesBelow !== '') {
try {
underComments = dataviewAPI
.page(dailyNote.path)
?.file.lists.values?.filter(
(item: object) =>
item.header.subpath === ProcessEntriesBelow?.replace(/#{1,} /g, '').trim() && item.children.length > 0,
);
} catch (e) {
console.error(e);
}
} else {
try {
underComments = dataviewAPI
.page(dailyNote.path)
?.file.lists.values?.filter((item: object) => item.children.length > 0);
} catch (e) {
console.error(e);
}
}
}
let fileContents = await vault.read(dailyNote);
let fileLines = getAllLinesFromFile(fileContents);
const startDate = getDateFromFile(dailyNote, 'day');
const endDate = getDateFromFile(dailyNote, 'day');
let processHeaderFound = false;
let memoType: string;
for (let i = 0; i < fileLines.length; i++) {
const line = fileLines[i];
if (line.length === 0) continue;
// if (line.contains('comment: ')) continue;
if (processHeaderFound == false && lineContainsParseBelowToken(line)) {
processHeaderFound = true;
}
if (processHeaderFound == true && !lineContainsParseBelowToken(line) && /^#{1,} /g.test(line)) {
processHeaderFound = false;
}
if (lineContainsTime(line) && processHeaderFound) {
const hourText = extractHourFromBulletLine(line);
const minText = extractMinFromBulletLine(line);
startDate.hours(parseInt(hourText));
startDate.minutes(parseInt(minText));
endDate.hours(parseInt(hourText));
if (parseInt(hourText) > 22) {
endDate.minutes(parseInt(minText));
} else {
endDate.minutes(parseInt(minText));
}
if (/^\s*[-*]\s(\[(.{1})\])\s/g.test(line)) {
const memoTaskType = extractMemoTaskTypeFromLine(line);
memoType = getTaskType(memoTaskType);
} else {
memoType = 'JOURNAL';
}
const rawText = extractTextFromTodoLine(line);
let originId = '';
if (rawText !== '') {
let hasId = Math.random().toString(36).slice(-6);
originId = hasId;
let linkId = '';
if (CommentOnMemos && /comment:(.*)#\^\S{6}]]/g.test(rawText)) {
linkId = extractCommentFromLine(rawText);
}
if (/\^\S{6}$/g.test(rawText)) {
hasId = rawText.slice(-6);
originId = hasId;
}
allMemos.push({
id: startDate.format('YYYYMMDDHHmmSS') + i,
content: rawText,
user_id: 1,
createdAt: startDate.format('YYYY/MM/DD HH:mm:SS'),
updatedAt: endDate.format('YYYY/MM/DD HH:mm:SS'),
memoType: memoType,
hasId: hasId,
linkId: linkId,
path: dailyNote.path,
});
}
if (/comment:(.*)#\^\S{6}]]/g.test(rawText) && CommentOnMemos && CommentsInOriginalNotes !== true) {
const commentId = extractCommentFromLine(rawText);
const hasId = '';
commentMemos.push({
id: startDate.format('YYYYMMDDHHmmSS') + i,
content: rawText,
user_id: 1,
createdAt: startDate.format('YYYY/MM/DD HH:mm:SS'),
updatedAt: endDate.format('YYYY/MM/DD HH:mm:SS'),
memoType: memoType,
hasId: hasId,
linkId: commentId,
});
continue;
}
if (
rawText !== '' &&
!rawText.contains(' comment') &&
underComments !== null &&
underComments !== undefined &&
underComments.length > 0
) {
// console.log(underComments.map((item) => console.log(item.text.replace(/^\d{2}:\d{2}/, ''))));
const originalText = line.replace(/^[-*]\s(\[(.{1})\]\s?)?/, '')?.trim();
const commentsInMemos = underComments.filter(
(item) => item.text === originalText || item.line === i || item.blockId === originId,
);
if (commentsInMemos.length === 0) continue;
if (commentsInMemos[0].children?.values?.length > 0) {
// console.log(commentsInMemos[0].children.values);
for (let j = 0; j < commentsInMemos[0].children.values.length; j++) {
// console.log(commentsInMemos[0].children.values[j].text);
const hasId = '';
let commentTime;
if (/^\d{12}/.test(commentsInMemos[0].children.values[j].text)) {
commentTime = commentsInMemos[0].children.values[j].text?.match(/^\d{14}/)[0];
} else {
commentTime = startDate.format('YYYYMMDDHHmmSS');
}
commentMemos.push({
id: commentTime + commentsInMemos[0].children.values[j].line,
content: commentsInMemos[0].children.values[j].text,
user_id: 1,
createdAt: moment(commentTime, 'YYYYMMDDHHmmSS').format('YYYY/MM/DD HH:mm:SS'),
updatedAt: moment(commentTime, 'YYYYMMDDHHmmSS').format('YYYY/MM/DD HH:mm:SS'),
memoType: commentsInMemos[0].children.values[j].task
? getTaskType(commentsInMemos[0].children.values[j].status)
: 'JOURNAL',
hasId: hasId,
linkId: originId,
path: commentsInMemos[0].children.values[j].path,
});
}
}
// console.log(underComments.filter((item: object) => item.text === rawText.trim()));
}
}
}
fileLines = null;
fileContents = null;
}
export async function getMemosFromNote(allMemos: any[], commentMemos: any[]): Promise<void> {
const notes = getAPI().pages(FetchMemosMark);
const dailyNotesPath = getDailyNotePath();
let files = notes?.values;
if (files.length === 0) return;
files = files.filter(
(item) =>
item.file.name !== QueryFileName &&
item.file.name !== DeleteFileName &&
item['excalidraw-plugin'] === undefined &&
item['kanban-plugin'] === undefined &&
item.file.folder !== dailyNotesPath,
// item.file.
);
// Get Memos from Note
for (let i = 0; i < files.length; i++) {
const createDate = files[i]['creation-date'];
// console.log(files[i]);
const list = files[i].file.lists?.filter((item) => item.parent === undefined);
if (list.length === 0) continue;
for (let j = 0; j < list.length; j++) {
const content = list[j].text;
const header = list[j].header.subpath;
const path = list[j].path;
const line = list[j].line;
let memoType = 'JOURNAL';
let hasId;
let realCreateDate = moment(createDate, 'YYYY-MM-DD HH:mm');
if (/\^\S{6}$/g.test(content)) {
hasId = content.slice(-6);
// originId = hasId;
} else {
hasId = Math.random().toString(36).slice(-6);
}
if (list[j].task === true) {
memoType = getTaskType(list[j].status);
}
if (header !== undefined) {
if (moment(header).isValid()) {
realCreateDate = moment(header);
// realCreateDate = momentDate.format('YYYYMMDDHHmmSS');
}
}
if (/^\d{2}:\d{2}/g.test(content)) {
const time = content.match(/^\d{2}:\d{2}/)[0];
const timeArr = time.split(':');
const hour = parseInt(timeArr[0], 10);
const minute = parseInt(timeArr[1], 10);
realCreateDate = moment(createDate, 'YYYYMMDDHHmmSS').hours(hour).minutes(minute);
// createDate = date.format('YYYYMMDDHHmmSS');
}
allMemos.push({
id: realCreateDate.format('YYYYMMDDHHmmSS') + line,
content: content,
user_id: 1,
createdAt: realCreateDate.format('YYYY/MM/DD HH:mm:SS'),
updatedAt: realCreateDate.format('YYYY/MM/DD HH:mm:SS'),
memoType: memoType,
hasId: hasId,
linkId: '',
path: path,
});
// Get Comment Memos From Note
if (list[j].children?.values.length > 0) {
for (let k = 0; k < list[j].children.values.length; k++) {
const childContent = list[j].children.values[k].text;
const childLine = list[j].children.values[k].line;
let childMemoType = 'JOURNAL';
let childRealCreateDate = realCreateDate;
let commentTime;
if (list[j].children.values[k].task === true) {
childMemoType = getTaskType(list[j].children.values[k].status);
}
if (/^\d{12}/.test(childContent)) {
commentTime = childContent?.match(/^\d{14}/)[0];
childRealCreateDate = moment(commentTime, 'YYYYMMDDHHmmSS');
}
if (/^\d{2}:\d{2}/g.test(childContent)) {
const time = childContent.match(/^\d{2}:\d{2}/)[0];
const timeArr = time.split(':');
const hour = parseInt(timeArr[0], 10);
const minute = parseInt(timeArr[1], 10);
childRealCreateDate = childRealCreateDate.hours(hour).minutes(minute);
// createDate = date.format('YYYYMMDDHHmmSS');
}
commentMemos.push({
id: childRealCreateDate.format('YYYYMMDDHHmmSS') + childLine,
content: childContent,
user_id: 1,
createdAt: childRealCreateDate.format('YYYY/MM/DD HH:mm:SS'),
updatedAt: childRealCreateDate.format('YYYY/MM/DD HH:mm:SS'),
memoType: childMemoType,
hasId: '',
linkId: hasId,
path: path,
});
// if()
}
}
}
}
return;
}
export async function getMemos(): Promise<allKindsofMemos> {
const memos: any[] | PromiseLike<any[]> = [];
const commentMemos: any[] | PromiseLike<any[]> = [];
const { vault } = appStore.getState().dailyNotesState.app;
const folder = getDailyNotePath();
if (folder === '' || folder === undefined) {
new Notice(t('Please check your daily note plugin OR periodic notes plugin settings'));
return;
}
const dailyNotesFolder = vault.getAbstractFileByPath(normalizePath(folder)) as TFolder;
if (!dailyNotesFolder) {
throw new DailyNotesFolderMissingError('Failed to find daily notes folder');
}
const dailyNotes = getAllDailyNotes();
for (const string in dailyNotes) {
if (dailyNotes[string] instanceof TFile && dailyNotes[string].extension === 'md') {
await getMemosFromDailyNote(dailyNotes[string], memos, commentMemos);
}
}
if (FetchMemosFromNote) {
await getMemosFromNote(memos, commentMemos);
}
return { memos, commentMemos };
}
const getAllLinesFromFile = (cache: string) => cache.split(/\r?\n/);
// const lineIsValidTodo = (line: string) => {
// //eslint-disable-next-line
// return /^\s*[\-\*]\s\[(\s|x|X|\\|\-|\>|D|\?|\/|\+|R|\!|i|B|P|C)\]\s?\s*\S/.test(line)
// }
const lineContainsTime = (line: string) => {
let regexMatch;
let indent = '\\s*';
if (CommentsInOriginalNotes) {
indent = '';
}
if (
DefaultMemoComposition != '' &&
/{TIME}/g.test(DefaultMemoComposition) &&
/{CONTENT}/g.test(DefaultMemoComposition)
) {
//eslint-disable-next-line
regexMatch =
'^' +
indent +
'(-|\\*)\\s(\\[(.{1})\\]\\s)?' +
DefaultMemoComposition.replace(/{TIME}/g, '(\\<time\\>)?\\d{1,2}:\\d{2}(\\<\\/time\\>)?').replace(
/{CONTENT}/g,
'(.*)$',
);
} else {
//eslint-disable-next-line
regexMatch = '^' + indent + '(-|\\*)\\s(\\[(.{1})\\]\\s)?(\\<time\\>)?\\d{1,2}\\:\\d{2}(.*)$';
}
const regexMatchRe = new RegExp(regexMatch, '');
//eslint-disable-next-line
return regexMatchRe.test(line);
// The below line excludes entries with a ':' after the time as I was having issues with my calendar
// being pulled in. Once made configurable will be simpler to manage.
// return /^\s*[\-\*]\s(\[(\s|x|X|\\|\-|\>|D|\?|\/|\+|R|\!|i|B|P|C)\]\s)?(\<time\>)?\d{1,2}\:\d{2}[^:](.*)$/.test(line);
};
const lineContainsParseBelowToken = (line: string) => {
if (ProcessEntriesBelow === '') {
return true;
}
const re = new RegExp(ProcessEntriesBelow.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'), '');
return re.test(line);
};
const extractTextFromTodoLine = (line: string) => {
let regexMatch;
if (
DefaultMemoComposition != '' &&
/{TIME}/g.test(DefaultMemoComposition) &&
/{CONTENT}/g.test(DefaultMemoComposition)
) {
//eslint-disable-next-line
regexMatch =
'^\\s*[\\-\\*]\\s(\\[(.{1})\\]\\s?)?' +
DefaultMemoComposition.replace(/{TIME}/g, '(\\<time\\>)?((\\d{1,2})\\:(\\d{2}))?(\\<\\/time\\>)?').replace(
/{CONTENT}/g,
'(.*)$',
);
} else {
//eslint-disable-next-line
regexMatch = '^\\s*[\\-\\*]\\s(\\[(.{1})\\]\\s?)?(\\<time\\>)?((\\d{1,2})\\:(\\d{2}))?(\\<\\/time\\>)?\\s?(.*)$';
}
const regexMatchRe = new RegExp(regexMatch, '');
//eslint-disable-next-line
return regexMatchRe.exec(line)?.[8];
// return /^\s*[\-\*]\s(\[(.{1})\]\s?)?(\<time\>)?((\d{1,2})\:(\d{2}))?(\<\/time\>)?\s?(.*)$/.exec(line)?.[8];
};
const extractHourFromBulletLine = (line: string) => {
let regexHourMatch;
if (
DefaultMemoComposition != '' &&
/{TIME}/g.test(DefaultMemoComposition) &&
/{CONTENT}/g.test(DefaultMemoComposition)
) {
//eslint-disable-next-line
regexHourMatch =
'^\\s*[\\-\\*]\\s(\\[(.{1})\\]\\s?)?' +
DefaultMemoComposition.replace(/{TIME}/g, '(\\<time\\>)?(\\d{1,2})\\:(\\d{2})(\\<\\/time\\>)?').replace(
/{CONTENT}/g,
'(.*)$',
);
} else {
//eslint-disable-next-line
regexHourMatch = '^\\s*[\\-\\*]\\s(\\[(.{1})\\]\\s?)?(\\<time\\>)?(\\d{1,2})\\:(\\d{2})(.*)$';
}
const regexMatchRe = new RegExp(regexHourMatch, '');
//eslint-disable-next-line
return regexMatchRe.exec(line)?.[4];
};
const extractMinFromBulletLine = (line: string) => {
let regexHourMatch;
if (
DefaultMemoComposition != '' &&
/{TIME}/g.test(DefaultMemoComposition) &&
/{CONTENT}/g.test(DefaultMemoComposition)
) {
//eslint-disable-next-line
regexHourMatch =
'^\\s*[\\-\\*]\\s(\\[(.{1})\\]\\s?)?' +
DefaultMemoComposition.replace(/{TIME}/g, '(\\<time\\>)?(\\d{1,2})\\:(\\d{2})(\\<\\/time\\>)?').replace(
/{CONTENT}/g,
'(.*)$',
);
} else {
//eslint-disable-next-line
regexHourMatch = '^\\s*[\\-\\*]\\s(\\[(.{1})\\]\\s?)?(\\<time\\>)?(\\d{1,2})\\:(\\d{2})(.*)$';
}
const regexMatchRe = new RegExp(regexHourMatch, '');
//eslint-disable-next-line
return regexMatchRe.exec(line)?.[5];
// /^\s*[\-\*]\s(\[(.{1})\]\s?)?(\<time\>)?(\d{1,2})\:(\d{2})(.*)$/.exec(line)?.[5];
};
const extractMemoTaskTypeFromLine = (line: string) =>
//eslint-disable-next-line
/^\s*[\-\*]\s(\[(.{1})\])\s(.*)$/.exec(line)?.[2];
// The below line excludes entries with a ':' after the time as I was having issues with my calendar
// being pulled in. Once made configurable will be simpler to manage.
// return /^\s*[\-\*]\s(\[(\s|x|X|\\|\-|\>|D|\?|\/|\+|R|\!|i|B|P|C)\]\s)?(\<time\>)?\d{1,2}\:\d{2}[^:](.*)$/.test(line);
// Get comment Id
const extractCommentFromLine = (line: string) => {
const regex = '#\\^(\\S{6})';
const regexMatchRe = new RegExp(regex, '');
return regexMatchRe.exec(line)[1];
}; | the_stack |
import { action, computed, observable, makeObservable, override } from "mobx";
import {
onPatch,
resolvePath,
applyPatch,
IAnyModelType,
Instance,
} from "mobx-state-tree";
import {
Form,
FormDefinition,
ValidationResponse,
GroupDefinition,
ErrorFunc,
IDisposer,
RepeatingForm,
} from "./form";
import { pathToSteps, stepsToPath } from "./utils";
import { FieldAccessor } from "./field-accessor";
import { FormAccessorBase } from "./form-accessor-base";
import { RepeatingFormAccessor } from "./repeating-form-accessor";
import { SubFormAccessor } from "./sub-form-accessor";
import { RepeatingFormIndexedAccessor } from "./repeating-form-indexed-accessor";
import { ValidateOptions } from "./validate-options";
import {
StateConverterOptions,
StateConverterOptionsWithContext,
} from "./converter";
import { checkConverterOptions } from "./decimalParser";
import {
Backend,
ProcessorOptions,
Process,
SaveFunc,
ProcessAll,
AccessUpdate,
} from "./backend";
import { Validation } from "./validationMessages";
import {
IAccessor,
IFormAccessor,
IAnyFormAccessor,
IRepeatingFormAccessor,
ISubFormAccessor,
} from "./interfaces";
export interface AccessorAllows {
(accessor: IAccessor): boolean;
}
export interface ErrorOrWarning {
(accessor: IAccessor): string | undefined;
}
export interface ExtraValidation {
(fieldAccessor: FieldAccessor<any, any>, value: any): ValidationResponse;
}
export interface RepeatingFormAccessorAllows {
(repeatingFormAccessor: RepeatingFormAccessor<any, any, any>): boolean;
}
export interface EventFunc<R, V> {
(event: any, accessor: FieldAccessor<R, V>): void;
}
export interface UpdateFunc<R, V> {
(accessor: FieldAccessor<R, V>): void;
}
// TODO: implement blur and pause validation
// blur would validate immediately after blur
// pause would show validation after the user stops input for a while
export type ValidationOption = "immediate" | "no"; // | "blur" | "pause";
export type BackendOptions<M> = {
save?: SaveFunc<M>;
process?: Process<M>;
processAll?: ProcessAll<M>;
};
type ValidationOptions = {
beforeSave: ValidationOption;
afterSave: ValidationOption;
pauseDuration: number;
};
export interface FormStateOptions<M> {
addMode?: boolean;
validation?: Partial<ValidationOptions>;
isDisabled?: AccessorAllows;
isHidden?: AccessorAllows;
isReadOnly?: AccessorAllows;
isRequired?: AccessorAllows;
isEnabled?: AccessorAllows;
getError?: ErrorOrWarning;
getWarning?: ErrorOrWarning;
backend?: BackendOptions<M> & ProcessorOptions;
extraValidation?: ExtraValidation;
focus?: EventFunc<any, any>;
blur?: EventFunc<any, any>;
update?: UpdateFunc<any, any>;
context?: any;
converterOptions?: StateConverterOptions;
requiredError?: string | ErrorFunc;
addModeDefaults?: string[];
}
export type SaveStatusOptions = "before" | "rightAfter" | "after";
export class FormState<
D extends FormDefinition<M>,
G extends GroupDefinition<D>,
M extends IAnyModelType
>
extends FormAccessorBase<D, G, M>
implements IFormAccessor<D, G, M>
{
@observable
saveStatus: SaveStatusOptions = "before";
validationBeforeSave: ValidationOption;
validationAfterSave: ValidationOption;
validationPauseDuration: number;
isDisabledFunc: AccessorAllows;
isHiddenFunc: AccessorAllows;
isReadOnlyFunc: AccessorAllows;
isRequiredFunc: AccessorAllows;
isEnabledFunc: AccessorAllows;
getErrorFunc: ErrorOrWarning;
getWarningFunc: ErrorOrWarning;
extraValidationFunc: ExtraValidation;
private noRawUpdate: boolean;
focusFunc: EventFunc<any, any> | undefined;
blurFunc: EventFunc<any, any> | undefined;
updateFunc: UpdateFunc<any, any> | undefined;
processor: Backend<M> | undefined;
_context: any;
_converterOptions: StateConverterOptions;
_requiredError: string | ErrorFunc;
_onPatchDisposer: IDisposer;
constructor(
public form: Form<M, D, G>,
public node: Instance<M>,
{
addMode = false,
isDisabled = () => false,
isHidden = () => false,
isReadOnly = () => false,
isRequired = () => false,
isEnabled = () => false,
getError = () => undefined,
getWarning = () => undefined,
backend = undefined,
extraValidation = () => false,
validation = {},
focus,
blur,
update,
context,
converterOptions = {},
requiredError = "Required",
addModeDefaults = [],
}: FormStateOptions<M> = {}
) {
super(form.definition, form.groupDefinition, undefined, addMode);
makeObservable(this);
this.noRawUpdate = false;
this._onPatchDisposer = onPatch(node, (patch) => {
if (patch.op === "remove") {
this.removePath(patch.path);
} else if (patch.op === "add") {
this.addPath(patch.path);
} else if (patch.op === "replace") {
this.replacePath(patch.path);
}
});
this.isDisabledFunc = isDisabled;
this.isHiddenFunc = isHidden;
this.isReadOnlyFunc = isReadOnly;
this.isRequiredFunc = isRequired;
this.isEnabledFunc = isEnabled;
this.getErrorFunc = getError;
this.getWarningFunc = getWarning;
this.extraValidationFunc = extraValidation;
const validationOptions: ValidationOptions = {
beforeSave: "immediate",
afterSave: "immediate",
pauseDuration: 0,
...validation,
};
this.validationBeforeSave = validationOptions.beforeSave;
this.validationAfterSave = validationOptions.afterSave;
this.validationPauseDuration = validationOptions.pauseDuration;
this.focusFunc = focus;
this.blurFunc = blur;
this.updateFunc = update;
this._context = context;
this._converterOptions = converterOptions;
this._requiredError = requiredError;
checkConverterOptions(this._converterOptions);
if (backend != null) {
const processor = new Backend(
this,
node,
backend.save,
backend.process,
backend.processAll,
backend
);
this.processor = processor;
this.updateFunc = (accessor: FieldAccessor<any, any>) => {
if (update != null) {
update(accessor);
}
processor.run(accessor.path);
};
}
this.initialize();
// this has to happen after initialization
if (addMode) {
this.setAddModeDefaults(addModeDefaults);
}
}
// needed by FormAccessor base
get state() {
return this;
}
// normally context is determined from state, but state owns it
@override
get context(): any {
return this._context;
}
dispose(): void {
// clean up onPatch
this._onPatchDisposer();
// do dispose on all accessors, cleaning up
this.flatAccessors.forEach((accessor) => {
accessor.dispose();
});
}
// we delegate the creation to here to avoid circular dependencies
// between form accessor and its subclasses
createRepeatingFormAccessor(
repeatingForm: RepeatingForm<any, any>,
parent: IAnyFormAccessor,
name: string
): IRepeatingFormAccessor<any, any, any> {
return new RepeatingFormAccessor(this, repeatingForm, parent, name);
}
createSubFormAccessor(
definition: any,
groupDefinition: any,
parent: IAnyFormAccessor,
name: string
): ISubFormAccessor<any, any, any> {
return new SubFormAccessor(this, definition, groupDefinition, parent, name);
}
@computed
get path(): string {
return "";
}
@override
get value(): Instance<M> {
return this.node;
}
@computed
get processPromise(): Promise<void> {
if (this.processor == null) {
return Promise.resolve();
}
return this.processor.isFinished();
}
@computed
get liveOnly(): boolean {
return this.saveStatus === "before";
}
stateConverterOptionsWithContext(
accessor: any
): StateConverterOptionsWithContext {
return {
context: this.context,
accessor: accessor,
...this._converterOptions,
};
}
@action
setSaveStatus(status: SaveStatusOptions) {
this.saveStatus = status;
}
@action
setValueWithoutRawUpdate(path: string, value: any) {
this.noRawUpdate = true;
applyPatch(this.node, [{ op: "replace", path, value }]);
this.noRawUpdate = false;
}
@action
replacePath(path: string) {
if (this.noRawUpdate) {
return;
}
const fieldAccessor = this.accessByPath(path);
if (
fieldAccessor === undefined ||
!(fieldAccessor instanceof FieldAccessor)
) {
// if this is any other accessor or undefined, we cannot re-render
// as there is no raw
return;
}
// set raw from value directly without re-converting
fieldAccessor.setRawFromValue();
}
@action
removePath(path: string) {
let accessor;
try {
accessor = this.accessByPath(path);
} catch {
// If no accessor is found we try to see if we are dealing with an array.
const steps = pathToSteps(path);
const newPath = stepsToPath(steps.slice(0, steps.length - 1));
accessor = this.accessByPath(newPath);
if (accessor === undefined) {
return;
}
// When we are dealing with an array we should redirect this action into the replacePath one.
// This in turn makes sure that the raw value is updated with the new array value.
if (Array.isArray(accessor.value)) {
this.replacePath(newPath);
}
// it's possible for a path to remove removed but it not
// being part of a repeating form -- in case of arrays treated
// as a value
// XXX not ideal to catch errors here. instead perhaps accessByPath
// should return undefined if it cannot resolve the path
return;
}
if (
accessor === undefined ||
!(accessor instanceof RepeatingFormIndexedAccessor)
) {
// if this isn't a repeating indexed accessor we don't need to react
return;
}
accessor.clear();
}
@action
addPath(path: string) {
// we want to avoid accessing the newly added item directly, as
// that would add it to the accessor map
const steps = pathToSteps(path);
if (steps.length === 0) {
return;
}
const index = parseInt(steps[steps.length - 1], 10);
// we don't care about insertions of non-indexed things
if (isNaN(index)) {
return;
}
const newPath = stepsToPath(steps.slice(0, steps.length - 1));
const accessor = this.accessByPath(newPath);
if (accessor === undefined) {
return;
}
if (accessor instanceof RepeatingFormAccessor) {
accessor.addIndex(index);
return;
}
// When we are dealing with an array we should redirect this action into the replacePath one.
// This in turn makes sure that the raw value is updated with the new array value.
if (Array.isArray(accessor.value)) {
this.replacePath(newPath);
}
// we cannot set it into add mode here, as this can be triggered
// by code like applySnapshot. Instead use the RepeatingFormAccessor
// API to ensure add mode is set
}
@action
async save(options: ValidateOptions = {}): Promise<boolean> {
if (this.processor == null) {
throw new Error("Cannot save without backend configuration");
}
let extraOptions = {};
if (this.processor.process == null) {
extraOptions = { ignoreGetError: true };
}
const isValid = this.validate({ ...extraOptions, ...options });
if (!options.ignoreSaveStatus) {
this.setSaveStatus("rightAfter");
}
if (!isValid) {
return false;
}
return this.processor.realSave().then((result) => {
this.resetDirtyState();
return result;
});
}
resetDirtyState() {
this.flatAccessors.forEach((accessor) => {
accessor.resetDirtyState();
});
}
@action
async resetSaveStatus() {
this.setSaveStatus("before");
}
@action
async processAll(liveOnly?: boolean) {
if (this.processor == null) {
throw new Error("Cannot process all without backend configuration");
}
return this.processor.realProcessAll(liveOnly);
}
@action
setExternalValidations(
validations: Validation[],
messageType: "error" | "warning"
) {
// a map of path to a map of validation_id -> message.
const pathToValidations = new Map<string, Map<string, string>>();
// which validation ids are touched at all
const affectedValidationIds = new Set<string>();
validations.forEach((validation) => {
affectedValidationIds.add(validation.id);
validation.messages.forEach((message) => {
let validationIdToMessage = pathToValidations.get(message.path);
if (validationIdToMessage == null) {
validationIdToMessage = new Map<string, string>();
}
pathToValidations.set(message.path, validationIdToMessage);
validationIdToMessage.set(validation.id, message.message);
});
});
[this, ...this.flatAccessors].forEach((accessor) => {
const validationIdToMessage = pathToValidations.get(accessor.path);
const externalMessages =
messageType === "error"
? accessor.externalErrors
: accessor.externalWarnings;
externalMessages.update(validationIdToMessage, affectedValidationIds);
});
}
@action
clearExternalValidations(messageType: "error" | "warning") {
[this, ...this.flatAccessors].forEach((accessor) => {
const externalMessages =
messageType === "error"
? accessor.externalErrors
: accessor.externalWarnings;
externalMessages.clear();
});
}
@action
clearAllValidations() {
this.clearExternalValidations("error");
this.clearExternalValidations("warning");
this.flatAccessors.forEach((accessor) => {
accessor.clearError();
});
}
@action
setAccessUpdate(accessUpdate: AccessUpdate) {
const accessor = this.accessByPath(accessUpdate.path);
if (accessor === undefined) {
return;
}
accessor.setAccess(accessUpdate);
}
getValue(path: string): any {
return resolvePath(this.node, path);
}
accessByPath(path: string): IAccessor | undefined {
const steps = pathToSteps(path);
return this.accessBySteps(steps);
}
@computed
get canShowValidationMessages(): boolean {
// immediately after a save we always want messages
if (this.saveStatus === "rightAfter") {
return true;
}
const policy =
this.saveStatus === "before"
? this.validationBeforeSave
: this.validationAfterSave;
if (policy === "immediate") {
return true;
}
if (policy === "no") {
return false;
}
// not implemented yet
if (policy === "blur" || policy === "pause") {
return false;
}
return true;
}
}
export type AnyFormState = FormState<any, any, any>; | the_stack |
const Flac = require('libflacjs/dist/libflac.js');
// declare window.webkitAudioContext for the ts compiler
interface Window {
webkitAudioContext: typeof AudioContext
}
function setCookie(key: string, value: string, exdays: number = -1) {
let d = new Date();
if (exdays < 0)
exdays = 10 * 365;
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires=" + d.toUTCString();
document.cookie = key + "=" + value + ";" + expires + ";sameSite=Strict;path=/";
}
function getPersistentValue(key: string, defaultValue: string = ""): string {
if (!!window.localStorage) {
const value = window.localStorage.getItem(key);
if (value !== null) {
return value;
}
window.localStorage.setItem(key, defaultValue);
return defaultValue;
}
// Fallback to cookies if localStorage is not available.
let name = key + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for (let c of ca) {
c = c.trimLeft();
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
setCookie(key, defaultValue);
return defaultValue;
}
function getChromeVersion(): number | null {
const raw = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);
return raw ? parseInt(raw[2]) : null;
}
function uuidv4(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
class Tv {
constructor(sec: number, usec: number) {
this.sec = sec;
this.usec = usec;
}
setMilliseconds(ms: number) {
this.sec = Math.floor(ms / 1000);
this.usec = Math.floor(ms * 1000) % 1000000;
}
getMilliseconds(): number {
return this.sec * 1000 + this.usec / 1000;
}
sec: number = 0;
usec: number = 0;
}
class BaseMessage {
constructor(_buffer?: ArrayBuffer) {
}
deserialize(buffer: ArrayBuffer) {
let view = new DataView(buffer);
this.type = view.getUint16(0, true);
this.id = view.getUint16(2, true);
this.refersTo = view.getUint16(4, true);
this.received = new Tv(view.getInt32(6, true), view.getInt32(10, true));
this.sent = new Tv(view.getInt32(14, true), view.getInt32(18, true));
this.size = view.getUint32(22, true);
}
serialize(): ArrayBuffer {
this.size = 26 + this.getSize();
let buffer = new ArrayBuffer(this.size);
let view = new DataView(buffer);
view.setUint16(0, this.type, true);
view.setUint16(2, this.id, true);
view.setUint16(4, this.refersTo, true);
view.setInt32(6, this.sent.sec, true);
view.setInt32(10, this.sent.usec, true);
view.setInt32(14, this.received.sec, true);
view.setInt32(18, this.received.usec, true);
view.setUint32(22, this.size, true);
return buffer;
}
getSize() {
return 0;
}
type: number = 0;
id: number = 0;
refersTo: number = 0;
received: Tv = new Tv(0, 0);
sent: Tv = new Tv(0, 0);
size: number = 0;
}
class CodecMessage extends BaseMessage {
constructor(buffer?: ArrayBuffer) {
super(buffer);
this.payload = new ArrayBuffer(0);
if (buffer) {
this.deserialize(buffer);
}
this.type = 1;
}
deserialize(buffer: ArrayBuffer) {
super.deserialize(buffer);
let view = new DataView(buffer);
let codecSize = view.getInt32(26, true);
let decoder = new TextDecoder("utf-8");
this.codec = decoder.decode(buffer.slice(30, 30 + codecSize));
let payloadSize = view.getInt32(30 + codecSize, true);
// console.log("payload size: " + payloadSize);
this.payload = buffer.slice(34 + codecSize, 34 + codecSize + payloadSize);
// console.log("payload: " + this.payload);
}
codec: string = "";
payload: ArrayBuffer;
}
class TimeMessage extends BaseMessage {
constructor(buffer?: ArrayBuffer) {
super(buffer);
if (buffer) {
this.deserialize(buffer);
}
this.type = 4;
}
deserialize(buffer: ArrayBuffer) {
super.deserialize(buffer);
let view = new DataView(buffer);
this.latency = new Tv(view.getInt32(26, true), view.getInt32(30, true));
}
serialize(): ArrayBuffer {
let buffer = super.serialize();
let view = new DataView(buffer);
view.setInt32(26, this.latency.sec, true);
view.setInt32(30, this.latency.usec, true);
return buffer;
}
getSize() {
return 8;
}
latency: Tv = new Tv(0, 0);
}
class JsonMessage extends BaseMessage {
constructor(buffer?: ArrayBuffer) {
super(buffer);
if (buffer) {
this.deserialize(buffer);
}
}
deserialize(buffer: ArrayBuffer) {
super.deserialize(buffer);
let view = new DataView(buffer);
let size = view.getUint32(26, true);
let decoder = new TextDecoder();
this.json = JSON.parse(decoder.decode(buffer.slice(30, 30 + size)));
}
serialize(): ArrayBuffer {
let buffer = super.serialize();
let view = new DataView(buffer);
let jsonStr = JSON.stringify(this.json);
view.setUint32(26, jsonStr.length, true);
let encoder = new TextEncoder();
let encoded = encoder.encode(jsonStr);
for (let i = 0; i < encoded.length; ++i)
view.setUint8(30 + i, encoded[i]);
return buffer;
}
getSize() {
let encoder = new TextEncoder();
let encoded = encoder.encode(JSON.stringify(this.json));
return encoded.length + 4;
// return JSON.stringify(this.json).length;
}
json: any;
}
class HelloMessage extends JsonMessage {
constructor(buffer?: ArrayBuffer) {
super(buffer);
if (buffer) {
this.deserialize(buffer);
}
this.type = 5;
}
deserialize(buffer: ArrayBuffer) {
super.deserialize(buffer);
this.mac = this.json["MAC"];
this.hostname = this.json["HostName"];
this.version = this.json["Version"];
this.clientName = this.json["ClientName"];
this.os = this.json["OS"];
this.arch = this.json["Arch"];
this.instance = this.json["Instance"];
this.uniqueId = this.json["ID"];
this.snapStreamProtocolVersion = this.json["SnapStreamProtocolVersion"];
}
serialize(): ArrayBuffer {
this.json = { "MAC": this.mac, "HostName": this.hostname, "Version": this.version, "ClientName": this.clientName, "OS": this.os, "Arch": this.arch, "Instance": this.instance, "ID": this.uniqueId, "SnapStreamProtocolVersion": this.snapStreamProtocolVersion };
return super.serialize();
}
mac: string = "";
hostname: string = "";
version: string = "0.1.0";
clientName = "Snapweb";
os: string = "";
arch: string = "web";
instance: number = 1;
uniqueId: string = "";
snapStreamProtocolVersion: number = 2;
}
class ServerSettingsMessage extends JsonMessage {
constructor(buffer?: ArrayBuffer) {
super(buffer);
if (buffer) {
this.deserialize(buffer);
}
this.type = 3;
}
deserialize(buffer: ArrayBuffer) {
super.deserialize(buffer);
this.bufferMs = this.json["bufferMs"];
this.latency = this.json["latency"];
this.volumePercent = this.json["volume"];
this.muted = this.json["muted"];
}
serialize(): ArrayBuffer {
this.json = { "bufferMs": this.bufferMs, "latency": this.latency, "volume": this.volumePercent, "muted": this.muted };
return super.serialize();
}
bufferMs: number = 0;
latency: number = 0;
volumePercent: number = 0;
muted: boolean = false;
}
class PcmChunkMessage extends BaseMessage {
constructor(buffer: ArrayBuffer, sampleFormat: SampleFormat) {
super(buffer);
this.deserialize(buffer);
this.sampleFormat = sampleFormat;
this.type = 2;
}
deserialize(buffer: ArrayBuffer) {
super.deserialize(buffer);
let view = new DataView(buffer);
this.timestamp = new Tv(view.getInt32(26, true), view.getInt32(30, true));
// this.payloadSize = view.getUint32(34, true);
this.payload = buffer.slice(38);//, this.payloadSize + 38));// , this.payloadSize);
// // console.log("ts: " + this.timestamp.sec + " " + this.timestamp.usec + ", payload: " + this.payloadSize + ", len: " + this.payload.byteLength);
}
readFrames(frames: number): ArrayBuffer {
let frameCnt = frames;
let frameSize = this.sampleFormat.frameSize();
if (this.idx + frames > this.payloadSize() / frameSize)
frameCnt = (this.payloadSize() / frameSize) - this.idx;
let begin = this.idx * frameSize;
this.idx += frameCnt;
let end = begin + frameCnt * frameSize;
// // console.log("readFrames: " + frames + ", result: " + frameCnt + ", begin: " + begin + ", end: " + end + ", payload: " + this.payload.byteLength);
return this.payload.slice(begin, end);
}
getFrameCount(): number {
return (this.payloadSize() / this.sampleFormat.frameSize());
}
isEndOfChunk(): boolean {
return this.idx >= this.getFrameCount();
}
startMs(): number {
return this.timestamp.getMilliseconds() + 1000 * (this.idx / this.sampleFormat.rate);
}
duration(): number {
return 1000 * ((this.getFrameCount() - this.idx) / this.sampleFormat.rate);
}
payloadSize(): number {
return this.payload.byteLength;
}
clearPayload(): void {
this.payload = new ArrayBuffer(0);
}
addPayload(buffer: ArrayBuffer) {
let payload = new ArrayBuffer(this.payload.byteLength + buffer.byteLength);
let view = new DataView(payload);
let viewOld = new DataView(this.payload);
let viewNew = new DataView(buffer);
for (let i = 0; i < viewOld.byteLength; ++i) {
view.setInt8(i, viewOld.getInt8(i));
}
for (let i = 0; i < viewNew.byteLength; ++i) {
view.setInt8(i + viewOld.byteLength, viewNew.getInt8(i));
}
this.payload = payload;
}
timestamp: Tv = new Tv(0, 0);
// payloadSize: number = 0;
payload: ArrayBuffer = new ArrayBuffer(0);
idx: number = 0;
sampleFormat: SampleFormat;
}
class AudioStream {
constructor(public timeProvider: TimeProvider, public sampleFormat: SampleFormat, public bufferMs: number) {
}
chunks: Array<PcmChunkMessage> = new Array<PcmChunkMessage>();
setVolume(percent: number, muted: boolean) {
// let base = 10;
this.volume = percent / 100; // (Math.pow(base, percent / 100) - 1) / (base - 1);
// console.log("setVolume: " + percent + " => " + this.volume + ", muted: " + this.muted);
this.muted = muted;
}
addChunk(chunk: PcmChunkMessage) {
this.chunks.push(chunk);
// let oldest = this.timeProvider.serverNow() - this.chunks[0].timestamp.getMilliseconds();
// let newest = this.timeProvider.serverNow() - this.chunks[this.chunks.length - 1].timestamp.getMilliseconds();
// // console.debug("chunks: " + this.chunks.length + ", oldest: " + oldest.toFixed(2) + ", newest: " + newest.toFixed(2));
while (this.chunks.length > 0) {
let age = this.timeProvider.serverNow() - this.chunks[0].timestamp.getMilliseconds();
// todo: consider buffer ms
if (age > 5000 + this.bufferMs) {
this.chunks.shift();
// console.log("Dropping old chunk: " + age.toFixed(2) + ", left: " + this.chunks.length);
}
else
break;
}
}
getNextBuffer(buffer: AudioBuffer, playTimeMs: number) {
if (!this.chunk) {
this.chunk = this.chunks.shift()
}
// let age = this.timeProvider.serverTime(this.playTime * 1000) - startMs;
let frames = buffer.length;
// // console.debug("getNextBuffer: " + frames + ", play time: " + playTimeMs.toFixed(2));
let left = new Float32Array(frames);
let right = new Float32Array(frames);
let read = 0;
let pos = 0;
// let volume = this.muted ? 0 : this.volume;
let serverPlayTimeMs = this.timeProvider.serverTime(playTimeMs);
if (this.chunk) {
let age = serverPlayTimeMs - this.chunk.startMs();// - 500;
let reqChunkDuration = frames / this.sampleFormat.msRate();
let secs = Math.floor(Date.now() / 1000);
if (this.lastLog != secs) {
this.lastLog = secs;
// console.log("age: " + age.toFixed(2) + ", req: " + reqChunkDuration);
}
if (age < -reqChunkDuration) {
// console.log("age: " + age.toFixed(2) + " < req: " + reqChunkDuration * -1 + ", chunk.startMs: " + this.chunk.startMs().toFixed(2) + ", timestamp: " + this.chunk.timestamp.getMilliseconds().toFixed(2));
// console.log("Chunk too young, returning silence");
} else {
if (Math.abs(age) > 5) {
// We are 5ms apart, do a hard sync, i.e. don't play faster/slower,
// but seek to the desired position instead
while (this.chunk && age > this.chunk.duration()) {
// console.log("Chunk too old, dropping (age: " + age.toFixed(2) + " > " + this.chunk.duration().toFixed(2) + ")");
this.chunk = this.chunks.shift();
if (!this.chunk)
break;
age = serverPlayTimeMs - (this.chunk as PcmChunkMessage).startMs();
}
if (this.chunk) {
if (age > 0) {
// console.log("Fast forwarding " + age.toFixed(2) + "ms");
this.chunk.readFrames(Math.floor(age * this.chunk.sampleFormat.msRate()));
}
else if (age < 0) {
// console.log("Playing silence " + -age.toFixed(2) + "ms");
let silentFrames = Math.floor(-age * this.chunk.sampleFormat.msRate());
left.fill(0, 0, silentFrames);
right.fill(0, 0, silentFrames);
read = silentFrames;
pos = silentFrames;
}
age = 0;
}
}
// else if (age > 0.1) {
// let rate = age * 0.0005;
// rate = 1.0 - Math.min(rate, 0.0005);
// // console.debug("Age > 0, rate: " + rate);
// // we are late (age > 0), this means we are not playing fast enough
// // => the real sample rate seems to be lower, we have to drop some frames
// this.setRealSampleRate(this.sampleFormat.rate * rate); // 0.9999);
// }
// else if (age < -0.1) {
// let rate = -age * 0.0005;
// rate = 1.0 + Math.min(rate, 0.0005);
// // console.debug("Age < 0, rate: " + rate);
// // we are early (age > 0), this means we are playing too fast
// // => the real sample rate seems to be higher, we have to insert some frames
// this.setRealSampleRate(this.sampleFormat.rate * rate); // 0.9999);
// }
// else {
// this.setRealSampleRate(this.sampleFormat.rate);
// }
let addFrames = 0;
let everyN = 0;
if (age > 0.1) {
addFrames = Math.ceil(age); // / 5);
} else if (age < -0.1) {
addFrames = Math.floor(age); // / 5);
}
// addFrames = -2;
let readFrames = frames + addFrames - read;
if (addFrames != 0)
everyN = Math.ceil((frames + addFrames - read) / (Math.abs(addFrames) + 1));
// addFrames = 0;
// // console.debug("frames: " + frames + ", readFrames: " + readFrames + ", addFrames: " + addFrames + ", everyN: " + everyN);
while ((read < readFrames) && this.chunk) {
let pcmChunk = this.chunk as PcmChunkMessage;
let pcmBuffer = pcmChunk.readFrames(readFrames - read);
let payload = new Int16Array(pcmBuffer);
// // console.debug("readFrames: " + (frames - read) + ", read: " + pcmBuffer.byteLength + ", payload: " + payload.length);
// read += (pcmBuffer.byteLength / this.sampleFormat.frameSize());
for (let i = 0; i < payload.length; i += 2) {
read++;
left[pos] = (payload[i] / 32768); // * volume;
right[pos] = (payload[i + 1] / 32768); // * volume;
if ((everyN != 0) && (read % everyN == 0)) {
if (addFrames > 0) {
pos--;
} else {
left[pos + 1] = left[pos];
right[pos + 1] = right[pos];
pos++;
// // console.log("Add: " + pos);
}
}
pos++;
}
if (pcmChunk.isEndOfChunk()) {
this.chunk = this.chunks.shift();
}
}
if (addFrames != 0)
// console.debug("Pos: " + pos + ", frames: " + frames + ", add: " + addFrames + ", everyN: " + everyN);
if (read == readFrames)
read = frames;
}
}
if (read < frames) {
// console.log("Failed to get chunk, read: " + read + "/" + frames + ", chunks left: " + this.chunks.length);
left.fill(0, pos);
right.fill(0, pos);
}
// copyToChannel is not supported by Safari
buffer.getChannelData(0).set(left);
buffer.getChannelData(1).set(right);
}
// setRealSampleRate(sampleRate: number) {
// if (sampleRate == this.sampleFormat.rate) {
// this.correctAfterXFrames = 0;
// }
// else {
// this.correctAfterXFrames = Math.ceil((this.sampleFormat.rate / sampleRate) / (this.sampleFormat.rate / sampleRate - 1.));
// // console.debug("setRealSampleRate: " + sampleRate + ", correct after X: " + this.correctAfterXFrames);
// }
// }
chunk?: PcmChunkMessage = undefined;
volume: number = 1;
muted: boolean = false;
lastLog: number = 0;
// correctAfterXFrames: number = 0;
}
class TimeProvider {
constructor(ctx: AudioContext | undefined = undefined) {
if (ctx) {
this.setAudioContext(ctx);
}
}
setAudioContext(ctx: AudioContext) {
this.ctx = ctx;
this.reset();
}
reset() {
this.diffBuffer.length = 0;
this.diff = 0;
}
setDiff(c2s: number, s2c: number) {
if (this.now() == 0) {
this.reset()
} else {
if (this.diffBuffer.push((c2s - s2c) / 2) > 100)
this.diffBuffer.shift();
let sorted = [...this.diffBuffer];
sorted.sort()
this.diff = sorted[Math.floor(sorted.length / 2)];
}
// // console.debug("c2s: " + c2s.toFixed(2) + ", s2c: " + s2c.toFixed(2) + ", diff: " + this.diff.toFixed(2) + ", now: " + this.now().toFixed(2) + ", server.now: " + this.serverNow().toFixed(2) + ", win.now: " + window.performance.now().toFixed(2));
// // console.log("now: " + this.now() + "\t" + this.now() + "\t" + this.now());
}
now() {
if (!this.ctx) {
return window.performance.now();
} else {
// Use the more accurate getOutputTimestamp if available, fallback to ctx.currentTime otherwise.
const contextTime = !!this.ctx.getOutputTimestamp ? this.ctx.getOutputTimestamp().contextTime : undefined;
return (contextTime !== undefined ? contextTime : this.ctx.currentTime) * 1000;
}
}
nowSec() {
return this.now() / 1000;
}
serverNow() {
return this.serverTime(this.now());
}
serverTime(localTimeMs: number) {
return localTimeMs + this.diff;
}
diffBuffer: Array<number> = new Array<number>();
diff: number = 0;
ctx: AudioContext | undefined;
}
class SampleFormat {
rate: number = 48000;
channels: number = 2;
bits: number = 16;
public msRate(): number {
return this.rate / 1000;
}
public toString(): string {
return this.rate + ":" + this.bits + ":" + this.channels;
}
public sampleSize(): number {
if (this.bits == 24) {
return 4;
}
return this.bits / 8;
}
public frameSize(): number {
return this.channels * this.sampleSize();
}
public durationMs(bytes: number) {
return (bytes / this.frameSize()) * this.msRate();
}
}
class Decoder {
setHeader(_buffer: ArrayBuffer): SampleFormat | null {
return new SampleFormat();
}
decode(_chunk: PcmChunkMessage): PcmChunkMessage | null {
return null;
}
}
class OpusDecoder extends Decoder {
setHeader(buffer: ArrayBuffer): SampleFormat | null {
let view = new DataView(buffer);
let ID_OPUS = 0x4F505553;
if (buffer.byteLength < 12) {
// console.error("Opus header too small: " + buffer.byteLength);
return null;
} else if (view.getUint32(0, true) != ID_OPUS) {
// console.error("Opus header too small: " + buffer.byteLength);
return null;
}
let format = new SampleFormat();
format.rate = view.getUint32(4, true);
format.bits = view.getUint16(8, true);
format.channels = view.getUint16(10, true);
// console.log("Opus samplerate: " + format.toString());
return format;
}
decode(_chunk: PcmChunkMessage): PcmChunkMessage | null {
return null;
}
}
class FlacDecoder extends Decoder {
constructor() {
super();
this.decoder = Flac.create_libflac_decoder(true);
if (this.decoder) {
let init_status = Flac.init_decoder_stream(this.decoder, this.read_callback_fn.bind(this), this.write_callback_fn.bind(this), this.error_callback_fn.bind(this), this.metadata_callback_fn.bind(this), false);
// console.log("Flac init: " + init_status);
Flac.setOptions(this.decoder, { analyseSubframes: true, analyseResiduals: true });
}
this.sampleFormat = new SampleFormat();
this.flacChunk = new ArrayBuffer(0);
// this.pcmChunk = new PcmChunkMessage();
// Flac.setOptions(this.decoder, {analyseSubframes: analyse_frames, analyseResiduals: analyse_residuals});
// flac_ok &= init_status == 0;
// // console.log("flac init : " + flac_ok);//DEBUG
}
decode(chunk: PcmChunkMessage): PcmChunkMessage | null {
// // console.log("Flac decode: " + chunk.payload.byteLength);
this.flacChunk = chunk.payload.slice(0);
this.pcmChunk = chunk;
this.pcmChunk!.clearPayload();
this.cacheInfo = { cachedBlocks: 0, isCachedChunk: true };
// // console.log("Flac len: " + this.flacChunk.byteLength);
while (this.flacChunk.byteLength && Flac.FLAC__stream_decoder_process_single(this.decoder)) {
Flac.FLAC__stream_decoder_get_state(this.decoder);
// let state = Flac.FLAC__stream_decoder_get_state(this.decoder);
// // console.log("State: " + state);
}
// // console.log("Pcm payload: " + this.pcmChunk!.payloadSize());
if (this.cacheInfo.cachedBlocks > 0) {
let diffMs = this.cacheInfo.cachedBlocks / this.sampleFormat.msRate();
// // console.log("Cached: " + this.cacheInfo.cachedBlocks + ", " + diffMs + "ms");
this.pcmChunk!.timestamp.setMilliseconds(this.pcmChunk!.timestamp.getMilliseconds() - diffMs);
}
return this.pcmChunk!;
}
read_callback_fn(bufferSize: number): Flac.ReadResult | Flac.CompletedReadResult {
// // console.log(' decode read callback, buffer bytes max=', bufferSize);
if (this.header) {
// console.log(" header: " + this.header.byteLength);
let data = new Uint8Array(this.header);
this.header = null;
return { buffer: data, readDataLength: data.byteLength, error: false };
} else if (this.flacChunk) {
// // console.log(" flacChunk: " + this.flacChunk.byteLength);
// a fresh read => next call to write will not be from cached data
this.cacheInfo.isCachedChunk = false;
let data = new Uint8Array(this.flacChunk.slice(0, Math.min(bufferSize, this.flacChunk.byteLength)));
this.flacChunk = this.flacChunk.slice(data.byteLength);
return { buffer: data, readDataLength: data.byteLength, error: false };
}
return { buffer: new Uint8Array(0), readDataLength: 0, error: false };
}
write_callback_fn(data: Array<Uint8Array>, frameInfo: Flac.BlockMetadata) {
// // console.log(" write frame metadata: " + frameInfo + ", len: " + data.length);
if (this.cacheInfo.isCachedChunk) {
// there was no call to read, so it's some cached data
this.cacheInfo.cachedBlocks += frameInfo.blocksize;
}
let payload = new ArrayBuffer((frameInfo.bitsPerSample / 8) * frameInfo.channels * frameInfo.blocksize);
let view = new DataView(payload);
for (let channel: number = 0; channel < frameInfo.channels; ++channel) {
let channelData = new DataView(data[channel].buffer, 0, data[channel].buffer.byteLength);
// // console.log("channelData: " + channelData.byteLength + ", blocksize: " + frameInfo.blocksize);
for (let i: number = 0; i < frameInfo.blocksize; ++i) {
view.setInt16(2 * (frameInfo.channels * i + channel), channelData.getInt16(2 * i, true), true);
}
}
this.pcmChunk!.addPayload(payload);
// // console.log("write: " + payload.byteLength + ", len: " + this.pcmChunk!.payloadSize());
}
/** @memberOf decode */
metadata_callback_fn(data: any) {
// console.info('meta data: ', data);
// let view = new DataView(data);
this.sampleFormat.rate = data.sampleRate;
this.sampleFormat.channels = data.channels;
this.sampleFormat.bits = data.bitsPerSample;
// console.log("metadata_callback_fn, sampleformat: " + this.sampleFormat.toString());
}
/** @memberOf decode */
error_callback_fn(err: any, errMsg: any) {
// console.error('decode error callback', err, errMsg);
}
setHeader(buffer: ArrayBuffer): SampleFormat | null {
this.header = buffer.slice(0);
Flac.FLAC__stream_decoder_process_until_end_of_metadata(this.decoder);
return this.sampleFormat;
}
sampleFormat: SampleFormat;
decoder: number;
header: ArrayBuffer | null = null;
flacChunk: ArrayBuffer;
pcmChunk?: PcmChunkMessage;
cacheInfo: { isCachedChunk: boolean, cachedBlocks: number } = { isCachedChunk: false, cachedBlocks: 0 };
}
class PlayBuffer {
constructor(buffer: AudioBuffer, playTime: number, source: AudioBufferSourceNode, destination: AudioNode) {
this.buffer = buffer;
this.playTime = playTime;
this.source = source;
this.source.buffer = this.buffer;
this.source.connect(destination);
this.onended = (_playBuffer: PlayBuffer) => { };
}
public onended: (playBuffer: PlayBuffer) => void
start() {
this.source.onended = () => {
this.onended(this);
}
this.source.start(this.playTime);
}
buffer: AudioBuffer;
playTime: number;
source: AudioBufferSourceNode;
num: number = 0;
}
class PcmDecoder extends Decoder {
setHeader(buffer: ArrayBuffer): SampleFormat | null {
let sampleFormat = new SampleFormat();
let view = new DataView(buffer);
sampleFormat.channels = view.getUint16(22, true);
sampleFormat.rate = view.getUint32(24, true);
sampleFormat.bits = view.getUint16(34, true);
return sampleFormat;
}
decode(chunk: PcmChunkMessage): PcmChunkMessage | null {
return chunk;
}
}
class SnapStream {
constructor(baseUrl: string) {
this.baseUrl = baseUrl;
this.timeProvider = new TimeProvider();
if (this.setupAudioContext()) {
this.connect();
} else {
alert("Sorry, but the Web Audio API is not supported by your browser");
}
}
private setupAudioContext(): boolean {
let AudioContext = window.AudioContext // Default
|| window.webkitAudioContext // Safari and old versions of Chrome
|| false;
if (AudioContext) {
let options: AudioContextOptions | undefined;
options = { latencyHint: "playback", sampleRate: this.sampleFormat ? this.sampleFormat.rate : undefined };
const chromeVersion = getChromeVersion();
if ((chromeVersion !== null && chromeVersion < 55) || !window.AudioContext) {
// Some older browsers won't decode the stream if options are provided.
options = undefined;
}
this.ctx = new AudioContext(options);
this.gainNode = this.ctx.createGain();
this.gainNode.connect(this.ctx.destination);
} else {
// Web Audio API is not supported
return false;
}
return true;
}
private connect() {
this.streamsocket = new WebSocket(this.baseUrl + '/stream');
this.streamsocket.binaryType = "arraybuffer";
this.streamsocket.onmessage = (ev) => this.onMessage(ev);
this.streamsocket.onopen = () => {
// console.log("on open");
let hello = new HelloMessage();
hello.mac = "00:00:00:00:00:00";
hello.arch = "web";
hello.os = navigator.platform;
hello.hostname = "Snapweb client";
hello.uniqueId = getPersistentValue("uniqueId", uuidv4());
this.sendMessage(hello);
this.syncTime();
this.syncHandle = window.setInterval(() => this.syncTime(), 1000);
}
this.streamsocket.onerror = (ev) => { console.error('error:', ev); };
this.streamsocket.onclose = () => {
window.clearInterval(this.syncHandle);
// console.info('connection lost, reconnecting in 1s');
setTimeout(() => this.connect(), 1000);
}
}
private onMessage(msg: MessageEvent) {
let view = new DataView(msg.data);
let type = view.getUint16(0, true);
if (type == 1) {
let codec = new CodecMessage(msg.data);
// console.log("Codec: " + codec.codec);
if (codec.codec == "flac") {
this.decoder = new FlacDecoder();
} else if (codec.codec == "pcm") {
this.decoder = new PcmDecoder();
} else if (codec.codec == "opus") {
this.decoder = new OpusDecoder();
alert("Codec not supported: " + codec.codec);
} else {
alert("Codec not supported: " + codec.codec);
}
if (this.decoder) {
this.sampleFormat = this.decoder.setHeader(codec.payload)!;
// console.log("Sampleformat: " + this.sampleFormat.toString());
if ((this.sampleFormat.channels != 2) || (this.sampleFormat.bits != 16)) {
alert("Stream must be stereo with 16 bit depth, actual format: " + this.sampleFormat.toString());
} else {
if (this.bufferDurationMs != 0) {
this.bufferFrameCount = Math.floor(this.bufferDurationMs * this.sampleFormat.msRate());
}
if (window.AudioContext) {
// we are not using webkitAudioContext, so it's safe to setup a new AudioContext with the new samplerate
// since this code is not triggered by direct user input, we cannt create a webkitAudioContext here
this.stopAudio();
this.setupAudioContext();
}
this.ctx.resume();
this.timeProvider.setAudioContext(this.ctx);
this.gainNode.gain.value = this.serverSettings!.muted ? 0 : this.serverSettings!.volumePercent / 100;
// this.timeProvider = new TimeProvider(this.ctx);
this.stream = new AudioStream(this.timeProvider, this.sampleFormat, this.bufferMs);
this.latency = (this.ctx.baseLatency !== undefined ? this.ctx.baseLatency : 0) + (this.ctx.outputLatency !== undefined ? this.ctx.outputLatency : 0)
// console.log("Base latency: " + this.ctx.baseLatency + ", output latency: " + this.ctx.outputLatency + ", latency: " + this.latency);
this.play();
}
}
} else if (type == 2) {
let pcmChunk = new PcmChunkMessage(msg.data, this.sampleFormat as SampleFormat);
if (this.decoder) {
let decoded = this.decoder.decode(pcmChunk);
if (decoded) {
this.stream!.addChunk(decoded);
}
}
} else if (type == 3) {
this.serverSettings = new ServerSettingsMessage(msg.data);
this.gainNode.gain.value = this.serverSettings.muted ? 0 : this.serverSettings.volumePercent / 100;
this.bufferMs = this.serverSettings.bufferMs - this.serverSettings.latency;
// console.log("ServerSettings bufferMs: " + this.serverSettings.bufferMs + ", latency: " + this.serverSettings.latency + ", volume: " + this.serverSettings.volumePercent + ", muted: " + this.serverSettings.muted);
} else if (type == 4) {
if (this.timeProvider) {
let time = new TimeMessage(msg.data);
this.timeProvider.setDiff(time.latency.getMilliseconds(), this.timeProvider.now() - time.sent.getMilliseconds());
}
// // console.log("Time sec: " + time.latency.sec + ", usec: " + time.latency.usec + ", diff: " + this.timeProvider.diff);
} else {
// console.info("Message not handled, type: " + type);
}
}
private sendMessage(msg: BaseMessage) {
msg.sent = new Tv(0, 0);
msg.sent.setMilliseconds(this.timeProvider.now());
msg.id = ++this.msgId;
if (this.streamsocket.readyState == this.streamsocket.OPEN) {
this.streamsocket.send(msg.serialize());
}
}
private syncTime() {
let t = new TimeMessage();
t.latency.setMilliseconds(this.timeProvider.now());
this.sendMessage(t);
// // console.log("prepareSource median: " + Math.round(this.median * 10) / 10);
}
private stopAudio() {
// if (this.ctx) {
// this.ctx.close();
// }
this.ctx.suspend();
while (this.audioBuffers.length > 0) {
let buffer = this.audioBuffers.pop();
buffer!.onended = () => { };
buffer!.source.stop();
}
while (this.freeBuffers.length > 0) {
this.freeBuffers.pop();
}
}
public stop() {
window.clearInterval(this.syncHandle);
this.stopAudio();
if ([WebSocket.OPEN, WebSocket.CONNECTING].includes(this.streamsocket.readyState)) {
this.streamsocket.onclose = () => { };
this.streamsocket.close();
}
}
public play() {
this.playTime = this.timeProvider.nowSec() + 0.1;
for (let i = 1; i <= this.audioBufferCount; ++i) {
this.playNext();
}
}
public playNext() {
let buffer = this.freeBuffers.pop() || this.ctx!.createBuffer(this.sampleFormat!.channels, this.bufferFrameCount, this.sampleFormat!.rate);
let playTimeMs = (this.playTime + this.latency) * 1000 - this.bufferMs;
this.stream!.getNextBuffer(buffer, playTimeMs);
let source = this.ctx!.createBufferSource();
let playBuffer = new PlayBuffer(buffer, this.playTime, source, this.gainNode!);
this.audioBuffers.push(playBuffer);
playBuffer.num = ++this.bufferNum;
playBuffer.onended = (buffer: PlayBuffer) => {
// let diff = this.timeProvider.nowSec() - buffer.playTime;
this.freeBuffers.push(this.audioBuffers.splice(this.audioBuffers.indexOf(buffer), 1)[0].buffer);
// // console.debug("PlayBuffer " + playBuffer.num + " ended after: " + (diff * 1000) + ", in flight: " + this.audioBuffers.length);
this.playNext();
}
playBuffer.start();
this.playTime += this.bufferFrameCount / (this.sampleFormat as SampleFormat).rate;
}
baseUrl: string;
streamsocket!: WebSocket;
playTime: number = 0;
msgId: number = 0;
bufferDurationMs: number = 80; // 0;
bufferFrameCount: number = 3844; // 9600; // 2400;//8192;
syncHandle: number = -1;
// ageBuffer: Array<number>;
audioBuffers: Array<PlayBuffer> = new Array<PlayBuffer>();
freeBuffers: Array<AudioBuffer> = new Array<AudioBuffer>();
timeProvider: TimeProvider;
stream: AudioStream | undefined;
ctx!: AudioContext; // | undefined;
gainNode!: GainNode;
serverSettings: ServerSettingsMessage | undefined;
decoder: Decoder | undefined;
sampleFormat: SampleFormat | undefined;
// median: number = 0;
audioBufferCount: number = 3;
bufferMs: number = 1000;
bufferNum: number = 0;
latency: number = 0;
}
export {
SnapStream,
}
export default {
SnapStream,
}; | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.