text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
/// <reference types="jquery" />
type FancyBoxInteractionTypes = "close" | "next" | "nextOrClose" | "toggleControls" | "zoom" | false;
type FancyBoxInteractionMethod = (slide?: FancyBoxSlide, event?: JQuery.Event) => FancyBoxInteractionTypes;
type FancyBoxInteractions = FancyBoxInteractionTypes | FancyBoxInteractionMethod;
interface FancyBoxPlainObject {
[key: string]: string | number | boolean | (() => void);
}
interface FancyBoxGroupItemWithFilledProps extends FancyBoxGroupItem {
$thumb?: JQuery;
thumb?: any;
contentType?: string;
index?: number;
}
interface FancyBoxGroupItem {
src: string;
type?: "image" | "inline" | "ajax" | "iframe" | "html";
opts?: FancyBoxOptions;
}
interface FancyBoxSlide extends FancyBoxGroupItemWithFilledProps {
$content?: JQuery;
$image?: JQuery;
$slide?: JQuery;
$spinner?: JQuery;
$iframe?: JQuery<HTMLIFrameElement>;
forcedDuration?: number;
height: number;
isComplete: boolean;
isLoaded: boolean;
isLoading: boolean;
isRevealed: boolean;
contentSource?: string;
pos: number;
width: number;
}
interface FancyBoxImageOption {
/**
* Wait for images to load before displaying
* true - wait for image to load and then display;
* false - display thumbnail and load the full-sized image over top,
* requires predefined image dimensions (`data-width` and `data-height` attributes)
*/
preload: boolean;
}
interface FancyBoxAjaxOption {
/**
* Object containing settings for ajax request
*/
settings: JQueryAjaxSettings;
}
interface FancyBoxIframeSettings {
/**
* Iframe template
*/
tpl?: string;
/**
* Preload iframe before displaying it
* This allows to calculate iframe content width and height
* (note: Due to "Same Origin Policy", you can't get cross domain data).
*/
preload?: boolean;
/**
* Custom CSS styling for iframe wrapping element
* You can use this to set custom iframe dimensions
*/
css?: FancyBoxPlainObject;
/**
* Iframe tag attributes
*/
attr?: FancyBoxPlainObject;
}
interface FancyBoxVideoOptions {
tpl?: string;
format?: string;
autoStart?: boolean;
}
interface FancyBoxButtonTemplateOptions {
download?: string;
zoom?: string;
close?: string;
arrowLeft?: string;
arrowRight?: string;
/**
* This small close button will be appended to your html/inline/ajax content by default,
* if "smallBtn" option is not set to false
*/
smallBtn?: string;
}
interface FancyBoxTouchOptions {
/**
* Allow to drag content vertically
*/
vertical?: boolean;
/**
* Continue movement after releasing mouse/touch when panning
*/
momentum?: boolean;
}
interface FancyThumbsOptions {
/**
* Display thumbnails on opening
*/
autoStart?: boolean;
/**
* Hide thumbnail grid when closing animation starts
*/
hideOnClose?: boolean;
/**
* Container is injected into this element
*/
parentEl?: string;
/**
* Vertical (y) or horizontal (x) scrolling
*/
axis?: "x" | "y";
}
interface FancyBoxInternationalizatioObject {
CLOSE?: string;
NEXT?: string;
PREV?: string;
ERROR?: string;
PLAY_START?: string;
PLAY_STOP?: string;
FULL_SCREEN?: string;
THUMBS?: string;
DOWNLOAD?: string;
SHARE?: string;
ZOOM?: string;
}
interface FancyBoxInternationalizationOptions {
[key: string]: FancyBoxInternationalizatioObject;
}
interface FancyBoxButtonTypes {
"zoom": string;
"share": string;
"slideShow": string;
"fullScreen": string;
"download": string;
"thumbs": string;
"close": string;
}
interface FancyBoxOptions {
/**
* Close existing modals
* Set this to false if you do not need to stack multiple instances
*/
closeExisting?: boolean;
/**
* Enable infinite gallery navigation
*/
loop?: boolean;
/**
* Horizontal space between slides
*/
gutter?: number;
/**
* Enable keyboard navigation
*/
keyboard?: boolean;
/**
* Should allow caption to overlap the content
*/
preventCaptionOverlap?: boolean;
/**
* Should display navigation arrows at the screen edges
*/
arrows?: boolean;
/**
* Should display counter at the top left corner
*/
infobar?: boolean;
/**
* Should display close button (using `btnTpl.smallBtn` template) over the content
* Can be true, false, "auto"
* If "auto" - will be automatically enabled for "html", "inline" or "ajax" items
*/
smallBtn?: boolean | "auto";
/**
* Should display toolbar (buttons at the top)
* Can be true, false, "auto"
* If "auto" - will be automatically hidden if "smallBtn" is enabled
*/
toolbar?: boolean | "auto";
/**
* What buttons should appear in the top right corner.
* Buttons will be created using templates from `btnTpl` option
* and they will be placed into toolbar (class="fancybox-toolbar"` element)
*/
buttons?: Array<keyof FancyBoxButtonTypes>;
/**
* Detect "idle" time in seconds
*/
idleTime?: number;
/**
* Disable right-click and use simple image protection for images
*/
protect?: boolean;
/**
* Shortcut to make content "modal" - disable keyboard navigtion, hide buttons, etc
*/
modal?: boolean;
image?: FancyBoxImageOption;
ajax?: FancyBoxAjaxOption;
iframe?: FancyBoxIframeSettings;
/**
* For HTML5 video only
*/
video?: FancyBoxVideoOptions;
/**
* Default content type if cannot be detected automatically
*/
defaultType?: "image" | "inline" | "ajax" | "iframe" | "html";
/**
* Open/close animation type
* Possible values:
* false - disable
* "zoom" - zoom images from/to thumbnail
* "fade"
* "zoom-in-out"
*/
animationEffect?: boolean | "zoom" | "fade" | "zoom-in-out";
/**
* Duration in ms for open/close animation
*/
animationDuration?: number;
/**
* Should image change opacity while zooming
* If opacity is "auto", then opacity will be changed if image and thumbnail have different aspect ratios
*/
zoomOpacity?: "auto" | boolean;
/**
* Transition effect between slides
* Possible values:
* false
* "fade"
* "slide"
* "circular"
* "tube"
* "zoom-in-out"
* "rotate"
*/
transitionEffect?: "fade" | "slide" | "circular" | "tube" | "zoom-in-out" | "rotate" | boolean;
/**
* Duration in ms for transition animation
*/
transitionDuration?: number;
/**
* Custom CSS class for slide element
*/
slideClass?: string;
/**
* Custom CSS class for layout
*/
baseClass?: string;
/**
* Base template for layout
*/
baseTpl?: string;
/**
* Loading indicator template
*/
spinnerTpl?: string;
/**
* Error message template
*/
errorTpl?: string;
/**
* Button templates
*/
btnTpl?: FancyBoxButtonTemplateOptions;
/**
* Container is injected into this element
*/
parentEl?: string;
/**
* Hide browser vertical scrollbars; use at your own risk
*/
hideScrollbar?: boolean;
/**
* Try to focus on the first focusable element after opening
*/
autoFocus?: boolean;
/**
* Put focus back to active element after closing
*/
backFocus?: boolean;
/**
* Do not let user to focus on element outside modal content
*/
trapFocus?: boolean;
fullScreen?: { autostart: boolean };
/**
* Set `touch: false` to disable panning/swiping
*/
touch?: FancyBoxTouchOptions | false;
/**
* Hash value when initializing manually,
* set `false` to disable hash change
*/
hash?: any;
/**
* Customize or add new media types
* Example:
* media : {
* youtube : {
* params : {
* autoplay : 0
* }
* }
* }
*/
media?: FancyBoxPlainObject;
slideShow?: { autoStart?: boolean; speed?: number; };
thumbs?: FancyThumbsOptions;
/**
* Use mousewheel to navigate gallery
* If 'auto' - enabled for images only
*/
wheel?: "auto" | false;
/**
* When instance has been initialized
*/
onInit?(instance: FancyBoxInstance): void;
/**
* Before the content of a slide is being loaded
*/
beforeLoad?(instance: FancyBoxInstance, current: FancyBoxSlide): void;
/**
* When the content of a slide is done loading
*/
afterLoad?(instance: FancyBoxInstance, current: FancyBoxSlide): void;
/**
* Before open animation starts
*/
beforeShow?(instance: FancyBoxInstance, current: FancyBoxSlide): void;
/**
* When content is done loading and animating
*/
afterShow?(instance: FancyBoxInstance, current: FancyBoxSlide): void;
/**
* Before the instance attempts to close. Return false to cancel the close.
*/
beforeClose?(instance: FancyBoxInstance, current: FancyBoxSlide): void;
/**
* After instance has been closed
*/
afterClose?(instance: FancyBoxInstance, current: FancyBoxSlide): void;
/**
* When instance is brought to front
*/
onActivate?(instance: FancyBoxInstance): void;
/**
* When other instance has been activated
*/
onDeactivate?(instance: FancyBoxInstance): void;
/**
* Clicked on the content
*/
clickContent?: FancyBoxInteractions;
/**
* Clicked on the slide
*/
clickSlide?: FancyBoxInteractions;
/**
* Clicked on the background (backdrop) element;
* if you have not changed the layout, then most likely you need to use `clickSlide` option
*/
clickOutside?: FancyBoxInteractions;
/**
* Same as previous two, but for double click
*/
dblclickContent?: FancyBoxInteractions;
/**
* Same as previous two, but for double click
*/
dblclickSlide?: FancyBoxInteractions;
/**
* Same as previous two, but for double click
*/
dblclickOutside?: FancyBoxInteractions;
lang?: string;
i18n?: FancyBoxInternationalizationOptions;
caption?: string | ((instance: FancyBoxInstance, current: FancyBoxSlide) => string);
}
interface FancyBoxRefs {
bg: JQuery;
caption: JQuery;
container: JQuery;
infobar: JQuery;
inner: JQuery;
navigation: JQuery;
stage: JQuery;
toolbar: JQuery;
}
interface FancyBoxFullScreen {
enabled(): boolean;
exit(): void;
isFullscreen(): boolean;
request(elem: HTMLElement): void;
toggle(elem: HTMLElement): void;
}
interface FancyBoxGestures {
$bg: JQuery;
$container: JQuery;
$stage: JQuery;
instance: FancyBoxInstance;
destroy(): void;
endPanning(): void;
endSwiping(swiping: "x" | "y", scrolling: boolean): void;
endZooming(): void;
limitMovement(): void;
limitPosition(newOffsetX: number, newOffsetY: number, newWidth: number, newHeight: number): void;
onPan(): void;
onSwipe(e: JQuery.Event): void;
onTap(e: JQuery.Event): void;
onZoom(): void;
onscroll(e: JQuery.ScrollEvent): void;
ontouchend(e: JQuery.TouchEndEvent): void;
ontouchmove(e: JQuery.TouchMoveEvent): void;
ontouchstart(e: JQuery.TouchStartEvent): void;
}
interface FancyBoxSlideShow {
$button?: JQuery;
$progress: JQuery;
instance: FancyBoxInstance;
clear(): void;
init(): void;
isActive: boolean;
set(force: boolean): void;
start(): void;
stop(): void;
timer?: number;
toggle(): void;
}
interface FancyThumbs {
$button?: JQuery;
$grid?: JQuery;
$list?: JQuery;
instance: FancyBoxInstance;
opts: FancyThumbsOptions;
create(): void;
focus(duration: number): void;
hide(): void;
init(instance: FancyBoxInstance): void;
isActive: boolean;
isVisible: boolean;
show(): void;
toggle(): void;
update(): void;
}
interface FancyBoxInstanceMethods {
/**
* Activates current instance - brings container to the front and enables keyboard,
* notifies other instances about deactivating
*/
activate(): void;
/**
* Populate current group with fresh content
* Check if each object has valid type and content
* @param content
*/
addContent(content: FancyBoxPlainObject | JQuery): void;
/**
* Attach an event handler functions for:
* - navigation buttons
* - browser scrolling, resizing;
* - focusing
* - keyboard
* - detecting inactivity
*/
addEvents(): void;
/**
* Prevent caption overlap,
* fix css inconsistency across browsers
* @param slide
*/
adjustCaption(slide: FancyBoxSlide): void;
/**
* Simple hack to fix inconsistency across browsers, described here (affects Edge, too):
* https://bugzilla.mozilla.org/show_bug.cgi?id=748518
* @param slide
*/
adjustLayout(slide: FancyBoxSlide): void;
/**
* Adjustments after slide content has been loaded
* @param slide
*/
afterLoad(slide: FancyBoxSlide): void;
/**
* Check if image dimensions exceed parent element
* @param nextWidth
* @param nextHeight
*/
canPan(nextWidth?: number, nextHeight?: number): boolean;
/**
* Horizontally center slide
* @param duration
*/
centerSlide(duration: number): void;
/**
* Check if image has srcset and get the source
* @param slide
*/
checkSrcset(slide: FancyBoxSlide): void;
/**
* Final adjustments after removing the instance
* @param e
*/
cleanUp(e: JQuery.Event): void;
/**
* Close current or all instances
* @param e
* @param duration
*/
close(e: JQuery.Event, duration?: number): void;
/**
* Final adjustments after current gallery item is moved to position
* and it`s content is loaded
*/
complete(): void;
/**
* Create new "slide" element
* These are gallery items that are actually added to DOM
* @param pos
*/
createSlide(pos: number): FancyBoxSlide;
/**
* Try to find and focus on the first focusable element
* @param e
* @param firstRun
*/
focus(e: JQuery.Event, firstRun: boolean): void;
/**
* Calculate image size to fit inside viewport
* @param slide
*/
getFitPos(slide: FancyBoxSlide): FancyBoxGetFitPosResults;
/**
* Check if we can and have to zoom from thumbnail
* @param slide
*/
getThumbPos(slide: FancyBoxSlide): FancyBoxThumbPos;
/**
* Hide toolbar and caption
* @param andCaption
*/
hideControls(andCaption: boolean): void;
/**
* Remove loading icon from the slide
* @param slide
*/
hideLoading(slide: FancyBoxSlide): void;
/**
* Create DOM structure
*/
init(): void;
/**
* Check if current slide is moved (swiped)
* @param slide
*/
isMoved(slide: FancyBoxSlide): boolean;
/**
* Check if current image dimensions are smaller than actual
* @param nextWidth
* @param nextHeight
*/
isScaledDown(nextWidth?: number, nextHeight?: number): boolean;
/**
* Check if current slide is zoomable
*/
isZoomable(): boolean;
/**
* Switch to selected gallery item
* @param pos
* @param duration
*/
jumpTo(pos: number, duration: number): void;
/**
* Load content into the slide
* @param slide
*/
loadSlide(slide: FancyBoxSlide): void;
/**
* Change to next gallery item
* @param duration
*/
next(duration: number): void;
/**
* Preload next and previous slides
* @param type
*/
preload(type: string): void;
/**
* Change to previous gallery item
* @param duration
*/
previous(duration: number): void;
/**
* Remove events added by the core
*/
removeEvents(): void;
/**
* Computes the slide size from image size and maxWidth/maxHeight
* @param slide
* @param imgWidth
* @param imgHeight
*/
resolveImageSlideSize(slide: FancyBoxSlide, imgWidth: number, imgHeight: number): void;
/**
* Make content visible
* This method is called right after content has been loaded or
* user navigates gallery and transition should start
* @param slide
*/
revealContent(slide: FancyBoxSlide): void;
/**
* Scale image to the actual size of the image;
* x and y values should be relative to the slide
* @param x
* @param y
* @param duration
*/
scaleToActual(x?: number, y?: number, duration?: number): void;
/**
* Scale image to fit inside parent element
* @param duration
*/
scaleToFit(duration: number): void;
/**
* Create full-size image
* @param slide
*/
setBigImage(slide: FancyBoxSlide): void;
/**
* Wrap and append content to the slide
* @param slide
* @param content
*/
setContent(slide: FancyBoxSlide, content: JQuery | string): void;
/**
* Display error message
* @param slide
*/
setError(slide: FancyBoxSlide): void;
/**
* Create iframe wrapper, iframe and bindings
* @param slide
*/
setIframe(slide: FancyBoxSlide): void;
/**
* Use thumbnail image, if possible
* @param slide
*/
setImage(slide: FancyBoxSlide): void;
/**
* Show toolbar and caption
*/
showControls(): void;
/**
* Show loading icon inside the slide
* @param slide
*/
showLoading(slide: FancyBoxSlide): void;
/**
* Toggle toolbar and caption
*/
toggleControls(): void;
/**
* Simple i18n support - replaces object keys found in template
* with corresponding values
* @param obj
* @param str
*/
translate(obj: any, str: string): string;
/**
* Call callback and trigger an event
* @param name
* @param slide
*/
trigger(name: string, slide: FancyBoxSlide): void;
/**
* Update content size and position for all slides
* @param e
*/
update(e: any): void;
/**
* Update infobar values, navigation button states and reveal caption
*/
updateControls(): void;
/**
* Update cursor style depending if content can be zoomed
* @param nextWidth
* @param nextHeight
*/
updateCursor(nextWidth: number, nextHeight: number): void;
/**
* Update slide content position and size
* @param slide
* @param e
*/
updateSlide(slide: FancyBoxSlide, e?: any): void;
}
interface FancyBoxInstance extends FancyBoxInstanceMethods {
$caption?: JQuery;
$refs?: FancyBoxRefs;
$trigger?: JQuery;
FullScreen: FancyBoxFullScreen;
Guestures: FancyBoxGestures;
SlideShow: FancyBoxSlideShow;
Thumbs: FancyThumbs;
currIndex: number;
currPos: number;
current: FancyBoxSlide;
firstRun: boolean;
group: FancyBoxGroupItem[];
hasHiddenControls: boolean;
id: number;
idleInterval: number;
idleSecondsCounter: number;
isAnimating: boolean;
isIdle: boolean;
isVisible: boolean;
opts: FancyBoxOptions;
prevIndex: number;
prevPos: number;
slides: { [key: number]: FancyBoxSlide };
}
interface FancyBoxThumbPos extends FancyBoxGetFitPosResults {
scaleX?: number;
scaleY?: number;
}
interface FancyBoxGetFitPosResults {
top?: number;
left?: number;
width?: number;
height?: number;
}
interface FancyBoxJQueryMethods {
animate($el: JQuery, to: FancyBoxThumbPos, duration: number, callback: () => void, leaveAnimationName: boolean): void;
close(all?: boolean): void;
defaults: FancyBoxOptions;
destroy(): void;
getInstance(command?: string | (() => void)): FancyBoxInstance;
getTranslate($el: JQuery): void;
isMobile: boolean;
open(items: JQuery | string | FancyBoxGroupItem[] | FancyBoxGroupItem, opts?: FancyBoxOptions, index?: number): FancyBoxInstance;
setTranslate($el: JQuery, props: { left?: number; top?: number; }): void;
stop($el: JQuery, callCallback: boolean): void;
use3d: string;
version: string;
}
interface JQuery {
fancybox(options?: FancyBoxOptions): JQuery;
}
interface JQueryStatic {
fancybox: FancyBoxJQueryMethods;
} | the_stack |
import { createRouterMatcher, normalizeRouteRecord } from '../../src/matcher'
import {
START_LOCATION_NORMALIZED,
RouteComponent,
RouteRecordRaw,
MatcherLocationRaw,
MatcherLocation,
} from '../../src/types'
import { MatcherLocationNormalizedLoose } from '../utils'
import { mockWarn } from 'jest-mock-warn'
// @ts-expect-error
const component: RouteComponent = null
// for normalized records
const components = { default: component }
describe('RouterMatcher.resolve', () => {
function assertRecordMatch(
record: RouteRecordRaw | RouteRecordRaw[],
location: MatcherLocationRaw,
resolved: Partial<MatcherLocationNormalizedLoose>,
start: MatcherLocation = START_LOCATION_NORMALIZED
) {
record = Array.isArray(record) ? record : [record]
const matcher = createRouterMatcher(record, {})
if (!('meta' in resolved)) {
resolved.meta = record[0].meta || {}
}
if (!('name' in resolved)) {
resolved.name = undefined
}
// add location if provided as it should be the same value
if ('path' in location && !('path' in resolved)) {
resolved.path = location.path
}
if ('redirect' in record) {
throw new Error('not handled')
} else {
// use one single record
if (!resolved.matched) resolved.matched = record.map(normalizeRouteRecord)
// allow passing an expect.any(Array)
else if (Array.isArray(resolved.matched))
resolved.matched = resolved.matched.map(m => ({
...normalizeRouteRecord(m as any),
aliasOf: m.aliasOf,
}))
}
// allows not passing params
resolved.params =
resolved.params || ('params' in location ? location.params : {})
const startCopy: MatcherLocation = {
...start,
matched: start.matched.map(m => ({
...normalizeRouteRecord(m),
aliasOf: m.aliasOf,
})) as MatcherLocation['matched'],
}
// make matched non enumerable
Object.defineProperty(startCopy, 'matched', { enumerable: false })
const result = matcher.resolve(location, startCopy)
expect(result).toEqual(resolved)
}
/**
*
* @param record - Record or records we are testing the matcher against
* @param location - location we want to reolve against
* @param [start] Optional currentLocation used when resolving
* @returns error
*/
function assertErrorMatch(
record: RouteRecordRaw | RouteRecordRaw[],
location: MatcherLocationRaw,
start: MatcherLocation = START_LOCATION_NORMALIZED
): any {
try {
assertRecordMatch(record, location, {}, start)
} catch (error) {
return error
}
throw new Error('Expected Error to be thrown')
}
describe('alias', () => {
it('resolves an alias', () => {
assertRecordMatch(
{
path: '/',
alias: '/home',
name: 'Home',
components,
meta: { foo: true },
},
{ path: '/home' },
{
name: 'Home',
path: '/home',
params: {},
meta: { foo: true },
matched: [
{
path: '/home',
name: 'Home',
components,
aliasOf: expect.objectContaining({ name: 'Home', path: '/' }),
meta: { foo: true },
},
],
}
)
})
it('multiple aliases', () => {
const record = {
path: '/',
alias: ['/home', '/start'],
name: 'Home',
components,
meta: { foo: true },
}
assertRecordMatch(
record,
{ path: '/' },
{
name: 'Home',
path: '/',
params: {},
meta: { foo: true },
matched: [
{
path: '/',
name: 'Home',
components,
aliasOf: undefined,
meta: { foo: true },
},
],
}
)
assertRecordMatch(
record,
{ path: '/home' },
{
name: 'Home',
path: '/home',
params: {},
meta: { foo: true },
matched: [
{
path: '/home',
name: 'Home',
components,
aliasOf: expect.objectContaining({ name: 'Home', path: '/' }),
meta: { foo: true },
},
],
}
)
assertRecordMatch(
record,
{ path: '/start' },
{
name: 'Home',
path: '/start',
params: {},
meta: { foo: true },
matched: [
{
path: '/start',
name: 'Home',
components,
aliasOf: expect.objectContaining({ name: 'Home', path: '/' }),
meta: { foo: true },
},
],
}
)
})
it('resolves the original record by name', () => {
assertRecordMatch(
{
path: '/',
alias: '/home',
name: 'Home',
components,
meta: { foo: true },
},
{ name: 'Home' },
{
name: 'Home',
path: '/',
params: {},
meta: { foo: true },
matched: [
{
path: '/',
name: 'Home',
components,
aliasOf: undefined,
meta: { foo: true },
},
],
}
)
})
it('resolves an alias with children to the alias when using the path', () => {
const children = [{ path: 'one', component, name: 'nested' }]
assertRecordMatch(
{
path: '/parent',
alias: '/p',
component,
children,
},
{ path: '/p/one' },
{
path: '/p/one',
name: 'nested',
params: {},
matched: [
{
path: '/p',
children,
components,
aliasOf: expect.objectContaining({ path: '/parent' }),
},
{
path: '/p/one',
name: 'nested',
components,
aliasOf: expect.objectContaining({ path: '/parent/one' }),
},
],
}
)
})
describe('nested aliases', () => {
const children = [
{
path: 'one',
component,
name: 'nested',
alias: 'o',
children: [
{ path: 'two', alias: 't', name: 'nestednested', component },
],
},
{
path: 'other',
alias: 'otherAlias',
component,
name: 'other',
},
]
const record = {
path: '/parent',
name: 'parent',
alias: '/p',
component,
children,
}
it('resolves the parent as an alias', () => {
assertRecordMatch(
record,
{ path: '/p' },
expect.objectContaining({
path: '/p',
name: 'parent',
matched: [
expect.objectContaining({
path: '/p',
aliasOf: expect.objectContaining({ path: '/parent' }),
}),
],
})
)
})
describe('multiple children', () => {
// tests concerning the /parent/other path and its aliases
it('resolves the alias parent', () => {
assertRecordMatch(
record,
{ path: '/p/other' },
expect.objectContaining({
path: '/p/other',
name: 'other',
matched: [
expect.objectContaining({
path: '/p',
aliasOf: expect.objectContaining({ path: '/parent' }),
}),
expect.objectContaining({
path: '/p/other',
aliasOf: expect.objectContaining({ path: '/parent/other' }),
}),
],
})
)
})
it('resolves the alias child', () => {
assertRecordMatch(
record,
{ path: '/parent/otherAlias' },
expect.objectContaining({
path: '/parent/otherAlias',
name: 'other',
matched: [
expect.objectContaining({
path: '/parent',
aliasOf: undefined,
}),
expect.objectContaining({
path: '/parent/otherAlias',
aliasOf: expect.objectContaining({ path: '/parent/other' }),
}),
],
})
)
})
it('resolves the alias parent and child', () => {
assertRecordMatch(
record,
{ path: '/p/otherAlias' },
expect.objectContaining({
path: '/p/otherAlias',
name: 'other',
matched: [
expect.objectContaining({
path: '/p',
aliasOf: expect.objectContaining({ path: '/parent' }),
}),
expect.objectContaining({
path: '/p/otherAlias',
aliasOf: expect.objectContaining({ path: '/parent/other' }),
}),
],
})
)
})
})
it('resolves the original one with no aliases', () => {
assertRecordMatch(
record,
{ path: '/parent/one/two' },
expect.objectContaining({
path: '/parent/one/two',
name: 'nestednested',
matched: [
expect.objectContaining({
path: '/parent',
aliasOf: undefined,
}),
expect.objectContaining({
path: '/parent/one',
aliasOf: undefined,
}),
expect.objectContaining({
path: '/parent/one/two',
aliasOf: undefined,
}),
],
})
)
})
it.todo('resolves when parent is an alias and child has an absolute path')
it('resolves when parent is an alias', () => {
assertRecordMatch(
record,
{ path: '/p/one/two' },
expect.objectContaining({
path: '/p/one/two',
name: 'nestednested',
matched: [
expect.objectContaining({
path: '/p',
aliasOf: expect.objectContaining({ path: '/parent' }),
}),
expect.objectContaining({
path: '/p/one',
aliasOf: expect.objectContaining({ path: '/parent/one' }),
}),
expect.objectContaining({
path: '/p/one/two',
aliasOf: expect.objectContaining({ path: '/parent/one/two' }),
}),
],
})
)
})
it('resolves a different child when parent is an alias', () => {
assertRecordMatch(
record,
{ path: '/p/other' },
expect.objectContaining({
path: '/p/other',
name: 'other',
matched: [
expect.objectContaining({
path: '/p',
aliasOf: expect.objectContaining({ path: '/parent' }),
}),
expect.objectContaining({
path: '/p/other',
aliasOf: expect.objectContaining({ path: '/parent/other' }),
}),
],
})
)
})
it('resolves when the first child is an alias', () => {
assertRecordMatch(
record,
{ path: '/parent/o/two' },
expect.objectContaining({
path: '/parent/o/two',
name: 'nestednested',
matched: [
expect.objectContaining({
path: '/parent',
aliasOf: undefined,
}),
expect.objectContaining({
path: '/parent/o',
aliasOf: expect.objectContaining({ path: '/parent/one' }),
}),
expect.objectContaining({
path: '/parent/o/two',
aliasOf: expect.objectContaining({ path: '/parent/one/two' }),
}),
],
})
)
})
it('resolves when the second child is an alias', () => {
assertRecordMatch(
record,
{ path: '/parent/one/t' },
expect.objectContaining({
path: '/parent/one/t',
name: 'nestednested',
matched: [
expect.objectContaining({
path: '/parent',
aliasOf: undefined,
}),
expect.objectContaining({
path: '/parent/one',
aliasOf: undefined,
}),
expect.objectContaining({
path: '/parent/one/t',
aliasOf: expect.objectContaining({ path: '/parent/one/two' }),
}),
],
})
)
})
it('resolves when the two last children are aliases', () => {
assertRecordMatch(
record,
{ path: '/parent/o/t' },
expect.objectContaining({
path: '/parent/o/t',
name: 'nestednested',
matched: [
expect.objectContaining({
path: '/parent',
aliasOf: undefined,
}),
expect.objectContaining({
path: '/parent/o',
aliasOf: expect.objectContaining({ path: '/parent/one' }),
}),
expect.objectContaining({
path: '/parent/o/t',
aliasOf: expect.objectContaining({ path: '/parent/one/two' }),
}),
],
})
)
})
it('resolves when all are aliases', () => {
assertRecordMatch(
record,
{ path: '/p/o/t' },
expect.objectContaining({
path: '/p/o/t',
name: 'nestednested',
matched: [
expect.objectContaining({
path: '/p',
aliasOf: expect.objectContaining({ path: '/parent' }),
}),
expect.objectContaining({
path: '/p/o',
aliasOf: expect.objectContaining({ path: '/parent/one' }),
}),
expect.objectContaining({
path: '/p/o/t',
aliasOf: expect.objectContaining({ path: '/parent/one/two' }),
}),
],
})
)
})
it('resolves when first and last are aliases', () => {
assertRecordMatch(
record,
{ path: '/p/one/t' },
expect.objectContaining({
path: '/p/one/t',
name: 'nestednested',
matched: [
expect.objectContaining({
path: '/p',
aliasOf: expect.objectContaining({ path: '/parent' }),
}),
expect.objectContaining({
path: '/p/one',
aliasOf: expect.objectContaining({ path: '/parent/one' }),
}),
expect.objectContaining({
path: '/p/one/t',
aliasOf: expect.objectContaining({ path: '/parent/one/two' }),
}),
],
})
)
})
})
it('resolves the original path of the named children of a route with an alias', () => {
const children = [{ path: 'one', component, name: 'nested' }]
assertRecordMatch(
{
path: '/parent',
alias: '/p',
component,
children,
},
{ name: 'nested' },
{
path: '/parent/one',
name: 'nested',
params: {},
matched: [
{
path: '/parent',
children,
components,
aliasOf: undefined,
},
{ path: '/parent/one', name: 'nested', components },
],
}
)
})
})
describe('LocationAsPath', () => {
it('resolves a normal path', () => {
assertRecordMatch(
{ path: '/', name: 'Home', components },
{ path: '/' },
{ name: 'Home', path: '/', params: {} }
)
})
it('resolves a normal path without name', () => {
assertRecordMatch(
{ path: '/', components },
{ path: '/' },
{ name: undefined, path: '/', params: {} }
)
})
it('resolves a path with params', () => {
assertRecordMatch(
{ path: '/users/:id', name: 'User', components },
{ path: '/users/posva' },
{ name: 'User', params: { id: 'posva' } }
)
})
it('resolves an array of params for a repeatable params', () => {
assertRecordMatch(
{ path: '/a/:p+', name: 'a', components },
{ name: 'a', params: { p: ['b', 'c', 'd'] } },
{ name: 'a', path: '/a/b/c/d', params: { p: ['b', 'c', 'd'] } }
)
})
it('resolves single params for a repeatable params', () => {
assertRecordMatch(
{ path: '/a/:p+', name: 'a', components },
{ name: 'a', params: { p: 'b' } },
{ name: 'a', path: '/a/b', params: { p: 'b' } }
)
})
it('keeps repeated params as a single one when provided through path', () => {
assertRecordMatch(
{ path: '/a/:p+', name: 'a', components },
{ path: '/a/b/c' },
{ name: 'a', params: { p: ['b', 'c'] } }
)
})
it('resolves a path with multiple params', () => {
assertRecordMatch(
{ path: '/users/:id/:other', name: 'User', components },
{ path: '/users/posva/hey' },
{ name: 'User', params: { id: 'posva', other: 'hey' } }
)
})
it('resolves a path with multiple params but no name', () => {
assertRecordMatch(
{ path: '/users/:id/:other', components },
{ path: '/users/posva/hey' },
{ name: undefined, params: { id: 'posva', other: 'hey' } }
)
})
it('returns an empty match when the path does not exist', () => {
assertRecordMatch(
{ path: '/', components },
{ path: '/foo' },
{ name: undefined, params: {}, path: '/foo', matched: [] }
)
})
it('allows an optional trailing slash', () => {
assertRecordMatch(
{ path: '/home/', name: 'Home', components },
{ path: '/home/' },
{ name: 'Home', path: '/home/', matched: expect.any(Array) }
)
})
it('allows an optional trailing slash with optional param', () => {
assertRecordMatch(
{ path: '/:a', components, name: 'a' },
{ path: '/a/' },
{ path: '/a/', params: { a: 'a' }, name: 'a' }
)
assertRecordMatch(
{ path: '/a/:a', components, name: 'a' },
{ path: '/a/a/' },
{ path: '/a/a/', params: { a: 'a' }, name: 'a' }
)
})
it('allows an optional trailing slash with missing optional param', () => {
assertRecordMatch(
{ path: '/:a?', components, name: 'a' },
{ path: '/' },
{ path: '/', params: { a: '' }, name: 'a' }
)
assertRecordMatch(
{ path: '/a/:a?', components, name: 'a' },
{ path: '/a/' },
{ path: '/a/', params: { a: '' }, name: 'a' }
)
})
it('keeps required trailing slash (strict: true)', () => {
const record = {
path: '/home/',
name: 'Home',
components,
options: { strict: true },
}
assertErrorMatch(record, { path: '/home' })
assertRecordMatch(
record,
{ path: '/home/' },
{ name: 'Home', path: '/home/', matched: expect.any(Array) }
)
})
it('rejects a trailing slash when strict', () => {
const record = {
path: '/home',
name: 'Home',
components,
options: { strict: true },
}
assertRecordMatch(
record,
{ path: '/home' },
{ name: 'Home', path: '/home', matched: expect.any(Array) }
)
assertErrorMatch(record, { path: '/home/' })
})
})
describe('LocationAsName', () => {
it('matches a name', () => {
assertRecordMatch(
{ path: '/home', name: 'Home', components },
{ name: 'Home' },
{ name: 'Home', path: '/home' }
)
})
it('matches a name and fill params', () => {
assertRecordMatch(
{ path: '/users/:id/m/:role', name: 'UserEdit', components },
{ name: 'UserEdit', params: { id: 'posva', role: 'admin' } },
{ name: 'UserEdit', path: '/users/posva/m/admin' }
)
})
it('throws if the named route does not exists', () => {
expect(
assertErrorMatch({ path: '/', components }, { name: 'Home' })
).toMatchSnapshot()
})
it('merges params', () => {
assertRecordMatch(
{ path: '/:a/:b', name: 'p', components },
{ name: 'p', params: { b: 'b' } },
{ name: 'p', path: '/a/b', params: { a: 'a', b: 'b' } },
{
params: { a: 'a' },
path: '/a',
matched: [],
meta: {},
name: undefined,
}
)
})
it('only keep existing params', () => {
assertRecordMatch(
{ path: '/:a/:b', name: 'p', components },
{ name: 'p', params: { b: 'b' } },
{ name: 'p', path: '/a/b', params: { a: 'a', b: 'b' } },
{
params: { a: 'a', c: 'c' },
path: '/a',
matched: [],
meta: {},
name: undefined,
}
)
})
it('drops optional params', () => {
assertRecordMatch(
{ path: '/:a/:b?', name: 'p', components },
{ name: 'p', params: { a: 'b' } },
{ name: 'p', path: '/b', params: { a: 'b' } },
{
params: { a: 'a', b: 'b' },
path: '/a',
matched: [],
meta: {},
name: undefined,
}
)
})
it('resolves root path with optional params', () => {
assertRecordMatch(
{ path: '/:tab?', name: 'h', components },
{ name: 'h' },
{ name: 'h', path: '/', params: {} }
)
})
})
describe('LocationAsRelative', () => {
mockWarn()
it('warns if a path isn not absolute', () => {
const record = {
path: '/parent',
components,
}
const matcher = createRouterMatcher([record], {})
matcher.resolve(
{ path: 'two' },
{
path: '/parent/one',
name: undefined,
params: {},
matched: [] as any,
meta: {},
}
)
expect('received "two"').toHaveBeenWarned()
})
it('matches with nothing', () => {
const record = { path: '/home', name: 'Home', components }
assertRecordMatch(
record,
{},
{ name: 'Home', path: '/home' },
{
name: 'Home',
params: {},
path: '/home',
matched: [record] as any,
meta: {},
}
)
})
it('replace params even with no name', () => {
const record = { path: '/users/:id/m/:role', components }
assertRecordMatch(
record,
{ params: { id: 'posva', role: 'admin' } },
{ name: undefined, path: '/users/posva/m/admin' },
{
path: '/users/ed/m/user',
name: undefined,
params: { id: 'ed', role: 'user' },
matched: [record] as any,
meta: {},
}
)
})
it('replace params', () => {
const record = {
path: '/users/:id/m/:role',
name: 'UserEdit',
components,
}
assertRecordMatch(
record,
{ params: { id: 'posva', role: 'admin' } },
{ name: 'UserEdit', path: '/users/posva/m/admin' },
{
path: '/users/ed/m/user',
name: 'UserEdit',
params: { id: 'ed', role: 'user' },
matched: [],
meta: {},
}
)
})
it('keep params if not provided', () => {
const record = {
path: '/users/:id/m/:role',
name: 'UserEdit',
components,
}
assertRecordMatch(
record,
{},
{
name: 'UserEdit',
path: '/users/ed/m/user',
params: { id: 'ed', role: 'user' },
},
{
path: '/users/ed/m/user',
name: 'UserEdit',
params: { id: 'ed', role: 'user' },
matched: [record] as any,
meta: {},
}
)
})
it('keep params if not provided even with no name', () => {
const record = { path: '/users/:id/m/:role', components }
assertRecordMatch(
record,
{},
{
name: undefined,
path: '/users/ed/m/user',
params: { id: 'ed', role: 'user' },
},
{
path: '/users/ed/m/user',
name: undefined,
params: { id: 'ed', role: 'user' },
matched: [record] as any,
meta: {},
}
)
})
it('merges params', () => {
assertRecordMatch(
{ path: '/:a/:b?', name: 'p', components },
{ params: { b: 'b' } },
{ name: 'p', path: '/a/b', params: { a: 'a', b: 'b' } },
{
name: 'p',
params: { a: 'a' },
path: '/a',
matched: [],
meta: {},
}
)
})
it('keep optional params', () => {
assertRecordMatch(
{ path: '/:a/:b?', name: 'p', components },
{},
{ name: 'p', path: '/a/b', params: { a: 'a', b: 'b' } },
{
name: 'p',
params: { a: 'a', b: 'b' },
path: '/a/b',
matched: [],
meta: {},
}
)
})
it('merges optional params', () => {
assertRecordMatch(
{ path: '/:a/:b?', name: 'p', components },
{ params: { a: 'c' } },
{ name: 'p', path: '/c/b', params: { a: 'c', b: 'b' } },
{
name: 'p',
params: { a: 'a', b: 'b' },
path: '/a/b',
matched: [],
meta: {},
}
)
})
it('throws if the current named route does not exists', () => {
const record = { path: '/', components }
const start = {
name: 'home',
params: {},
path: '/',
matched: [record],
}
// the property should be non enumerable
Object.defineProperty(start, 'matched', { enumerable: false })
expect(
assertErrorMatch(
record,
{ params: { a: 'foo' } },
{
...start,
matched: start.matched.map(normalizeRouteRecord),
meta: {},
}
)
).toMatchSnapshot()
})
})
describe('children', () => {
const ChildA = { path: 'a', name: 'child-a', components }
const ChildB = { path: 'b', name: 'child-b', components }
const ChildC = { path: 'c', name: 'child-c', components }
const ChildD = { path: '/absolute', name: 'absolute', components }
const ChildWithParam = { path: ':p', name: 'child-params', components }
const NestedChildWithParam = {
...ChildWithParam,
name: 'nested-child-params',
}
const NestedChildA = { ...ChildA, name: 'nested-child-a' }
const NestedChildB = { ...ChildB, name: 'nested-child-b' }
const NestedChildC = { ...ChildC, name: 'nested-child-c' }
const Nested = {
path: 'nested',
name: 'nested',
components,
children: [NestedChildA, NestedChildB, NestedChildC],
}
const NestedWithParam = {
path: 'nested/:n',
name: 'nested',
components,
children: [NestedChildWithParam],
}
it('resolves children', () => {
const Foo = {
path: '/foo',
name: 'Foo',
components,
children: [ChildA, ChildB, ChildC],
}
assertRecordMatch(
Foo,
{ path: '/foo/b' },
{
name: 'child-b',
path: '/foo/b',
params: {},
matched: [Foo, { ...ChildB, path: `${Foo.path}/${ChildB.path}` }],
}
)
})
it('resolves children with empty paths', () => {
const Nested = { path: '', name: 'nested', components }
const Foo = {
path: '/foo',
name: 'Foo',
components,
children: [Nested],
}
assertRecordMatch(
Foo,
{ path: '/foo' },
{
name: 'nested',
path: '/foo',
params: {},
matched: [Foo, { ...Nested, path: `${Foo.path}` }],
}
)
})
it('resolves nested children with empty paths', () => {
const NestedNested = { path: '', name: 'nested', components }
const Nested = {
path: '',
name: 'nested-nested',
components,
children: [NestedNested],
}
const Foo = {
path: '/foo',
name: 'Foo',
components,
children: [Nested],
}
assertRecordMatch(
Foo,
{ path: '/foo' },
{
name: 'nested',
path: '/foo',
params: {},
matched: [
Foo,
{ ...Nested, path: `${Foo.path}` },
{ ...NestedNested, path: `${Foo.path}` },
],
}
)
})
it('resolves nested children', () => {
const Foo = {
path: '/foo',
name: 'Foo',
components,
children: [Nested],
}
assertRecordMatch(
Foo,
{ path: '/foo/nested/a' },
{
name: 'nested-child-a',
path: '/foo/nested/a',
params: {},
matched: [
Foo,
{ ...Nested, path: `${Foo.path}/${Nested.path}` },
{
...NestedChildA,
path: `${Foo.path}/${Nested.path}/${NestedChildA.path}`,
},
],
}
)
})
it('resolves nested children with named location', () => {
const Foo = {
path: '/foo',
name: 'Foo',
components,
children: [Nested],
}
assertRecordMatch(
Foo,
{ name: 'nested-child-a' },
{
name: 'nested-child-a',
path: '/foo/nested/a',
params: {},
matched: [
Foo,
{ ...Nested, path: `${Foo.path}/${Nested.path}` },
{
...NestedChildA,
path: `${Foo.path}/${Nested.path}/${NestedChildA.path}`,
},
],
}
)
})
it('resolves nested children with relative location', () => {
const Foo = {
path: '/foo',
name: 'Foo',
components,
children: [Nested],
}
assertRecordMatch(
Foo,
{},
{
name: 'nested-child-a',
path: '/foo/nested/a',
params: {},
matched: [
Foo,
{ ...Nested, path: `${Foo.path}/${Nested.path}` },
{
...NestedChildA,
path: `${Foo.path}/${Nested.path}/${NestedChildA.path}`,
},
],
},
{
name: 'nested-child-a',
matched: [],
params: {},
path: '/foo/nested/a',
meta: {},
}
)
})
it('resolves nested children with params', () => {
const Foo = {
path: '/foo',
name: 'Foo',
components,
children: [NestedWithParam],
}
assertRecordMatch(
Foo,
{ path: '/foo/nested/a/b' },
{
name: 'nested-child-params',
path: '/foo/nested/a/b',
params: { p: 'b', n: 'a' },
matched: [
Foo,
{
...NestedWithParam,
path: `${Foo.path}/${NestedWithParam.path}`,
},
{
...NestedChildWithParam,
path: `${Foo.path}/${NestedWithParam.path}/${NestedChildWithParam.path}`,
},
],
}
)
})
it('resolves nested children with params with named location', () => {
const Foo = {
path: '/foo',
name: 'Foo',
components,
children: [NestedWithParam],
}
assertRecordMatch(
Foo,
{ name: 'nested-child-params', params: { p: 'a', n: 'b' } },
{
name: 'nested-child-params',
path: '/foo/nested/b/a',
params: { p: 'a', n: 'b' },
matched: [
Foo,
{
...NestedWithParam,
path: `${Foo.path}/${NestedWithParam.path}`,
},
{
...NestedChildWithParam,
path: `${Foo.path}/${NestedWithParam.path}/${NestedChildWithParam.path}`,
},
],
}
)
})
it('resolves absolute path children', () => {
const Foo = {
path: '/foo',
name: 'Foo',
components,
children: [ChildA, ChildD],
}
assertRecordMatch(
Foo,
{ path: '/absolute' },
{
name: 'absolute',
path: '/absolute',
params: {},
matched: [Foo, ChildD],
}
)
})
it('resolves children with root as the parent', () => {
const Nested = { path: 'nested', name: 'nested', components }
const Parent = {
path: '/',
name: 'parent',
components,
children: [Nested],
}
assertRecordMatch(
Parent,
{ path: '/nested' },
{
name: 'nested',
path: '/nested',
params: {},
matched: [Parent, { ...Nested, path: `/nested` }],
}
)
})
it('resolves children with parent with trailing slash', () => {
const Nested = { path: 'nested', name: 'nested', components }
const Parent = {
path: '/parent/',
name: 'parent',
components,
children: [Nested],
}
assertRecordMatch(
Parent,
{ path: '/parent/nested' },
{
name: 'nested',
path: '/parent/nested',
params: {},
matched: [Parent, { ...Nested, path: `/parent/nested` }],
}
)
})
})
}) | the_stack |
* DescribeSyncJobs返回参数结构体
*/
export interface DescribeSyncJobsResponse {
/**
* 任务数目
*/
TotalCount?: number
/**
* 任务详情数组
*/
JobList?: Array<SyncJobInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeMigrateJobs返回参数结构体
*/
export interface DescribeMigrateJobsResponse {
/**
* 任务数目
*/
TotalCount: number
/**
* 任务详情数组
*/
JobList: Array<MigrateJobInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 描述详细迁移过程
*/
export interface MigrateDetailInfo {
/**
* 总步骤数
*/
StepAll: number
/**
* 当前步骤
*/
StepNow: number
/**
* 总进度,如:"10"
*/
Progress: string
/**
* 当前步骤进度,如:"1"
*/
CurrentStepProgress: string
/**
* 主从差距,MB;在增量同步阶段有效,目前支持产品为:redis和mysql
*/
MasterSlaveDistance: number
/**
* 主从差距,秒;在增量同步阶段有效,目前支持产品为:mysql
*/
SecondsBehindMaster: number
/**
* 步骤信息
*/
StepInfo: Array<MigrateStepDetailInfo>
}
/**
* DeleteMigrateJob返回参数结构体
*/
export interface DeleteMigrateJobResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* CreateMigrateCheckJob请求参数结构体
*/
export interface CreateMigrateCheckJobRequest {
/**
* 数据迁移任务ID
*/
JobId: string
}
/**
* ModifySubscribeVipVport请求参数结构体
*/
export interface ModifySubscribeVipVportRequest {
/**
* 数据订阅实例的ID
*/
SubscribeId: string
/**
* 指定目的子网,如果传此参数,DstIp必须在目的子网内
*/
DstUniqSubnetId?: string
/**
* 目标IP,与DstPort至少传一个
*/
DstIp?: string
/**
* 目标PORT,支持范围为:[1025-65535]
*/
DstPort?: number
}
/**
* 灾备同步的实例信息,记录主实例或灾备实例的信息
*/
export interface SyncInstanceInfo {
/**
* 地域英文名,如:ap-guangzhou
*/
Region: string
/**
* 实例短ID
*/
InstanceId: string
}
/**
* ModifySubscribeName返回参数结构体
*/
export interface ModifySubscribeNameResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* CreateSyncJob返回参数结构体
*/
export interface CreateSyncJobResponse {
/**
* 灾备同步任务ID
*/
JobId?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeMigrateCheckJob请求参数结构体
*/
export interface DescribeMigrateCheckJobRequest {
/**
* 数据迁移任务ID
*/
JobId: string
}
/**
* IsolateSubscribe返回参数结构体
*/
export interface IsolateSubscribeResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ModifySubscribeObjects返回参数结构体
*/
export interface ModifySubscribeObjectsResponse {
/**
* 异步任务的ID
*/
AsyncRequestId?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* SwitchDrToMaster请求参数结构体
*/
export interface SwitchDrToMasterRequest {
/**
* 灾备实例的信息
*/
DstInfo: SyncInstanceInfo
/**
* 数据库的类型 (如 mysql)
*/
DatabaseType: string
}
/**
* StartSyncJob请求参数结构体
*/
export interface StartSyncJobRequest {
/**
* 灾备同步任务ID
*/
JobId: string
}
/**
* CreateMigrateJob请求参数结构体
*/
export interface CreateMigrateJobRequest {
/**
* 数据迁移任务名称
*/
JobName: string
/**
* 迁移任务配置选项
*/
MigrateOption: MigrateOption
/**
* 源实例数据库类型,目前支持:mysql,redis,mongodb,postgresql,mariadb,percona。不同地域数据库类型的具体支持情况,请参考控制台创建迁移页面。
*/
SrcDatabaseType: string
/**
* 源实例接入类型,值包括:extranet(外网),cvm(CVM自建实例),dcg(专线接入的实例),vpncloud(云VPN接入的实例),cdb(腾讯云数据库实例),ccn(云联网实例)
*/
SrcAccessType: string
/**
* 源实例信息,具体内容跟迁移任务类型相关
*/
SrcInfo: SrcInfo
/**
* 目标实例数据库类型,目前支持:mysql,redis,mongodb,postgresql,mariadb,percona。不同地域数据库类型的具体支持情况,请参考控制台创建迁移页面。
*/
DstDatabaseType: string
/**
* 目标实例接入类型,目前支持:cdb(腾讯云数据库实例)
*/
DstAccessType: string
/**
* 目标实例信息
*/
DstInfo: DstInfo
/**
* 需要迁移的源数据库表信息,用json格式的字符串描述。当MigrateOption.MigrateObject配置为2(指定库表迁移)时必填。
对于database-table两级结构的数据库:
[{Database:db1,Table:[table1,table2]},{Database:db2}]
对于database-schema-table三级结构:
[{Database:db1,Schema:s1
Table:[table1,table2]},{Database:db1,Schema:s2
Table:[table1,table2]},{Database:db2,Schema:s1
Table:[table1,table2]},{Database:db3},{Database:db4
Schema:s1}]
*/
DatabaseInfo?: string
}
/**
* 订阅实例信息
*/
export interface SubscribeInfo {
/**
* 数据订阅的实例ID
*/
SubscribeId?: string
/**
* 数据订阅实例的名称
*/
SubscribeName?: string
/**
* 数据订阅实例绑定的通道ID
*/
ChannelId?: string
/**
* 数据订阅绑定实例对应的产品名称
*/
Product?: string
/**
* 数据订阅实例绑定的数据库实例ID
*/
InstanceId?: string
/**
* 数据订阅实例绑定的数据库实例状态
*/
InstanceStatus?: string
/**
* 数据订阅实例的配置状态,unconfigure - 未配置, configuring - 配置中,configured - 已配置
*/
SubsStatus?: string
/**
* 上次修改时间
*/
ModifyTime?: string
/**
* 创建时间
*/
CreateTime?: string
/**
* 隔离时间
*/
IsolateTime?: string
/**
* 到期时间
*/
ExpireTime?: string
/**
* 下线时间
*/
OfflineTime?: string
/**
* 最近一次修改的消费时间起点,如果从未修改则为零值
*/
ConsumeStartTime?: string
/**
* 数据订阅实例所属地域
*/
Region?: string
/**
* 计费方式,0 - 包年包月,1 - 按量计费
*/
PayType?: number
/**
* 数据订阅实例的Vip
*/
Vip?: string
/**
* 数据订阅实例的Vport
*/
Vport?: number
/**
* 数据订阅实例Vip所在VPC的唯一ID
*/
UniqVpcId?: string
/**
* 数据订阅实例Vip所在子网的唯一ID
*/
UniqSubnetId?: string
/**
* 数据订阅实例的状态,creating - 创建中,normal - 正常运行,isolating - 隔离中,isolated - 已隔离,offlining - 下线中,offline - 已下线
*/
Status?: string
/**
* SDK最后一条确认消息的时间戳,如果SDK一直消费,也可以作为SDK当前消费时间点
*/
SdkConsumedTime?: string
/**
* 标签
注意:此字段可能返回 null,表示取不到有效值。
*/
Tags?: Array<TagItem>
/**
* 自动续费标识。0-不自动续费,1-自动续费
注意:此字段可能返回 null,表示取不到有效值。
*/
AutoRenewFlag?: number
/**
* 订阅实例版本;txdts-旧版数据订阅,kafka-kafka版本数据订阅
注意:此字段可能返回 null,表示取不到有效值。
*/
SubscribeVersion?: string
}
/**
* ModifySubscribeName请求参数结构体
*/
export interface ModifySubscribeNameRequest {
/**
* 数据订阅实例的ID
*/
SubscribeId: string
/**
* 数据订阅实例的名称,长度限制为[1,60]
*/
SubscribeName: string
}
/**
* 灾备同步任务信息
*/
export interface SyncJobInfo {
/**
* 灾备任务id
*/
JobId: string
/**
* 灾备任务名
*/
JobName: string
/**
* 任务同步
*/
SyncOption: SyncOption
/**
* 源接入类型
*/
SrcAccessType: string
/**
* 源数据类型
*/
SrcDatabaseType: string
/**
* 源实例信息
*/
SrcInfo: SyncInstanceInfo
/**
* 灾备接入类型
*/
DstAccessType: string
/**
* 灾备数据类型
*/
DstDatabaseType: string
/**
* 灾备实例信息
*/
DstInfo: SyncInstanceInfo
/**
* 任务信息
*/
Detail: SyncDetailInfo
/**
* 任务状态
*/
Status: number
/**
* 迁移库表
*/
DatabaseInfo: string
/**
* 创建时间
*/
CreateTime: string
/**
* 开始时间
*/
StartTime: string
/**
* 结束时间
*/
EndTime: string
}
/**
* ModifySubscribeConsumeTime返回参数结构体
*/
export interface ModifySubscribeConsumeTimeResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 目的实例信息,具体内容跟迁移任务类型相关
*/
export interface DstInfo {
/**
* 目标实例地域,如ap-guangzhou
*/
Region: string
/**
* 目标实例ID,如cdb-jd92ijd8
*/
InstanceId?: string
/**
* 目标实例vip。已废弃,无需填写
*/
Ip?: string
/**
* 目标实例vport。已废弃,无需填写
*/
Port?: number
/**
* 目前只对MySQL有效。当为整实例迁移时,1-只读,0-可读写。
*/
ReadOnly?: number
/**
* 目标数据库账号
*/
User?: string
/**
* 目标数据库密码
*/
Password?: string
}
/**
* DescribeSubscribeConf返回参数结构体
*/
export interface DescribeSubscribeConfResponse {
/**
* 订阅实例ID
*/
SubscribeId?: string
/**
* 订阅实例名称
*/
SubscribeName?: string
/**
* 订阅通道
*/
ChannelId?: string
/**
* 订阅数据库类型
*/
Product?: string
/**
* 被订阅的实例
*/
InstanceId?: string
/**
* 被订阅的实例的状态,可能的值有running,offline,isolate
*/
InstanceStatus?: string
/**
* 订阅实例状态,可能的值有unconfigure-未配置,configuring-配置中,configured-已配置
*/
SubsStatus?: string
/**
* 订阅实例生命周期状态,可能的值有:normal-正常,isolating-隔离中,isolated-已隔离,offlining-下线中
*/
Status?: string
/**
* 订阅实例创建时间
*/
CreateTime?: string
/**
* 订阅实例被隔离时间
*/
IsolateTime?: string
/**
* 订阅实例到期时间
*/
ExpireTime?: string
/**
* 订阅实例下线时间
*/
OfflineTime?: string
/**
* 订阅实例消费时间起点。
*/
ConsumeStartTime?: string
/**
* 订阅实例计费类型,1-小时计费,0-包年包月
*/
PayType?: number
/**
* 订阅通道Vip
*/
Vip?: string
/**
* 订阅通道Port
*/
Vport?: number
/**
* 订阅通道所在VpcId
*/
UniqVpcId?: string
/**
* 订阅通道所在SubnetId
*/
UniqSubnetId?: string
/**
* 当前SDK消费时间位点
*/
SdkConsumedTime?: string
/**
* 订阅SDK IP地址
*/
SdkHost?: string
/**
* 订阅对象类型0-全实例订阅,1-DDL数据订阅,2-DML结构订阅,3-DDL数据订阅+DML结构订阅
*/
SubscribeObjectType?: number
/**
* 订阅对象,当SubscribeObjectType 为0时,此字段为空数组
*/
SubscribeObjects?: Array<SubscribeObject>
/**
* 修改时间
*/
ModifyTime?: string
/**
* 地域
*/
Region?: string
/**
* 订阅实例的标签
注意:此字段可能返回 null,表示取不到有效值。
*/
Tags?: Array<TagItem>
/**
* 自动续费标识,0-不自动续费,1-自动续费
注意:此字段可能返回 null,表示取不到有效值。
*/
AutoRenewFlag?: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAsyncRequestInfo请求参数结构体
*/
export interface DescribeAsyncRequestInfoRequest {
/**
* 任务 ID
*/
AsyncRequestId: string
}
/**
* 源实例信息
*/
export interface SrcInfo {
/**
* 阿里云AccessKey。源库是阿里云RDS5.6适用
*/
AccessKey?: string
/**
* 实例的IP地址
*/
Ip?: string
/**
* 实例的端口
*/
Port?: number
/**
* 实例的用户名
*/
User?: string
/**
* 实例的密码
*/
Password?: string
/**
* 阿里云RDS实例ID。源库是阿里云RDS5.6/5.6适用
*/
RdsInstanceId?: string
/**
* CVM实例短ID,格式如:ins-olgl39y8,与云服务器控制台页面显示的实例ID相同。如果是CVM自建实例,需要传递此字段
*/
CvmInstanceId?: string
/**
* 专线网关ID,格式如:dcg-0rxtqqxb
*/
UniqDcgId?: string
/**
* 私有网络ID,格式如:vpc-92jblxto
*/
VpcId?: string
/**
* 私有网络下的子网ID,格式如:subnet-3paxmkdz
*/
SubnetId?: string
/**
* VPN网关ID,格式如:vpngw-9ghexg7q
*/
UniqVpnGwId?: string
/**
* 数据库实例ID,格式如:cdb-powiqx8q
*/
InstanceId?: string
/**
* 地域英文名,如:ap-guangzhou
*/
Region?: string
/**
* 当实例为RDS实例时,填写为aliyun, 其他情况均填写others
*/
Supplier?: string
/**
* 云联网ID,如:ccn-afp6kltc
注意:此字段可能返回 null,表示取不到有效值。
*/
CcnId?: string
/**
* 数据库版本,当实例为RDS实例时才有效,格式如:5.6或者5.7,默认为5.6
*/
EngineVersion?: string
}
/**
* 抽样检验时的抽样参数
*/
export interface ConsistencyParams {
/**
* 数据内容检测参数。表中选出用来数据对比的行,占表的总行数的百分比。取值范围是整数[1-100]
*/
SelectRowsPerTable: number
/**
* 数据内容检测参数。迁移库表中,要进行数据内容检测的表,占所有表的百分比。取值范围是整数[1-100]
*/
TablesSelectAll: number
/**
* 数据数量检测,检测表行数是否一致。迁移库表中,要进行数据数量检测的表,占所有表的百分比。取值范围是整数[1-100]
*/
TablesSelectCount: number
}
/**
* ModifyMigrateJob请求参数结构体
*/
export interface ModifyMigrateJobRequest {
/**
* 待修改的数据迁移任务ID
*/
JobId: string
/**
* 数据迁移任务名称
*/
JobName?: string
/**
* 迁移任务配置选项
*/
MigrateOption?: MigrateOption
/**
* 源实例接入类型,值包括:extranet(外网),cvm(CVM自建实例),dcg(专线接入的实例),vpncloud(云VPN接入的实例),cdb(云上CDB实例)
*/
SrcAccessType?: string
/**
* 源实例信息,具体内容跟迁移任务类型相关
*/
SrcInfo?: SrcInfo
/**
* 目标实例接入类型,值包括:extranet(外网),cvm(CVM自建实例),dcg(专线接入的实例),vpncloud(云VPN接入的实例),cdb(云上CDB实例). 目前只支持cdb.
*/
DstAccessType?: string
/**
* 目标实例信息, 其中目标实例地域不允许修改.
*/
DstInfo?: DstInfo
/**
* 当选择'指定库表'迁移的时候, 需要设置待迁移的源数据库表信息,用符合json数组格式的字符串描述, 如下所例。
对于database-table两级结构的数据库:
[{"Database":"db1","Table":["table1","table2"]},{"Database":"db2"}]
对于database-schema-table三级结构:
[{"Database":"db1","Schema":"s1","Table":["table1","table2"]},{"Database":"db1","Schema":"s2","Table":["table1","table2"]},{"Database":"db2","Schema":"s1","Table":["table1","table2"]},{"Database":"db3"},{"Database":"db4","Schema":"s1"}]
如果是'整个实例'的迁移模式,不需设置该字段
*/
DatabaseInfo?: string
}
/**
* CreateSubscribe请求参数结构体
*/
export interface CreateSubscribeRequest {
/**
* 订阅的数据库类型,目前支持的有 mysql
*/
Product: string
/**
* 实例付费类型,1小时计费,0包年包月
*/
PayType: number
/**
* 购买时长。PayType为0时必填。单位为月,最大支持120
*/
Duration?: number
/**
* 购买数量,默认为1,最大为10
*/
Count?: number
/**
* 是否自动续费,默认为0,1表示自动续费。小时计费实例设置该标识无效。
*/
AutoRenew?: number
/**
* 实例资源标签
*/
Tags?: Array<TagItem>
}
/**
* CreateMigrateCheckJob返回参数结构体
*/
export interface CreateMigrateCheckJobResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 迁移中的步骤信息
*/
export interface MigrateStepDetailInfo {
/**
* 步骤序列
*/
StepNo: number
/**
* 步骤展现名称
*/
StepName: string
/**
* 步骤英文标识
*/
StepId: string
/**
* 步骤状态:0-默认值,1-成功,2-失败,3-执行中,4-未执行
*/
Status: number
/**
* 当前步骤开始的时间,格式为"yyyy-mm-dd hh:mm:ss",该字段不存在或者为空是无意义
注意:此字段可能返回 null,表示取不到有效值。
*/
StartTime: string
}
/**
* ModifySubscribeObjects请求参数结构体
*/
export interface ModifySubscribeObjectsRequest {
/**
* 数据订阅实例的ID
*/
SubscribeId: string
/**
* 数据订阅的类型,可选的值有:0 - 全实例订阅;1 - 数据订阅;2 - 结构订阅;3 - 数据订阅+结构订阅
*/
SubscribeObjectType: number
/**
* 订阅的数据库表信息
*/
Objects?: Array<SubscribeObject>
}
/**
* DescribeMigrateCheckJob返回参数结构体
*/
export interface DescribeMigrateCheckJobResponse {
/**
* 校验任务状态:unavailable(当前不可用), starting(开始中),running(校验中),finished(校验完成)
*/
Status?: string
/**
* 任务的错误码
*/
ErrorCode?: number
/**
* 任务的错误信息
*/
ErrorMessage?: string
/**
* Check任务总进度,如:"30"表示30%
*/
Progress?: string
/**
* 校验是否通过,0-未通过,1-校验通过, 3-未校验
*/
CheckFlag?: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 数据订阅地域售卖信息
*/
export interface SubscribeRegionConf {
/**
* 地域名称,如广州
注意:此字段可能返回 null,表示取不到有效值。
*/
RegionName: string
/**
* 地区标识,如ap-guangzhou
注意:此字段可能返回 null,表示取不到有效值。
*/
Region: string
/**
* 地域名称,如华南地区
注意:此字段可能返回 null,表示取不到有效值。
*/
Area: string
/**
* 是否为默认地域,0 - 不是,1 - 是的
注意:此字段可能返回 null,表示取不到有效值。
*/
IsDefaultRegion: number
/**
* 当前地域的售卖情况,1 - 正常, 2-灰度,3 - 停售
注意:此字段可能返回 null,表示取不到有效值。
*/
Status: number
}
/**
* ActivateSubscribe请求参数结构体
*/
export interface ActivateSubscribeRequest {
/**
* 订阅实例ID。
*/
SubscribeId: string
/**
* 数据库实例ID
*/
InstanceId: string
/**
* 数据订阅类型0-全实例订阅,1数据订阅,2结构订阅,3数据订阅与结构订阅
*/
SubscribeObjectType: number
/**
* 订阅对象
*/
Objects?: SubscribeObject
/**
* 数据订阅服务所在子网。默认为数据库实例所在的子网内。
*/
UniqSubnetId?: string
/**
* 订阅服务端口;默认为7507
*/
Vport?: number
}
/**
* OfflineIsolatedSubscribe请求参数结构体
*/
export interface OfflineIsolatedSubscribeRequest {
/**
* 数据订阅实例的ID
*/
SubscribeId: string
}
/**
* DescribeSubscribes请求参数结构体
*/
export interface DescribeSubscribesRequest {
/**
* 数据订阅的实例ID
*/
SubscribeId?: string
/**
* 数据订阅的实例名称
*/
SubscribeName?: string
/**
* 绑定数据库实例的ID
*/
InstanceId?: string
/**
* 数据订阅实例的通道ID
*/
ChannelId?: string
/**
* 计费模式筛选,可能的值:0-包年包月,1-按量计费
*/
PayType?: string
/**
* 订阅的数据库产品,如mysql
*/
Product?: string
/**
* 数据订阅实例的状态,creating - 创建中,normal - 正常运行,isolating - 隔离中,isolated - 已隔离,offlining - 下线中
*/
Status?: Array<string>
/**
* 数据订阅实例的配置状态,unconfigure - 未配置, configuring - 配置中,configured - 已配置
*/
SubsStatus?: Array<string>
/**
* 返回记录的起始偏移量
*/
Offset?: number
/**
* 单次返回的记录数量
*/
Limit?: number
/**
* 排序方向,可选的值为"DESC"和"ASC",默认为"DESC",按创建时间逆序排序
*/
OrderDirection?: string
/**
* 标签过滤条件
*/
TagFilters?: Array<TagFilter>
/**
* 订阅实例版本;txdts-旧版数据订阅,kafka-kafka版本数据订阅
*/
SubscribeVersion?: string
}
/**
* ResetSubscribe返回参数结构体
*/
export interface ResetSubscribeResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* StartSyncJob返回参数结构体
*/
export interface StartSyncJobResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeSubscribes返回参数结构体
*/
export interface DescribeSubscribesResponse {
/**
* 符合查询条件的实例总数
*/
TotalCount?: number
/**
* 数据订阅实例的信息列表
*/
Items?: Array<SubscribeInfo>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 灾备任务校验步骤
*/
export interface SyncCheckStepInfo {
/**
* 步骤序列
*/
StepNo: number
/**
* 步骤展现名称
*/
StepName: string
/**
* 步骤执行结果代码
*/
StepCode: number
/**
* 步骤执行结果提示
*/
StepMessage: string
}
/**
* CreateSyncCheckJob返回参数结构体
*/
export interface CreateSyncCheckJobResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* StopMigrateJob请求参数结构体
*/
export interface StopMigrateJobRequest {
/**
* 数据迁移任务ID
*/
JobId: string
}
/**
* DescribeSyncCheckJob请求参数结构体
*/
export interface DescribeSyncCheckJobRequest {
/**
* 要查询的灾备同步任务ID
*/
JobId: string
}
/**
* DescribeRegionConf返回参数结构体
*/
export interface DescribeRegionConfResponse {
/**
* 可售卖地域的数量
*/
TotalCount?: number
/**
* 可售卖地域详情
*/
Items?: Array<SubscribeRegionConf>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ModifySyncJob返回参数结构体
*/
export interface ModifySyncJobResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeAsyncRequestInfo返回参数结构体
*/
export interface DescribeAsyncRequestInfoResponse {
/**
* 任务执行结果信息
*/
Info?: string
/**
* 任务执行状态,可能的值有:success,failed,running
*/
Status?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* CompleteMigrateJob请求参数结构体
*/
export interface CompleteMigrateJobRequest {
/**
* 数据迁移任务ID
*/
JobId: string
/**
* 完成任务的方式,仅支持旧版MySQL迁移任务。waitForSync-等待主从差距为0才停止,immediately-立即完成,不会等待主从差距一致。默认为waitForSync
*/
CompleteMode?: string
}
/**
* ResetSubscribe请求参数结构体
*/
export interface ResetSubscribeRequest {
/**
* 数据订阅实例的ID
*/
SubscribeId: string
}
/**
* 标签
*/
export interface TagItem {
/**
* 标签键值
*/
TagKey: string
/**
* 标签值
注意:此字段可能返回 null,表示取不到有效值。
*/
TagValue?: string
}
/**
* 标签过滤
*/
export interface TagFilter {
/**
* 标签键值
*/
TagKey: string
/**
* 标签值
*/
TagValue?: Array<string>
}
/**
* ModifySubscribeConsumeTime请求参数结构体
*/
export interface ModifySubscribeConsumeTimeRequest {
/**
* 数据订阅实例的ID
*/
SubscribeId: string
/**
* 消费时间起点,也即是指定订阅数据的时间起点,时间格式如:Y-m-d h:m:s,取值范围为过去24小时之内
*/
ConsumeStartTime: string
}
/**
* SwitchDrToMaster返回参数结构体
*/
export interface SwitchDrToMasterResponse {
/**
* 后台异步任务请求id
*/
AsyncRequestId?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ModifyMigrateJob返回参数结构体
*/
export interface ModifyMigrateJobResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* CreateSyncJob请求参数结构体
*/
export interface CreateSyncJobRequest {
/**
* 灾备同步任务名
*/
JobName: string
/**
* 灾备同步任务配置选项
*/
SyncOption: SyncOption
/**
* 源实例数据库类型,目前仅包括:mysql
*/
SrcDatabaseType: string
/**
* 源实例接入类型,目前仅包括:cdb(云上cdb实例)
*/
SrcAccessType: string
/**
* 源实例信息
*/
SrcInfo: SyncInstanceInfo
/**
* 目标实例数据库类型,目前仅包括:mysql
*/
DstDatabaseType: string
/**
* 目标实例接入类型,目前仅包括:cdb(云上cdb实例)
*/
DstAccessType: string
/**
* 目标实例信息
*/
DstInfo: SyncInstanceInfo
/**
* 需要同步的源数据库表信息,用json格式的字符串描述。
对于database-table两级结构的数据库:
[{Database:db1,Table:[table1,table2]},{Database:db2}]
*/
DatabaseInfo?: string
}
/**
* DescribeSyncJobs请求参数结构体
*/
export interface DescribeSyncJobsRequest {
/**
* 灾备同步任务ID
*/
JobId?: string
/**
* 灾备同步任务名
*/
JobName?: string
/**
* 排序字段,可以取值为JobId、Status、JobName、CreateTime
*/
Order?: string
/**
* 排序方式,升序为ASC,降序为DESC
*/
OrderSeq?: string
/**
* 偏移量,默认为0
*/
Offset?: number
/**
* 返回实例数量,默认20,有效区间[1,100]
*/
Limit?: number
}
/**
* DescribeMigrateJobs请求参数结构体
*/
export interface DescribeMigrateJobsRequest {
/**
* 数据迁移任务ID
*/
JobId?: string
/**
* 数据迁移任务名称
*/
JobName?: string
/**
* 排序字段,可以取值为JobId、Status、JobName、MigrateType、RunMode、CreateTime
*/
Order?: string
/**
* 排序方式,升序为ASC,降序为DESC
*/
OrderSeq?: string
/**
* 偏移量,默认为0
*/
Offset?: number
/**
* 返回实例数量,默认20,有效区间[1,100]
*/
Limit?: number
/**
* 标签过滤条件
*/
TagFilters?: Array<TagFilter>
}
/**
* 描述详细同步任务过程
*/
export interface SyncDetailInfo {
/**
* 总步骤数
*/
StepAll: number
/**
* 当前步骤
*/
StepNow: number
/**
* 总进度
*/
Progress: string
/**
* 当前步骤进度
*/
CurrentStepProgress: string
/**
* 主从差距,MB
*/
MasterSlaveDistance: number
/**
* 主从差距,秒
*/
SecondsBehindMaster: number
/**
* 步骤信息
*/
StepInfo: Array<SyncStepDetailInfo>
}
/**
* ModifySubscribeAutoRenewFlag返回参数结构体
*/
export interface ModifySubscribeAutoRenewFlagResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* StopMigrateJob返回参数结构体
*/
export interface StopMigrateJobResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 灾备同步任务配置选项
*/
export interface SyncOption {
/**
* 同步对象,1-整个实例,2-指定库表
*/
SyncObject: number
/**
* 同步开始设置,1-立即开始
*/
RunMode?: number
/**
* 同步模式, 3-全量且增量同步
*/
SyncType?: number
/**
* 数据一致性检测, 1-无需配置
*/
ConsistencyType?: number
}
/**
* OfflineIsolatedSubscribe返回参数结构体
*/
export interface OfflineIsolatedSubscribeResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 同步任务进度
*/
export interface SyncStepDetailInfo {
/**
* 步骤编号
*/
StepNo: number
/**
* 步骤名
*/
StepName: string
/**
* 能否中止
*/
CanStop: number
/**
* 步骤号
*/
StepId: number
}
/**
* IsolateSubscribe请求参数结构体
*/
export interface IsolateSubscribeRequest {
/**
* 订阅实例ID
*/
SubscribeId: string
}
/**
* ModifySubscribeAutoRenewFlag请求参数结构体
*/
export interface ModifySubscribeAutoRenewFlagRequest {
/**
* 订阅实例ID,例如:subs-8uey736k
*/
SubscribeId: string
/**
* 自动续费标识。1-自动续费,0-不自动续费
*/
AutoRenewFlag: number
}
/**
* DeleteSyncJob返回参数结构体
*/
export interface DeleteSyncJobResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* CreateSyncCheckJob请求参数结构体
*/
export interface CreateSyncCheckJobRequest {
/**
* 灾备同步任务ID
*/
JobId: string
}
/**
* ModifySyncJob请求参数结构体
*/
export interface ModifySyncJobRequest {
/**
* 待修改的灾备同步任务ID
*/
JobId: string
/**
* 灾备同步任务名称
*/
JobName?: string
/**
* 灾备同步任务配置选项
*/
SyncOption?: SyncOption
/**
* 当选择'指定库表'灾备同步的时候, 需要设置待同步的源数据库表信息,用符合json数组格式的字符串描述, 如下所例。
对于database-table两级结构的数据库:
[{"Database":"db1","Table":["table1","table2"]},{"Database":"db2"}]
*/
DatabaseInfo?: string
}
/**
* DescribeRegionConf请求参数结构体
*/
export type DescribeRegionConfRequest = null
/**
* CompleteMigrateJob返回参数结构体
*/
export interface CompleteMigrateJobResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* StartMigrateJob返回参数结构体
*/
export interface StartMigrateJobResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 数据数据订阅的对象
*/
export interface SubscribeObject {
/**
* 数据订阅对象的类型,0-数据库,1-数据库内的表
注意:此字段可能返回 null,表示取不到有效值。
*/
ObjectsType: number
/**
* 订阅数据库的名称
注意:此字段可能返回 null,表示取不到有效值。
*/
DatabaseName: string
/**
* 订阅数据库中表名称数组
注意:此字段可能返回 null,表示取不到有效值。
*/
TableNames?: Array<string>
}
/**
* CreateMigrateJob返回参数结构体
*/
export interface CreateMigrateJobResponse {
/**
* 数据迁移任务ID
*/
JobId?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeSubscribeConf请求参数结构体
*/
export interface DescribeSubscribeConfRequest {
/**
* 订阅实例ID
*/
SubscribeId: string
}
/**
* ModifySubscribeVipVport返回参数结构体
*/
export interface ModifySubscribeVipVportResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 迁移任务详情
*/
export interface MigrateJobInfo {
/**
* 数据迁移任务ID
*/
JobId: string
/**
* 数据迁移任务名称
*/
JobName: string
/**
* 迁移任务配置选项
*/
MigrateOption: MigrateOption
/**
* 源实例数据库类型:mysql,redis,mongodb,postgresql,mariadb,percona
*/
SrcDatabaseType: string
/**
* 源实例接入类型,值包括:extranet(外网),cvm(cvm自建实例),dcg(专线接入的实例),vpncloud(云vpn接入的实例),cdb(腾讯云数据库实例),ccn(云联网实例)
*/
SrcAccessType: string
/**
* 源实例信息,具体内容跟迁移任务类型相关
*/
SrcInfo: SrcInfo
/**
* 目标实例数据库类型:mysql,redis,mongodb,postgresql,mariadb,percona
*/
DstDatabaseType: string
/**
* 目标实例接入类型,目前支持:cdb(腾讯云数据库实例)
*/
DstAccessType: string
/**
* 目标实例信息
*/
DstInfo: DstInfo
/**
* 需要迁移的源数据库表信息,如果需要迁移的是整个实例,该字段为[]
*/
DatabaseInfo: string
/**
* 任务创建(提交)时间
*/
CreateTime: string
/**
* 任务开始执行时间
*/
StartTime: string
/**
* 任务执行结束时间
*/
EndTime: string
/**
* 任务状态,取值为:1-创建中(Creating),3-校验中(Checking)4-校验通过(CheckPass),5-校验不通过(CheckNotPass),7-任务运行(Running),8-准备完成(ReadyComplete),9-任务成功(Success),10-任务失败(Failed),11-撤销中(Stopping),12-完成中(Completing)
*/
Status: number
/**
* 任务详情
*/
Detail: MigrateDetailInfo
/**
* 任务错误信息提示,当任务发生错误时,不为null或者空值
*/
ErrorInfo: Array<ErrorInfo>
/**
* 标签
注意:此字段可能返回 null,表示取不到有效值。
*/
Tags: Array<TagItem>
}
/**
* DeleteMigrateJob请求参数结构体
*/
export interface DeleteMigrateJobRequest {
/**
* 数据迁移任务ID
*/
JobId: string
}
/**
* DeleteSyncJob请求参数结构体
*/
export interface DeleteSyncJobRequest {
/**
* 待删除的灾备同步任务ID
*/
JobId: string
}
/**
* ActivateSubscribe返回参数结构体
*/
export interface ActivateSubscribeResponse {
/**
* 配置数据订阅任务ID。
*/
AsyncRequestId?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* CreateSubscribe返回参数结构体
*/
export interface CreateSubscribeResponse {
/**
* 数据订阅实例的ID数组
注意:此字段可能返回 null,表示取不到有效值。
*/
SubscribeIds?: Array<string>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 迁移任务配置选项
*/
export interface MigrateOption {
/**
* 任务运行模式,值包括:1-立即执行,2-定时执行
*/
RunMode: number
/**
* 期望执行时间,当runMode=2时,该字段必填,时间格式:yyyy-mm-dd hh:mm:ss
*/
ExpectTime?: string
/**
* 数据迁移类型,值包括:1-结构迁移,2-全量迁移,3-全量+增量迁移
*/
MigrateType?: number
/**
* 迁移对象,1-整个实例,2-指定库表
*/
MigrateObject?: number
/**
* 抽样数据一致性检测参数,1-未配置,2-全量检测,3-抽样检测, 4-仅校验不一致表,5-不检测
*/
ConsistencyType?: number
/**
* 是否用源库Root账户覆盖目标库,值包括:0-不覆盖,1-覆盖,选择库表或者结构迁移时应该为0
*/
IsOverrideRoot?: number
/**
* 不同数据库用到的额外参数.以JSON格式描述.
Redis可定义如下的参数:
{
"ClientOutputBufferHardLimit":512, 从机缓冲区的硬性容量限制(MB)
"ClientOutputBufferSoftLimit":512, 从机缓冲区的软性容量限制(MB)
"ClientOutputBufferPersistTime":60, 从机缓冲区的软性限制持续时间(秒)
"ReplBacklogSize":512, 环形缓冲区容量限制(MB)
"ReplTimeout":120, 复制超时时间(秒)
}
MongoDB可定义如下的参数:
{
'SrcAuthDatabase':'admin',
'SrcAuthFlag': "1",
'SrcAuthMechanism':"SCRAM-SHA-1"
}
MySQL暂不支持额外参数设置。
*/
ExternParams?: string
/**
* 仅用于“抽样数据一致性检测”,ConsistencyType配置为抽样检测时,必选
*/
ConsistencyParams?: ConsistencyParams
}
/**
* 迁移任务错误信息及提示
*/
export interface ErrorInfo {
/**
* 具体的报错日志, 包含错误码和错误信息
*/
ErrorLog: string
/**
* 报错对应的帮助文档Ur
*/
HelpDoc: string
}
/**
* DescribeSyncCheckJob返回参数结构体
*/
export interface DescribeSyncCheckJobResponse {
/**
* 任务校验状态: starting(开始中),running(校验中),finished(校验完成)
*/
Status?: string
/**
* 任务校验结果代码
*/
ErrorCode?: number
/**
* 提示信息
*/
ErrorMessage?: string
/**
* 任务执行步骤描述
*/
StepInfo?: Array<SyncCheckStepInfo>
/**
* 校验标志:0(尚未校验成功) , 1(校验成功)
*/
CheckFlag?: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* StartMigrateJob请求参数结构体
*/
export interface StartMigrateJobRequest {
/**
* 数据迁移任务ID
*/
JobId: string
} | the_stack |
import { CircleCollider } from './CircleCollider';
import { CollisionContact } from '../Detection/CollisionContact';
import { PolygonCollider } from './PolygonCollider';
import { EdgeCollider } from './EdgeCollider';
import { SeparatingAxis, SeparationInfo } from './SeparatingAxis';
import { Line } from '../../Math/line';
import { Vector } from '../../Math/vector';
import { TransformComponent } from '../../EntityComponentSystem';
import { Pair } from '../Detection/Pair';
export const CollisionJumpTable = {
CollideCircleCircle(circleA: CircleCollider, circleB: CircleCollider): CollisionContact[] {
const circleAPos = circleA.worldPos;
const circleBPos = circleB.worldPos;
const combinedRadius = circleA.radius + circleB.radius;
const distance = circleAPos.distance(circleBPos);
if (distance > combinedRadius) {
return [];
}
// negative means overlap
const separation = combinedRadius - distance;
// Normal points from A -> B
const normal = circleBPos.sub(circleAPos).normalize();
const tangent = normal.perpendicular();
const mvt = normal.scale(separation);
const point = circleA.getFurthestPoint(normal);
const local = circleA.getFurthestLocalPoint(normal);
const info: SeparationInfo = {
collider: circleA,
separation,
axis: normal,
point: point
};
return [new CollisionContact(circleA, circleB, mvt, normal, tangent, [point], [local], info)];
},
CollideCirclePolygon(circle: CircleCollider, polygon: PolygonCollider): CollisionContact[] {
let minAxis = SeparatingAxis.findCirclePolygonSeparation(circle, polygon);
if (!minAxis) {
return [];
}
// make sure that the minAxis is pointing away from circle
const samedir = minAxis.dot(polygon.center.sub(circle.center));
minAxis = samedir < 0 ? minAxis.negate() : minAxis;
const point = circle.getFurthestPoint(minAxis);
const xf = circle.owner?.get(TransformComponent) ?? new TransformComponent();
const local = xf.applyInverse(point);
const normal = minAxis.normalize();
const info: SeparationInfo = {
collider: circle,
separation: -minAxis.size,
axis: normal,
point: point,
localPoint: local,
side: polygon.findSide(normal.negate()),
localSide: polygon.findLocalSide(normal.negate())
};
return [new CollisionContact(circle, polygon, minAxis, normal, normal.perpendicular(), [point], [local], info)];
},
CollideCircleEdge(circle: CircleCollider, edge: EdgeCollider): CollisionContact[] {
// TODO not sure this actually abides by local/world collisions
// Are edge.begin and edge.end local space or world space? I think they should be local
// center of the circle in world pos
const cc = circle.center;
// vector in the direction of the edge
const edgeWorld = edge.asLine();
const e = edgeWorld.end.sub(edgeWorld.begin);
// amount of overlap with the circle's center along the edge direction
const u = e.dot(edgeWorld.end.sub(cc));
const v = e.dot(cc.sub(edgeWorld.begin));
const side = edge.asLine();
const localSide = edge.asLocalLine();
// Potential region A collision (circle is on the left side of the edge, before the beginning)
if (v <= 0) {
const da = edgeWorld.begin.sub(cc);
const dda = da.dot(da); // quick and dirty way of calc'n distance in r^2 terms saves some sqrts
// save some sqrts
if (dda > circle.radius * circle.radius) {
return []; // no collision
}
const normal = da.normalize();
const separation = circle.radius - Math.sqrt(dda);
const info: SeparationInfo = {
collider: circle,
separation: separation,
axis: normal,
point: side.begin,
side: side,
localSide: localSide
};
return [
new CollisionContact(circle, edge, normal.scale(separation), normal, normal.perpendicular(), [side.begin], [localSide.begin], info)
];
}
// Potential region B collision (circle is on the right side of the edge, after the end)
if (u <= 0) {
const db = edgeWorld.end.sub(cc);
const ddb = db.dot(db);
if (ddb > circle.radius * circle.radius) {
return [];
}
const normal = db.normalize();
const separation = circle.radius - Math.sqrt(ddb);
const info: SeparationInfo = {
collider: circle,
separation: separation,
axis: normal,
point: side.end,
side: side,
localSide: localSide
};
return [
new CollisionContact(circle, edge, normal.scale(separation), normal, normal.perpendicular(), [side.end], [localSide.end], info)
];
}
// Otherwise potential region AB collision (circle is in the middle of the edge between the beginning and end)
const den = e.dot(e);
const pointOnEdge = edgeWorld.begin
.scale(u)
.add(edgeWorld.end.scale(v))
.scale(1 / den);
const d = cc.sub(pointOnEdge);
const dd = d.dot(d);
if (dd > circle.radius * circle.radius) {
return []; // no collision
}
let normal = e.perpendicular();
// flip correct direction
if (normal.dot(cc.sub(edgeWorld.begin)) < 0) {
normal.x = -normal.x;
normal.y = -normal.y;
}
normal = normal.normalize();
const separation = circle.radius - Math.sqrt(dd);
const mvt = normal.scale(separation);
const info: SeparationInfo = {
collider: circle,
separation: separation,
axis: normal,
point: pointOnEdge,
side: side,
localSide: localSide
};
return [
new CollisionContact(
circle,
edge,
mvt,
normal.negate(),
normal.negate().perpendicular(),
[pointOnEdge],
[pointOnEdge.sub(edge.worldPos)],
info
)
];
},
CollideEdgeEdge(): CollisionContact[] {
// Edge-edge collision doesn't make sense
return [];
},
CollidePolygonEdge(polygon: PolygonCollider, edge: EdgeCollider): CollisionContact[] {
const pc = polygon.center;
const ec = edge.center;
const dir = ec.sub(pc).normalize();
// build a temporary polygon from the edge to use SAT
const linePoly = new PolygonCollider({
points: [edge.begin, edge.end, edge.end.add(dir.scale(100)), edge.begin.add(dir.scale(100))],
offset: edge.offset
});
linePoly.owner = edge.owner;
const tx = edge.owner?.get(TransformComponent);
if (tx) {
linePoly.update(edge.owner.get(TransformComponent));
}
// Gross hack but poly-poly works well
const contact = this.CollidePolygonPolygon(polygon, linePoly);
if (contact.length) {
// Fudge the contact back to edge
contact[0].colliderB = edge;
(contact[0].id as any) = Pair.calculatePairHash(polygon.id, edge.id);
// contact[0].info.collider
}
return contact;
},
CollidePolygonPolygon(polyA: PolygonCollider, polyB: PolygonCollider): CollisionContact[] {
// Multi contact from SAT
// https://gamedev.stackexchange.com/questions/111390/multiple-contacts-for-sat-collision-detection
// do a SAT test to find a min axis if it exists
const separationA = SeparatingAxis.findPolygonPolygonSeparation(polyA, polyB);
// If there is no overlap from boxA's perspective we can end early
if (separationA.separation > 0) {
return [];
}
const separationB = SeparatingAxis.findPolygonPolygonSeparation(polyB, polyA);
// If there is no overlap from boxB's perspective exit now
if (separationB.separation > 0) {
return [];
}
// Separations are both negative, we want to pick the least negative (minimal movement)
const separation = separationA.separation > separationB.separation ? separationA : separationB;
// The incident side is the most opposite from the axes of collision on the other collider
const other = separation.collider === polyA ? polyB : polyA;
const incident = other.findSide(separation.axis.negate()) as Line;
// Clip incident side by the perpendicular lines at each end of the reference side
// https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm
const reference = separation.side;
const refDir = reference.dir().normalize();
// Find our contact points by clipping the incident by the collision side
const clipRight = incident.clip(refDir.negate(), -refDir.dot(reference.begin));
let clipLeft: Line | null = null;
if (clipRight) {
clipLeft = clipRight.clip(refDir, refDir.dot(reference.end));
}
// If there is no left there is no collision
if (clipLeft) {
// We only want clip points below the reference edge, discard the others
const points = clipLeft.getPoints().filter((p) => {
return reference.below(p);
});
let normal = separation.axis;
let tangent = normal.perpendicular();
// Point Contact A -> B
if (polyB.worldPos.sub(polyA.worldPos).dot(normal) < 0) {
normal = normal.negate();
tangent = normal.perpendicular();
}
// Points are clipped from incident which is the other collider
// Store those as locals
let localPoints: Vector[] = [];
if (separation.collider === polyA) {
const xf = polyB.owner?.get(TransformComponent) ?? new TransformComponent();
localPoints = points.map((p) => xf.applyInverse(p));
} else {
const xf = polyA.owner?.get(TransformComponent) ?? new TransformComponent();
localPoints = points.map((p) => xf.applyInverse(p));
}
return [new CollisionContact(polyA, polyB, normal.scale(-separation.separation), normal, tangent, points, localPoints, separation)];
}
return [];
},
FindContactSeparation(contact: CollisionContact, localPoint: Vector) {
const shapeA = contact.colliderA;
const txA = contact.colliderA.owner?.get(TransformComponent) ?? new TransformComponent();
const shapeB = contact.colliderB;
const txB = contact.colliderB.owner?.get(TransformComponent) ?? new TransformComponent();
// both are circles
if (shapeA instanceof CircleCollider && shapeB instanceof CircleCollider) {
const combinedRadius = shapeA.radius + shapeB.radius;
const distance = txA.pos.distance(txB.pos);
const separation = combinedRadius - distance;
return -separation;
}
// both are polygons
if (shapeA instanceof PolygonCollider && shapeB instanceof PolygonCollider) {
if (contact.info.localSide) {
let side: Line;
let worldPoint: Vector;
if (contact.info.collider === shapeA) {
side = new Line(txA.apply(contact.info.localSide.begin), txA.apply(contact.info.localSide.end));
worldPoint = txB.apply(localPoint);
} else {
side = new Line(txB.apply(contact.info.localSide.begin), txB.apply(contact.info.localSide.end));
worldPoint = txA.apply(localPoint);
}
return side.distanceToPoint(worldPoint, true);
}
}
// polygon v circle
if (
(shapeA instanceof PolygonCollider && shapeB instanceof CircleCollider) ||
(shapeB instanceof PolygonCollider && shapeA instanceof CircleCollider)
) {
const worldPoint = txA.apply(localPoint);
if (contact.info.side) {
return contact.info.side.distanceToPoint(worldPoint, true);
}
}
// polygon v edge
if (
(shapeA instanceof EdgeCollider && shapeB instanceof PolygonCollider) ||
(shapeB instanceof EdgeCollider && shapeA instanceof PolygonCollider)
) {
let worldPoint: Vector;
if (contact.info.collider === shapeA) {
worldPoint = txB.apply(localPoint);
} else {
worldPoint = txA.apply(localPoint);
}
if (contact.info.side) {
return contact.info.side.distanceToPoint(worldPoint, true);
}
}
// circle v edge
if (
(shapeA instanceof CircleCollider && shapeB instanceof EdgeCollider) ||
(shapeB instanceof CircleCollider && shapeA instanceof EdgeCollider)
) {
// Local point is always on the edge which is always shapeB
const worldPoint = txB.apply(localPoint);
let circlePoint: Vector;
if (shapeA instanceof CircleCollider) {
circlePoint = shapeA.getFurthestPoint(contact.normal);
}
const dist = worldPoint.distance(circlePoint);
if (contact.info.side) {
return dist > 0 ? -dist : 0;
}
}
return 0;
}
}; | the_stack |
declare namespace egret {
/**
* Easing function set. Different easing functions are used to make an animation proceed according to the corresponding equation
* @see http://edn.egret.com/cn/index.php/article/index/id/53 Easing effect Demo
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 缓动函数集合,使用不同的缓动函数使得动画按照对应的方程进行
* @see http://edn.egret.com/cn/index.php/article/index/id/53 缓动效果演示
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
class Ease {
/**
* @version Egret 2.4
* @platform Web,Native
*/
constructor();
/**
* get.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* get。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static get(amount: number): (t: number) => number;
/**
* get pow in.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* get pow in。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static getPowIn(pow: number): (t: number) => number;
/**
* get pow out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* get pow out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static getPowOut(pow: number): (t: number) => number;
/**
* get pow in out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* get pow in out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static getPowInOut(pow: number): (t: number) => number;
/**
* quad in.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* quad in。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static quadIn: (t: number) => number;
/**
* quad out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* quad out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static quadOut: (t: number) => number;
/**
* quad in out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* quad in out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static quadInOut: (t: number) => number;
/**
* cubic in.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* cubic in。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static cubicIn: (t: number) => number;
/**
* cubic out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* cubic out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static cubicOut: (t: number) => number;
/**
* cubic in out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* cubic in out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static cubicInOut: (t: number) => number;
/**
* quart in.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* quart in。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static quartIn: (t: number) => number;
/**
* quart out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* quart out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static quartOut: (t: number) => number;
/**
* quart in out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* quart in out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static quartInOut: (t: number) => number;
/**
* quint in.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* quint in。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static quintIn: (t: number) => number;
/**
* quint out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* quint out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static quintOut: (t: number) => number;
/**
* quint in out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* quint in out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static quintInOut: (t: number) => number;
/**
* sine in.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* sine in。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static sineIn(t: number): number;
/**
* sine out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* sine out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static sineOut(t: number): number;
/**
* sine in out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* sine in out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static sineInOut(t: number): number;
/**
* get back in.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* get back in。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static getBackIn(amount: number): (t: number) => number;
/**
* back in.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* back in。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static backIn: (t: number) => number;
/**
* get back out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* get back out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static getBackOut(amount: number): (t: any) => number;
/**
* back out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* back out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static backOut: (t: any) => number;
/**
* get back in out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* get back in out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static getBackInOut(amount: number): (t: number) => number;
/**
* back in out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* back in out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static backInOut: (t: number) => number;
/**
* circ in.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* circ in。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static circIn(t: number): number;
/**
* circ out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* circ out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static circOut(t: number): number;
/**
* circ in out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* circ in out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static circInOut(t: number): number;
/**
* bounce in.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* bounce in。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static bounceIn(t: number): number;
/**
* bounce out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* bounce out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static bounceOut(t: number): number;
/**
* bounce in out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* bounce in out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static bounceInOut(t: number): number;
/**
* get elastic in.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* get elastic in。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static getElasticIn(amplitude: number, period: number): (t: number) => number;
/**
* elastic in.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* elastic in。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static elasticIn: (t: number) => number;
/**
* get elastic out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* get elastic out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static getElasticOut(amplitude: number, period: number): (t: number) => number;
/**
* elastic out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* elastic out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static elasticOut: (t: number) => number;
/**
* get elastic in out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* get elastic in out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static getElasticInOut(amplitude: number, period: number): (t: number) => number;
/**
* elastic in out.See example.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* elastic in out。请查看示例
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static elasticInOut: (t: number) => number;
}
}
declare namespace egret {
/**
* Tween is the animation easing class of Egret
* @see http://edn.egret.com/cn/docs/page/576 Tween ease animation
* @version Egret 2.4
* @platform Web,Native
* @includeExample extension/tween/Tween.ts
* @language en_US
*/
/**
* Tween是Egret的动画缓动类
* @see http://edn.egret.com/cn/docs/page/576 Tween缓动动画
* @version Egret 2.4
* @platform Web,Native
* @includeExample extension/tween/Tween.ts
* @language zh_CN
*/
class Tween extends EventDispatcher {
/**
* 不做特殊处理
* @constant {number} egret.Tween.NONE
* @private
*/
private static NONE;
/**
* 循环
* @constant {number} egret.Tween.LOOP
* @private
*/
private static LOOP;
/**
* 倒序
* @constant {number} egret.Tween.REVERSE
* @private
*/
private static REVERSE;
/**
* @private
*/
private static _tweens;
/**
* @private
*/
private static IGNORE;
/**
* @private
*/
private static _plugins;
/**
* @private
*/
private static _inited;
/**
* @private
*/
private _target;
/**
* @private
*/
private _useTicks;
/**
* @private
*/
private ignoreGlobalPause;
/**
* @private
*/
private loop;
/**
* @private
*/
private pluginData;
/**
* @private
*/
private _curQueueProps;
/**
* @private
*/
private _initQueueProps;
/**
* @private
*/
private _steps;
/**
* @private
*/
private paused;
/**
* @private
*/
private duration;
/**
* @private
*/
private _prevPos;
/**
* @private
*/
private position;
/**
* @private
*/
private _prevPosition;
/**
* @private
*/
private _stepPosition;
/**
* @private
*/
private passive;
/**
* Activate an object and add a Tween animation to the object
* @param target {any} The object to be activated
* @param props {any} Parameters, support loop onChange onChangeObj
* @param pluginData {any} Write realized
* @param override {boolean} Whether to remove the object before adding a tween, the default value false
* Not recommended, you can use Tween.removeTweens(target) instead.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 激活一个对象,对其添加 Tween 动画
* @param target {any} 要激活 Tween 的对象
* @param props {any} 参数,支持loop(循环播放) onChange(变化函数) onChangeObj(变化函数作用域)
* @param pluginData {any} 暂未实现
* @param override {boolean} 是否移除对象之前添加的tween,默认值false。
* 不建议使用,可使用 Tween.removeTweens(target) 代替。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static get(target: any, props?: {
loop?: boolean;
onChange?: Function;
onChangeObj?: any;
}, pluginData?: any, override?: boolean): Tween;
/**
* Delete all Tween animations from an object
* @param target The object whose Tween to be deleted
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 删除一个对象上的全部 Tween 动画
* @param target 需要移除 Tween 的对象
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static removeTweens(target: any): void;
/**
* Pause all Tween animations of a certain object
* @param target The object whose Tween to be paused
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 暂停某个对象的所有 Tween
* @param target 要暂停 Tween 的对象
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static pauseTweens(target: any): void;
/**
* Resume playing all easing of a certain object
* @param target The object whose Tween to be resumed
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 继续播放某个对象的所有缓动
* @param target 要继续播放 Tween 的对象
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static resumeTweens(target: any): void;
/**
* @private
*
* @param delta
* @param paused
*/
private static tick(timeStamp, paused?);
private static _lastTime;
/**
* @private
*
* @param tween
* @param value
*/
private static _register(tween, value);
/**
* Delete all Tween
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 删除所有 Tween
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static removeAllTweens(): void;
/**
* 创建一个 egret.Tween 对象
* @private
* @version Egret 2.4
* @platform Web,Native
*/
constructor(target: any, props: any, pluginData: any);
/**
* @private
*
* @param target
* @param props
* @param pluginData
*/
private initialize(target, props, pluginData);
/**
* @private
*
* @param value
* @param actionsMode
* @returns
*/
setPosition(value: number, actionsMode?: number): boolean;
/**
* @private
*
* @param startPos
* @param endPos
* @param includeStart
*/
private _runAction(action, startPos, endPos, includeStart?);
/**
* @private
*
* @param step
* @param ratio
*/
private _updateTargetProps(step, ratio);
/**
* Whether setting is paused
* @param value {boolean} Whether to pause
* @returns Tween object itself
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 设置是否暂停
* @param value {boolean} 是否暂停
* @returns Tween对象本身
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
setPaused(value: boolean): Tween;
/**
* @private
*
* @param props
* @returns
*/
private _cloneProps(props);
/**
* @private
*
* @param o
* @returns
*/
private _addStep(o);
/**
* @private
*
* @param o
* @returns
*/
private _appendQueueProps(o);
/**
* @private
*
* @param o
* @returns
*/
private _addAction(o);
/**
* @private
*
* @param props
* @param o
*/
private _set(props, o);
/**
* Wait the specified milliseconds before the execution of the next animation
* @param duration {number} Waiting time, in milliseconds
* @param passive {boolean} Whether properties are updated during the waiting time
* @returns Tween object itself
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 等待指定毫秒后执行下一个动画
* @param duration {number} 要等待的时间,以毫秒为单位
* @param passive {boolean} 等待期间属性是否会更新
* @returns Tween对象本身
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
wait(duration: number, passive?: boolean): Tween;
/**
* Modify the property of the specified object to a specified value
* @param props {Object} Property set of an object
* @param duration {number} Duration
* @param ease {egret.Ease} Easing algorithm
* @returns {egret.Tween} Tween object itself
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 将指定对象的属性修改为指定值
* @param props {Object} 对象的属性集合
* @param duration {number} 持续时间
* @param ease {egret.Ease} 缓动算法
* @returns {egret.Tween} Tween对象本身
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
to(props: any, duration?: number, ease?: Function): Tween;
/**
* Execute callback function
* @param callback {Function} Callback method
* @param thisObj {any} this action scope of the callback method
* @param params {any[]} Parameter of the callback method
* @returns {egret.Tween} Tween object itself
* @version Egret 2.4
* @platform Web,Native
* @example
* <pre>
* egret.Tween.get(display).call(function (a:number, b:string) {
* console.log("a: " + a); // the first parameter passed 233
* console.log("b: " + b); // the second parameter passed “hello”
* }, this, [233, "hello"]);
* </pre>
* @language en_US
*/
/**
* 执行回调函数
* @param callback {Function} 回调方法
* @param thisObj {any} 回调方法this作用域
* @param params {any[]} 回调方法参数
* @returns {egret.Tween} Tween对象本身
* @version Egret 2.4
* @platform Web,Native
* @example
* <pre>
* egret.Tween.get(display).call(function (a:number, b:string) {
* console.log("a: " + a); //对应传入的第一个参数 233
* console.log("b: " + b); //对应传入的第二个参数 “hello”
* }, this, [233, "hello"]);
* </pre>
* @language zh_CN
*/
call(callback: Function, thisObj?: any, params?: any[]): Tween;
/**
* Now modify the properties of the specified object to the specified value
* @param props {Object} Property set of an object
* @param target The object whose Tween to be resumed
* @returns {egret.Tween} Tween object itself
* @version Egret 2.4
* @platform Web,Native
*/
/**
* 立即将指定对象的属性修改为指定值
* @param props {Object} 对象的属性集合
* @param target 要继续播放 Tween 的对象
* @returns {egret.Tween} Tween对象本身
* @version Egret 2.4
* @platform Web,Native
*/
set(props: any, target?: any): Tween;
/**
* Execute
* @param tween {egret.Tween} The Tween object to be operated. Default: this
* @returns {egret.Tween} Tween object itself
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 执行
* @param tween {egret.Tween} 需要操作的 Tween 对象,默认this
* @returns {egret.Tween} Tween对象本身
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
play(tween?: Tween): Tween;
/**
* Pause
* @param tween {egret.Tween} The Tween object to be operated. Default: this
* @returns {egret.Tween} Tween object itself
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 暂停
* @param tween {egret.Tween} 需要操作的 Tween 对象,默认this
* @returns {egret.Tween} Tween对象本身
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
pause(tween?: Tween): Tween;
/**
* @method egret.Tween#tick
* @param delta {number}
* @private
* @version Egret 2.4
* @platform Web,Native
*/
$tick(delta: number): void;
}
}
declare namespace egret.tween {
type EaseType = 'quadIn' | 'quadOut' | 'quadOut' | 'quadInOut' | 'cubicIn' | 'cubicOut' | 'cubicInOut' | 'quartIn' | 'quartOut' | 'quartInOut' | 'quintIn' | 'quintOut' | 'quintInOut' | 'sineIn' | 'sineOut' | 'sineInOut' | 'backIn' | 'backOut' | 'backInOut' | 'circIn' | 'circOut' | 'circInOut' | 'bounceIn' | 'bounceOut' | 'bounceInOut' | 'elasticIn' | 'elasticOut' | 'elasticInOut';
/**
* Abstract class, Indicate the base action.
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* 抽象类,表示一个基本动作
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
abstract class BasePath extends EventDispatcher {
/**
* the name of this action.
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* 动作的名称
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
name: string;
}
/**
* Indicate the to action. See <code>Tween.to</code>
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* 表示一个to动作,参见<code>Tween.to</code>
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
class To extends BasePath {
/**
* Property set of an object
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* 对象的属性集合
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
props: Object;
/**
* Duration
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* 持续时间
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
duration: number;
/**
* Easing algorithm
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* 缓动算法
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
ease: EaseType | Function;
}
/**
* Indicate the wait action. See <code>Tween.wait</code>
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* 表示一个wait动作,参见<code>Tween.wait</code>
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
class Wait extends BasePath {
/**
* Duration
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* 持续时间
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
duration: number;
/**
* Whether properties are updated during the waiting time
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* 等待期间属性是否会更新
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
passive: boolean;
}
/**
* Indicate the set action. See <code>Tween.set</code>
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* 表示一个set动作,参见<code>Tween.set</code>
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
class Set extends BasePath {
/**
* Property set of an object
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* 对象的属性集合
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
props: Object;
}
/**
* Indicate the tick action. See <code>Tween.tick</code>
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* 表示一个tick动作,参见<code>Tween.tick</code>
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
class Tick extends BasePath {
/**
* Delta time
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* 增加的时间
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
delta: number;
}
/**
* TweenItem is a wrapper for Tween, which can set the behavior of Tween by setting attributes and adding Path.
*
* @event pathComplete Dispatched when some Path has complete.
* @event complete Dispatched when all Paths has complete.
*
* @defaultProperty props
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* TweenItem是对Tween的包装器,能通过设置属性和添加Path的方式设置Tween的行为。
* 通常用于使用在EXML中定义组件的动画。
*
* @event pathComplete 当某个Path执行完毕时会派发此事件。
* @event complete 当所有Path执行完毕时会派发此事件。
*
* @defaultProperty props
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
/**
* Use in exml:
* ```
* <tween:TweenItem target="{this.button}">
* <tween:props>
* <e:Object loop="{true}"/>
* </tween:props>
* <tween:paths>
* <e:Array>
* <tween:To duration="500">
* <tween:props>
* <e:Object x="{100}" y="{200}" />
* </tween:props>
* </tween:To>
* <tween:Wait duration="1000" />
* <tween:To duration="1000">
* <tween:props>
* <e:Object x="{200}" y="{100}" />
* </tween:props>
* </tween:To>
* </e:Array>
* </tween:paths>
* </tween:TweenItem>
* ```
*/
class TweenItem extends EventDispatcher {
private tween;
constructor();
/**
* @private
*/
private _props;
/**
* The Tween's props.
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* Tween的props参数。
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
props: any;
/**
* @private
*/
private _target;
/**
* The Tween's target.
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* Tween的target参数。
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
target: any;
/**
* @private
*/
private _paths;
/**
* The Actions in Tween.
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* TweenItem中添加的行为。
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
paths: BasePath[];
/**
* Play the Tween
* @time The starting position, the default is from the last position to play
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* 播放Tween
* @time 播放的起始位置, 默认为从上次位置继续播放
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
play(time?: number): void;
/**
* Pause the Tween
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* 暂停Tween
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
pause(): void;
/**
* Stop the Tween
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* 停止Tween
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
stop(): void;
private createTween();
private applyPaths();
private applyPath(path);
private pathComplete(path);
}
/**
* TweenGroup is a collection of TweenItem that can be played in parallel with each Item
*
* @event itemComplete Dispatched when some TweenItem has complete.
* @event complete Dispatched when all TweenItems has complete.
*
* @version Egret 3.1.8
* @platform Web,Native
* @includeExample extension/tween/TweenWrapper.ts
* @language en_US
*/
/**
* TweenGroup是TweenItem的集合,可以并行播放每一个Item
* @version Egret 3.1.8
* @platform Web,Native
* @includeExample extension/tween/TweenWrapper.ts
* @language zh_CN
*/
class TweenGroup extends EventDispatcher {
private completeCount;
constructor();
/**
* @private
*/
private _items;
/**
* The Array that TweenItems in TweenGroup.
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* TweenGroup要控制的TweenItem集合。
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
items: TweenItem[];
private registerEvent(add);
/**
* Play the all TweenItems
* @time The starting position, the default is from the last position to play。If use 0, the group will play from the start position.
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* 播放所有的TweenItem
* @time 播放的起始位置, 默认为从上次位置继续播放。如果为0,则从起始位置开始播放。
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
play(time?: number): void;
/**
* Pause the all TweenItems
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* 暂停播放所有的TweenItem
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
pause(): void;
/**
* Stop the all TweenItems
* @version Egret 3.1.8
* @platform Web,Native
* @language en_US
*/
/**
* 停止所有的TweenItem
* @version Egret 3.1.8
* @platform Web,Native
* @language zh_CN
*/
stop(): void;
private itemComplete(e);
}
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement, Operator } from "../shared";
/**
* Statement provider for service [nimble](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonnimblestudio.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Nimble extends PolicyStatement {
public servicePrefix = 'nimble';
/**
* Statement provider for service [nimble](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonnimblestudio.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 accept EULAs
*
* Access Level: Write
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-eula-acceptances.html
*/
public toAcceptEulas() {
return this.to('AcceptEulas');
}
/**
* Grants permission to create a launch profile
*
* Access Level: Write
*
* Dependent actions:
* - ec2:CreateNetworkInterface
* - ec2:RunInstances
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-launch-profiles.html
*/
public toCreateLaunchProfile() {
return this.to('CreateLaunchProfile');
}
/**
* Grants permission to create a streaming image
*
* Access Level: Write
*
* Dependent actions:
* - ec2:DescribeImages
* - ec2:DescribeSnapshots
* - ec2:ModifyInstanceAttribute
* - ec2:ModifySnapshotAttribute
* - ec2:RegisterImage
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-streaming-images.html
*/
public toCreateStreamingImage() {
return this.to('CreateStreamingImage');
}
/**
* Grants permission to create a streaming session
*
* Access Level: Write
*
* Dependent actions:
* - ec2:CreateNetworkInterface
* - ec2:CreateNetworkInterfacePermission
* - nimble:GetLaunchProfile
* - nimble:GetLaunchProfileInitialization
* - nimble:ListEulaAcceptances
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-streaming-sessions.html
*/
public toCreateStreamingSession() {
return this.to('CreateStreamingSession');
}
/**
* Grants permission to create a StreamingSessionStream
*
* Access Level: Write
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-streaming-sessions-sessionid-streams.html
*/
public toCreateStreamingSessionStream() {
return this.to('CreateStreamingSessionStream');
}
/**
* Grants permission to create a studio
*
* Access Level: Write
*
* Dependent actions:
* - iam:PassRole
* - sso:CreateManagedApplicationInstance
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios.html
*/
public toCreateStudio() {
return this.to('CreateStudio');
}
/**
* Grants permission to create a studio component. A studio component designates a network resource to which a launch profile will provide access
*
* Access Level: Write
*
* Dependent actions:
* - ds:AuthorizeApplication
* - ds:DescribeDirectories
* - ec2:DescribeSecurityGroups
* - fsx:DescribeFileSystems
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-studio-components.html
*/
public toCreateStudioComponent() {
return this.to('CreateStudioComponent');
}
/**
* Grants permission to delete a launch profile
*
* Access Level: Write
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-launch-profiles-launchprofileid.html
*/
public toDeleteLaunchProfile() {
return this.to('DeleteLaunchProfile');
}
/**
* Grants permission to delete a launch profile member
*
* Access Level: Write
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-launch-profiles-launchprofileid-membership-principalid.html
*/
public toDeleteLaunchProfileMember() {
return this.to('DeleteLaunchProfileMember');
}
/**
* Grants permission to delete a streaming image
*
* Access Level: Write
*
* Dependent actions:
* - ec2:DeleteSnapshot
* - ec2:DeregisterImage
* - ec2:ModifyInstanceAttribute
* - ec2:ModifySnapshotAttribute
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-streaming-images-streamingimageid.html
*/
public toDeleteStreamingImage() {
return this.to('DeleteStreamingImage');
}
/**
* Grants permission to delete a streaming session
*
* Access Level: Write
*
* Dependent actions:
* - ec2:DeleteNetworkInterface
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-streaming-sessions-sessionid.html
*/
public toDeleteStreamingSession() {
return this.to('DeleteStreamingSession');
}
/**
* Grants permission to delete a studio
*
* Access Level: Write
*
* Dependent actions:
* - sso:DeleteManagedApplicationInstance
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid.html
*/
public toDeleteStudio() {
return this.to('DeleteStudio');
}
/**
* Grants permission to delete a studio component
*
* Access Level: Write
*
* Dependent actions:
* - ds:UnauthorizeApplication
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-studio-components-studiocomponentid.html
*/
public toDeleteStudioComponent() {
return this.to('DeleteStudioComponent');
}
/**
* Grants permission to delete a studio member
*
* Access Level: Write
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-membership-principalid.html
*/
public toDeleteStudioMember() {
return this.to('DeleteStudioMember');
}
/**
* Grants permission to get a EULA
*
* Access Level: Read
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/eulas-eulaid.html
*/
public toGetEula() {
return this.to('GetEula');
}
/**
* Grants permission to allow Nimble Studio portal to show the appropriate features for this account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/nimble-studio/latest/userguide/security-iam-service-with-iam.html
*/
public toGetFeatureMap() {
return this.to('GetFeatureMap');
}
/**
* Grants permission to get a launch profile
*
* Access Level: Read
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-launch-profiles-launchprofileid.html
*/
public toGetLaunchProfile() {
return this.to('GetLaunchProfile');
}
/**
* Grants permission to get a launch profile's details, which includes the summary of studio components and streaming images used by the launch profile
*
* Access Level: Read
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-launch-profiles-launchprofileid-details.html
*/
public toGetLaunchProfileDetails() {
return this.to('GetLaunchProfileDetails');
}
/**
* Grants permission to get a launch profile initialization. A launch profile initialization is a dereferenced version of a launch profile, including attached studio component connection information
*
* Access Level: Read
*
* Dependent actions:
* - ds:DescribeDirectories
* - ec2:DescribeSecurityGroups
* - fsx:DescribeFileSystems
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-launch-profiles-launchprofileid-init.html
*/
public toGetLaunchProfileInitialization() {
return this.to('GetLaunchProfileInitialization');
}
/**
* Grants permission to get a launch profile member
*
* Access Level: Read
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-launch-profiles-launchprofileid-init.html
*/
public toGetLaunchProfileMember() {
return this.to('GetLaunchProfileMember');
}
/**
* Grants permission to get a streaming image
*
* Access Level: Read
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-streaming-images-streamingimageid.html
*/
public toGetStreamingImage() {
return this.to('GetStreamingImage');
}
/**
* Grants permission to get a streaming session
*
* Access Level: Read
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-streaming-sessions-sessionid.html
*/
public toGetStreamingSession() {
return this.to('GetStreamingSession');
}
/**
* Grants permission to get a streaming session stream
*
* Access Level: Read
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-streaming-sessions-sessionid-streams-streamid.html
*/
public toGetStreamingSessionStream() {
return this.to('GetStreamingSessionStream');
}
/**
* Grants permission to get a studio
*
* Access Level: Read
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid.html
*/
public toGetStudio() {
return this.to('GetStudio');
}
/**
* Grants permission to get a studio component
*
* Access Level: Read
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-studio-components-studiocomponentid.html
*/
public toGetStudioComponent() {
return this.to('GetStudioComponent');
}
/**
* Grants permission to get a studio member
*
* Access Level: Read
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-membership-principalid.html
*/
public toGetStudioMember() {
return this.to('GetStudioMember');
}
/**
* Grants permission to list EULA acceptances
*
* Access Level: Read
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-eula-acceptances.html
*/
public toListEulaAcceptances() {
return this.to('ListEulaAcceptances');
}
/**
* Grants permission to list EULAs
*
* Access Level: Read
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/eulas.html
*/
public toListEulas() {
return this.to('ListEulas');
}
/**
* Grants permission to list launch profile members
*
* Access Level: Read
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-launch-profiles-launchprofileid-membership.html
*/
public toListLaunchProfileMembers() {
return this.to('ListLaunchProfileMembers');
}
/**
* Grants permission to list launch profiles
*
* Access Level: Read
*
* Possible conditions:
* - .ifPrincipalId()
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-launch-profiles.html
*/
public toListLaunchProfiles() {
return this.to('ListLaunchProfiles');
}
/**
* Grants permission to list streaming images
*
* Access Level: Read
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-streaming-images.html
*/
public toListStreamingImages() {
return this.to('ListStreamingImages');
}
/**
* Grants permission to list streaming sessions
*
* Access Level: Read
*
* Possible conditions:
* - .ifCreatedBy()
* - .ifOwnedBy()
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-streaming-sessions.html
*/
public toListStreamingSessions() {
return this.to('ListStreamingSessions');
}
/**
* Grants permission to list studio components
*
* Access Level: Read
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-studio-components.html
*/
public toListStudioComponents() {
return this.to('ListStudioComponents');
}
/**
* Grants permission to list studio members
*
* Access Level: Read
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-membership.html
*/
public toListStudioMembers() {
return this.to('ListStudioMembers');
}
/**
* Grants permission to list all studios
*
* Access Level: Read
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios.html
*/
public toListStudios() {
return this.to('ListStudios');
}
/**
* Grants permission to list all tags on a Nimble Studio resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-sso-configuration.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to add/update launch profile members
*
* Access Level: Write
*
* Dependent actions:
* - sso-directory:DescribeUsers
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-launch-profiles-launchprofileid-membership.html
*/
public toPutLaunchProfileMembers() {
return this.to('PutLaunchProfileMembers');
}
/**
* Grants permission to report metrics and logs for the Nimble Studio portal to monitor application health
*
* Access Level: Write
*
* https://docs.aws.amazon.com/nimble-studio/latest/userguide/security-iam-service-with-iam.html
*/
public toPutStudioLogEvents() {
return this.to('PutStudioLogEvents');
}
/**
* Grants permission to add/update studio members
*
* Access Level: Write
*
* Dependent actions:
* - sso-directory:DescribeUsers
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-membership.html
*/
public toPutStudioMembers() {
return this.to('PutStudioMembers');
}
/**
* Grants permission to repair the studio's AWS SSO configuration
*
* Access Level: Write
*
* Dependent actions:
* - sso:CreateManagedApplicationInstance
* - sso:GetManagedApplicationInstance
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/tags-resourcearn.html
*/
public toStartStudioSSOConfigurationRepair() {
return this.to('StartStudioSSOConfigurationRepair');
}
/**
* Grants permission to add or overwrite one or more tags for the specified Nimble Studio resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/tags-resourcearn.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to disassociate one or more tags from the specified Nimble Studio resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/tags-resourcearn.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to update a launch profile
*
* Access Level: Write
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-launch-profiles-launchprofileid.html
*/
public toUpdateLaunchProfile() {
return this.to('UpdateLaunchProfile');
}
/**
* Grants permission to update a launch profile member
*
* Access Level: Write
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-launch-profiles-launchprofileid-membership-principalid.html
*/
public toUpdateLaunchProfileMember() {
return this.to('UpdateLaunchProfileMember');
}
/**
* Grants permission to update a streaming image
*
* Access Level: Write
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-streaming-images-streamingimageid.html
*/
public toUpdateStreamingImage() {
return this.to('UpdateStreamingImage');
}
/**
* Grants permission to update a studio
*
* Access Level: Write
*
* Dependent actions:
* - iam:PassRole
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid.html
*/
public toUpdateStudio() {
return this.to('UpdateStudio');
}
/**
* Grants permission to update a studio component
*
* Access Level: Write
*
* Dependent actions:
* - ds:AuthorizeApplication
* - ds:DescribeDirectories
* - ec2:DescribeSecurityGroups
* - fsx:DescribeFileSystems
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-studio-components-studiocomponentid.html
*/
public toUpdateStudioComponent() {
return this.to('UpdateStudioComponent');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"AcceptEulas",
"CreateLaunchProfile",
"CreateStreamingImage",
"CreateStreamingSession",
"CreateStreamingSessionStream",
"CreateStudio",
"CreateStudioComponent",
"DeleteLaunchProfile",
"DeleteLaunchProfileMember",
"DeleteStreamingImage",
"DeleteStreamingSession",
"DeleteStudio",
"DeleteStudioComponent",
"DeleteStudioMember",
"PutLaunchProfileMembers",
"PutStudioLogEvents",
"PutStudioMembers",
"StartStudioSSOConfigurationRepair",
"UpdateLaunchProfile",
"UpdateLaunchProfileMember",
"UpdateStreamingImage",
"UpdateStudio",
"UpdateStudioComponent"
],
"Read": [
"GetEula",
"GetFeatureMap",
"GetLaunchProfile",
"GetLaunchProfileDetails",
"GetLaunchProfileInitialization",
"GetLaunchProfileMember",
"GetStreamingImage",
"GetStreamingSession",
"GetStreamingSessionStream",
"GetStudio",
"GetStudioComponent",
"GetStudioMember",
"ListEulaAcceptances",
"ListEulas",
"ListLaunchProfileMembers",
"ListLaunchProfiles",
"ListStreamingImages",
"ListStreamingSessions",
"ListStudioComponents",
"ListStudioMembers",
"ListStudios",
"ListTagsForResource"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type studio to the statement
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid.html#studios-studioid-model-studio
*
* @param studioId - Identifier for the studioId.
* @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:
* - .ifAwsRequestTag()
* - .ifAwsResourceTag()
* - .ifAwsTagKeys()
* - .ifStudioId()
*/
public onStudio(studioId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:nimble:${Region}:${Account}:studio/${StudioId}';
arn = arn.replace('${StudioId}', studioId);
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 streaming-image to the statement
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-streaming-images-streamingimageid.html#studios-studioid-streaming-images-streamingimageid-model-streamingimage
*
* @param streamingImageId - Identifier for the streamingImageId.
* @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:
* - .ifAwsRequestTag()
* - .ifAwsResourceTag()
* - .ifAwsTagKeys()
* - .ifStudioId()
*/
public onStreamingImage(streamingImageId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:nimble:${Region}:${Account}:streaming-image/${StreamingImageId}';
arn = arn.replace('${StreamingImageId}', streamingImageId);
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 studio-component to the statement
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-studio-components-studiocomponentid.html#studios-studioid-studio-components-studiocomponentid-model-studiocomponent
*
* @param studioComponentId - Identifier for the studioComponentId.
* @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:
* - .ifAwsRequestTag()
* - .ifAwsResourceTag()
* - .ifAwsTagKeys()
* - .ifStudioId()
*/
public onStudioComponent(studioComponentId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:nimble:${Region}:${Account}:studio-component/${StudioComponentId}';
arn = arn.replace('${StudioComponentId}', studioComponentId);
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 launch-profile to the statement
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-launch-profiles-launchprofileid.html#studios-studioid-launch-profiles-launchprofileid-model-launchprofile
*
* @param launchProfileId - Identifier for the launchProfileId.
* @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:
* - .ifAwsRequestTag()
* - .ifAwsResourceTag()
* - .ifAwsTagKeys()
* - .ifStudioId()
*/
public onLaunchProfile(launchProfileId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:nimble:${Region}:${Account}:launch-profile/${LaunchProfileId}';
arn = arn.replace('${LaunchProfileId}', launchProfileId);
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 streaming-session to the statement
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-streaming-sessions-sessionid.html#studios-studioid-streaming-sessions-sessionid-model-streamingsession
*
* @param streamingSessionId - Identifier for the streamingSessionId.
* @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:
* - .ifAwsRequestTag()
* - .ifAwsResourceTag()
* - .ifAwsTagKeys()
* - .ifCreatedBy()
* - .ifOwnedBy()
*/
public onStreamingSession(streamingSessionId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:nimble:${Region}:${Account}:streaming-session/${StreamingSessionId}';
arn = arn.replace('${StreamingSessionId}', streamingSessionId);
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 eula to the statement
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/eulas-eulaid.html#eulas-eulaid-model-eula
*
* @param eulaId - Identifier for the eulaId.
* @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:
* - .ifAwsRequestTag()
* - .ifAwsResourceTag()
* - .ifAwsTagKeys()
* - .ifRequesterPrincipalId()
*/
public onEula(eulaId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:nimble:${Region}:${Account}:eula/${EulaId}';
arn = arn.replace('${EulaId}', eulaId);
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 eula-acceptance to the statement
*
* https://docs.aws.amazon.com/nimble-studio/latest/api/studios-studioid-eula-acceptances.html#studios-studioid-eula-acceptances-prop-listeulaacceptancesoutput-eulaacceptances
*
* @param eulaAcceptanceId - Identifier for the eulaAcceptanceId.
* @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:
* - .ifAwsRequestTag()
* - .ifAwsResourceTag()
* - .ifAwsTagKeys()
* - .ifStudioId()
*/
public onEulaAcceptance(eulaAcceptanceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:nimble:${Region}:${Account}:eula-acceptance/${EulaAcceptanceId}';
arn = arn.replace('${EulaAcceptanceId}', eulaAcceptanceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Filters access based on the createdBy request parameter or the ID of the creator of the resource
*
* https://docs.aws.amazon.com/nimble-studio/latest/userguide/security-iam-service-with-iam.html
*
* Applies to actions:
* - .toListStreamingSessions()
*
* Applies to resource types:
* - streaming-session
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifCreatedBy(value: string | string[], operator?: Operator | string) {
return this.if(`createdBy`, value, operator || 'StringLike');
}
/**
* Filters access based on the ownedBy request parameter or the ID of the owner of the resource
*
* https://docs.aws.amazon.com/nimble-studio/latest/userguide/security-iam-service-with-iam.html
*
* Applies to actions:
* - .toListStreamingSessions()
*
* Applies to resource types:
* - streaming-session
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifOwnedBy(value: string | string[], operator?: Operator | string) {
return this.if(`ownedBy`, value, operator || 'StringLike');
}
/**
* Filters access based on the principalId request parameter
*
* https://docs.aws.amazon.com/nimble-studio/latest/userguide/security-iam-service-with-iam.html
*
* Applies to actions:
* - .toListLaunchProfiles()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifPrincipalId(value: string | string[], operator?: Operator | string) {
return this.if(`principalId`, value, operator || 'StringLike');
}
/**
* Filters access to Nimble Studio portal using the ID of the logged in user
*
* https://docs.aws.amazon.com/nimble-studio/latest/userguide/security-iam-service-with-iam.html
*
* Applies to resource types:
* - eula
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifRequesterPrincipalId(value: string | string[], operator?: Operator | string) {
return this.if(`requesterPrincipalId`, value, operator || 'StringLike');
}
/**
* Filters access to resources in a specific studio
*
* https://docs.aws.amazon.com/nimble-studio/latest/userguide/security-iam-service-with-iam.html
*
* Applies to resource types:
* - studio
* - streaming-image
* - studio-component
* - launch-profile
* - eula-acceptance
*
* @param value The value(s) to check
* @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike`
*/
public ifStudioId(value: string | string[], operator?: Operator | string) {
return this.if(`studioId`, value, operator || 'ArnLike');
}
} | the_stack |
import {CommonModule} from '@angular/common';
import {Component, DebugElement, EventEmitter, Input, NgModule, OnInit, Output, SimpleChanges} from '@angular/core';
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {MatIconModule} from '@angular/material';
import {By} from '@angular/platform-browser';
import {TextBrickModule} from '../../../bricks/text-brick/text-brick';
import {TEXT_BRICK_TAG} from '../../../bricks/text-brick/text-brick.constant';
import {PlaceholderRendererModule} from '../../../modules/components/placeholder-renderer/placeholder-renderer.module';
import {PickOutModule} from '../../../modules/pick-out/pick-out.module';
import {RadarModule} from '../../../modules/radar/radar';
import {TowModule} from '../../../modules/tow/tow';
import {WallModelFactory} from '../../factory/wall-model.factory';
import {IWallModel} from '../../model/interfaces/wall-model.interface';
import {BrickRegistry} from '../../registry/brick-registry.service';
import {WallCanvasBrickComponent, WallCanvasComponent} from '../wall-canvas/wall-canvas';
import {IWallUiApi} from './interfaces/ui-api.interface';
import {IOnWallFocus} from './interfaces/wall-component/on-wall-focus.interface';
import {IOnWallStateChange} from './interfaces/wall-component/on-wall-state-change.interface';
import {IFocusContext} from './interfaces/wall-component/wall-component-focus-context.interface';
import {IWallComponent} from './interfaces/wall-component/wall-component.interface';
import {WallComponent} from './wall.component';
class TestScope {
rootNativeElement: HTMLElement;
component: WallComponent;
debugElement: DebugElement;
fixture: ComponentFixture<WallComponent>;
uiApi: IWallUiApi;
wallModel: IWallModel;
initialize() {
return this.createComponent();
}
getDebugElementByCss(query: string): DebugElement {
return this.debugElement.query(By.css(query));
}
getElementsByTagName(tag: string): HTMLCollectionOf<any> {
return this.rootNativeElement.getElementsByTagName(tag);
}
getElementsByClassName(query: string): HTMLCollectionOf<any> {
return this.rootNativeElement.getElementsByClassName(query);
}
render(): Promise<any> {
this.fixture.detectChanges();
return this.fixture.whenStable();
}
destroy() {
}
private createComponent() {
// Fixture for debugging and testing a component.
this.fixture = TestBed.createComponent(WallComponent);
// DebugElement is abstraction over nativeElement,
// because nativeElement might be different in different environments
this.debugElement = this.fixture.debugElement;
// it's root of component, not direct component so
// type is HTMLElement because we run it in Browser, for mobile nativeElement might be different
this.rootNativeElement = this.fixture.nativeElement;
this.component = this.fixture.componentInstance;
this.wallModel = this.createWallModel();
// simulate the parent setting the input property
this.component.model = this.wallModel;
this.fixture.detectChanges();
const initialChange: SimpleChanges = {
model: {
firstChange: true,
currentValue: this.wallModel,
previousValue: undefined,
isFirstChange: () => true
}
};
this.component.ngOnChanges(initialChange);
this.uiApi = this.wallModel.api.ui;
}
private createWallModel(): IWallModel {
const wallModelFactory: WallModelFactory = TestBed.get(WallModelFactory);
return wallModelFactory.create({});
}
}
@Component({
selector: 'fixture-brick',
template: ``
})
class FixtureComponent implements OnInit, IOnWallStateChange, IOnWallFocus, IWallComponent {
@Input() id: string;
@Input() state: any;
@Input() wallModel: IWallModel;
@Output() stateChanges: EventEmitter<any> = new EventEmitter();
ngOnInit() {
}
onWallFocus(focusContext?: IFocusContext): void {
}
onWallStateChange(state: any): void {
}
}
@NgModule({
exports: [
FixtureComponent
],
declarations: [
FixtureComponent
],
entryComponents: [
FixtureComponent
]
})
class FixtureModule {
constructor(private brickRegistry: BrickRegistry) {
this.brickRegistry.register({
tag: 'fixture',
name: 'Fixture',
component: FixtureComponent,
description: 'Just start writing with plain text'
});
}
}
describe('WallComponent', () => {
let testScope: TestScope;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
CommonModule,
PickOutModule,
TowModule,
RadarModule,
PlaceholderRendererModule,
TextBrickModule,
FixtureModule,
MatIconModule
],
providers: [
BrickRegistry,
WallModelFactory
],
declarations: [
WallComponent,
WallCanvasComponent,
WallCanvasBrickComponent,
]
}).compileComponents();
}));
beforeEach(() => {
testScope = new TestScope();
testScope.initialize();
});
afterEach(() => {
testScope.destroy();
testScope = null;
});
it('should create', () => {
expect(testScope.component).toBeDefined();
});
describe('[Initialization]', () => {
it('should register "ui" api', () => {
expect(testScope.wallModel.api.ui).toBeDefined();
});
});
describe('[Interaction with brick]', () => {
it('should pass id to component', () => {
testScope.wallModel.api.core2.addBrickAtStart('fixture', {});
testScope.fixture.detectChanges();
const fixtureComponent = testScope.getDebugElementByCss('fixture-brick').componentInstance;
expect(fixtureComponent.id).toBeDefined();
});
it('should pass state to component', () => {
const fixtureState = {
foo: 'foo'
};
testScope.wallModel.api.core2.addBrickAtStart('fixture', fixtureState);
testScope.fixture.detectChanges();
const fixtureComponent = testScope.getDebugElementByCss('fixture-brick').componentInstance;
expect(fixtureComponent.state).toEqual(fixtureState);
});
it('should call onWallStateChange callback when state is changed by model', () => {
const brickSnapshot = testScope.wallModel.api.core2.addBrickAtStart('fixture');
testScope.fixture.detectChanges();
const fixtureComponent = testScope.getDebugElementByCss('fixture-brick').componentInstance;
spyOn(fixtureComponent, 'onWallStateChange');
// test action
const newFixtureState = {
foo: 'foo'
};
testScope.wallModel.api.core2.updateBrickState(brickSnapshot.id, newFixtureState);
// bind internal wall component state to the DOM
testScope.fixture.detectChanges();
// test assertions
expect(fixtureComponent.onWallStateChange).toHaveBeenCalled();
const stateChangeArguments = (fixtureComponent.onWallStateChange as jasmine.Spy)
.calls.mostRecent().args;
expect(stateChangeArguments[0]).toEqual(newFixtureState);
});
it('should pass wallModel to component', () => {
testScope.wallModel.api.core2.addBrickAtStart('fixture', {});
testScope.fixture.detectChanges();
const fixtureComponent = testScope.getDebugElementByCss('fixture-brick').componentInstance;
expect(fixtureComponent.wallModel).toEqual(testScope.wallModel);
});
it('should listen changes from @Output stateChanges component property', () => {
const fixtureBrickSnapshot = testScope.wallModel.api.core2.addBrickAtStart('fixture', {});
testScope.fixture.detectChanges();
const fixtureComponent = testScope.getDebugElementByCss('fixture-brick').componentInstance;
spyOn(testScope.wallModel.api.core2, 'updateBrickState');
const newFixtureState = {foo: 'foo'};
// test action
fixtureComponent.stateChanges.emit(newFixtureState);
// test assertions
expect(testScope.wallModel.api.core2.updateBrickState).toHaveBeenCalled();
const updateBrickStateArgs = (testScope.wallModel.api.core2.updateBrickState as jasmine.Spy)
.calls.mostRecent().args;
expect(updateBrickStateArgs[0]).toEqual(fixtureBrickSnapshot.id);
expect(updateBrickStateArgs[1]).toEqual(newFixtureState);
});
it('should call onWallFocus callback', () => {
const fixtureBrickSnapshot = testScope.wallModel.api.core2.addBrickAtStart('fixture');
testScope.fixture.detectChanges();
const fixtureComponent = testScope.getDebugElementByCss('fixture-brick').componentInstance;
spyOn(fixtureComponent, 'onWallFocus');
// test action
testScope.uiApi.mode.edit.focusOnBrickId(fixtureBrickSnapshot.id);
testScope.fixture.detectChanges();
// test assertion
expect(fixtureComponent.onWallFocus).toHaveBeenCalled();
});
it('should pass onWallFocus context', () => {
const fixtureBrickSnapshot = testScope.wallModel.api.core2.addBrickAtStart('fixture', {});
testScope.fixture.detectChanges();
const fixtureComponent = testScope.getDebugElementByCss('fixture-brick').componentInstance;
spyOn(fixtureComponent, 'onWallFocus');
// test action
const focusContext = {initiator: '', details: 'foo'};
testScope.uiApi.mode.edit.focusOnBrickId(fixtureBrickSnapshot.id, focusContext);
testScope.fixture.detectChanges();
// test assertion
const wallFocusArgs = (fixtureComponent.onWallFocus as jasmine.Spy)
.calls.mostRecent().args;
expect(wallFocusArgs[0]).toBe(focusContext);
});
});
describe('[Canvas UI interaction]', () => {
it('should add default brick when user clicks by expander', async(() => {
// test action
testScope.getElementsByClassName('wall-canvas__expander')[0].click();
testScope.render().then(() => {
// test assertion
const textBrickElement = testScope.getElementsByTagName('text-brick')[0];
expect(textBrickElement).toBeDefined();
});
}));
});
describe('[UI Api]', () => {
describe('selectBrick()', () => {
it('should select brick', () => {
const textBrickSnapshot = testScope.wallModel.api.core2.addBrickAtStart('text');
// test action
testScope.uiApi.mode.navigation.selectBrick(textBrickSnapshot.id);
// test assertions
const selectedBricks = testScope.uiApi.mode.navigation.getSelectedBrickIds();
expect(selectedBricks.length).toBe(1);
expect(selectedBricks[0]).toBe(textBrickSnapshot.id);
});
it('should trigger SelectedBrick event after brick selection', () => {
const textBrickSnapshot = testScope.wallModel.api.core2.addBrickAtStart('text');
let selectedBrickIds;
testScope.uiApi.mode.navigation.selectedBricks$.subscribe((e) => selectedBrickIds = e);
// test action
testScope.uiApi.mode.navigation.selectBrick(textBrickSnapshot.id);
expect(selectedBrickIds).toBeDefined();
expect(selectedBrickIds).toEqual([textBrickSnapshot.id]);
});
it('should select new brick and discard previous', () => {
const textBrickSnapshot1 = testScope.wallModel.api.core2.addBrickAtStart('text');
const textBrickSnapshot2 = testScope.wallModel.api.core2.addBrickAtStart('text');
testScope.uiApi.mode.navigation.selectBrick(textBrickSnapshot1.id);
expect(testScope.uiApi.mode.navigation.getSelectedBrickIds().length).toBe(1);
expect(testScope.uiApi.mode.navigation.getSelectedBrickIds()[0]).toBe(textBrickSnapshot1.id);
// test action
testScope.uiApi.mode.navigation.selectBrick(textBrickSnapshot2.id);
expect(testScope.uiApi.mode.navigation.getSelectedBrickIds().length).toBe(1);
expect(testScope.uiApi.mode.navigation.getSelectedBrickIds()[0]).toBe(textBrickSnapshot2.id);
});
it('should select few bricks', () => {
const textBrickSnapshot1 = testScope.wallModel.api.core2.addBrickAtStart('text');
const textBrickSnapshot2 = testScope.wallModel.api.core2.addBrickAfterBrickId(textBrickSnapshot1.id, 'text');
// test action
testScope.uiApi.mode.navigation.selectBricks([textBrickSnapshot1.id, textBrickSnapshot2.id]);
// test assertions
const selectedBricks = testScope.uiApi.mode.navigation.getSelectedBrickIds();
expect(selectedBricks.length).toBe(2);
expect(selectedBricks[0]).toBe(textBrickSnapshot1.id);
expect(selectedBricks[1]).toBe(textBrickSnapshot2.id);
});
it('should sort selected bricks based their layout position', () => {
const textBrickSnapshot1 = testScope.wallModel.api.core2.addBrickAtStart('text');
const textBrickSnapshot2 = testScope.wallModel.api.core2.addBrickAfterBrickId(textBrickSnapshot1.id, 'text');
// test action
testScope.uiApi.mode.navigation.selectBricks([textBrickSnapshot2.id, textBrickSnapshot1.id]);
// test assertions
const selectedBricks = testScope.uiApi.mode.navigation.getSelectedBrickIds();
expect(selectedBricks.length).toBe(2);
expect(selectedBricks[0]).toBe(textBrickSnapshot1.id);
expect(selectedBricks[1]).toBe(textBrickSnapshot2.id);
});
it('should trigger SelectedBrickEvent event after brick selections', () => {
testScope.wallModel.api.core2.addDefaultBrick();
testScope.wallModel.api.core2.addDefaultBrick();
let selectedBrickIds;
testScope.uiApi.mode.navigation.selectedBricks$.subscribe((e) => selectedBrickIds = e);
const brickIds = testScope.wallModel.api.core2.getBrickIds();
// test action
testScope.uiApi.mode.navigation.selectBricks(brickIds);
expect(selectedBrickIds).toEqual(brickIds);
});
});
describe('unSelectBricks()', () => {
it('should unselect all brick ids', () => {
testScope.wallModel.api.core2.addDefaultBrick();
// test action
testScope.uiApi.mode.navigation.selectBricks(testScope.wallModel.api.core2.getBrickIds());
expect(testScope.uiApi.mode.navigation.getSelectedBrickIds().length).toBe(1);
// test assertions
testScope.uiApi.mode.navigation.unSelectAllBricks();
expect(testScope.uiApi.mode.navigation.getSelectedBrickIds().length).toBe(0);
});
it('should trigger SelectedBrickEvent event after brick unselection', () => {
testScope.wallModel.api.core2.addDefaultBrick();
// test action
testScope.uiApi.mode.navigation.selectBricks(testScope.wallModel.api.core2.getBrickIds());
expect(testScope.uiApi.mode.navigation.getSelectedBrickIds().length).toBe(1);
let selectedBrickIds;
testScope.uiApi.mode.navigation.selectedBricks$.subscribe((e) => selectedBrickIds = e);
// test assertions
testScope.uiApi.mode.navigation.unSelectAllBricks();
// test assertions
expect(selectedBrickIds).toEqual([]);
});
});
describe('focusOnPreviousTextBrick()', () => {
it('should call onWallFocus callback', async(() => {
const brickSnapshot1 = testScope.wallModel.api.core2.addBrickAtStart('text');
const brickSnapshot2 = testScope.wallModel.api.core2.addBrickAfterBrickId(brickSnapshot1.id, 'fixture');
testScope.render().then(() => {
const textBrickDebugElement = testScope.getDebugElementByCss('text-brick');
spyOn(textBrickDebugElement.componentInstance, 'onWallFocus');
// test action
testScope.uiApi.mode.edit.focusOnPreviousTextBrick(brickSnapshot2.id);
testScope.fixture.detectChanges();
// test assertion
expect(textBrickDebugElement.componentInstance.onWallFocus).toHaveBeenCalled();
});
}));
it('should pass focus context', async(() => {
const brickSnapshot1 = testScope.wallModel.api.core2.addBrickAtStart('text');
const brickSnapshot2 = testScope.wallModel.api.core2.addBrickAfterBrickId(brickSnapshot1.id, 'fixture');
testScope.render().then(() => {
const textBrickDebugElement = testScope.getDebugElementByCss('text-brick');
spyOn(textBrickDebugElement.componentInstance, 'onWallFocus');
// test action
const focusContext = {
initiator: 'unit-test',
details: 'foo'
};
testScope.uiApi.mode.edit.focusOnPreviousTextBrick(brickSnapshot2.id, focusContext);
testScope.fixture.detectChanges();
// test assertion
expect(textBrickDebugElement.componentInstance.onWallFocus).toHaveBeenCalled();
const onWallFocusArgs = (textBrickDebugElement.componentInstance.onWallFocus as jasmine.Spy)
.calls.mostRecent().args;
expect(onWallFocusArgs[0]).toEqual(focusContext);
});
}));
});
});
describe('[Model events reaction]', () => {
it('should render default brick', () => {
testScope.wallModel.api.core2.addDefaultBrick();
testScope.fixture.detectChanges();
expect(testScope.getElementsByTagName('text-brick').length).toBe(1);
});
it('should render text brick and pass state', async(() => {
const textBrickState = {
text: 'initial'
};
testScope.wallModel.api.core2.addBrickAtStart(TEXT_BRICK_TAG, textBrickState);
testScope.render().then(() => {
const textBrickElement = testScope.getElementsByTagName('text-brick')[0];
expect(textBrickState.text).toBe(textBrickElement.getElementsByTagName('p')[0].innerText);
});
}));
});
}); | the_stack |
interface ISO8601DateString extends String {}
/**
* Payload of an error sent to TrackJS. Useful when manipulating errors via
* the `onError` callback.
*/
interface TrackJSPayload {
/**
* Stack trace at time of asynchronous callback binding.
*/
bindStack?: string;
/**
* Timestamp of the asynchronous callback binding.
*/
bindTime?: ISO8601DateString;
/**
* Telemetry logs gathered from the console.
*/
console: {
/** Timestamp the event occurred */
timestamp: ISO8601DateString;
/** Console sevity of the event */
severity: string;
/** Formatted message captured */
message: string;
}[];
/**
* Context provided about the current customer (you)
*/
customer: {
/** Customer application id */
application?: string;
/** Unique Id describing the current page view */
correlationId: string;
/** Customer-provided visitor session ID */
sessionId?: string;
/** Customer token */
token: string;
/** Customer-provided visitor user ID */
userId?: string;
/** Customer-provided system version ID */
version?: string;
};
/**
* How the error was captured. Can be "window","direct","global", "ajax" or
* "catch"
*/
entry: string;
/**
* Context about the browser environment
*/
environment: {
/** How long the visitor has been on the page in MS */
age: number;
/**
* Other discovered JavaScript libraries on the DOM. Hashmap of
* name: version pairs.
*/
dependencies: { [name: string]: string };
/** browser userAgent string */
userAgent: string;
/** current window height */
viewportHeight: number;
/** current window width */
viewportWidth: number;
};
/**
* Custom environment metadata.
*/
metadata: {
/** metadata group name */
key: string;
/** metadata value */
value: string;
}[];
/** Error message */
message: string;
/**
* Telemetry logs gathered from the network.
*/
network: {
/** Timestamp the request started */
startedOn: ISO8601DateString;
/** Timestamp the request completed */
completedOn: ISO8601DateString;
/** HTTP Method used */
method: string;
/** URL Requested */
url: string;
/** HTTP Status Code */
statusCode: number;
/** HTTP Status Text */
statusText: string;
}[];
/** location of the browser at the time of the error */
url: string;
/** stack trace */
stack: string;
/** client-reported time the error occurred */
timestamp: ISO8601DateString;
/**
* Telemetry logs gathered from the visitor.
*/
visitor: {
/** timestamp the event occurred */
timestamp: ISO8601DateString;
/** visitor action taken. "input" or "click" */
action: string;
/** DOM element acted upon */
element: {
/** name of the element tag. IE "input" */
tag: string;
/** hashmap of element attributes */
attributes: { [attributeName: string]: string };
/** value of the element */
value: {
/** Number of characters in the value */
length: number;
/** Patterns describing the value. */
pattern: string;
};
};
}[];
/** version of the tracker.js lib */
version: string;
/** Number of messages throttled clientside */
throttled: number;
}
/**
* Configuration options that can be passed to `trackJs.configure()`
*/
interface TrackJSOptions {
/**
* Whether duplicate errors should be suppressed before sending.
* default true.
*/
dedupe?: boolean;
/**
* Custom handler to be notified *before* an error is transmitted. Can be used
* to modify or ignore error data.
*/
onError?: (payload: TrackJSPayload) => boolean;
/**
* Custom handler for serializing non-string data in errors and telemetry
* events.
*/
serialize?: (what: any) => string;
/**
* Customer-provided identification of the visitor session. Use this to
* correlate TrackJS Error reports with other reporting data.
*/
sessionId?: string;
/**
* Customer-provided identification of the visitor. Use this to identify the
* current user.
*/
userId?: string;
/**
* Customer-provided identification of the running system. Use this to
* identify the version of the code running. Recommend to use either a SEMVER
* representation, or a VCS Hash Key.
*/
version?: string;
}
/**
* Configuration options that are initialized from `window._trackJs`
*/
interface TrackJSInitOptions extends TrackJSOptions {
/**
* Your account token. Get this from `https://my.trackjs.com/install`
*/
token: string;
/**
* Whether the tracker script is enabled. Default true.
*/
enabled?: boolean;
/**
* TrackJS Application token. Get this from `https://my.trackjs.com/Account/Applications`
*/
application?: string;
/**
* Options for recording errors from native callback interfaces, such as
* `setTimeout` and `addEventListener`.
*/
callback?: {
/**
* Whether errors should be recorded when caught from callback functions.
* default true.
*/
enabled?: boolean;
/**
* Whether stack traces should be generated at the time of invocation of an
* asynchronous action. This will produce stack traces similar to the
* "async" traces in Chrome Developer tools.
* There is a performance impact to enabling this. Confirm behavior in your
* application before releasing.
* default false.
*/
bindStack?: boolean;
};
/**
* Options for recording errors and telemetry from the console.
*/
console?: {
/**
* Whether events should be recorded from the console.
* default true.
*/
enabled?: boolean;
/**
* Whether console messages should be passed through to the browser console
* or hidden by TrackJS. Useful for removing debug messaging from production.
* default true.
*/
display?: boolean;
/**
* Whether an error should be recorded by a call to `console.error`.
* default true.
*/
error?: boolean;
/**
* Limit the console functions to be watched by whitelisting them here.
* default ["log","debug","info","warn","error"]
*/
watch?: string[];
};
/**
* Options for recording errors and telemetry from the network.
*/
network?: {
/**
* Whether events should be recorded from the network.
* default true.
*/
enabled?: boolean;
/**
* Whether an error should be recorded by XHR responses with status code
* 400 or greater.
* default true.
*/
error?: boolean;
};
/**
* Options for recording telemetry from the visitor.
*/
visitor?: {
/**
* Whether events should be recorded from the visitor actions.
* default true.
*/
enabled?: boolean;
};
/**
* Options for recording errors from the global window.
*/
window?: {
/**
* Whether events should be recorded from globally unhandled errors.
* default true.
*/
enabled?: boolean;
/**
* Whether events should be recorded from globally unhandled promise
* rejections, if supported. default true.
*/
promise?: boolean;
};
}
/**
* The TrackJS global namespace for functions.
*/
interface TrackJSStatic {
/**
* Adds a new key-value pair to the metadata store. If the key already exists
* it will be updated.
*
* @param {String} key
* @param {String} value
*/
addMetadata(key: string, value: string): void;
/**
* Invokes the provided function within a try/catch wrapper that forwards
* the error to TrackJS.
*
* @param {Function} func The function to be invoked.
* @param {Object} context The context to invoke the function with.
* @param {...} Additional arguments passed to the function.
* @return {*} Output of the function.
*/
attempt(func: Function, context?: any, ...args: any[]): any;
/**
* Configures the instance of TrackJS with the provided configuration.
*
* @param {Object} options The Configuration object to apply
* @returns {Boolean} True if the configuration was successful.
*/
configure(options: TrackJSOptions): boolean;
/**
* Non-exposed browser console logging. Use this private console to prevent
* messages from being exposed into the standard browser console.
*/
console: {
/**
* Records context into the Telemetry log with normal severity
*
* @param {...} args Arguments to be serialized into the Telemetry log.
*/
log(...args: any[]): void;
/**
* Records context into the Telemetry log with DEBUG severity
*
* @param {...} args Arguments to be serialized into the Telemetry log.
*/
debug(...args: any[]): void;
/**
* Records context into the Telemetry log with INFO severity
*
* @param {...} args Arguments to be serialized into the Telemetry log.
*/
info(...args: any[]): void;
/**
* Records context into the Telemetry log with WARN severity
*
* @param {...} args Arguments to be serialized into the Telemetry log.
*/
warn(...args: any[]): void;
/**
* Records context into the Telemetry log with ERROR severity. If console
* errors are enabled, which is default, this will also transmit an error.
*
* @param {...} args Arguments to be serialized into the Telemetry log.
*/
error(...args: any[]): void;
};
/**
* Removes a key from the metadata store, if it exists.
*
* @param {String} key
*/
removeMetadata(key: string): void;
/**
* Directly invokes an error to be sent to TrackJS.
*
* @param {Error|Object|String} error The error to be tracked. If error does
* not have a stacktrace, will attempt to generate one.
*/
track(error: Error | Object | String): void;
/**
* Returns a wrapped and watched version of the function to automatically
* catch any errors that may arise.
*
* @param {Function} func The function to be watched.
* @param {Object} context The context to invoke the function with.
* @return {Function} Wrapped function
*/
watch(func: Function, context?: any): Function;
/**
* Wrap and watch all of the functions on an object that will
* automatically catch any errors that may arise.
*
* @param {Object} obj The Object containing functions to be watched
* @return {Object} Object now containing wrapped functions.
*/
watchAll(obj: Object): Object;
/**
* Running version of the tracker script
*/
version: string;
}
/**
* TrackJS initialization object, hanging off of the window.
*/
interface Window {
_trackJs: TrackJSInitOptions
}
declare var trackJs: TrackJSStatic;
declare module "Tracker" {
export = trackJs;
} | the_stack |
import { EndpointCaller, IErrorResponse, ISuccessResponse } from '../../src/rest/EndpointCaller';
import { IQueryResults } from '../../src/rest/QueryResults';
import { FakeResults } from '../Fake';
export function EndpointCallerTest() {
describe('EndpointCaller', function () {
describe('using generic call', function () {
beforeEach(function () {
jasmine.Ajax.install();
});
afterEach(function () {
jasmine.Ajax.uninstall();
});
const basicCallParams = {
method: 'POST',
requestData: {},
url: 'this is an XMLHTTPRequest',
queryString: [],
responseType: 'text',
errorsAsSuccess: false
};
it('should use XMLHTTPRequest by default', function () {
var endpointCaller = new EndpointCaller();
endpointCaller.call(basicCallParams);
expect(jasmine.Ajax.requests.mostRecent().url).toBe('this is an XMLHTTPRequest');
});
it('should use the provided XMLHTTPRequest', function () {
class CustomXMLHttpRequest extends XMLHttpRequest {}
var endpointCaller = new EndpointCaller({ xmlHttpRequest: CustomXMLHttpRequest });
endpointCaller.call(basicCallParams);
expect(jasmine.Ajax.requests.mostRecent() instanceof CustomXMLHttpRequest).toBe(true);
});
it('should set withCredentials to "true" by default', function () {
var endpointCaller = new EndpointCaller();
endpointCaller.call(basicCallParams);
expect(jasmine.Ajax.requests.mostRecent().withCredentials).toBe(true);
});
it('should set withCredentials to "true" when anonymous is "false"', function () {
var endpointCaller = new EndpointCaller({ anonymous: false });
endpointCaller.call(basicCallParams);
expect(jasmine.Ajax.requests.mostRecent().withCredentials).toBe(true);
});
it('should set withCredentials to "false" when anonymous is "true"', function () {
var endpointCaller = new EndpointCaller({ anonymous: true });
endpointCaller.call(basicCallParams);
expect(jasmine.Ajax.requests.mostRecent().withCredentials).toBe(false);
});
it('should set the auth if provided', function () {
var endpointCaller = new EndpointCaller({
accessToken: 'myToken'
});
endpointCaller.call(basicCallParams);
expect(jasmine.Ajax.requests.mostRecent().requestHeaders['Authorization']).toBe('Bearer myToken');
endpointCaller = new EndpointCaller({
username: 'john@doe.com',
password: 'hunter123'
});
endpointCaller.call(basicCallParams);
expect(jasmine.Ajax.requests.mostRecent().requestHeaders['Authorization']).toBe('Basic ' + btoa('john@doe.com:hunter123'));
});
});
describe('using XMLHTTPRequest', function () {
beforeEach(function () {
jasmine.Ajax.install();
});
afterEach(function () {
jasmine.Ajax.uninstall();
});
it('should set the correct requested params on the XMLHTTPRequest', function () {
var endpointCaller = new EndpointCaller();
endpointCaller.call({
method: 'POST',
requestData: {
foo: 'bar',
bar: 'foo',
bahh: 'bohh'
},
url: 'foo.bar.com',
queryString: [],
responseType: 'text',
errorsAsSuccess: false
});
var fakeRequest = jasmine.Ajax.requests.mostRecent();
expect(fakeRequest.method).toBe('POST');
expect(fakeRequest.params).toBe('foo=bar&bar=foo&bahh=bohh');
expect(fakeRequest.url).toBe('foo.bar.com');
expect(fakeRequest.requestHeaders['Content-Type']).toBe('application/x-www-form-urlencoded; charset=UTF-8');
endpointCaller.call({
method: 'GET',
requestData: {},
url: 'foo.bar.com',
queryString: ['a=b', 'c=d'],
responseType: 'arraybuffer',
errorsAsSuccess: false
});
fakeRequest = jasmine.Ajax.requests.mostRecent();
expect(fakeRequest.method).toBe('GET');
expect(fakeRequest.params).toBeUndefined();
expect(fakeRequest.url).toBe('foo.bar.com?a=b&c=d');
expect(Object.keys(fakeRequest.requestHeaders).length).toBe(0);
endpointCaller.call({
method: 'GET',
requestData: {
e: 'f',
g: 'h'
},
url: 'foo.bar.com',
queryString: ['a=b', 'c=d'],
responseType: 'json',
errorsAsSuccess: false
});
fakeRequest = jasmine.Ajax.requests.mostRecent();
expect(fakeRequest.method).toBe('GET');
expect(fakeRequest.params).toBeUndefined();
expect(fakeRequest.url).toBe('foo.bar.com?a=b&c=d&e=f&g=h');
expect(Object.keys(fakeRequest.requestHeaders).length).toBe(0);
});
describe('using response type text', function () {
beforeEach(function () {
this.endpointCaller = new EndpointCaller();
this.promise = this.endpointCaller.call({
method: 'POST',
requestData: {
foo: 'bar',
bar: 'foo',
bahh: 'bohh'
},
url: 'foo.bar.com',
queryString: [],
responseType: 'text',
errorsAsSuccess: false
});
});
afterEach(function () {
this.endpointCaller = undefined;
this.promise = undefined;
});
it('should work if responseContentType is text', function (done) {
this.promise
.then((response: ISuccessResponse<IQueryResults>) => {
expect(response.data.results.length).toBe(10);
expect(response.duration).toBeDefined();
})
.then(() => {
done();
});
jasmine.Ajax.requests.mostRecent().respondWith({
status: 200,
contentType: 'text',
responseText: FakeResults.createFakeResults()
});
});
it('should work if responseContentType is application/json', function (done) {
this.promise
.then((response: ISuccessResponse<IQueryResults>) => {
expect(response.data.results.length).toBe(10);
expect(response.duration).toBeDefined();
})
.then(() => {
done();
});
var fakeRequest = jasmine.Ajax.requests.mostRecent();
fakeRequest.respondWith({
status: 200,
contentType: 'application/json',
responseText: JSON.stringify(FakeResults.createFakeResults())
});
});
it('should behave properly if there is an error', function (done) {
this.promise
.then((response: ISuccessResponse<IQueryResults>) => {
// This should never execute, and always go to the catch statement
expect(false).toBe(true);
})
.catch((error: IErrorResponse) => {
expect(error.statusCode).toBe(500);
return error.statusCode;
})
.then(() => {
done();
});
jasmine.Ajax.requests.mostRecent().respondWith({
status: 500
});
});
it('should behave properly if there is an error in the body', function (done) {
this.promise
.then((response: ISuccessResponse<IQueryResults>) => {
// This should never execute, and always go to the catch statement
expect(false).toBe(true);
})
.catch((error: IErrorResponse) => {
expect(error.statusCode).toBe(404);
return error.statusCode;
})
.then(() => {
done();
});
jasmine.Ajax.requests.mostRecent().respondWith({
status: 200,
responseText: {
statusCode: 404
},
contentType: 'text'
});
});
});
describe('using response type json', function () {
beforeEach(function () {
this.endpointCaller = new EndpointCaller();
this.promise = this.endpointCaller.call({
method: 'POST',
requestData: {
foo: 'bar',
bar: 'foo',
bahh: 'bohh'
},
url: 'foo.bar.com',
queryString: [],
responseType: 'json',
errorsAsSuccess: false
});
});
afterEach(function () {
this.endpointCaller = undefined;
this.promise = undefined;
});
it('should work if responseContentType is text', function (done) {
this.promise
.then((response: ISuccessResponse<IQueryResults>) => {
expect(response.data.results.length).toBe(10);
expect(response.duration).toBeDefined();
return response.duration;
})
.then(() => {
done();
});
jasmine.Ajax.requests.mostRecent().respondWith({
status: 200,
contentType: 'text',
response: FakeResults.createFakeResults()
});
});
it('should work if responseContentType is application/json', function (done) {
this.promise
.then((response: ISuccessResponse<IQueryResults>) => {
expect(response.data.results.length).toBe(10);
expect(response.duration).toBeDefined();
return response.duration;
})
.then(() => {
done();
});
var fakeRequest = jasmine.Ajax.requests.mostRecent();
fakeRequest.respondWith({
status: 200,
contentType: 'application/json',
response: FakeResults.createFakeResults()
});
});
it('should allow to modify the request with an option', function () {
let endpointCaller = new EndpointCaller({
accessToken: 'myToken',
requestModifier: requestInfo => {
requestInfo.method = 'GET';
return requestInfo;
}
});
endpointCaller.call({
method: 'POST',
requestData: {},
url: 'this is an XMLHTTPRequest',
queryString: [],
responseType: 'text',
errorsAsSuccess: false
});
expect(jasmine.Ajax.requests.mostRecent().method).toBe('GET');
});
});
});
});
} | the_stack |
import {
apigatewayv2 as APIGatewayV2,
AwsProvider,
cloudfront as CloudFront,
iam as IAM,
lambdafunction as LambdaFunction,
s3 as S3,
sqs as SQS
} from "@cdktf/provider-aws";
import { App, Fn, TerraformStack } from "cdktf";
import { Construct } from "constructs";
import { ArchiveProvider, DataArchiveFile } from "@cdktf/provider-archive";
import { Resource } from "@cdktf/provider-null";
import * as path from "path";
import { CoreBuildOptions } from "@sls-next/core";
import { LambdaBuildOptions } from "src/types";
const DEFAULT_OUTPUT_DIR = ".serverless_nextjs";
const DEFAULT_AWS_REGION = "us-east-1";
export type NextJsLambdaAppProps = {
/**
* The app name. This will prefix names of various infrastructure such as Lambda, S3 bucket, SQS queue, etc.
* Please ensure the name only contains alphanumeric characters and dashes to be compatible across all resources.
*/
appName: string;
/**
* The AWS region to provision the Next.js app infrastructure.
* If omitted, it will default to us-east-1.
*/
region?: string;
coreBuildOptions?: CoreBuildOptions;
lambdaBuildOptions?: LambdaBuildOptions;
imageLambdaPolicyConfig?: Partial<IAM.IamPolicyConfig>;
defaultLambdaPolicyConfig?: Partial<IAM.IamPolicyConfig>;
s3BucketConfig?: Partial<S3.S3BucketConfig>;
apiGatewayApiConfig?: Partial<APIGatewayV2.Apigatewayv2ApiConfig>;
apiGatewayApiMainStageConfig?: Partial<APIGatewayV2.Apigatewayv2StageConfig>;
apiGatewayDefaultRouteConfig?: Partial<APIGatewayV2.Apigatewayv2RouteConfig>;
apiGatewayImageRouteConfig?: Partial<APIGatewayV2.Apigatewayv2RouteConfig>;
apiGatewayDefaultIntegrationConfig?: Partial<APIGatewayV2.Apigatewayv2IntegrationConfig>;
apiGatewayImageIntegrationConfig?: Partial<APIGatewayV2.Apigatewayv2IntegrationConfig>;
domainConfig?: Partial<APIGatewayV2.Apigatewayv2DomainNameConfig>;
defaultLambdaConfig?: Partial<LambdaFunction.LambdaFunctionConfig>;
defaultLambdaPermissionConfig?: Partial<LambdaFunction.LambdaPermissionConfig>;
defaultLambdaRegenerationEventSourceMappingConfig?: Partial<LambdaFunction.LambdaEventSourceMapping>;
defaultLambdaRoleConfig?: Partial<IAM.IamRoleConfig>;
imageLambdaConfig?: Partial<LambdaFunction.LambdaFunctionConfig>;
imageLambdaPermissionConfig?: Partial<LambdaFunction.LambdaPermissionConfig>;
imageLambdaRoleConfig?: Partial<IAM.IamRoleConfig>;
regenerationQueueConfig?: Partial<SQS.SqsQueueConfig>;
regenerationQueuePolicyConfig?: Partial<SQS.SqsQueuePolicyConfig>;
cloudFrontDistributionConfig?: Partial<CloudFront.CloudfrontDistributionConfig>;
cloudFrontCachePolicyConfig?: Partial<CloudFront.CloudfrontCachePolicyConfig>;
};
/**
* A Terraform for CDK construct to deploy Next.js apps to Lambda + API Gateway V2 + CloudFront.
* This requires minimal configuration to deploy, and nearly all of the Terraform resource configurations can be overridden.
* Note: this is a work-in-progress and may not function properly.
* Refer to Terraform docs at {@link https://registry.terraform.io/providers/hashicorp/aws/latest/docs}
*/
export class NextJsLambdaApp extends Construct {
protected readonly props: NextJsLambdaAppProps;
protected s3Bucket: S3.S3Bucket;
protected defaultLambda: LambdaFunction.LambdaFunction;
protected imageLambda: LambdaFunction.LambdaFunction;
protected apiGatewayApi: APIGatewayV2.Apigatewayv2Api;
protected apiGatewayDefaultIntegration: APIGatewayV2.Apigatewayv2Integration;
protected apiGatewayImageIntegration: APIGatewayV2.Apigatewayv2Integration;
protected apiGatewayDefaultRoute: APIGatewayV2.Apigatewayv2Route;
protected apiGatewayImagesRoute: APIGatewayV2.Apigatewayv2Route;
protected cloudFrontDistribution: CloudFront.CloudfrontDistribution;
protected regenerationQueue: SQS.SqsQueue;
protected defaultLambdaRole: IAM.IamRole;
protected imageLambdaRole: IAM.IamRole;
protected apiGatewayMainStage: APIGatewayV2.Apigatewayv2Stage;
protected defaultLambdaZip: DataArchiveFile;
protected imageLambdaZip: DataArchiveFile;
protected defaultLambdaPolicy: IAM.IamPolicy;
protected imageLambdaPolicy: IAM.IamPolicy;
protected uploadAssetsResource: Resource;
protected defaultLambdaRegenerationEventSourceMapping: LambdaFunction.LambdaEventSourceMapping;
protected defaultLambdaPermission: LambdaFunction.LambdaPermission;
protected imageLambdaPermission: LambdaFunction.LambdaPermission;
protected cloudFrontCachePolicy: CloudFront.CloudfrontCachePolicy;
protected buildResource: Resource;
protected invalidateCloudFrontResource: Resource;
public constructor(
scope: Construct,
id: string,
props: NextJsLambdaAppProps
) {
super(scope, id);
this.props = props;
const coreBuildOptions: CoreBuildOptions = {
outputDir: DEFAULT_OUTPUT_DIR,
nextConfigDir: "./"
};
const lambdaBuildOptions: LambdaBuildOptions = {
bucketName:
this.props.s3BucketConfig?.bucket ??
`${this.props.appName}-sls-next-bucket`,
bucketRegion: this.props.region ?? DEFAULT_AWS_REGION
};
// Build app using LambdaBuilder if we are supposed to build (see if this can be a TerraForm null resource component
// Note that the code can't be executed directly since we are using Terraform to apply the changes, so we need to
// FIXME: implement this script
this.buildResource = new Resource(this, "BuildResource", {});
this.buildResource.addOverride("provisioner", [
{
"local-exec": {
command: `node ${__dirname}/dist/build/scripts/buildApp.js --coreBuildOptions ${JSON.stringify(
coreBuildOptions
)} --lambdaBuildOptions ${JSON.stringify(lambdaBuildOptions)}`
}
}
]);
// Zip up code
new ArchiveProvider(this, "Archive");
this.defaultLambdaZip = new DataArchiveFile(this, "DefaultLambdaZip", {
sourceDir: path.join(
coreBuildOptions.outputDir ?? DEFAULT_OUTPUT_DIR,
"default-lambda"
),
outputPath: "default-lambda.zip",
type: "zip"
});
this.imageLambdaZip = new DataArchiveFile(this, "ImageLambdaZip", {
sourceDir: path.join(
coreBuildOptions.outputDir ?? DEFAULT_OUTPUT_DIR,
"image-lambda"
),
outputPath: "image-lambda.zip",
type: "zip"
});
// Create infrastructure all within the same region, or us-east-1 if not specified
new AwsProvider(this, "AWS", {
region: this.props.region ?? DEFAULT_AWS_REGION
});
// S3 bucket
this.s3Bucket = this.createS3Bucket();
// Upload assets. We don't use the S3.S3BucketObject resources since it will force S3 state to be the same as the source,
// so previous assets may be lost. Instead, we execute a script via a custom resource which will retain the last 2 versions
// and delete other old resources.
// FIXME: implement this script
this.uploadAssetsResource = new Resource(this, "UploadAssetsResource", {
dependsOn: [this.s3Bucket]
});
this.uploadAssetsResource.addOverride("provisioner", [
{
"local-exec": {
command: `node ${__dirname}/dist/deploy/cdktf/scripts/uploadAssets.js --coreBuildOptions ${JSON.stringify(
props.coreBuildOptions
)} --lambdaBuildOptions ${JSON.stringify(props.lambdaBuildOptions)}`
}
}
]);
// SQS queue for regeneration
this.regenerationQueue = this.createRegenerationQueue();
// Default lambda which also handles regeneration requests
this.defaultLambdaPolicy = this.createDefaultLambdaPolicy();
this.defaultLambdaRole = this.createDefaultLambdaRole();
this.defaultLambda = this.createDefaultLambda();
this.defaultLambdaRegenerationEventSourceMapping =
this.createDefaultLambdaRegenerationEventSourceMapping();
// Image lambda for image optimization
this.imageLambdaPolicy = this.createImageLambdaPolicy();
this.imageLambdaRole = this.createImageLambdaRole();
this.imageLambda = this.createImageLambda();
// API Gateway V2
this.apiGatewayApi = this.createAPIGatewayApi();
this.apiGatewayMainStage = this.createAPIGatewayMainStage();
// Permissions for API Gateway to invoke Lambda
this.defaultLambdaPermission = this.createDefaultLambdaPermission();
this.imageLambdaPermission = this.createImageLambdaPermission();
// API Gateway Lambda Integrations
this.apiGatewayDefaultIntegration =
this.createAPIGatewayDefaultIntegration();
this.apiGatewayImageIntegration = this.createAPIGatewayImageIntegration();
// API Gateway Routes
this.apiGatewayDefaultRoute = this.createAPIGatewayDefaultRoute();
this.apiGatewayImagesRoute = this.createAPIGatewayImageRoute();
// CloudFront distribution created on top of API Gateway V2 for caching static files purposes
this.cloudFrontCachePolicy = this.createCloudFrontCachePolicy();
this.cloudFrontDistribution = this.createCloudFrontDistribution();
// Run custom script to invalidate CF distribution, since there is no Terraform resource to do so but we need to do it each time.
// FIXME: implement this script and allow custom paths
const invalidationPaths = ["/*"];
this.invalidateCloudFrontResource = new Resource(
this,
"invalidateCloudFrontResource",
{
dependsOn: [this.defaultLambda, this.imageLambda, this.apiGatewayApi]
}
);
this.invalidateCloudFrontResource.addOverride("provisioner", [
{
"local-exec": {
command: `node ./dist/deploy/scripts/invalidateCloudFrontDistribution.js --paths ${JSON.stringify(
invalidationPaths
)}`
}
}
]);
}
/**
* Create an API Gateway V2 HTTP API which will serve all Next.js requests.
* @protected
*/
protected createAPIGatewayApi(): APIGatewayV2.Apigatewayv2Api {
const apiGatewayApiConfig: APIGatewayV2.Apigatewayv2ApiConfig = {
name: `${this.props.appName}-sls-next-api-gateway`,
description: `${this.props.appName} API Gateway`,
protocolType: "HTTP"
};
Object.assign(apiGatewayApiConfig, this.props.apiGatewayApiConfig);
return new APIGatewayV2.Apigatewayv2Api(
this,
"ApiGateway",
apiGatewayApiConfig
);
}
protected createAPIGatewayMainStage(): APIGatewayV2.Apigatewayv2Stage {
const apiGatewayApiMainStageConfig: APIGatewayV2.Apigatewayv2StageConfig = {
apiId: this.apiGatewayApi.id,
name: "main",
autoDeploy: true
};
Object.assign(
apiGatewayApiMainStageConfig,
this.props.apiGatewayApiMainStageConfig
);
return new APIGatewayV2.Apigatewayv2Stage(
this,
"ApiGatewayMainStage",
apiGatewayApiMainStageConfig
);
}
protected createS3Bucket(): S3.S3Bucket {
const s3BucketConfig: S3.S3BucketConfig = {
bucket: `${this.props.appName}-sls-next-bucket`,
accelerationStatus: "Enabled"
};
Object.assign(s3BucketConfig, this.props.s3BucketConfig);
return new S3.S3Bucket(this, "NextJsS3Bucket", s3BucketConfig);
}
protected createDefaultLambda(): LambdaFunction.LambdaFunction {
const lambdaConfig: LambdaFunction.LambdaFunctionConfig = {
functionName: `${this.props.appName}-sls-next-default-lambda`,
role: this.defaultLambdaRole.arn,
memorySize: 512,
runtime: "nodejs14.x",
handler: "index.handler",
description: `${this.props.appName} Default Lambda`,
timeout: 15,
filename: this.defaultLambdaZip.outputPath,
sourceCodeHash: this.defaultLambdaZip.outputBase64Sha256
};
Object.assign(lambdaConfig, this.props.defaultLambdaConfig);
return new LambdaFunction.LambdaFunction(
this,
"DefaultLambda",
lambdaConfig
);
}
protected createImageLambda(): LambdaFunction.LambdaFunction {
const lambdaConfig: LambdaFunction.LambdaFunctionConfig = {
functionName: `${this.props.appName}-sls-next-image-lambda`,
role: this.imageLambdaRole.arn,
memorySize: 512,
runtime: "nodejs14.x",
handler: "index.handler",
description: `${this.props.appName} Image Lambda`,
timeout: 15,
filename: this.imageLambdaZip.outputPath,
sourceCodeHash: this.imageLambdaZip.outputBase64Sha256
};
Object.assign(lambdaConfig, this.props.imageLambdaConfig);
return new LambdaFunction.LambdaFunction(this, "ImageLambda", lambdaConfig);
}
protected createRegenerationQueue(): SQS.SqsQueue {
const regenerationQueueConfig: SQS.SqsQueueConfig = {
name: `${this.props.appName}-sls-next-regen-queue.fifo`,
fifoQueue: true
};
Object.assign(regenerationQueueConfig, this.props.regenerationQueueConfig);
return new SQS.SqsQueue(this, "RegenerationQueue", regenerationQueueConfig);
}
protected createRegenerationQueuePolicy(): SQS.SqsQueuePolicyConfig {
const regenerationQueuePolicyConfig: SQS.SqsQueuePolicyConfig = {
policy: JSON.stringify({
Version: "2012-10-17",
Statement: [
{
Sid: "RegenerationQueueStatement",
Effect: "Allow",
Principal: `${this.defaultLambdaRole.id}`,
Action: "sqs:SendMessage",
Resource: `${this.regenerationQueue.arn}`
}
]
}),
queueUrl: this.regenerationQueue.url
};
Object.assign(
regenerationQueuePolicyConfig,
this.props.regenerationQueuePolicyConfig
);
return regenerationQueuePolicyConfig;
}
protected createCloudFrontDistribution(): CloudFront.CloudfrontDistribution {
const cloudFrontDistributionConfig: CloudFront.CloudfrontDistributionConfig =
{
defaultCacheBehavior: {
allowedMethods: [
"DELETE",
"GET",
"HEAD",
"OPTIONS",
"PATCH",
"POST",
"PUT"
],
cachedMethods: ["GET", "HEAD"],
targetOriginId: this.apiGatewayApi.id,
viewerProtocolPolicy: "redirect-to-https",
compress: true,
cachePolicyId: this.cloudFrontCachePolicy.id
},
enabled: true,
origin: [
{
customOriginConfig: {
httpPort: 80,
httpsPort: 443,
originProtocolPolicy: "https-only",
originSslProtocols: ["TLSv1.2"]
},
domainName: Fn.replace(
this.apiGatewayApi.apiEndpoint,
"https://",
""
),
originId: this.apiGatewayApi.id,
originPath: `/${this.apiGatewayMainStage.name}`
}
],
restrictions: { geoRestriction: { restrictionType: "none" } },
viewerCertificate: { cloudfrontDefaultCertificate: true }
};
Object.assign(
cloudFrontDistributionConfig,
this.props.cloudFrontDistributionConfig
);
return new CloudFront.CloudfrontDistribution(
this,
"CloudFrontDistribution",
cloudFrontDistributionConfig
);
}
protected createCloudFrontCachePolicy(): CloudFront.CloudfrontCachePolicy {
const cloudFrontCachePolicyConfig: CloudFront.CloudfrontCachePolicyConfig =
{
name: `${this.props.appName}-cache-policy`,
comment: `${this.props.appName} cache policy`,
defaultTtl: 0,
minTtl: 0,
maxTtl: 31536000,
parametersInCacheKeyAndForwardedToOrigin: {
enableAcceptEncodingBrotli: true,
enableAcceptEncodingGzip: true,
cookiesConfig: {
cookieBehavior: "all"
},
headersConfig: {
headerBehavior: "whitelist",
headers: {
items: ["Accept", "Accept-Language", "Authorization"]
}
},
queryStringsConfig: {
queryStringBehavior: "all"
}
}
};
Object.assign(
cloudFrontCachePolicyConfig,
this.props.cloudFrontCachePolicyConfig
);
return new CloudFront.CloudfrontCachePolicy(
this,
"CloudFrontCachePolicy",
cloudFrontCachePolicyConfig
);
}
protected createAPIGatewayDefaultRoute(): APIGatewayV2.Apigatewayv2Route {
const apiGatewayDefaultRouteConfig: APIGatewayV2.Apigatewayv2RouteConfig = {
apiId: this.apiGatewayApi.id,
routeKey: "$default",
target: `integrations/${this.apiGatewayDefaultIntegration.id}`
};
Object.assign(
apiGatewayDefaultRouteConfig,
this.props.apiGatewayDefaultRouteConfig
);
return new APIGatewayV2.Apigatewayv2Route(
this,
"ApiGatewayDefaultRoute",
apiGatewayDefaultRouteConfig
);
}
protected createAPIGatewayImageRoute(): APIGatewayV2.Apigatewayv2Route {
const apiGatewayImageRouteConfig: APIGatewayV2.Apigatewayv2RouteConfig = {
apiId: this.apiGatewayApi.id,
routeKey: "GET /_next/image",
target: `integrations/${this.apiGatewayImageIntegration.id}`
};
Object.assign(
apiGatewayImageRouteConfig,
this.props.apiGatewayImageRouteConfig
);
return new APIGatewayV2.Apigatewayv2Route(
this,
"ApiGatewayImageRoute",
apiGatewayImageRouteConfig
);
}
protected createAPIGatewayDefaultIntegration(): APIGatewayV2.Apigatewayv2Integration {
const apiGatewayDefaultIntegrationConfig: APIGatewayV2.Apigatewayv2IntegrationConfig =
{
apiId: this.apiGatewayApi.id,
integrationType: "AWS_PROXY",
integrationUri: this.defaultLambda.arn,
integrationMethod: "POST",
payloadFormatVersion: "2.0"
};
Object.assign(
apiGatewayDefaultIntegrationConfig,
this.props.apiGatewayDefaultIntegrationConfig
);
return new APIGatewayV2.Apigatewayv2Integration(
this,
"ApiGatewayDefaultIntegration",
apiGatewayDefaultIntegrationConfig
);
}
protected createDefaultLambdaPermission(): LambdaFunction.LambdaPermission {
const defaultLambdaPermissionConfig: LambdaFunction.LambdaPermissionConfig =
{
statementId: "AllowExecutionFromAPIGateway",
action: "lambda:InvokeFunction",
functionName: this.defaultLambda.functionName,
principal: "apigateway.amazonaws.com"
};
Object.assign(
defaultLambdaPermissionConfig,
this.props.defaultLambdaPermissionConfig
);
return new LambdaFunction.LambdaPermission(
this,
"DefaultLambdaPermission",
defaultLambdaPermissionConfig
);
}
protected createImageLambdaPermission(): LambdaFunction.LambdaPermission {
const imageLambdaPermissionConfig: LambdaFunction.LambdaPermissionConfig = {
statementId: "AllowExecutionFromAPIGateway",
action: "lambda:InvokeFunction",
functionName: this.imageLambda.functionName,
principal: "apigateway.amazonaws.com"
};
Object.assign(
imageLambdaPermissionConfig,
this.props.defaultLambdaPermissionConfig
);
return new LambdaFunction.LambdaPermission(
this,
"ImageLambdaPermission",
imageLambdaPermissionConfig
);
}
protected createAPIGatewayImageIntegration(): APIGatewayV2.Apigatewayv2Integration {
const apiGatewayImageIntegrationConfig: APIGatewayV2.Apigatewayv2IntegrationConfig =
{
apiId: this.apiGatewayApi.id,
integrationType: "AWS_PROXY",
integrationUri: this.imageLambda.arn,
integrationMethod: "POST",
payloadFormatVersion: "2.0"
};
Object.assign(
apiGatewayImageIntegrationConfig,
this.props.apiGatewayImageIntegrationConfig
);
return new APIGatewayV2.Apigatewayv2Integration(
this,
"ApiGatewayImageIntegration",
apiGatewayImageIntegrationConfig
);
}
// IAM Roles
protected createDefaultLambdaRole(): IAM.IamRole {
const defaultLambdaRoleConfig: IAM.IamRoleConfig = {
assumeRolePolicy: JSON.stringify({
Version: "2012-10-17",
Statement: [
{
Action: "sts:AssumeRole",
Effect: "Allow",
Sid: "DefaultLambdaAssumeRolePolicy",
Principal: {
Service: "lambda.amazonaws.com"
}
}
]
}),
managedPolicyArns: [
"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",
this.defaultLambdaPolicy.arn
]
};
Object.assign(defaultLambdaRoleConfig, this.props.defaultLambdaRoleConfig);
return new IAM.IamRole(this, `DefaultLambdaRole`, defaultLambdaRoleConfig);
}
protected createImageLambdaRole(): IAM.IamRole {
const imageLambdaRoleConfig: IAM.IamRoleConfig = {
assumeRolePolicy: JSON.stringify({
Version: "2012-10-17",
Statement: [
{
Action: "sts:AssumeRole",
Effect: "Allow",
Sid: "ImageLambdaAssumeRolePolicy",
Principal: {
Service: "lambda.amazonaws.com"
}
}
]
}),
managedPolicyArns: [
"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",
this.imageLambdaPolicy.arn
]
};
Object.assign(imageLambdaRoleConfig, this.props.imageLambdaRoleConfig);
return new IAM.IamRole(this, `ImageLambdaRole`, imageLambdaRoleConfig);
}
protected createDefaultLambdaPolicy(): IAM.IamPolicy {
const defaultLambdaPolicyConfig: IAM.IamPolicyConfig = {
policy: JSON.stringify({
Version: "2012-10-17",
Statement: [
{
Action: "s3:GetObject",
Effect: "Allow",
Resource: `${this.s3Bucket.arn}/*`
},
{
Action: "s3:PutObject",
Effect: "Allow",
Resource: `${this.s3Bucket.arn}/*`
},
{
Action: "s3:ListBucket",
Effect: "Allow",
Resource: this.s3Bucket.arn
},
{
Action: "sqs:SendMessage",
Effect: "Allow",
Resource: this.regenerationQueue.arn
},
{
Action: "sqs:ReceiveMessage",
Effect: "Allow",
Resource: this.regenerationQueue.arn
},
{
Action: "sqs:DeleteMessage",
Effect: "Allow",
Resource: this.regenerationQueue.arn
},
{
Action: "sqs:GetQueueAttributes",
Effect: "Allow",
Resource: this.regenerationQueue.arn
}
]
})
};
Object.assign(
defaultLambdaPolicyConfig,
this.props.defaultLambdaPolicyConfig
);
return new IAM.IamPolicy(
this,
"DefaultLambdaPolicy",
defaultLambdaPolicyConfig
);
}
/**
* Attach the default lambda to the regeneration queue so it can process regeneration event messages.
* @protected
*/
protected createDefaultLambdaRegenerationEventSourceMapping(): LambdaFunction.LambdaEventSourceMapping {
const defaultLambdaRegenerationEventSourceMappingConfig: LambdaFunction.LambdaEventSourceMappingConfig =
{
functionName: this.defaultLambda.arn,
eventSourceArn: this.regenerationQueue.arn
};
Object.assign(
defaultLambdaRegenerationEventSourceMappingConfig,
this.props.defaultLambdaRegenerationEventSourceMappingConfig
);
return new LambdaFunction.LambdaEventSourceMapping(
this,
"DefaultLambdaRegenerationEventSourceMapping",
defaultLambdaRegenerationEventSourceMappingConfig
);
}
private createImageLambdaPolicy(): IAM.IamPolicy {
const imageLambdaPolicyConfig: IAM.IamPolicyConfig = {
policy: JSON.stringify({
Version: "2012-10-17",
Statement: [
{
Action: "s3:GetObject",
Effect: "Allow",
Resource: `${this.s3Bucket.arn}/*`
},
{
Action: "s3:ListBucket",
Effect: "Allow",
Resource: this.s3Bucket.arn
}
]
})
};
Object.assign(imageLambdaPolicyConfig, this.props.imageLambdaPolicyConfig);
return new IAM.IamPolicy(
this,
"ImageLambdaPolicy",
imageLambdaPolicyConfig
);
}
} | the_stack |
import { CGColor, IRGBColor } from './cg-color';
import { CGCounts } from './cg-counts';
import { CGDatabase, IDocEntry } from './cg-database';
import { CGLegend } from './cg-legend';
import { CGMappings } from './cg-mappings';
import { CGTopGrid, IWordTag } from './cg-top-grid';
import { CGTopGridLayers } from './cg-top-grid-layers';
import { CGVocabulary } from './cg-vocabulary';
export interface IWordLabel {
word: string;
wordId: number;
scaledWeight: number;
point: IPoint;
color: IRGBColor;
}
export interface IPoint {
x: number;
y: number;
}
export interface IScaledGridData {
wordLabels: IWordLabel[];
rowDistance: number;
colDistance: number;
}
export interface IWordTagsWithMetadata {
wordTags: IWordTag[];
minWeight: number;
maxWeight: number;
}
/** Contains all entities that make up a counting grid and helper methods for displaying the grid. */
export class CountingGridModel {
public static readonly piThreshhold = 0.0001;
public vocabulary: CGVocabulary;
public topGrid: CGTopGrid;
public color: CGColor;
public mappings: CGMappings;
public counts: CGCounts;
public database: CGDatabase;
public legend: CGLegend;
public topGridLayers: CGTopGridLayers;
public maxDocuments = 100;
private randomOffsets: number[];
private searchWordTagsCache: { [name: string]: IWordTagsWithMetadata } = {};
public constructor(
topPiText: string,
colorBrowserText: string,
wordsText: string,
docMapText: string,
databaseText: string,
legendText: string,
correspondencesText: string,
topPiLayersText: string
) {
this.color = new CGColor(colorBrowserText);
this.vocabulary = new CGVocabulary(correspondencesText);
this.topGrid = new CGTopGrid(topPiText, this.vocabulary);
this.mappings = new CGMappings(docMapText);
this.counts = new CGCounts(wordsText);
this.database = new CGDatabase(databaseText);
this.legend = new CGLegend(legendText);
this.topGridLayers = new CGTopGridLayers(topPiLayersText);
this.randomOffsets = Array.from({ length: this.vocabulary.lexicon.length }, () => Math.floor(Math.random() * 15));
}
public getScaledGridData(
searchWordIds: number[],
width: number,
height: number,
translationX = 0,
translationY = 0,
zoomRatio = 1
): IScaledGridData {
const rowDistance = height / Math.max(this.topGrid.rowLength, 1);
const colDistance = width / Math.max(this.topGrid.columnLength, 1);
const visibilityArray = this.constructVisibilityArray(translationX, translationY, rowDistance, colDistance, zoomRatio);
const scaledGridData = {
rowDistance,
colDistance,
wordLabels: [],
} as IScaledGridData;
const wordTagsAndMetadata = this.getWordTags(searchWordIds);
const measureMaxMinusMin = wordTagsAndMetadata.maxWeight - wordTagsAndMetadata.minWeight;
wordTagsAndMetadata.wordTags.forEach((wordTag) => {
if (visibilityArray[wordTag.row][wordTag.col] !== true) {
return;
}
const scaledWeight = ((wordTag.weight - wordTagsAndMetadata.minWeight) / measureMaxMinusMin);
if (scaledWeight === 0) {
return;
}
const preY =
Math.floor(((wordTag.row * rowDistance) + (this.randomOffsets[wordTag.wordId] * zoomRatio) + translationY) % height);
const preX =
Math.floor(((wordTag.col * colDistance) + (this.randomOffsets[wordTag.wordId] * zoomRatio) + translationX) % width);
const currentColor = this.color.getColor(wordTag.row, wordTag.col);
scaledGridData.wordLabels.push({
word: wordTag.word,
wordId: wordTag.wordId,
point: {
y: preY > 0 ? preY : preY + height,
x: preX > 0 ? preX : preX + width,
},
scaledWeight,
color: currentColor,
});
});
scaledGridData.wordLabels = scaledGridData.wordLabels.sort((a, b) => a.scaledWeight - b.scaledWeight);
return scaledGridData;
}
public getDocumentEntryList(row: number, col: number, searchWordIds?: number[], maxWordsInSearch = 100): IDocEntry[] {
if (row == null || col == null) {
return [];
}
const docList = this.mappings.getMappings(row, col);
const docFinalWeights: { [name: number]: number } = {};
if (searchWordIds != null && searchWordIds.length > 0) {
// With search terms.
const docWeights: { [name: number]: number } = {};
const docWeightsSearch: { [name: number]: number } = {};
const wordTagsForPoint = this.getWordTags(searchWordIds).wordTags
.filter((wordTag) => wordTag.col === col && wordTag.row === row)
.sort((a, b) => a.weight - b.weight);
let maxDocWeight = 0;
wordTagsForPoint.forEach((wordTag, wordIndex) => {
// For perf, limit the amount of words involved in the search.
if (wordIndex < maxWordsInSearch) {
docList.forEach((docEntry) => {
const wordCounts = this.counts.getWordCounts(docEntry.entryId, wordTag.wordId);
if (wordCounts > 0) {
for (let lay = 1; lay < this.topGridLayers.layerLength + 1; lay++) {
if (docWeights[docEntry.entryId] == null) {
docWeights[docEntry.entryId] = 0;
}
docWeights[docEntry.entryId] += this.topGridLayers.getWordProbability(lay, row, col, wordTag.wordId);
if (docWeights[docEntry.entryId] > maxDocWeight) {
maxDocWeight = docWeights[docEntry.entryId];
}
}
}
});
}
});
searchWordIds.forEach((searchWordId) => {
docList.forEach((docEntry) => {
const wordCounts = this.counts.getWordCounts(docEntry.entryId, searchWordId);
if (docWeightsSearch[docEntry.entryId] == null) {
docWeightsSearch[docEntry.entryId] = 0;
}
if (wordCounts > 0) {
docWeightsSearch[docEntry.entryId]++;
}
});
});
docList.forEach((docEntry) => {
docFinalWeights[docEntry.entryId] =
(docWeightsSearch[docEntry.entryId] == null ? 0 : docWeightsSearch[docEntry.entryId])
* docEntry.weight
* ((docWeights[docEntry.entryId] == null ? 0 : docWeights[docEntry.entryId]) / maxDocWeight);
});
} else {
// Without search terms.
const docWeights: { [name: number]: number } = {};
this.topGrid.getWordEntryList(row, col).forEach((wordEntry, wordIndex) => {
// For perf, limit the amount of words involved in the search.
if (wordIndex < maxWordsInSearch) {
docList.forEach((docEntry) => {
const wordCounts = this.counts.getWordCounts(docEntry.entryId, wordEntry.wordId);
if (wordCounts > 0) {
if (docWeights[docEntry.entryId] == null) {
docWeights[docEntry.entryId] = 0;
}
docWeights[docEntry.entryId] += this.topGrid.getWordProbability(row, col, wordEntry.wordId);
}
});
}
});
docList.forEach((docEntry) => {
docFinalWeights[docEntry.entryId] =
docEntry.weight * (docWeights[docEntry.entryId] == null ? 0 : docWeights[docEntry.entryId]);
});
}
return docList
.sort((a, b) => {
return docFinalWeights[b.entryId] - docFinalWeights[a.entryId];
})
.map((docEntryWeight) => {
return this.database.getDocEntry(docEntryWeight.entryId);
})
// Limit to 100 docs. Perf gains.
.slice(0, this.maxDocuments);
}
private constructVisibilityArray(
translationX: number,
translationY: number,
rowDistance: number,
colDistance: number,
zoomRatio: number
): boolean[][] {
if (zoomRatio > 1.5) {
// Subtract one so they do not dissapear as soon as they touch the end of the page.
let minY = (Math.floor(-translationY / rowDistance) - 1) % this.topGrid.rowLength;
let minX = (Math.floor(-translationX / colDistance) - 1) % this.topGrid.columnLength;
minY = minY > 0 ? minY : minY + this.topGrid.rowLength;
minX = minX > 0 ? minX : minX + this.topGrid.columnLength;
// Add one so they do not dissapear as soon as they touch the end of the page.
let maxY = (Math.floor(-translationY / rowDistance + this.topGrid.rowLength / zoomRatio) + 1) % this.topGrid.rowLength;
let maxX = (Math.floor(-translationX / colDistance + this.topGrid.columnLength / zoomRatio) + 1) % this.topGrid.columnLength;
maxY = maxY > 0 ? maxY : maxY + this.topGrid.rowLength;
maxX = maxX > 0 ? maxX : maxX + this.topGrid.columnLength;
// row = 0 and col = 0 is not used, since they are 1 indexed.
const visibility: boolean[][] = Array.from({ length: this.topGrid.rowLength + 1 }, () => {
return Array.from({ length: this.topGrid.columnLength + 1 }, () => false);
});
let currX = minX;
do {
currX = ((currX + 1) % (this.topGrid.columnLength + 1));
let currY = minY;
visibility[currY][currX] = true;
do {
currY = ((currY + 1) % (this.topGrid.rowLength + 1));
visibility[currY][currX] = true;
} while (currY !== maxY);
} while (currX !== maxX);
return visibility;
}
return Array.from({ length: this.topGrid.rowLength + 1 }, () => {
return Array.from({ length: this.topGrid.columnLength + 1 }, () => true);
});
}
private getWordTags(searchWordIds: number[]): IWordTagsWithMetadata {
if (searchWordIds == null || searchWordIds.length === 0) {
return {
wordTags: this.topGrid.wordTags,
maxWeight: this.topGrid.maxWeight,
minWeight: this.topGrid.minWeight,
};
}
const cachedWordTags = this.searchWordTagsCache[JSON.stringify(searchWordIds)];
if (cachedWordTags != null) {
return cachedWordTags;
}
// Initialize array to 0.
const layeredWeights =
Array.from({ length: this.topGridLayers.layerLength }, () => {
return Array.from({ length: this.topGrid.rowLength }, () => {
return Array.from({ length: this.topGrid.columnLength }, () => 0);
});
});
// Keep track of max layered weight.
let maxLayeredWeight = 0;
// Weight the layers based on search words.
for (let row = 1; row < this.topGrid.rowLength + 1; row++) {
for (let col = 1; col < this.topGrid.columnLength + 1; col++) {
const docMappings = this.mappings.getMappings(row, col);
docMappings.forEach((docMapping) => {
let weight = 0;
let numberOfNonZeroWordCounts = 0;
searchWordIds.forEach((wordId) => {
const wordCount = this.counts.getWordCounts(docMapping.entryId, wordId);
numberOfNonZeroWordCounts += (wordCount === 0 ? 0 : 1);
weight += Math.min(25 /* Max Weight */, 20 /* Base Weight */ + (wordCount - 1));
});
layeredWeights[docMapping.layer][row - 1][col - 1] +=
numberOfNonZeroWordCounts !== 0 ? Math.pow(weight, 1 + Math.log(numberOfNonZeroWordCounts)) : 0;
});
for (let lay = 1; lay < this.topGridLayers.layerLength + 1; lay++) {
if (layeredWeights[lay - 1][row - 1][col - 1] > maxLayeredWeight) {
maxLayeredWeight = layeredWeights[lay - 1][row - 1][col - 1];
}
}
}
}
const wordTagsWithMedadata: IWordTagsWithMetadata = {
wordTags: [],
maxWeight: 0,
minWeight: 1,
};
// Create new mapping based on new weights.
for (let row = 1; row < this.topGrid.rowLength + 1; row++) {
for (let col = 1; col < this.topGrid.columnLength + 1; col++) {
for (let lay = 1; lay < this.topGridLayers.layerLength + 1; lay++) {
this.topGridLayers.getWordEntryList(lay, row, col).forEach((wordEntry) => {
const weight = wordEntry.weight * layeredWeights[lay - 1][row - 1][col - 1] / maxLayeredWeight;
if (weight > CountingGridModel.piThreshhold) {
const wordTag = {
row,
col,
wordId: wordEntry.wordId,
word: this.vocabulary.getLexiconWordById(wordEntry.wordId).word,
weight,
} as IWordTag;
wordTagsWithMedadata.wordTags.push(wordTag);
if (wordTag.weight > wordTagsWithMedadata.maxWeight) {
wordTagsWithMedadata.maxWeight = wordTag.weight;
}
if (wordTag.weight < wordTagsWithMedadata.minWeight) {
wordTagsWithMedadata.minWeight = wordTag.weight;
}
}
});
}
}
}
// Cache the result.
this.searchWordTagsCache[JSON.stringify(searchWordIds)] = wordTagsWithMedadata;
return wordTagsWithMedadata;
}
} | the_stack |
module TDev {
//declare class RenderState;
export interface IndexedString
{
idx:number;
s:string;
}
}
module TDev.AST {
export var api = TDev.api;
var currentNodeId = 1;
export var proMode = false;
export var blockMode = false;
export var legacyMode = true;
export var propRenames:StringMap<string> = {};
export var crossKindRenames:StringMap<string> = {};
export var writableLocalsInClosures = true;
export var allowCppCompiler = false;
export function reset()
{
currentNodeId = 1;
api.cleanup()
}
export function stableReset(entropy:string)
{
reset()
var r = new Random.RC4()
r.addEntropy(Util.stringToUint8Array(Util.toUTF8(entropy)))
uniqueAstId = (len) => r.uniqueId(len);
}
export class AstNode
{
public nodeId:number = currentNodeId++;
public stableId:string;
public errorIsOk:boolean;
public _kind:Kind;
public _error:string = null;
public isInvisible:boolean;
public annotations:RT.AstAnnotation[];
public _converterValue:string;
private isAstNode() { return true; }
public isPlaceholder() { return false; }
public hasValue() { return false; }
public isStmt() { return false; }
public getKind():Kind { return this._kind; }
public nodeType():string { return null; }
public children():AstNode[] { return []; }
public errorOf(e:ExprHolder)
{
if (this._error != null) return this._error;
else return e.getError();
}
private shouldCopy(propName:string)
{
return propName != "kind" && propName != "type";
}
public getError() { return this._error; }
public setError(m:string) { this._error = m; }
public clearError() { this._error = null; }
public writeTo(tw:TokenWriter) : void
{
Util.oops("writeTo not implemented");
}
public serialize() : string
{
var tw = TokenWriter.forStorage();
this.writeTo(tw);
return tw.finalize();
}
public accept(v:NodeVisitor):any
{
Util.oops("accept not implemented");
return null;
}
static freshNameCore(n:string, nameExists:(s:string) => boolean)
{
if (n == "") n = "x";
if (!nameExists(n)) return n;
if (n == "i") {
var better = ["j", "k", "l", "m", "n"].filter((n) => !nameExists(n))[0];
if (better) return better;
}
var prefix = TDev.RT.String_.trim_end(n, "0123456789");
var k = parseFloat(n.substr(prefix.length)) || 2;
while (nameExists(prefix + k)) k++;
return prefix + k;
}
}
export interface IStableNameEntry
{
getName():string;
initStableName(refresh:boolean);
getStableName():string;
setStableName(s:any);
deriveStableName(st:Stmt,ix:number);
}
export var uniqueAstId : (len:number) => string = (len) => Random.uniqueId(len);
// -------------------------------------------------------------------------------------------------------
// Statements
// -------------------------------------------------------------------------------------------------------
export class Stmt
extends AstNode
implements IStableNameEntry
{
private _name: string;
private stableName: string;
private stableVersions : string[];
public tutorialWarning: string;
public isUnreachable:boolean;
public _hint:string;
public _compilerBreakLabel:any;
public _compilerContinueLabel:any;
public _converterAwait:boolean;
public _compilerInfo:any;
public _inlineErrors:InlineError[];
constructor() {
super()
}
public isStmt() { return true; }
public isJump() { return false; }
public isExecutableStmt() { return false; }
public primaryBody():Block { return null; }
public calcNode():ExprHolder { return null; }
public children():AstNode[] { return this.calcNode() != null ? [this.calcNode()] : []; }
public getError()
{
var c = this.calcNode();
if (c != null)
return this.errorOf(c);
else
return this._error;
}
public getHint()
{
var r:string = null
if (this.calcNode())
r = this.calcNode().hint
if (!r) return this._hint
if (this._hint) return r + "\n" + this._hint
return r
}
public addHint(msg:string)
{
if (!this._hint) this._hint = msg
else this._hint += "\n" + msg
}
public clearError()
{
this._error = null
this._hint = null
this.isUnreachable = false
}
public debuggerRenderContext: {
isOnStackTrace ?: boolean;
isBreakPoint?: boolean;
isCurrentExecPoint?: boolean;
} = {};
public renderedAs:HTMLElement;
public renderedAsId:string;
public renderState:any; //RenderState;
public loopVariable():LocalDef { return null }
public setupForEdit() { }
// if this instanceof Block, these are attached at the beginning of the body, and otherwise after the the current statement
public diffStmts:Stmt[];
public diffAltStmt:Stmt;
public diffStatus:number; // -1, 0, +1, -N for moved old statements
public diffFeatures:any;
public stepState:any;
public nextStmt():Stmt
{
if (this.parent instanceof Block) {
var stmts = (<Block>this.parent).stmts
var idx = stmts.indexOf(this)
if (idx >= 0)
return stmts[idx + 1]
}
return null
}
public isCommentedOut()
{
return this.parent && (this.parent.isTopCommentedOut() || this.parent.isCommentedOut())
}
public isTopCommentedOut() { return false }
public parent:Stmt;
public parentBlock():AST.Block { return this.parent instanceof AST.Block ? <AST.Block> this.parent : null; }
public isLoneChild() { var p = this.parentBlock(); return p && p.stmts.length == 1; }
public isLastChild() { var p = this.parentBlock(); return p && p.stmts.peek() == this; }
public isFirstChild() { var p = this.parentBlock(); return p && p.stmts[0] == this; }
public allowSimplify() { return false }
public onDelete() { }
public isFirstNonComment() { var p = this.parentBlock(); return p && p.firstNonComment() == this; }
public isLastNonComment() { var p = this.parentBlock(); return p && p.lastNonComment() == this; }
public getName(): string { return this._name; }
public setName(s: string) {
this._name = s;
}
public getStableName() : string {
return this.stableName;
}
// input should be a string or an array of strings
public setStableName(s : any) {
if(s instanceof Array) {
this.stableName = s ? s.pop() : undefined;
// this.stableVersions = s;
this.stableVersions = undefined;
} else {
this.stableName = s;
this.stableVersions = undefined;
}
//console.log(">>>>> setStableName: "+this+" -> "+this.stableName+", ["+this.stableVersions+"]");
//if(this.stableName=="main") console.log(">>>>> "+(Script ? Script.serialize() : "undef"));
}
public initStableName(refresh = false) {
if(!this.stableName || refresh) {
this.setStableName(uniqueAstId(16));
}
}
public deriveStableName(s:Stmt, ix:number) {
this.setStableName(s.getStableName()+"$"+ix);
}
public writeId(tw:TokenWriter)
{
if(this.stableVersions) {
this.stableVersions.forEach(x => tw.uniqueId(x));
}
tw.uniqueId(this.getStableName());
}
public writeIdOpt(tw:TokenWriter)
{
this.writeId(tw);
}
public parentApp():App
{
var pa = this.parentAction()
if (pa) return pa.parent;
return null;
}
public parentAction():Action
{
for (var p = this.parent; p && !(p instanceof ActionHeader); p = p.parent)
;
if (p) return (<ActionHeader>p).action;
else return null;
}
public helpTopic()
{
return this.nodeType();
}
public forSearch() { return ""; }
public notifyChange()
{
if (this.parent) this.parent.notifyChange();
}
public innerBlocks()
{
return <Block[]>this.children().filter(c => c instanceof Block)
}
public isDescendant(stmt: Stmt) : boolean {
while (!!stmt) {
stmt = stmt.parent;
if (stmt == this) return true;
}
return false;
}
public matches(d:AstNode) {
var n = this.calcNode()
if (n)
for (var i = 0; i < n.tokens.length; ++i)
if (n.tokens[i].matches(d)) return true;
return false
}
public docText():string { return null }
}
// A special variety of statement that is displayed inline. Useful for
// making parts of the record definition clickable.
export class InlineStmt
extends Stmt
{
constructor() {
super();
}
public accept(v:NodeVisitor) { v.visitInlineStmt(this); }
public nodeType() {
return "inlineStmt";
}
}
// To hold a single token that holds the decl name. That
// allows the calculator to switch into editing mode, which is convenient.
// The [getName] and [setName] functions from the [DeclNameHolder] reflect
// the value of the (supposedly) single [DeclName] token that's in there.
export class DeclNameHolder
extends InlineStmt
{
public maxLength = -1; // used by the UI/typechecker
public defaultTemplate: string; // use to example when user deletes all characters
private exprHolder = new AST.ExprHolder();
constructor(public parentDecl : Decl) {
super();
this.exprHolder.tokens = [ new DeclName() ]
this.exprHolder.parsed = new Literal(); // placeholder
this.exprHolder.locals = [];
}
public children() {
return this.exprHolder.tokens;
}
public calcNode(): ExprHolder {
return this.exprHolder;
}
public notifyChange() {
var toks = this.exprHolder.tokens;
if (toks[0] && toks[0] instanceof DeclName) {
var newName = (<DeclName>toks[0]).data;
if (newName.length)
super.setName(newName);
else
(<DeclName>toks[0]).data = this.getName();
}
this.parentDecl.notifyChange();
}
public setName(v: string) {
super.setName(v);
var toks = this.exprHolder.tokens;
if (toks[0] && toks[0] instanceof DeclName)
(<DeclName>toks[0]).data = v;
}
}
export class Comment
extends Stmt
{
public text:string;
public mdDecl:AST.Decl;
constructor() {
super()
}
public nodeType() { return "comment"; }
public accept(v:NodeVisitor) { return v.visitComment(this); }
public writeTo(tw:TokenWriter)
{
this.writeIdOpt(tw);
tw.comment(this.text);
}
public forSearch() { return this.text.toLowerCase(); }
public docText() { return this.text }
// this means normal statement, and not Record or Field
public isExecutableStmt() { return true; }
}
export class FieldComment
extends Comment
{
constructor (private field: AST.RecordField) {
super()
}
public notifyChange() {
this.field.description =
this.parent.children().map(c => (<Comment> c).text)
.join("\n");
if (!this.field.description)
(<CodeBlock> this.parent).setChildren([]);
super.notifyChange();
}
}
export class Block
extends Stmt
{
public stmts:Stmt[];
constructor() {
super()
}
public nodeType() { return "block"; }
public children() { return this.stmts; }
public immutableReason = null;
public count() { return this.stmts.length; }
public newChild(s:Stmt) { s.parent = this; }
public setChild(i:number, s:Stmt)
{
this.stmts[i] = s;
this.newChild(s);
this.notifyChange();
}
public setChildren(s:Stmt[])
{
this.stmts = s;
this.stmts.forEach((q:Stmt) => this.newChild(q))
this.notifyChange();
}
public push(s:Stmt)
{
this.stmts.push(s);
this.newChild(s);
this.notifyChange();
}
public pushRange(s:Stmt[])
{
this.stmts.pushRange(s);
this.stmts.forEach((q:Stmt) => this.newChild(q))
this.notifyChange();
}
public writeTo(tw:TokenWriter)
{
tw.beginBlock();
this.stmts.forEach((s:Stmt) => { s.writeTo(tw); });
tw.endBlock();
}
public emptyStmt():Stmt { return Util.abstract() }
public allowEmpty() { return false; }
public allowAdding() { return true; }
public allowAddOf(n:Stmt) { return false }
public isBlockPlaceholder()
{
return this.stmts.length == 0 || (this.stmts.length == 1 && this.stmts[0].isPlaceholder());
}
public replaceChild(s:Stmt, newOnes:Stmt[])
{
var idx = this.stmts.indexOf(s)
var newCh = (idx >= 0 ? this.stmts.slice(0, idx) : []).concat(newOnes).concat(this.stmts.slice(idx + 1))
this.setChildren(newCh)
}
public forEach(f:(s:Stmt)=>void):void { this.stmts.forEach(f) }
public map(f: (s: Stmt) => any): any[]{ return this.stmts.map(f); }
public firstNonComment(): Stmt {
return this.stmts.filter(stmt => stmt.nodeType() !== "comment")[0];
}
public lastNonComment(): Stmt {
return this.stmts.filter(stmt => stmt.nodeType() !== "comment").peek();
}
public stmtsWithDiffs(): Stmt[]
{
if (this.diffStmts || this.stmts.some(s => !!s.diffStmts)) {
var res:AST.Stmt[] = []
if (this.diffStmts) res.pushRange(this.diffStmts)
this.stmts.forEach(s => {
res.push(s)
if (s.diffStmts)
res.pushRange(s.diffStmts)
})
return res;
} else {
return this.stmts;
}
}
public forEachInnerBlock(f:(b:Block)=>void)
{
for (var i = 0; i < this.stmts.length; ++i) {
var ch = this.stmts[i].children()
for (var j = 0; j < ch.length; ++j) {
if (ch[j] instanceof Block)
f(<Block>ch[j])
}
}
}
}
export enum BlockFlags {
None = 0x0000,
IsPageRender = 0x0001,
IsPageInit = 0x0002,
}
export class CodeBlock
extends Block
{
constructor() {
super()
}
public flags:BlockFlags;
public emptyStmt() { return Parser.emptyExprStmt(); }
public accept(v:NodeVisitor) { return v.visitCodeBlock(this); }
public nodeType() { return "codeBlock"; }
public newlyWrittenLocals:LocalDef[];
public allowAddOf(n:Stmt) { return n && n.isExecutableStmt() }
public writeTo(tw:TokenWriter)
{
tw.beginBlock();
for (var i = 0; i < this.stmts.length; ++i) {
var s = this.stmts[i]
if (s instanceof If && isElseIf(this.stmts[i+1])) {
var si = <If>s;
si.writeCore(tw)
var numOpen = 1
tw.keyword("else").op("{")
while (true) {
if (!isElseIf(this.stmts[i+1]))
break;
i++;
si = <If>this.stmts[i];
si.writeCore(tw)
tw.keyword("else");
if (!si.rawElseBody.isBlockPlaceholder()) {
tw.node(si.rawElseBody);
break;
}
tw.op("{");
numOpen++;
}
while (numOpen-- > 0)
tw.op("}");
tw.nl();
} else {
s.writeTo(tw)
}
}
tw.endBlock();
}
}
export class ConditionBlock
extends Block
{
constructor() {
super()
}
public emptyStmt() { return Parser.emptyCondition(); }
public accept(v:NodeVisitor) { return v.visitConditionBlock(this); }
public nodeType() { return "conditionBlock"; }
public allowAddOf(n:Stmt) { return n instanceof ForeachClause }
public allowEmpty() { return true; }
}
export class ParameterBlock
extends Block
{
constructor() {
super()
this.stmts = [];
}
public allowEmpty() { return true; }
public emptyStmt(name? : string, kind? : Kind)
{
var isOut = (<ActionHeader>this.parent).outParameters == this;
var r = new ActionParameter(mkLocal((<AST.ActionHeader>this.parent).action.nameLocal(name || (isOut ? "r" : "p")), kind || api.core.Number), isOut);
r.parent = this;
return r;
}
public accept(v:NodeVisitor) { return v.visitParameterBlock(this); }
public allowAddOf(n:Stmt) { return n instanceof ActionParameter }
// no need to offload parameters
public nodeType() { return "parameterBlock"; }
public children()
{
if (this.parent && (<ActionHeader>this.parent).inParameters == this) {
var act = (<ActionHeader>this.parent).action
if (act && act.modelParameter)
return [<Stmt>act.modelParameter].concat(this.stmts)
}
return this.stmts
}
}
export class BindingBlock
extends Block
{
constructor() {
super()
this.stmts = [];
}
public allowEmpty() { return true; }
public emptyStmt():Stmt { return null; } // no can do
public accept(v:NodeVisitor) { return v.visitBindingBlock(this); }
public nodeType() { return "bindingBlock"; }
public allowAddOf(n:Stmt) { return n instanceof Binding }
}
export class ResolveBlock
extends Block
{
constructor() {
super()
this.stmts = [];
}
public allowEmpty() { return true; }
public emptyStmt():Stmt { return null; } // no can do
public accept(v:NodeVisitor) { return v.visitResolveBlock(this); }
public push(s:Stmt) { this.stmts.push(s); s.parent = this; }
public nodeType() { return "resolveBlock"; }
public allowAddOf(n:Stmt) { return n instanceof ResolveClause }
}
export class FieldBlock
extends Block
{
constructor() {
super()
this.stmts = [];
}
public allowEmpty() { return true; }
public isKeyBlock() { return this.parentDef.keys == this; }
public allowAddOf(n:Stmt) { return n instanceof RecordField }
public mkUniqName(basename: string) {
var names = this.parentDef.getFields().map((f) => f.getName());
return AstNode.freshNameCore(basename, (n) => names.indexOf(n) >= 0)
}
public mkField(basename:string, k:Kind)
{
var n = this.mkUniqName(basename);
var r = new RecordField(n, k, this.isKeyBlock());
return r;
}
public emptyStmt()
{
var basename = "f"
var k = api.core.String
if (this.isKeyBlock()) {
if (this.parentDef.recordType == RecordType.Table) {
var kinds = Script.getKinds().filter((k: Kind) =>
(k != this.parentDef.entryKind &&
k.isData && k.hasContext(KindContext.RowKey)) &&
(!this.parentDef.locallypersisted() || (<RecordEntryKind>k).getRecord().locallypersisted()) &&
(!this.parentDef.cloudEnabled || (<RecordEntryKind>k).getRecord().cloudEnabled));
if (kinds.length == 0) return null;
k = kinds[0];
basename = "l"
} else {
basename = "k"
}
}
return this.mkField(basename, k);
}
public accept(v:NodeVisitor) { return v.visitFieldBlock(this); }
public parentDef:RecordDef;
public notifyChange()
{
super.notifyChange();
this.parentDef.notifyChange();
}
public fields():RecordField[] { return <RecordField[]>this.stmts; }
public nodeType() { return "fieldBlock"; }
}
export class InlineActionBlock
extends Block
{
constructor() {
super()
this.stmts = [];
}
public allowAdding() { return !!(<InlineActions>this.parent).getOptionsParameter() }
public allowEmpty() { return true; }
public emptyStmt() { return OptionalParameter.mk(""); }
public accept(v:NodeVisitor) { return v.visitInlineActionBlock(this); }
public push(s:Stmt) { this.stmts.push(s); s.parent = this; }
public nodeType() { return "inlineActionBlock"; }
public allowAddOf(n:Stmt) { return n instanceof InlineAction }
}
export class Loop
extends Stmt
{
public body:CodeBlock;
public primaryBody() { return this.body; }
public isExecutableStmt() { return true; }
public loopVariable():LocalDef { return null }
}
export class For
extends Loop
{
public boundLocal:LocalDef;
public upperBound:ExprHolder;
public nodeType() { return "for"; }
public calcNode() { return this.upperBound; }
public children() { return [<AstNode> this.upperBound, this.body]; }
public accept(v:NodeVisitor) { return v.visitFor(this); }
public allowSimplify() { return true }
public loopVariable():LocalDef { return this.boundLocal }
public writeTo(tw:TokenWriter)
{
this.writeIdOpt(tw);
tw.keyword("for").op("0").op("\u2264").id(this.boundLocal.getName()).op("<");
tw.node(this.upperBound).keyword("do").node(this.body);
}
private parseFrom(p:Parser)
{
this.setStableName(p.consumeLabel());
p.skipOp("0");
p.skipOp("\u2264");
this.boundLocal = mkLocal(p.parseId("i"), api.core.Number);
p.skipOp("<");
this.upperBound = p.parseExpr();
p.skipKw("do");
this.body = p.parseBlock();
this.body.parent = this;
}
public forSearch() { return "for do " + this.upperBound.forSearch(); }
}
export class Foreach
extends Loop
{
public boundLocal:LocalDef;
public collection:ExprHolder;
// the block contains Where stmts only (at the moment; in future there might be OrderBy etc)
public conditions:ConditionBlock;
public nodeType() { return "foreach"; }
public calcNode() { return this.collection; }
public accept(v:NodeVisitor) { return v.visitForeach(this); }
public children() { return [<AstNode> this.collection, this.conditions, this.body]; }
public allowSimplify() { return true }
public loopVariable():LocalDef { return this.boundLocal }
public writeTo(tw:TokenWriter)
{
this.writeIdOpt(tw);
tw.keyword("foreach").id(this.boundLocal.getName()).keyword("in").node(this.collection).nl();
this.conditions.stmts.forEach((c:Stmt) => { c.writeTo(tw) });
tw.keyword("do").node(this.body);
}
private parseFrom(p:Parser)
{
this.setStableName(p.consumeLabel());
this.boundLocal = mkLocal(p.parseId("e"), api.core.Unknown);
p.skipKw("in");
this.collection = p.parseExpr();
var conds:Stmt[] = []
p.shiftLabel();
while (p.gotKw("where")) {
p.shift();
var wh = mkWhere(p.parseExpr());
wh.setStableName(p.consumeLabel());
conds.push(wh);
p.shiftLabel();
}
if (conds.every(s => s instanceof Where && (<Where>s).condition.getLiteral() === true))
conds = []
this.conditions = new ConditionBlock();
this.conditions.setChildren(conds);
this.conditions.parent = this;
p.skipKw("do");
this.body = p.parseBlock();
this.body.parent = this;
}
public forSearch() { return "foreach for each in do " + this.collection.forSearch(); }
}
export class While
extends Loop
{
public condition:ExprHolder;
public nodeType() { return "while"; }
public calcNode() { return this.condition; }
public accept(v:NodeVisitor) { return v.visitWhile(this); }
public children() { return [<AstNode> this.condition, this.body]; }
public writeTo(tw:TokenWriter)
{
this.writeIdOpt(tw);
tw.keyword("while").node(this.condition);
tw.keyword("do").node(this.body);
}
private parseFrom(p:Parser)
{
this.setStableName(p.consumeLabel());
this.condition = p.parseExpr();
p.skipKw("do");
this.body = p.parseBlock();
this.body.parent = this;
}
public forSearch() { return "while do " + this.condition.forSearch(); }
}
export interface IfBranch
{
condition: ExprHolder;
body: CodeBlock;
}
export class If
extends Stmt
{
public rawCondition:ExprHolder;
public rawThenBody:CodeBlock;
public rawElseBody:CodeBlock;
// this is filled out by every type check when not isElseIf
// the last branch has condition==null - it's the final else branch
public branches: IfBranch[];
public parentIf: If;
public isElseIf:boolean;
public displayElse:boolean = true;
public allowSimplify() { return !this.isElseIf }
public nodeType() { return this.isElseIf ? "elseIf" : "if"; }
public accept(v:NodeVisitor) { return this.isElseIf ? v.visitElseIf(this) : v.visitIf(this); }
constructor() {
super()
}
public calcNode() { return this.rawCondition; }
public children() { return [<AstNode> this.rawCondition, this.rawThenBody, this.rawElseBody]; }
public setElse(s:CodeBlock)
{
this.rawElseBody = s;
s.parent = this;
}
public isTopCommentedOut()
{
if (!this.isElseIf && this.rawElseBody.isBlockPlaceholder() && this.rawCondition.getLiteral() === false) {
var n = this.nextStmt()
if (n instanceof If && (<If>n).isElseIf)
return false
return true
}
return false
}
public primaryBody() { return this.rawThenBody; }
public isExecutableStmt() { return true; }
public writeTo(tw:TokenWriter)
{
if (this.isElseIf)
tw.keyword("else")
this.writeCore(tw)
if (!this.rawElseBody.isBlockPlaceholder())
tw.keyword("else").node(this.rawElseBody);
}
public writeCore(tw:TokenWriter)
{
this.writeIdOpt(tw);
tw.keyword("if").node(this.rawCondition).keyword("then").node(this.rawThenBody);
}
public parseFrom(p:Parser)
{
this.setStableName(p.consumeLabel());
this.rawCondition = p.parseExpr();
p.skipKw("then");
this.rawThenBody = p.parseBlock();
this.rawThenBody.parent = this;
this.setElse(Parser.emptyBlock())
}
public forSearch() { return "if then " + this.rawCondition.forSearch(); }
public bodies():CodeBlock[]
{
if (this.isElseIf) return []
return this.branches.map(b => b.body)
}
}
export function isElseIf(s:Stmt) {
return s instanceof If && (<If>s).isElseIf;
}
export class Box
extends Stmt
{
public body:CodeBlock;
constructor() {
super()
}
private emptyExpr = Parser.emptyExpr();
public nodeType() { return "boxed"; }
public calcNode() { return this.emptyExpr; }
public primaryBody() { return this.body; }
public accept(v:NodeVisitor) { return v.visitBox(this); }
public children() { return [<AstNode>this.body]; }
public isExecutableStmt() { return true; }
public writeTo(tw:TokenWriter)
{
this.writeIdOpt(tw);
tw.keyword("do").id("box").node(this.body);
}
private parseFrom(p:Parser)
{
this.setStableName(p.consumeLabel());
this.body = p.parseBlock();
this.body.parent = this;
}
public forSearch() { return "boxed"; }
}
export class ExprStmt
extends Stmt
{
public expr:ExprHolder;
constructor() {
super()
}
public isVarDef() {
return this.expr.looksLikeVarDef ||
(!!this.expr.assignmentInfo() && this.expr.assignmentInfo().definedVars.length > 0);
}
public isPagePush() { return !!this.expr.assignmentInfo() && this.expr.assignmentInfo().isPagePush; }
public nodeType() { return "exprStmt"; }
public calcNode() { return this.expr; }
public isPlaceholder() { return this.expr.isPlaceholder(); }
public accept(v:NodeVisitor) { return v.visitExprStmt(this); }
public isExecutableStmt() { return true; }
public allowSimplify() { return true }
public isJump()
{
if (this.expr.parsed) {
var p = this.expr.parsed.getCalledProperty()
if (p == api.core.ReturnProp ||
p == api.core.BreakProp ||
p == api.core.ContinueProp)
return true
}
return false
}
public helpTopic() { return this.isVarDef() ? "var" : "commands"; }
public writeTo(tw:TokenWriter)
{
this.writeIdOpt(tw);
if (this.isPlaceholder()) tw.keyword("skip");
else tw.node(this.expr);
tw.op0(";").nl();
}
public forSearch() { return (this.isVarDef() ? "var " : "") + this.expr.forSearch(); }
public docText():string
{
var prop = this.expr.parsed ? this.expr.parsed.getCalledProperty() : null
if (!prop) return null;
if (prop.getName() == "docs render") return this.docsRender();
else if (prop.parentKind == api.getKind("Docs") && prop.getName() == "bitmatrix") return this.bitmatrixRender();
return null;
}
private bitmatrixRender(): string {
var c = <Call>this.expr.parsed
if (c.args.length != 2) return null;
var bits = c.args[1].getStringLiteral() || ""
return "```` bitmatrix\n" + bits + "\n````"
}
private docsRender(): string {
var c = <Call>this.expr.parsed
var arg0 = <GlobalDef>c.args[0].getCalledProperty()
if (arg0 instanceof GlobalDef) {
var url = arg0.url
}
if (!url) return null
if (arg0.getKind() == api.core.Picture) {
var h = c.args[1].getNumberLiteral() || 12
var cap = c.args[2].getStringLiteral() || ""
return "{pic:" + arg0.getName() + ":" + h + "x" + h + (cap ? ":" + cap : "") + "}"
}
if (arg0.getKind().getName() == "Document") {
var cap = c.args[1].getStringLiteral() || arg0.getName()
return "[" + cap + "] (" + url + ")"
}
return null
}
}
export class InlineActionBase
extends Stmt
{
public recordField:RecordField;
public _sort_key:number;
public getName() { return "" }
}
export class OptionalParameter
extends InlineActionBase
{
public _opt_name:string;
public expr:ExprHolder;
public getName()
{
return this.recordField ? this.recordField.getName() : this._opt_name;
}
constructor() {
super()
}
static mk(name:string)
{
var opt = new AST.OptionalParameter()
opt.expr = AST.Parser.emptyExpr()
opt._opt_name = name
return opt
}
public nodeType() { return "optionalParameter"; }
public calcNode() { return this.expr; }
public accept(v:NodeVisitor) { return v.visitOptionalParameter(this); }
public children() { return [<AstNode> this.expr]; }
public writeTo(tw:TokenWriter)
{
this.writeIdOpt(tw);
tw.keyword("where").id(this.getName()).op(":=").node(this.expr).op0(";").nl();
}
public parseFrom(p:Parser)
{
this.setStableName(p.consumeLabel());
this._opt_name = p.parseId()
p.skipOp(":=")
this.expr = p.parseExpr();
p.skipOp(";")
}
public forSearch() { return "with " + this.getName() + " := " + this.expr.forSearch(); }
static optionsParameter(prop:IProperty) : PropertyParameter
{
if (!prop) return null
var last = prop.getParameters().peek()
if (!last) return null
if (!/\?$/.test(last.getName())) return null
var lk = last.getKind()
if (!lk.isUserDefined()) return null
var rec = lk.getRecord()
if (rec && rec.tableKind.getProperty("create"))
return last
return null
}
}
export class InlineAction
extends InlineActionBase
{
public name:LocalDef;
public inParameters:LocalDef[] = [];
public outParameters:LocalDef[] = [];
public body:CodeBlock;
public closure:LocalDef[];
public allLocals:LocalDef[];
public isImplicit:boolean;
public isOptional:boolean;
public children() { return [<AstNode> this.body] }
public nodeType() { return "inlineAction"; }
public helpTopic() { return "inlineActions"; }
public getName() { return this.recordField ? this.recordField.getName() : this.name.getName() }
constructor() { super() }
static mk(name:LocalDef)
{
var inl = new InlineAction();
inl.name = name;
inl.body = new CodeBlock();
inl.body.parent = inl;
inl.body.setChildren([inl.body.emptyStmt()]);
return inl;
}
public writeTo(tw:TokenWriter)
{
this.writeIdOpt(tw);
var writeParms = (parms:LocalDef[]) =>
{
var first = true;
parms.forEach((l) => {
if (!first) tw.op0(",").space();
l.writeWithType(this.parentApp(), tw);
first = false;
});
}
tw.keyword("where");
if (this.isImplicit)
tw.op("implicit")
if (this.isOptional)
tw.op("optional")
tw.id(this.name.getName()).op0("(");
writeParms(this.inParameters);
tw.op0(")");
if (this.outParameters.length > 0) {
tw.space().keyword("returns").space().op0("(");
writeParms(this.outParameters);
tw.op0(")");
}
this.body.writeTo(tw);
}
public parseFrom(p:Parser)
{
this.setStableName(p.consumeLabel());
if (p.gotOp("implicit")) {
this.isImplicit = true
p.shift()
}
if (p.gotOp("optional")) {
this.isOptional = true
p.shift()
}
var hd = p.parseActionHeader();
this.name = mkLocal(hd.name, api.core.Unknown);
if (this.isImplicit)
this.name.isSynthetic = true;
this.inParameters = hd.inParameters.map((p) => p.local);
this.outParameters = hd.outParameters.map((p) => p.local);
this.body = p.parseBlock();
this.body.parent = this;
}
public forSearch() { return "where " + this.name.getName(); } // TODO add parameters?
public accept(v:NodeVisitor) { return v.visitInlineAction(this); }
// public isExecutableStmt() { return true; } ??
}
export class InlineActions
extends ExprStmt
{
public actions:InlineActionBlock = new InlineActionBlock();
constructor() {
super()
this.actions = new InlineActionBlock();
this.actions.parent = this;
}
public nodeType() { return "inlineActions"; }
public isPlaceholder() { return false; }
public accept(v:NodeVisitor) { return v.visitInlineActions(this); }
public children() { return [<AstNode> this.expr, this.actions]; }
public getOptionsParameter():PropertyParameter
{
var topCall = this.calcNode().topCall()
if (!topCall) return null
var optionsParm = AST.OptionalParameter.optionsParameter(topCall.getCalledProperty())
return optionsParm
}
public optionalParameters():InlineActionBase[]
{
return (<InlineActionBase[]>this.actions.stmts).filter(s => {
if (s instanceof InlineAction)
return (<InlineAction>s).isOptional
else if (s instanceof OptionalParameter)
return true
else
Util.oops("bad element " + s.nodeType())
})
}
public normalActions():InlineAction[]
{
return <InlineAction[]>this.actions.stmts.filter(s => s instanceof InlineAction && !(<InlineAction>s).isOptional)
}
public implicitAction():InlineAction
{
var last = this.actions.stmts.peek()
if (last instanceof InlineAction) {
var i = <InlineAction>last
return i.isImplicit ? i : null
}
return null
}
static isImplicitActionKind(k:Kind)
{
if (k instanceof ActionKind) {
var ak = <ActionKind>k
return ak.getInParameters().length == 0 && ak.getOutParameters().length == 0
}
return false
}
public writeTo(tw:TokenWriter)
{
super.writeTo(tw);
this.actions.forEach((a) => a.writeTo(tw));
}
public sortOptionals()
{
var opt0 = this.optionalParameters()[0]
if (!opt0 || !opt0.recordField) return
var lst = opt0.recordField.def().values.stmts
var problem = false
this.actions.forEach((iab:InlineActionBase) => {
if (iab.recordField) {
iab._sort_key = lst.indexOf(iab.recordField)
if (iab._sort_key < 0) problem = true
} else if (iab instanceof InlineAction) {
iab._sort_key = (<InlineAction>iab).isImplicit ? 1.1e10 : 1e10;
} else {
problem = true
}
})
if (problem) return
this.actions.stmts.sort((a:InlineActionBase, b:InlineActionBase) => a._sort_key - b._sort_key)
this.actions.notifyChange()
}
static implicitActionParameter(prop:IProperty) : PropertyParameter
{
if (!prop) return null
var parms = prop.getParameters()
if (OptionalParameter.optionsParameter(prop)) parms.pop()
var last = parms.peek()
if (!last) return null
if (last.getName() == "body" && InlineActions.isImplicitActionKind(last.getKind()))
return last
return null
}
}
export class ForeachClause
extends Stmt
{
constructor() {
super()
}
}
export class Where
extends ForeachClause
{
public condition:ExprHolder;
constructor() {
super()
}
public nodeType() { return "where"; }
public calcNode() { return this.condition; }
public accept(v:NodeVisitor) { return v.visitWhere(this); }
public isPlaceholder()
{
return this.condition.isPlaceholder() ||
(this.condition.tokens.length == 1 && this.condition.tokens[0].getText() == "true");
}
public writeTo(tw:TokenWriter)
{
this.writeIdOpt(tw);
tw.keyword("where").node(this.condition).nl();
}
public forSearch() { return "where " + this.condition.forSearch(); }
}
// pseudo-statements - they can be selected just like statements in the code editor
export class ActionParameter
extends Stmt
{
// We're using the same tricks as for the [RecordField] to turn this
// into an editable statement.
private exprHolder = new AST.ExprHolder();
constructor(public local:LocalDef, private isOut = false, public isClosure = false) {
super();
this.setupForEdit()
}
public setupForEdit() {
var name = new FieldName(this.isOut);
name.data = this.getName();
this.exprHolder.tokens = [ <AST.Token> name ].concat(propertyRefsForKind(this.local.getKind()));
this.exprHolder.parsed = new AST.Literal(); // placeholder
this.exprHolder.locals = [];
}
public calcNode() {
return this.exprHolder;
}
public notifyChange() {
// See [RecordField] for comments. In essence, we're reflecting the
// changes performed via the editor onto our [LocalDef]. Further
// calls to [getName] and [getKind] will fetch the value from the
// [LocalDef].
var toks = this.exprHolder.tokens;
if (toks.length == 0 && this.parent) {
var pb = <ParameterBlock> this.parent;
var ch = pb.children().filter(x => x != this);
pb.setChildren(ch);
} else if (toks[0] && toks[0] instanceof FieldName) {
// Propagate the new name, if any.
var newName = (<FieldName>toks[0]).data;
if (this.getName() != newName) {
var uniqName = this.parentAction().nameLocal(newName);
this.local.rename(uniqName);
(<AST.FieldName> toks[0]).data = uniqName;
}
// Propagate the kind, if any.
if (toks.length > 1) {
var k = this.exprHolder.getKind();
if (isProperKind(k) && k != this.local.getKind()) {
this.local.setKind(k);
TypeChecker.tcApp(Script);
}
}
}
if (toks.length > 1 && toks[1] instanceof AST.PropertyRef)
(<AST.PropertyRef>toks[1]).skipArrow = true;
super.notifyChange();
}
public getName() { return this.local.getName(); }
public getKind() { return this.local.getKind(); }
public nodeType() { return "actionParameter"; }
public accept(v:NodeVisitor) { return v.visitActionParameter(this); }
public theAction() { return (<AST.ActionHeader>this.parent.parent).action; }
public forSearch() { return this.getName() + " " + this.getKind().toString(); }
public writeTo(tw:TokenWriter)
{
tw.keyword("var");
this.local.writeWithType(this.parentApp(), tw);
tw.op0(";").nl();
}
public matches(d:AstNode)
{
return this.getKind() && this.getKind().matches(d)
}
}
export class ActionHeader
extends Stmt
{
public inParameters:ParameterBlock = new ParameterBlock();
public outParameters:ParameterBlock = new ParameterBlock();
constructor(public action:Action) {
super()
this.inParameters.parent = this;
this.outParameters.parent = this;
}
public getName() { return this.action.getName(); }
public nodeType() { return "actionHeader"; }
public children() {
return [<AST.Stmt>this.inParameters, this.outParameters, this.action.body];
}
public primaryBody() { return this.action.body; }
public accept(v:NodeVisitor) { return v.visitActionHeader(this); }
public writeTo(tw:TokenWriter)
{
this.action.writeHeader(tw)
}
public notifyChange()
{
super.notifyChange();
this.action.notifyChange();
}
}
export interface ProfilingAstNodeData {
count: number; // number of node executions
duration: number; // total duration of node executions
}
export interface DebuggingAstNodeInfo {
alwaysTrue?: boolean;
alwaysFalse?: boolean;
visited?: boolean;
critical?: number;
max?: { critical: number };
errorMessage?: string;
// other stuff may go here
}
// -------------------------------------------------------------------------------------------------------
// Declarations
// -------------------------------------------------------------------------------------------------------
export class Decl
extends Stmt
{
public _wasTypechecked = false;
public deleted:boolean;
public parent:App;
public wasAutoNamed = false;
public visitorState:any;
public diffStatus:number;
public diffAltDecl:Decl;
public isExternal: boolean;
public nameHolder: DeclNameHolder;
constructor() {
super();
this.nameHolder = new DeclNameHolder(this);
}
public getCoreName() { return this.nameHolder.getName(); }
public getName() { return this.nameHolder.getName(); }
public setName(name: string) { this.nameHolder.setName(name);}
public getIconArtId(): string { return null; }
public hasErrors() { return !!this.getError(); }
public hasWarnings() { return false }
public getDescription(skip?:boolean) { return ""; }
public isBrowsable() { return true; }
public propertyForSearch():IProperty { return null; }
public toString() { return this.getName(); }
public helpTopic(): string { return null; }
public usageKey():string { return null; }
public freshlyCreated() { }
public getDefinedKind():Kind { return null }
public matches(d:AstNode)
{
if (this.getKind() && this.getKind().matches(d))
return true
return this == d
}
public cachedSerialized:IndexedString;
public canRename() { return true; }
public notifyChange()
{
super.notifyChange();
if (this.cachedSerialized) {
var idx = this.cachedSerialized.idx;
if (idx > 0)
this.cachedSerialized.idx = -idx;
}
}
public nodeType() { return "decl"; }
public accept(v:NodeVisitor) { return v.visitDecl(this); }
}
export class PropertyDecl
extends Decl
{
constructor() {
super()
this._usage = new TokenUsage(this);
}
public getSignature():string { return Property.getSignatureCore(<any>this); }
public canCacheSearch() { return false; }
public thingSetKindName() { return null; }
public getInfixPriority() { return 0; }
public forwardsTo() { return this; }
public forwardsToStmt():Stmt { return null; }
public propertyForSearch():IProperty { return <IProperty> (<any> this); }
public parentKind:Kind;
public getCapability() { return PlatformCapability.None }
public getExplicitCapability() { return this.getCapability() }
public isBeta() { return false }
public showIntelliButton() { return true }
public getImports() : IImport[] { return undefined; }
public isExtensionAction() { return false; }
public shouldPauseInterperter() { return false; }
public isImplemented() { return true; }
public isImplementedAnywhere() { return this.isImplemented() }
public isSupported() { return true; }
public getSpecialApply():string { return null; }
public isBrowsable() { return true; }
private _usage:TokenUsage;
public getUsage() { return this._usage; }
public lastMatchScore:number;
public useFullName:boolean;
public helpTopic() { return this.nodeType(); }
public getFlags() { return PropertyFlags.None }
public getArrow()
{
return "\u200A";
}
public runtimeName()
{
return Api.runtimeName(this.getName())
}
// tracing
public needsSpecialTracing() { return false; }
public needsTracing() { return false; }
public needsTimestamping() { return false; }
public hasPauseContinue() { return false; }
static mkPPext(s:IProperty, name:string, k:Kind)
{
var pp = new PropertyParameter(name, k);
pp.parentProperty = s;
return pp;
}
public mkPP(name:string, k:Kind) { return PropertyDecl.mkPPext(<any>this, name, k); }
public getParameters():PropertyParameter[] { return [this.mkPP("_this_", this.parentKind)]; }
public getResult():PropertyParameter { return this.mkPP(this.getName(), this.getKind()); }
public getNamespace()
{
var pkn = this.thingSetKindName()
if (!pkn) return null
var k = api.getKind(pkn)
if (!k) return null
return k.shortName() + "\u200A";
}
public setName(s:string)
{
super.setName(s);
if (this.parent) {
this.parent.notifyChangeAll();
}
}
/*
getCategory():PropertyCategory;
*/
}
export var artSymbol = "\u273f";
export var dataSymbol = "\u25f3";
export var codeSymbol = "\u25b7";
export class GlobalDef
extends PropertyDecl
implements IProperty
{
public readonly:boolean = false;
public comment:string = "";
public url:string = "";
public isResource:boolean = false;
public isTransient: boolean = true;
public cloudEnabled: boolean = false;
public debuggingData: { critical: number; max: { critical: number }; };
public usageLevel:number;
constructor() {
super()
}
public children() : AstNode[] { return []; }
public nodeType() { return "globalDef"; }
public helpTopic() { return this.thingSetKindName() }
public accept(v:NodeVisitor) { return v.visitGlobalDef(this); }
public getDescription()
{
if (this.isResource && this.getKind() == api.core.Color)
return lf("color #{0}", this.url);
return lf("a global variable")
}
public forSearch()
{
return this.stringResourceValue() || this.url || ""
}
public stringResourceValue()
{
if (this.isResource && this.getKind() == api.core.String && this.url) {
return RT.String_.valueFromArtUrl(this.url)
}
return null
}
public thingSetKindName() { return this.isResource ? "art" : "data"; }
public getCategory() { return PropertyCategory.Data; }
public setKind(k:Kind)
{
this._kind = k;
//if (!k.isSerializable)
// this.isTransient = true;
}
public writeTo(tw:TokenWriter)
{
this.writeId(tw);
tw.nl().keyword("var").id(this.getName()).op(":").kind(this.parent, this.getKind());
tw.beginBlock();
if (!!this.comment)
tw.comment(this.comment);
if (this.isResource) {
tw.boolOptAttr("is_resource", this.isResource);
if (!!this.url) tw.stringAttr("url", this.url);
} else
tw.boolOptAttr("readonly", this.readonly);
tw.boolOptAttr("transient", this.isTransient);
tw.boolOptAttr("cloudenabled", this.cloudEnabled);
tw.endBlock();
}
static parse(p:Parser)
{
var v = new GlobalDef();
v.setStableName(p.consumeLabel());
v.isTransient = false;
p.addDecl(v);
v.setName(p.parseId());
v.setKind(p.parseTypeAnnotation());
p.parseBraced(() => {
if (p.gotKey("readonly")) v.readonly = p.parseBool();
if (p.gotKey("transient")) v.isTransient = p.parseBool();
if (p.gotKey("cloudenabled")) v.cloudEnabled = p.parseBool();
if (p.gotKey("is_resource")) {
v.isResource = p.parseBool();
if (v.isResource) v.readonly = true;
}
if (p.gotKey("url")) v.url = p.parseString();
if (p.got(TokenType.Comment)) v.comment += p.shift().data + "\n";
});
if (v.cloudEnabled) v.isTransient = false;
}
public getRecordPersistence()
{
if (this.cloudEnabled) return RecordPersistence.Cloud;
if (!this.isTransient) return RecordPersistence.Local;
return RecordPersistence.Temporary;
}
public notifyChange() {
super.notifyChange();
// we are editing data structure definitions! Must ensure to remove all stale state.
if (Runtime.theRuntime)
Runtime.theRuntime.resetData();
}
}
export class SingletonDef
extends Decl
{
public isExtension = false;
private _description : string;
public firstLibraryRef:LibraryRef;
public _isBrowsable = true;
constructor() {
super()
this.usage = new TokenUsage(this);
}
public usage:TokenUsage;
public getUsage() { return this.usage; }
public nodeType() { return "singletonDef"; }
public accept(v:NodeVisitor) { return v.visitSingletonDef(this); }
public getDescription(skip?: boolean) {
if (!this._description) {
this._description = this.getKind().getHelp(!skip);
if (this.isExtension && this.firstLibraryRef.resolved) {
var stringResource = this.firstLibraryRef.resolved
.resources().filter(n => n.getName() == "namespacedocs.json")[0]
if (stringResource) {
try {
var jsdocs = JSON.parse(RT.String_.valueFromArtUrl(stringResource.url));
if (jsdocs[this.getName()]) this._description = jsdocs[this.getName()];
} catch (e) { }
}
}
}
return this._description;
}
public isBrowsable() { return this._isBrowsable; }
public usageMult() { return 1; }
public usageKey() {
return Util.tagify(this.getKind().getName());
}
}
export class PlaceholderDef
extends Decl
{
constructor() {
super()
}
public nodeType() { return "placeholderDef"; }
public getDescription() { return "need " + this.getKind().toString() + " here"; }
public isBrowsable() { return false; }
public escapeDef:any;
public getName() { return "need " + this.getKind().serialize() + (this.label ? ":" + this.label : ""); }
public label:string;
public longError()
{
return lf("TD100: insert {0:a} here", this.label || this.getKind().toString())
}
}
export interface ParameterAnnotations {
hints?:string[];
enumMap?:StringMap<string>;
pichints?:StringMap<string>;
language?:string;
}
export class Action
extends PropertyDecl
implements IPropertyWithNamespaces
{
constructor() {
super()
this.header = new ActionHeader(this);
}
public nodeType() { return "action"; }
public header:ActionHeader;
public _isTest:boolean;
public isTest():boolean { return this._isTest && (this.isCompilerTest() || !this.hasInParameters()) }
public isNormalAction() { return !this.isPage() && !this.isEvent() && !this.isLambda }
public isEvent() { return !!this.eventInfo; }
public isPage() { return this._isPage; }
public isPrivate: boolean;
public isQuery: boolean;
public isOffline: boolean;
public isLambda:boolean;
public numUnsupported = 0;
private isShareTarget:boolean;
private definedKind:UserActionKind;
public body:CodeBlock;
public _hasErrors:boolean;
public _errorsOK:boolean;
public _isPage:boolean;
public _isActionTypeDef:boolean;
public _compilerInlineAction:InlineAction;
public _compilerParentAction:Action; // this is only set for synthetic actions created in compiler for lambda expressions
public _compilerInlineBody:Stmt;
public _skipIntelliProfile:boolean;
public allLocals:LocalDef[];
public accept(v:NodeVisitor) { return v.visitAction(this); }
public children() { return [this.header]; }
public hasErrors() { return this._hasErrors; }
public isMainAction() { return this.parent && this.parent.mainAction() == this; }
public eventInfo:EventInfo;
public parentLibrary():LibraryRef { return this.parent && this.parent.isTopLevel && this.parent.thisLibRef; }
public thingSetKindName() { return this.isEvent() ? null : "code"; }
public isActionTypeDef() { return this._isActionTypeDef; }
public isExtensionAction() : boolean { return false }
public extensionForward():Action { return this }
public hasWarnings() { return this.numUnsupported > 0 }
public getExtensionKind():Kind
{
var p = this.getInParameters()
if (p.length >= 1 && !/\?$/.test(p[0].getName()) &&
p[0].getKind().isExtensionEnabled())
return p[0].getKind()
return null
}
public getHelpPath() : string {
var desc = this.getDescription()
var m = /{help:([^}]+)}/i.exec(desc);
return m ? m[1] : undefined;
}
public getNamespaces():string[]
{
var desc = this.getDescription()
if (!/{namespace:/.test(desc)) return []
var res = [];
desc.replace(/{namespace:([^}]+)}/g, (m, ns) => { res.push(ns); return "" })
return res
}
public getShimName():string
{
var shm = /{(shim|asm):([^{}]*)}/.exec(this.getDescription())
if (shm) return shm[2]
return null
}
public getFlags()
{
var flags = !this.isAtomic ? PropertyFlags.Async : PropertyFlags.None
if (this.body)
for (var i = 0; i < this.body.stmts.length; ++i) {
var s = this.body.stmts[i].docText()
if (s != null) {
var m = /{action:([^\}]+)}/i.exec(s);
if (m) {
m[1].split(',').forEach(fl => {
switch (fl.toLowerCase()) {
case "ignorereturn":
flags |= PropertyFlags.IgnoreReturnValue; break;
case "libsonly":
flags |= PropertyFlags.LibsOnly; break;
default:
this.setError(lf("unknown flag")); break;
}
})
}
} else {
break;
}
}
return flags
}
public clearError()
{
super.clearError();
this.numUnsupported = 0
}
public isInLibrary() { return false }
public markUsed() { }
public isLibInit()
{
return !this.isPrivate && this.getName() == "_libinit" && this.getOutParameters().length == 0 && this.getInParameters().length == 0;
}
public modelParameter:ActionParameter;
public helpTopic() {
return this.isActionTypeDef() ? "action types" :
this.isPage() ? "pages" :
this.isEvent() ? "events" :
"code";
}
public isAtomic: boolean = false;
public canBeInlined: boolean = false;
public debuggingData: { critical: number; max: { critical: number }; };
public isCompilerTest()
{
return this._isTest && /^E: /.test(this.getName())
}
public getModelDef()
{
if (!this.modelParameter) return null
if (this.modelParameter.getKind() instanceof RecordEntryKind) {
return (<RecordEntryKind>this.modelParameter.getKind()).getRecord()
}
return null
}
public getInlineHelp():string
{
if (this.eventInfo) return this.eventInfo.type.help;
if (!this.body) return "";
var desc = ""
for (var i = 0; i < this.body.stmts.length; ++i) {
var s = this.body.stmts[i]
if (s instanceof Comment) {
var c = <Comment>s;
if (desc) desc += "\n";
desc += c.text;
} else {
break;
}
}
return desc;
}
public getDescription():string
{
var desc = this.getInlineHelp();
if (desc) return desc;
return this.isActionTypeDef() ? lf("an function type definition")
: this.isEvent() ? lf("an event handler")
: this.isPage() ? lf("a page") : lf("a function")
}
// IProperty
public getCategory():PropertyCategory { return PropertyCategory.Action; }
public getParameters() : PropertyParameter[]
{
return super.getParameters().concat(
this.getInParameters().map((p:ActionParameter) => this.mkPP(p.getName(), p.getKind())));
}
public getResult() : PropertyParameter
{
var op = this.getOutParameters();
if (op.length == 1)
return this.mkPP(op[0].getName(), op[0].getKind());
else
return this.mkPP("result", api.core.Nothing);
}
public getDefinedKind()
{
if (!this.isActionTypeDef()) return null
if (!this.definedKind) this.definedKind = new UserActionKind(this)
return this.definedKind
}
public setEventInfo(ei:EventInfo)
{
this.eventInfo = ei;
this.isAtomic = false;
if (!!ei) {
this.header.inParameters.immutableReason = lf("Types, order, and number of event parameters cannot be edited.");
this.header.outParameters.immutableReason = lf("Events cannot have out parameters.");
}
}
public getPageBlock(init:boolean) : CodeBlock
{
var ch = this.body.children();
if (ch.length != 2 || !(ch[0] instanceof If) || !(ch[1] instanceof If))
return null;
var ifInit = <If>ch[0];
var renderIf = <If>ch[1];
var ifToks = ifInit.rawCondition.tokens;
if (!ifInit.rawElseBody.isBlockPlaceholder()) return null;
if (!renderIf.rawElseBody.isBlockPlaceholder()) return null;
if (ifToks.length != 2 || !(ifToks[0] instanceof ThingRef) || !(ifToks[1] instanceof PropertyRef))
return null;
if ((<ThingRef>ifToks[0]).data != "box" || (<PropertyRef>ifToks[1]).data != "is init")
return null;
this.body.isInvisible = true;
function markInvisible(i:If) {
i.isInvisible = true;
i.rawElseBody.isInvisible = true;
var s0 = i.rawElseBody.stmts[0]
if (s0) s0.isInvisible = true;
}
markInvisible(ifInit);
markInvisible(renderIf);
return init ? ifInit.rawThenBody : renderIf.rawThenBody;
}
public getInParameters():ActionParameter[] { return <ActionParameter[]>this.header.inParameters.stmts; }
public getOutParameters():ActionParameter[] { return <ActionParameter[]>this.header.outParameters.stmts; }
public getAllParameters():ActionParameter[] { return this.getInParameters().concat(this.getOutParameters()); }
public hasInParameters() { return this.getInParameters().length > 0; }
public hasOutParameters() { return this.getOutParameters().length > 0; }
public nameLocal(n:string, usedNames:any = {})
{
return AstNode.freshNameCore(n,
(n:string) =>
usedNames.hasOwnProperty(n) ||
this.allLocals.some((l:LocalDef) => l.getName() == n) ||
api.getThing(n) != null);
}
public isPlugin()
{
if (this.getName() != "plugin")
return false
var parms = this.getInParameters()
if (parms.length != 1)
return false
if (parms[0].getKind() == api.core.String ||
parms[0].getKind() == api.core.Editor)
return true
return false
}
public isButtonPlugin()
{
if (this.isPrivate) return false
var parms = this.getInParameters()
if (parms.length != 1) return false
// the type may be unresolved
return parms[0].getKind().getName() == "Editor"
}
public isRunnable() {
if (this.isActionTypeDef() || this.isEvent() || this.isPrivate) return false;
if (Cloud.isRestricted() && this.hasInParameters()) return false; // input parameters not support in restricted
return this.isPlugin()
|| this.isButtonPlugin()
|| !this.hasInParameters()
|| (!this.isPage() && this.getInParameters().every((a) => !!a.getKind().picker));
}
public writeHeader(tw:TokenWriter, forLibSig = false)
{
var writeParms = (parms:ActionParameter[]) =>
{
var first = true;
parms.forEach((l:ActionParameter) => {
if (!first)
tw.op0(",").space();
if (!forLibSig)
l.writeIdOpt(tw);
l.local.writeWithType(this.parent, tw);
first = false;
});
}
tw.nl().keyword(this.isEvent() ? "event" : "action");
if (forLibSig) {
tw.op(!this.isAtomic ? "async" : "sync");
}
//if (forLibSig && this.isPage()) tw.op("page")
if (this.isActionTypeDef())
tw.op("type")
tw.id(this.getName()).op0("(");
var parms = this.getInParameters();
if (this.modelParameter) {
parms = parms.slice(0);
parms.unshift(this.modelParameter);
}
writeParms(parms);
tw.op0(")");
if (this.hasOutParameters()) {
tw.keyword("returns").op0("(");
writeParms(this.getOutParameters());
tw.op0(")");
}
}
public writeTo(tw:TokenWriter)
{
this.writeId(tw);
this.writeHeader(tw);
if (tw.skipActionBodies) {
tw.beginBlock();
tw.endBlock();
} else {
this.body.writeTo(tw);
}
tw.backspaceBlockEnd();
if (this.isPrivate)
tw.keyword("meta").keyword("private").op0(";").nl();
if (this.isPage())
tw.keyword("meta").keyword("page").op0(";").nl();
if (this.isAtomic && !this.isEvent())
tw.keyword("meta").keyword("sync").op0(";").nl();
if (this.isTest())
tw.keyword("meta").keyword("test").op0(";").nl();
if (this.isOffline)
tw.keyword("meta").keyword("offline").op0(";").nl();
if (this.isQuery)
tw.keyword("meta").keyword("query").op0(";").nl();
tw.endBlock();
}
public toString() { return this.getName(); }
public getStats() : StatsComputer
{
var s = new StatsComputer()
s.dispatch(this)
return s;
}
public freshlyCreated()
{
if (!this.isPage() || this.modelParameter) return;
var decl = <RecordDef> Parser.parseDecl("table __name__ { type = 'Object'; fields { } }");
decl.setName(Script.freshName(this.getName() + " page data"));
Script.addDecl(decl);
var l = AST.mkLocal(modelSymbol, decl.entryKind);
this.modelParameter = new ActionParameter(l);
}
private initParameterAnnotations()
{
if (this.parameterAnnotations) return;
this.parameterAnnotations = {};
var descr = this.getDescription();
descr.replace(/\{(hints|enum):([^:{}]*):([^{}]*)/g,(mtch, tp, arg, vals : string) => {
var annot = this.getParameterAnnotation(arg);
annot.hints = vals.split(',');
if (tp == "enum") {
annot.enumMap = {}
annot.hints = annot.hints.map(a => {
var m = /([^=]*)=(.+)$/i.exec(a)
if (m) {
annot.enumMap[m[1]] = m[2]
return m[1]
}
else {
annot.enumMap[a] = a;
return a
}
});
(<any>annot.hints).enumMap = annot.enumMap
}
return ""
})
descr.replace(/\{pichints:([^:{}]*):([^{}]*)/g,(mtch, arg, vals: string) => {
this.getParameterAnnotation(arg).pichints = Util.splitKeyValues(vals);
return ""
})
descr.replace(/\{language:([^:{}]*):([^{}]*)/g,(mtch, arg, vals: string) => {
this.getParameterAnnotation(arg).language = vals
return ""
})
}
private getParameterAnnotation(name:string): ParameterAnnotations
{
this.initParameterAnnotations()
if (!this.parameterAnnotations.hasOwnProperty(name))
this.parameterAnnotations[name] = {}
return this.parameterAnnotations[name]
}
private parameterAnnotations:StringMap<ParameterAnnotations>;
public mkPP(name:string, k:Kind) {
var r = super.mkPP(name, k)
var annot = this.getParameterAnnotation(name)
if (annot.hints) r.setDeflStrings(annot.hints)
if (annot.pichints) r.setDeflStringArtIds(annot.pichints);
if (annot.language) r.languageHint = annot.language;
if (annot.enumMap) r.enumMap = annot.enumMap;
return r
}
}
export class ExtensionProperty
extends Property
{
constructor(public shortcutTo:Action)
{
super(shortcutTo.getInParameters()[0].getKind(), shortcutTo.getName(), shortcutTo.getDescription(), [], api.core.Nothing)
}
public getCategory() { return PropertyCategory.Action; }
public getParameters() { return this.shortcutTo.getParameters().slice(1); }
public getResult() { return this.shortcutTo.getResult() }
public getName() { return this.shortcutTo.getName() }
public getDescription() { return this.shortcutTo.getDescription() }
public getSignature() { return this.shortcutTo.getSignature() }
public getFlags() { return this.shortcutTo.getFlags() }
public canRename() { return false }
}
export class LocalDef
extends Decl
{
constructor() {
super()
}
public nodeType() { return "localDef"; }
public accept(v:NodeVisitor) { return v.visitLocalDef(this); }
public getDescription():string { return ": " + this.getKind().toString() + lf(" -- a local variable"); }
public rename(nn:string) { this.setName(nn); }
public setKind(k: Kind) { this._kind = k }
public usageKey() { return this.getName(); }
public lastUsedAt = 0;
public lambdaNameStatus:number;
public isRegular:boolean;
public isSynthetic:boolean;
public isHiddenOut:boolean;
public isOut:boolean;
// if _isMutable && _isCaptured then the local needs to be captured by reference
public _isMutable:boolean; // set by TypeChecker for locals written after initialization
public _isCaptured:boolean; // set by TypeChecker for locals captured in closures
public _lastWriteLocation:Stmt;
public _converterAction:InlineAction;
public _converterUses:number;
public isByRef() { return this._isMutable && this._isCaptured }
public writeWithType(app:App, tw:TokenWriter)
{
tw.id(this.getName()).op0(':').kind(app, this.getKind());
}
public clone() { return mkLocal(this.getName(), this.getKind()); }
}
export interface AppEditorState
{
tutorialId?: string;
tutorialStep?: number;
tutorialFast?: boolean;
tutorialValidated?: boolean;
tutorialRedisplayed?: number;
tutorialMode?: string;
tutorialNumSteps?: number;
tutorialUpdateKey?: string;
tutorialAnonymousId?: string;
deployWebsite?: string;
parentScriptGuid?: string;
collabSessionId?: string;
groupId?: string;
buttonPlugins?: StringMap<any>;
libraryLocalBindings?: StringMap<string>; // library stable id -> installation guid
splitScreen?: boolean;
cordova?: Apps.CordovaOptions;
}
export interface HeaderWithState extends Cloud.Header
{
editorState: AppEditorState;
}
export enum LanguageFeature
{
None = 0x0000,
JS = 0x0001,
ContextCheck = 0x0002,
Refs = 0x0004,
LocalCloud = 0x0008,
UnicodeModel = 0x0010,
AllAsync = 0x0020,
UppercaseMultiplex = 0x0040,
Current = JS|Refs|ContextCheck|LocalCloud|UnicodeModel|AllAsync|UppercaseMultiplex
}
export enum AnnotationMode {
None, Coverage, Profiling, Crash
}
export class AppImports implements CompiledImports {
public npmModules: StringMap<string> = {};
public bowerModules: StringMap<string> = {};
public clientScripts: StringMap<string> = {};
public cordovaPlugins: StringMap<string> = {};
public pipPackages: StringMap<string> = {};
public touchDevelopPlugins: StringMap<string> = {};
public importTouchDevelop(tc : TypeChecker, t: Call, plugin: string, scriptId: string) {
if (scriptId) {
this.touchDevelopPlugins[scriptId] = "1";
}
}
public importPip(tc : TypeChecker, t: Call, pkg: string, v: string) {
if (pkg) {
var pkgs = this.pipPackages;
if (pkgs.hasOwnProperty(pkg)) {
if (pkgs[pkg] == "error") return;
var newOne = AppImports.combinePipVersions(pkgs[pkg], v)
if (newOne == "error")
tc.markError(t, lf("TD196: pip package '{0}' versions '{1}' and '{2}' conflict", pkg, pkgs[pkg], v))
pkgs[pkg] = newOne
} else
pkgs[pkg] = v;
}
}
public importCordova(tc : TypeChecker, t: Call, plugin: string, v: string) {
if (plugin) {
var plugins = this.cordovaPlugins
if (plugins.hasOwnProperty(plugin)) {
if (plugins[plugin] == "error") return;
var newOne = AppImports.combineNpmVersions(plugins[plugin], v)
if (newOne == "error")
tc.markError(t, lf("TD187: cordova plugin '{0}' versions '{1}' and '{2}' conflict", plugin, plugins[plugin], v))
plugins[plugin] = newOne
} else
plugins[plugin] = v;
}
}
static combineNpmModules(topApp: App): StringMap<string> {
var imports: StringMap<string> = {}
topApp.librariesAndThis().filter(l => !!l.resolved).forEach(l => {
Object.keys(l.resolved.imports.npmModules).forEach(k => {
var v = l.resolved.imports.npmModules[k]
if (imports.hasOwnProperty(k)) {
imports[k] = AppImports.combineNpmVersions(imports[k], v)
} else {
imports[k] = v
}
})
})
return imports
}
static combinePipPackages(topApp: App): StringMap<string> {
var imports: StringMap<string> = {}
topApp.librariesAndThis().filter(l => !!l.resolved).forEach(l => {
Object.keys(l.resolved.imports.pipPackages).forEach(k => {
var v = l.resolved.imports.pipPackages[k]
if (imports.hasOwnProperty(k)) {
imports[k] = AppImports.combinePipVersions(imports[k], v)
} else {
imports[k] = v
}
})
})
return imports
}
static combineCordovaPlugins(topApp: App): StringMap<string> {
var plugins: StringMap<string> = {
"cordova-plugin-console": "*",
"cordova-plugin-websql": "*",
"cordova-plugin-inappbrowser": "*",
}
Object.keys(topApp.imports.cordovaPlugins)
.filter(k => topApp.imports.cordovaPlugins.hasOwnProperty(k))
.forEach(k => plugins[k] = AppImports.combineNpmVersions(plugins[k], topApp.imports.cordovaPlugins[k]));
topApp.librariesAndThis().filter(l => !!l.resolved).forEach(l => {
Object.keys(l.resolved.imports.cordovaPlugins).forEach(k => {
var v = l.resolved.imports.cordovaPlugins[k]
if (plugins.hasOwnProperty(k)) {
plugins[k] = AppImports.combineNpmVersions(plugins[k], v)
} else {
plugins[k] = v
}
})
})
return plugins
}
static combineTouchDevelopPlugins(topApp: App): StringMap<string> {
var plugins: StringMap<string> = {};
Object.keys(topApp.imports.touchDevelopPlugins)
.forEach(k => plugins[k] = "1");
topApp.librariesAndThis().filter(l => !!l.resolved).forEach(l => {
Object.keys(l.resolved.imports.touchDevelopPlugins).forEach(k => plugins[k] = "1");
})
return plugins
}
public importClientScript(tc : TypeChecker, t: Call, mod: string, v: string) {
if (mod && v != null) {
var imports = this.clientScripts;
imports[mod] = v;
}
}
public importNpm(tc : TypeChecker, t: Call, mod: string, v: string) {
if (mod && v != null) {
var imports = this.npmModules
if (imports.hasOwnProperty(mod)) {
if (imports[mod] == "error") return;
var newOne = AppImports.combineNpmVersions(imports[mod], v)
if (newOne == "error")
tc.markError(t, lf("TD180: npm module '{0}' versions '{1}' and '{2}' conflict", mod, imports[mod], v))
imports[mod] = newOne;
}
else
imports[mod] = v
}
}
public importBower(tc : TypeChecker, t: Call, mod: string, v: string) {
if (mod && v != null) {
var imports = this.bowerModules
if (imports.hasOwnProperty(mod)) {
if (imports[mod] == "error") return;
var newOne = AppImports.combineNpmVersions(imports[mod], v)
if (newOne == "error")
tc.markError(t, lf("TD197: bower module '{0}' versions '{1}' and '{2}' conflict", mod, imports[mod], v))
imports[mod] = newOne;
}
else
imports[mod] = v
}
}
static combinePipVersions(v0: string, v1: string) {
if (v0 === v1) return v0
if (v0 === undefined || (v1 && v0 === "*")) return v1
if (v1 === undefined || (v0 && v1 === "*")) return v0
// TODO
return "error"
}
static combineNpmVersions(v0: string, v1: string) {
if (v0 === v1) return v0
if (v0 === undefined || (v1 && v0 === "*")) return v1
if (v1 === undefined || (v0 && v1 === "*")) return v0
return "error"
}
}
// Meta statement used to make the script signature clickable
export class AppHeaderStmt
extends InlineStmt
{
constructor(public parentDef: App) {
super();
}
}
export class App
extends Decl
{
static currentVersion = "v2.2,js,ctx,refs,localcloud,unicodemodel,allasync,upperplex";
constructor(p:Parser) {
// should be only contructed by the parser
super()
this.setStableName("app");
this.thisLibRef = LibraryRef.topScriptLibrary(this);
this.setName("no name");
this.version = App.currentVersion;
this.headerStmt = new AppHeaderStmt(this);
this.nameHolder.maxLength = 52;
this.nameHolder.defaultTemplate = lf("ADJ script");
}
// split screen is used as a hit when loaded in the editor, serialized when publishing
static metaMapping = [ "showAd", "isLibrary", "isCloud", "hasIds", "splitScreen", "useCppCompiler" ];
public headerStmt: AppHeaderStmt;
public nodeType() { return "app"; }
public things:Decl[] = [];
public getDescription() { return this.comment; }
public thisLibRef:LibraryRef;
public editorState:AppEditorState = {};
public parentIds:string[] = []; // used for merging
public rootId:string = uniqueAstId(24);
private languageFeatures = LanguageFeature.Current;
private usedIds:any = {};
public syntheticIds:StringMap<boolean> = {};
public diffRemovedThings: Decl[];
public imports = new AppImports();
public notifyVersionMarker:any = new Object();
public libNamespaceCache = new LibNamespaceCache(this);
public blockExternalLinks:boolean = undefined;
public entireShim = false;
public _forcedUpdate:string;
public recompiler:Compiler;
public recompiledScript:CompiledScript;
public clearRecompiler() {
this.recompiler = null;
this.recompiledScript = null;
}
// visual annotation mode
public annotatedBy: AnnotationMode = AnnotationMode.None;
public htmlColor()
{
if (Cloud.isRestricted()) return "#0095ff"
if (!this.color) return ScriptIcons.stableColorFromName(this.getName());
else return "#" + this.color.replace("#", "").slice(-6);
}
public iconName() { return "emptycircle" } // this.icon || ScriptIcons.stableIconFromName(this.getName())
public iconPath() { return "svg:" + this.iconName() + ",white"; }
private version:string;
public icon:string;
public color:string;
public iconArtId: string;
public splashArtId: string;
public comment: string = "";
public hasLibraries(): boolean { return this.libraries().length > 0; }
public hasTests():boolean { return this.allActions().some((a) => a.isTest()); }
public isTestOnly():boolean { return !this.mainAction() && this.hasTests() }
public localGuid:string = Util.guidGen();
public isLibrary: boolean;
public useCppCompiler: boolean;
public isCloud: boolean;
public isTopLevel = false;
private seed:string;
public showAd:boolean;
public isDocsTopic() { return this.comment && /#docs/i.test(this.comment); }
public isTutorial() { return this.isDocsTopic() && this.allActions().some(a => /^#\d/.test(a.getName())) }
public hasIds: boolean;
public splitScreen: boolean;
private stillParsing:boolean = true;
public accept(v:NodeVisitor) { return v.visitApp(this); }
public children() { return this.things; }
private _platform = PlatformCapability.Current;
public debuggingData: { critical: number; max: { critical: number }; };
public usesCloud()
{
return this.records().some(r => r.cloudEnabled) || this.variables().some(r => r.cloudEnabled);
}
public usesCloudLibs()
{
return this.librariesAndThis().some(l => l.isCloud())
}
public usesCppCompiler()
{
return this.librariesAndThis().some(l => l.resolved && l.resolved.useCppCompiler)
}
private meta:any = {};
public notifyChange()
{
this.notifyVersionMarker = new Object();
super.notifyChange()
}
public getGlobalErrorDecl(ignoreLibs:boolean) { return this.things.filter((t) => t.hasErrors() && !(t instanceof Action) && (!ignoreLibs || !(t instanceof LibraryRef)))[0]; }
public getDefinedKinds()
{
var kindList:Kind[] = []
this.things.map(t => {
var tp = t.getDefinedKind()
if (tp) kindList.push(tp)
})
return kindList
}
public getKinds() : Kind[]
{
var kindList = api.getKinds().concat(this.getDefinedKinds())
this.libraries().forEach((l) => {
kindList.pushRange(l.getPublicKinds());
});
return kindList;
}
static platforms = [
{ cap: PlatformCapability.Current, id: "current", name: lf("Current device (overrides the rest)") },
{ cap: PlatformCapability.Accelerometer, id: "accelerometer", name: lf("Accelerometer") },
{ cap: PlatformCapability.Camera, id: "camera", name: lf("Camera") },
{ cap: PlatformCapability.CloudData, id: "clouddata", name: lf("Cloud Data") },
{ cap: PlatformCapability.Compass, id: "compass", name: lf("Compass") },
{ cap: PlatformCapability.Contacts, id: "contacts", name: lf("Contacts") },
{ cap: PlatformCapability.EditorOnly, id: "editoronly", name: lf("Editor only") },
{ cap: PlatformCapability.Gyroscope, id: "gyroscope", name: lf("Gyroscope") },
{ cap: PlatformCapability.Location, id: "location", name: lf("Location") },
{ cap: PlatformCapability.Maps, id: "maps", name: lf("Maps") },
{ cap: PlatformCapability.Media, id: "media", name: lf("Media libraries on device") },
{ cap: PlatformCapability.Microphone, id: "microphone", name: lf("Microphone") },
{ cap: PlatformCapability.Motion, id: "motion", name: lf("Motion") },
{ cap: PlatformCapability.MusicAndSounds, id: "musicandsounds", name: lf("Music and Sounds") },
{ cap: PlatformCapability.Network, id: "network", name: lf("Network") },
{ cap: PlatformCapability.Proximity, id: "proximity", name: lf("NFC") },
{ cap: PlatformCapability.Orientation, id: "orientation", name: lf("Orientation") },
{ cap: PlatformCapability.Phone, id: "phone", name: lf("Phone specific") },
{ cap: PlatformCapability.Radio, id: "radio", name: lf("Radio") },
{ cap: PlatformCapability.Search, id: "search", name: lf("Search") },
{ cap: PlatformCapability.Speech, id: "speech", name: lf("Speech") },
{ cap: PlatformCapability.Translation, id: "translation", name: lf("Translation") },
{ cap: PlatformCapability.Tiles, id: "tiles", name: lf("Tiles") },
{ cap: PlatformCapability.Npm, id: "npm", name: lf("Node Package Manager") },
{ cap: PlatformCapability.Cordova, id: "cordova", name: lf("Cordova Plugin Manager") },
{ cap: PlatformCapability.Shell, id: "shell", name: lf("Touch Develop Local Shell") },
];
static capabilityName(p:PlatformCapability)
{
return App.platforms.filter((k) => !!(k.cap & p)).map((k) => k.name).join(", ")
}
static capabilityString(p:PlatformCapability)
{
return App.platforms.filter((k) => !!(k.cap & p)).map((k) => k.id).join(",")
}
static orderThings(things:Decl[], mixActions = false)
{
var score = (t:Decl) => {
if (t instanceof Action) {
var a = <Action>t;
if (mixActions) return 1
if (a.isPage()) return 3;
else if (a.isEvent()) return 2;
else if (a.isMainAction()) return 0.5;
else if (a.isPrivate) return 1.5;
else return 1;
} else if (t instanceof GlobalDef) {
var g = <GlobalDef>t;
if (g.isResource) return 5;
else return 4;
} else if (t instanceof RecordDef) {
return 6;
} else if (t instanceof LibraryRef) {
return 7;
} else {
return 0; // unknown
}
}
var cmp = (a:Decl, b:Decl) => {
var diff = score(a) - score(b);
if (diff == 0) {
var an = a.getName()
var bn = b.getName()
for (var i = 0; i < an.length; ++i)
if (an.charAt(i) != bn.charAt(i))
break;
if (/^[0-9]$/.test(an.charAt(i)) && /^[0-9]$/.test(bn.charAt(i))) {
var dot = false;
var c = ""
var beg = i - 1;
while (beg > 0 && /^[0-9\.]$/.test(c = an.charAt(beg))) {
if (c == ".") {
if (dot) break;
dot = true;
}
beg--;
}
beg++;
var am = /^(\d*(\.\d+)?)/.exec(an.slice(beg))
var bm = /^(\d*(\.\d+)?)/.exec(bn.slice(beg))
return parseFloat(am[1]) - parseFloat(bm[1])
}
if (a.getName() < b.getName()) return -1;
else if (a == b) return 0;
else return 1;
} else return diff;
}
things.sort(cmp);
}
public orderedThings(mixActions = false)
{
var th = this.things.slice(0);
App.orderThings(th, mixActions)
return th;
}
public canUseProperty(p:IProperty)
{
return (this.getPlatform() & p.getCapability()) == p.getCapability();
}
public canUseCapability(p:PlatformCapability)
{
return (this.getPlatform() & p) == p;
}
public supportsAllPlatforms(p:PlatformCapability)
{
return (this.getPlatform() & p) == this.getPlatform();
}
public getPlatform() : PlatformCapability
{
if (this._platform & PlatformCapability.Current)
return api.core.currentPlatform;
return this._platform;
}
public getPlatformRaw() : PlatformCapability
{
return this._platform;
}
public setPlatform(p:PlatformCapability)
{
this._platform = p;
}
private setPlatformString(p:string)
{
if (!p) this._platform = PlatformCapability.None;
var platform = App.fromCapabilityList(p.split(/,/));
if (platform == 0x3fffff) platform = PlatformCapability.Current;
if (platform) this._platform = platform;
}
static _platformMapping:any;
static capabilityByName(n:string)
{
if (!App._platformMapping) {
App._platformMapping = {}
App.platforms.forEach((k) => App._platformMapping[k.id] = k.cap);
}
n = n.toLowerCase();
if (App._platformMapping.hasOwnProperty(n)) return App._platformMapping[n];
else return PlatformCapability.None;
}
static fromCapabilityList(ps:string[])
{
var platform = PlatformCapability.None;
ps.forEach((p) => { platform |= App.capabilityByName(p) })
return platform;
}
public getCapabilityString()
{
return App.capabilityString(this._platform);
}
public getIconArtId() {
return this.iconArtId;
}
public getBoxInfo()
{
return lf("script properties");
}
private setVersion(v:string)
{
var f = LanguageFeature.None;
v.split(/,/).forEach((t) => {
switch (t) {
case 'js': f |= LanguageFeature.JS; break;
case 'ctx': f |= LanguageFeature.ContextCheck; break;
case 'refs': f |= LanguageFeature.Refs; break;
case 'localcloud': f |= LanguageFeature.LocalCloud; break;
case 'unicodemodel': f |= LanguageFeature.UnicodeModel; break;
case 'allasync': f |= LanguageFeature.AllAsync; break;
case 'upperplex': f |= LanguageFeature.UppercaseMultiplex; break;
default: break;
}
})
this.languageFeatures = f;
}
public addFeatures(f:LanguageFeature)
{
this.languageFeatures |= f;
}
public featureMissing(f:LanguageFeature)
{
return (this.languageFeatures & f) == 0;
}
public setMeta(k:string, v:string)
{
if (<any>v === true) v = "yes";
switch (k) {
case "icon": this.icon = v; break;
case "name": this.setName(v); break;
case "color": this.color = v; break;
case "seed": this.seed = v; break;
case "version": this.setVersion(v); break;
case "platform": this.setPlatformString(v); break;
case "parentIds": this.parentIds = v.split(/,\s*/).filter(x => !!x); break;
case "editorState":
if (v) try { this.editorState = JSON.parse(v); } catch (e) { Util.check(false, "editor state corrupted"); }
break;
case "rootId": this.rootId = v; break;
case "iconArtId": this.iconArtId = v; break;
case "splashArtId": this.splashArtId = v; break;
default:
if (App.metaMapping.indexOf(k) >= 0)
(<any>this)[k] = v == "yes";
this.meta[k] = v;
}
}
public mainAction()
{
var c0 = this.allActions().filter((a: Action) => a.isRunnable())
if (this.isTutorial()) {
var main0 = c0.filter((a: Action) => a.getName() == "#0 main")[0];
if (main0) return main0;
}
var c1 = c0.filter((a) => !a.isPage())
var c2 = c0.filter((a: Action) => a.getName() == "main");
if (c2.length == 0) c2 = c1;
if (c2.length == 0) c2 = c0;
/*
// the phone app doesn't sort
// we don't want locale-sensitive sort here
c1.sort((a, b) => {
var aa = a.getName().toLowerCase();
var bb = b.getName().toLowerCase();
if (aa < bb) return -1;
else if (aa > bb) return +1;
else return 0;
});
*/
if (c2.length > 0) return c2[0];
else return null;
}
public findActionByName(name: string) : Action {
for (var i = 0; i < this.things.length; i++) {
var t = this.things[i];
if (t instanceof Action && t.getName() == name) return <Action>t;
}
return null;
}
public allActions():Action[] { return <Action[]>this.things.filter((t) => t instanceof Action); }
public actions():Action[] { return <Action[]>this.things.filter((t) => t instanceof Action && !((<Action>t).isEvent()) && !((<Action>t).isActionTypeDef())); }
public events():Action[] { return <Action[]>this.things.filter((t) => t instanceof Action && ((<Action>t).isEvent())); }
public actionTypeDefs():Action[] { return <Action[]>this.things.filter((t) => t instanceof Action && ((<Action>t).isActionTypeDef())); }
public libraries():LibraryRef[] { return <LibraryRef[]>this.things.filter((t) => t instanceof LibraryRef); }
public librariesAndThis():LibraryRef[] { return [this.thisLibRef].concat(this.libraries()); }
public variables():GlobalDef[] { return <GlobalDef[]>this.things.filter((t) => t instanceof GlobalDef && !(<AST.GlobalDef> t).isResource); }
public resources():GlobalDef[] { return <GlobalDef[]>this.things.filter((t) => t instanceof GlobalDef && !!(<AST.GlobalDef> t).isResource); }
public variablesAndResources():GlobalDef[] { return <GlobalDef[]>this.things.filter((t) => t instanceof GlobalDef); }
public records():RecordDef[] { return <RecordDef[]>this.things.filter((t) => t instanceof RecordDef); }
public parsingFinished()
{
//this.stillParsing = true;
//this.usedIds = {};
//this.things.forEach(t => this.addToUsedIds(t))
this.stillParsing = false;
}
public setStableNames()
{
//TODO remove?
}
public findStableName(s:string) : Decl
{
if (!s) return null;
if (s == this.getStableName()) return this;
return this.things.filter((d) => d.getStableName() == s)[0];
}
public toMeta():any
{
var r = {
type: "app",
version: App.currentVersion,
name: this.getName(),
icon: this.iconName(),
color: this.htmlColor(),
comment: TokenWriter.normalizeComment(this.comment),
seed: this.seed,
localGuid: this.localGuid,
platform: this.getCapabilityString(),
rootId: this.rootId,
parentIds: this.parentIds.join(","),
};
if (this.iconArtId) r["iconArtId"] = this.iconArtId;
if (this.splashArtId) r["splashArtId"] = this.splashArtId;
App.metaMapping.forEach((k) => {
r[k] = (<any>this)[k] ? "yes" : "no";
})
return r;
}
public toJsonScript() : any
{
var r = {
kind: "script",
time: 0,
id: "",
userid: "me",
username: lf("Me"),
name: this.getName(),
description: this.comment,
icon: this.icon,
iconbackground: this.color,
iconArtId: this.iconArtId,
splashArtId: this.splashArtId,
positivereviews: 0,
cumulativepositivereviews: 0,
comments: 0,
capabilities: [],
flows: [],
haserrors: this.hasErrors(),
rootid: "",
updateid: "",
ishidden: true,
islibrary: this.isLibrary,
useCppCompiler: this.useCppCompiler,
installations: 0,
runs: 0,
};
return r;
}
public loadMeta(m:any)
{
Object.keys(m).forEach((k) => {
this.setMeta(k, m[k]);
});
this.comment = m.comment || "";
}
public serializeFinal()
{
var tw = TokenWriter.forStorage();
this.writeFinal(tw);
return tw.finalize();
}
public serializeMeta()
{
var tw = TokenWriter.forStorage();
this.writeMeta(tw);
return tw.finalize();
}
private writeMeta(tw:TokenWriter)
{
tw.meta("version", App.currentVersion);
tw.meta("name", this.getName());
tw.metaOpt("icon", this.icon);
var c = this.color
if (c) {
if (c.length == 7 && c[0] == '#') c = "#ff" + c.slice(1)
c = c.toLowerCase()
tw.metaOpt("color", c)
}
tw.meta("rootId", this.rootId);
tw.metaOpt("iconArtId", this.iconArtId);
tw.metaOpt("splashArtId", this.splashArtId);
App.metaMapping.forEach((k) => {
tw.metaOpt(k, (<any>this)[k] ? "yes" : "");
})
tw.meta("platform", this.getCapabilityString());
tw.meta("parentIds", this.parentIds.join(","));
if (!!this.comment)
tw.comment(this.comment);
}
private writeFinal(tw:TokenWriter)
{
}
public writeTo(tw:TokenWriter)
{
this.writeMeta(tw);
this.things.forEach((t) => t.writeTo(tw));
if (!tw.skipActionBodies)
this.writeFinal(tw);
}
public notifyChangeAll()
{
this.notifyChange();
for (var i = 0; i < this.things.length; ++i)
this.things[i].notifyChange();
}
static sanitizeScriptTextForCloud(s:string)
{
var r = "";
if (s) {
s = s.replace(/(\r?\n)+$/, "");
s.split(/\n/).forEach((ln) => {
if (/^meta (stableNames|editorState)/.test(ln)) { }
else {
r += ln + "\n";
}
});
}
return r;
}
private addToUsedIds(t:Decl)
{
var u = this.usedIds;
var process = (t:IStableNameEntry) => {
if (!t.getStableName() || /_/.test(t.getStableName())) {
var enc = ""
if (!this.stillParsing) {
enc = uniqueAstId(16)
} else {
// otherwise, we're dealing with legacy script that needs a deterministic stable name
enc = Util.toUTF8(t.getName().replace(/[ _]/g, ""))
enc = enc.replace(/[^a-zA-Z0-9]/g, (c) => c.charCodeAt(0).toString(16))
if (enc.length > 20)
enc = enc.slice(0, 20)
if (/^[0-9]/.test(enc)) enc = "x" + enc
if (u.hasOwnProperty(enc)) {
var add = 1
while (u.hasOwnProperty(enc + add)) add++;
enc = enc + add
}
}
this.syntheticIds[enc] = true
t.setStableName(enc)
}
u[t.getStableName()] = t;
}
var declExists = (d:Decl) => {
return d && (d == t || this.things.indexOf(d) >= 0);
}
if (t.getStableName() && declExists(u[t.getStableName()]))
t.setStableName(null);
process(t);
if (t instanceof RecordDef)
(<RecordDef>t).getFields().forEach(f => {
if (f.getStableName()) {
var q = u[f.getStableName()]
if (q &&
(declExists(q) ||
(q instanceof RecordField && declExists(q.def()) && q.def().getFields().indexOf(q) >= 0)))
f.setStableName(null);
}
process(f);
})
}
public recomputeStableName(t:AST.Decl)
{
this.addToUsedIds(t);
}
public resetStableName(t:AST.Decl)
{
t.setStableName(null);
this.recomputeStableName(t)
}
public addDecl(t:AST.Decl)
{
t.parent = this;
this.addToUsedIds(t);
this.things.push(t);
}
public deleteDecl(t:AST.Decl)
{
var i = this.things.indexOf(t);
t.deleted = true;
if (i >= 0)
this.things.splice(i, 1);
}
public hasDecl(t:AST.Decl) { return t == this || this.things.indexOf(t) >= 0; }
public namesMatch(a:string, b:string)
{
return a.replace(/\s*\d+$/, "") == b.replace(/\s*\d+$/,"");
}
public freshName(n:string)
{
return AstNode.freshNameCore(n,
(n:string) =>
n == "this" ||
this.things.some((d:Decl) => d.getName() == n || d.getCoreName() == n));
}
public findAstNodeById(id:string, allowNonStmt = false)
{
if (!id) return null;
var s = new SearchForId(id)
s.dispatch(this)
if (s.foundNode && (allowNonStmt || s.foundNode instanceof Stmt))
return { node: s.foundNode, stmt: s.lastStmt, decl: s.lastDecl }
else
return null;
}
public findStmtByStableName(name: string): Stmt
{
var s = new SearchForStableName(name);
s.dispatch(this)
return <Stmt>s.found;
}
}
// -------------------------------------------------------------------------------------------------------
// Expressions
// -------------------------------------------------------------------------------------------------------
export class ExprHolder
extends AstNode
{
public tokens:Token[];
public parsed:Expr;
public locals:LocalDef[];
public definedLocals:LocalDef[];
public looksLikeVarDef: boolean;
public hasFix: boolean;
public profilingExprData: ProfilingAstNodeData;
public debuggingData: DebuggingAstNodeInfo = {};
public reachingDefs: ReachingDefsMgr;
public dominators: DominatorsMgr;
public usedSet: UsedSetMgr;
public aeSet: AvailableExpressionsMgr;
public cpSet: ConstantPropagationMgr;
public diffTokens:Token[];
public isAwait:boolean;
/** white + first 27 colors from http://www.vendian.org/mncharity/dir3/blackbody/ */
static heatmapColors: string[] =
["#ffffff", "#fff5f5", "#fff3ef", "#fff0e9", "#ffeee3", "#ffebdc", "#ffe8d5",
"#ffe4ce", "#ffe1c6", "#ffddbe", "#ffd9b6", "#ffd5ad", "#ffd1a3", "#ffcc99",
"#ffc78f", "#ffc184", "#ffbb78", "#ffb46b", "#ffad5e", "#ffa54f", "#ff9d3f",
"#ff932c", "#ff8912", "#ff7e00", "#ff7300", "#ff6500", "#ff5300", "#ff3800"];
static profilingDurationBucketSize: number; // each bucket gets its own color
constructor() {
super()
}
public nodeType() { return "exprHolder"; }
public hasValue() { return true; }
public isPlaceholder() { return this.tokens.length == 0 || (this.tokens.length == 1 && this.tokens[0].isPlaceholder()); }
private calcNode() { return this; }
public accept(v:NodeVisitor) { return v.visitExprHolder(this); }
public children() { return this.tokens; }
public assignmentInfo() { return !this.parsed ? null : this.parsed.assignmentInfo(); }
public hint = "";
public getError()
{
if (this._error != null)
return this._error;
if (this.debuggingData.errorMessage)
return this.debuggingData.errorMessage;
for (var i = 0; i < this.tokens.length; ++i)
if (this.tokens[i]._error != null)
return this.tokens[i]._error;
return null;
}
public topCall(e:Expr = null):Call
{
if (!e) e = this.parsed
if (!e) return null
var prop = e.getCalledProperty()
if (prop == api.core.AssignmentProp)
return this.topCall((<Call>e).args[1])
else if (prop == api.core.AsyncProp)
return this.topCall((<Call>e).args[1])
else if (e instanceof Call)
return <Call>e
return null
}
public getLiteral():any
{
if (this.tokens.length == 1) return this.tokens[0].getLiteral()
return undefined;
}
public clearError()
{
super.clearError();
this.hint = "";
this.hasFix = false
}
public writeTo(tw:TokenWriter)
{
if (this.isPlaceholder()) {
tw.op("...");
return;
}
var isDigit = (o:Token) => o instanceof Operator && /^[0-9\.]$/.test((<Operator>o).data);
var prev = null;
this.tokens.forEach((t:Token) => {
if (isDigit(t)) {
if (!isDigit(prev))
tw.sep();
tw.op0((<Operator>t).data);
} else {
tw.node(t);
}
prev = t;
});
}
public forSearch()
{
var r = "";
var wasDigit = false;
this.tokens.forEach((t:Token) => {
var isDigit = false;
var s = t.forSearch();
if (t instanceof Operator)
isDigit = /[0-9\.]/.test(s);
if (!!s) {
if (wasDigit && isDigit)
r += s;
else
r += " " + s;
wasDigit = isDigit;
}
});
return r;
}
}
// -------------------------------------------------------------------------------------------------------
// Tokens
// -------------------------------------------------------------------------------------------------------
export class Token
extends AstNode
{
public tokenFix:string;
constructor() {
super()
}
public getText() { return null; }
public toString() { return this.getText(); }
public hasValue() { return true; }
public renderedAs:HTMLElement;
public forSearch() { return ""; }
public matches(d:AstNode) { return false; }
public getCall():Call { return null }
public getOperator():string { return null; }
public getFunArgs():string[] { return null; }
public getProperty():IProperty { return null; }
public getCalledProperty():IProperty { return null; }
public getLiteral():any { return null; }
public getStringLiteral():string
{
if (typeof this.getLiteral() == "string")
return this.getLiteral()
return null
}
public getNumberLiteral():number
{
if (typeof this.getLiteral() == "number")
return this.getLiteral()
return null
}
public getThing():Decl { return null; }
public getLocalDef():LocalDef {
var r = this.getThing()
if (r instanceof LocalDef) return <LocalDef>r
else return null;
}
public isDigit() { return false }
public getForwardedDecl():Decl
{
var p = this.getProperty()
if (!p) return null
return p.forwardsTo()
}
public eq(other:Token):boolean
{
return this.nodeType() == other.nodeType() && this.getText() == other.getText();
}
}
export class Expr
extends Token
{
public loc:StackOp;
public languageHint:string;
public enumVal: string;
public hintVal: string;
public hintArtId: string;
constructor() {
super()
}
public flatten(prop:IProperty) { return [this]; }
public calledAction() : Action { return null; }
public anyCalledAction():Action { return this.calledAction() || this.calledExtensionAction() }
public calledExtensionAction():Action { return null }
public referencedRecordField() : RecordField { return null; }
public referencedRecord() : RecordDef { return null; }
public referencedData() : GlobalDef { return null; }
public referencedLibrary() : LibraryRef { return null; }
public referencedLocal():LocalDef { return null; }
public getLiftedSetter() : IProperty { return null; }
public calledProp() : IProperty { return null; }
public assignmentInfo() : AssignmentInfo { return null; }
public isRefValue() { return false }
public allowRefUse() { return false }
public isEscapeDef() { return false }
}
export class Literal
extends Expr
{
public data:any;
public stringForm:string; // set for number literals
public possiblyNegative:boolean;
constructor() {
super()
}
public nodeType() { return "literal"; }
public getText() { return this.data + ""; }
public accept(v:NodeVisitor) { return v.visitLiteral(this); }
public getLiteral() { return this.data; }
public writeTo(tw:TokenWriter)
{
switch (typeof this.data) {
case "string":
tw.string(this.data);
break;
case "number":
// TODO get rid of 'e' notation
// note that this is pretty much dead code most of the time, as numbers are represented as sequences of Operator nodes
tw.op(this.data.toString());
break;
case "boolean":
tw.id(this.data ? "true" : "false");
break;
default:
Util.oops("cannot writeTo " + this.data);
break;
}
}
public forSearch() : string
{
switch (typeof this.data) {
case "string":
return this.data.toLowerCase();
case "number":
return this.data.toString();
case "boolean":
return this.data ? "true" : "false";
default:
Util.oops("cannot writeTo " + this.data);
return "";
}
}
}
// The token that stands for the decl name itself. While, strictly
// speaking, it is a literal, having a subclass allows the renderer to
// render it without quotes.
export class DeclName
extends Literal
{
constructor() {
super();
}
public accept(v:AST.NodeVisitor) { return v.visitDeclName(this); }
}
export class Operator
extends Token
{
public data:string;
public call:Call;
public funArgs:LocalDef[];
constructor() {
super()
}
public getText() { return this.data; }
public nodeType() { return "operator"; }
public accept(v:NodeVisitor) { return v.visitOperator(this); }
public getOperator() { return this.data; }
public isDigit() { return /^[0-9.\-]$/.test(this.data) }
public funSpan:number;
public writeTo(tw:TokenWriter)
{
if (this.data == "(" || this.data == ")")
tw.op0(this.data);
else if (this.data == ",")
tw.op0(this.data).space();
else if (/^fun:/.test(this.data))
tw.op("fun:" + this.getFunArgs().map(idUrlQuote).join(","))
else
tw.op(this.data);
}
public forSearch() { return this.data; }
public getFunArgs():string[]
{
if (!/^fun:/.test(this.data))
return
if (this.funArgs)
return this.funArgs.map(p => p.getName())
return this.data.slice(4).split(",").map(idUrlUnquote)
}
}
export class PropertyRef
extends Token
{
public data:string;
public prop:IProperty;
public call:Call;
public skipArrow:boolean;
public fromOp:Operator;
constructor() {
super()
}
public nodeType() { return "propertyRef"; }
public accept(v:NodeVisitor) { return v.visitPropertyRef(this); }
public getText():string { return !this.prop ? this.data : this.prop.getName(); }
public getProperty() { return this.prop }
public getOrMakeProp():IProperty
{
if (this.prop) return this.prop;
return new UnresolvedProperty(api.core.Unknown, this.data)
}
static mkProp(p:IProperty)
{
var r = new PropertyRef();
r.prop = p;
return r;
}
public writeTo(tw:TokenWriter)
{
var c = tw.lastChar;
if (!/^[A-Za-z0-9_\)]$/.test(c))
tw.space();
tw.op0("\u2192").id0(this.getText());
}
public forSearch() { return this.getText().toLowerCase(); }
public matches(d:AstNode) {
if (!this.prop) return false;
if (this.prop.forwardsTo() == d)
return true;
if (d instanceof RecordField && (<RecordField>d).asProperty() == this.prop)
return true;
return false;
}
public getCall() { return this.call }
}
export class ThingRef
extends Expr
{
static placeholderPrefix = "\u0001need ";
public data:string;
public def:Decl;
public namespaceLibrary:LibraryRef;
public _namespaceLibraryName:string;
public _lastTypechecker:any;
constructor() {
super()
}
public getText() { return !this.def ? this.data : this.def.getName(); }
public shortName()
{
return !this.def ? null :
this.def instanceof SingletonDef ? this.def.getKind().shortName() : null;
}
public nodeType() { return "thingRef"; }
public isPlaceholder() { return this.getText() == "$skip" || this.getText() == "..."; }
public accept(v:NodeVisitor) { return v.visitThingRef(this); }
public forceLocal = false;
public getThing():Decl { return this.def; }
public referencedLocal():LocalDef
{
if (this.def instanceof LocalDef)
return <LocalDef>this.def
return null
}
public isEscapeDef()
{
return this.def instanceof PlaceholderDef && !!(<PlaceholderDef>this.def).escapeDef
}
public namespaceLibraryName()
{
if (this.namespaceLibrary)
return (this._namespaceLibraryName = this.namespaceLibrary.getName())
return this._namespaceLibraryName
}
public writeTo(tw:TokenWriter)
{
if (this.def instanceof LocalDef)
tw.sep().op0("$").id0(this.getText());
else if (this.def instanceof PlaceholderDef)
tw.id("\u0001" + this.def.getName())
else if (this.namespaceLibraryName())
tw.id(this.getText()).op0("[").id("lib").id(this.namespaceLibraryName()).op0("]")
else if (this.def instanceof SingletonDef && (<SingletonDef>this.def).firstLibraryRef)
tw.id(this.getText()).op0("[").id("lib").id((<SingletonDef>this.def).firstLibraryRef.getName()).op0("]")
else
tw.id(this.getText());
}
public forSearch() { return this.getText().toLowerCase() }
public matches(d:AstNode) { return this.def == d; }
}
export class AssignmentInfo
{
public missingArguments = 0;
public definedVars:LocalDef[] = [];
public targets:Expr[] = [];
public sources:LocalDef[] = [];
public isPagePush = false;
public fixContextError:boolean;
}
export class Call
extends Expr
{
public propRef:PropertyRef;
public args:Expr[];
public _assignmentInfo:AssignmentInfo;
public runAsAsync:boolean;
public autoGet:boolean;
public isSynthetic:boolean;
public isShim:boolean;
public savedFix:Call;
public funAction:InlineAction;
public optionalConstructor:InlineActions;
public compiledTypeArgs:any;
// this is for break, return, and show
public topRetLocal:LocalDef;
public topAffectedStmt:Stmt;
public topPostCall:Expr;
constructor() {
super()
}
public children() { return this.args; }
public assignmentInfo() { return this._assignmentInfo; }
public nodeType() { return "call"; }
public getCalledProperty():IProperty { return this.prop(); }
public getText()
{
var res = this.propRef.getText() + "(";
for (var i = 0; i < this.args.length; ++i) {
if (i > 0) res += ", ";
res += this.args[i].getText();
}
res += ")";
return res;
}
public referencedRecord()
{
var prop = this.prop()
if (prop instanceof AST.RecordDef)
return <AST.RecordDef>prop
return null
}
public referencedRecordField()
{
var prop = this.prop()
if (!prop) return null
var fwd = prop.forwardsToStmt()
if (fwd instanceof RecordField)
return <RecordField>fwd
return null
}
public referencedData():AST.GlobalDef
{
if (this.prop() && this.prop().getCategory() == PropertyCategory.Data)
return <GlobalDef>this.prop().forwardsTo();
else
return null;
}
public referencedLibrary() : LibraryRef
{
var prop = this.prop()
if (prop instanceof LibraryRef)
return <LibraryRef>prop
return null
}
public getCall() { return this }
public getLiftedSetter()
{
var prop = this.prop()
if (!prop) return null
if (prop.getFlags() & PropertyFlags.Async) return null
if (prop.getParameters().length != 1) return null
var tp = prop.getResult().getKind()
if (tp.equals(api.core.Nothing)) return null
var setter = prop.parentKind.getProperty("set " + prop.getName())
if (setter &&
!(setter.getFlags() & PropertyFlags.Async) &&
setter.getResult().getKind().equals(api.core.Nothing)) {
var parms = setter.getParameters()
if (parms.length == 2 && parms[1].getKind().equals(tp))
return setter
}
return null
}
public isRefValue()
{
var gd = this.referencedData()
if (gd) return true
var rcf = this.referencedRecordField()
if (rcf && !rcf.isKey) return true;
// if (this.getLiftedSetter()) return true;
return false
}
public allowAssignment()
{
return this.allowRefUse() || !!this.getLiftedSetter();
}
public allowRefUse()
{
if (!this.isRefValue()) return false
var gd = this.referencedData()
if (gd && gd.readonly) return false
return true
}
public prop() { return this.propRef.prop; }
public calledProp() { return this.prop(); }
public flatten(prop:IProperty) : Expr[]
{
if (this.propRef.prop == prop) {
return this.args.collect((e:Expr) => e.flatten(prop));
} else {
return [this];
}
}
public accept(v:NodeVisitor) {
var p = this.prop()
if (!p || p.parentKind != api.core.Unknown) // fast path
return v.visitCall(this)
if (p == api.core.AssignmentProp)
return v.visitAssignment(this)
else if (p == api.core.ReturnProp)
return v.visitReturn(this)
else if (p == api.core.BreakProp)
return v.visitBreak(this)
else if (p == api.core.ContinueProp)
return v.visitContinue(this)
else if (p == api.core.ShowProp)
return v.visitShow(this)
return v.visitCall(this);
}
public calledAction():AST.Action
{
if (this.prop() && this.prop().getCategory() == PropertyCategory.Action)
return <Action>this.prop().forwardsTo();
else
return null;
}
public calledExtensionAction():AST.Action
{
var prop = this.prop()
if (prop instanceof ExtensionProperty)
return (<ExtensionProperty>prop).shortcutTo
var act = this.calledAction()
if (act && act.isExtensionAction())
return act.extensionForward();
return null
}
public awaits()
{
return !this.runAsAsync && this.prop() && !!(this.prop().getFlags() & PropertyFlags.Async);
}
}
// -------------------------------------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------------------------------------
export function mkLocal(name:string, k:Kind)
{
var r = new LocalDef();
r.setName(name);
r._kind = k;
return r;
}
export function mkLit(v:any)
{
var r = new Literal();
r.data = v;
return r;
}
export function mkOp(v:string) : Operator
{
var o = new Operator();
o.data = v;
return o;
}
export function mkFunOp(args:string[]) : Operator
{
return mkOp("fun:" + args.map(idUrlQuote).join(","))
}
export function mkThing(v:string, forceLocal = false) : Expr
{
if (v == "true" || v == "false")
return mkLit(v == "true");
var t = new ThingRef();
t.data = v;
t.forceLocal = forceLocal;
return t;
}
export function mkLocalRef(l:LocalDef)
{
return mkThing(l.getName(), true)
}
export function mkPlaceholderByKind(k:Kind)
{
return mkPlaceholder(<any>{ getName: () => "this", getKind: () => k })
}
export function mkPlaceholder(p:PropertyParameter)
{
var name = p.getName();
if (name == "this" || p.parentProperty.getInfixPriority() > 0 || name == p.getKind().getStemName())
name = "";
var def = new PlaceholderDef();
def.label = name;
def._kind = p.getKind();
var t = new ThingRef();
t.def = def;
t.data = def.getName();
return t;
}
export function mkPropRef(v:string) : PropertyRef
{
var p = new PropertyRef();
p.data = v;
return p;
}
export function mkSingletonDef(n:string, k:Kind) : SingletonDef
{
var s = new SingletonDef();
s.setName(n);
s._kind = k;
if (k.isPrivate) s._isBrowsable = false;
return s;
}
export function mkTok(json:any) : Token
{
switch (json.type) {
case "literal": return mkLit(json.data);
case "operator": return mkOp(json.data);
case "propertyRef": return mkPropRef(json.data);
case "thingRef": return mkThing(json.data, json.forceLocal);
default: Util.die();
}
}
export function mkParam(name:string, k:Kind) { return mkLocal(name, k); }
export function mkPlaceholderThingRef() { return mkThing("$skip"); }
export function mkExprStmt(expr:ExprHolder, p:Parser = null)
{
var r = new ExprStmt();
if(p) {
r.setStableName(p.consumeLabel());
}
r.expr = expr;
return r;
}
export function exprToStmt(expr: Expr)
{
var r = new ExprHolder();
r.tokens = [];
r.locals = [];
r.parsed = expr;
return mkExprStmt(r);
}
export function mkWhere(expr:ExprHolder)
{
var r = new Where();
r.condition = expr;
return r;
}
export function mkFakeCall(prop:PropertyRef, args:Expr[] = [])
{
var t = new Call();
t.propRef = prop;
t.args = args;
t.isSynthetic = true;
return t;
}
export function mkCall(prop:PropertyRef, a:Expr[])
{
var t = new Call();
Util.assert(a.length > 0)
t.propRef = prop;
prop.call = t;
t.args = a;
return t;
}
export function idUrlQuote(s:string)
{
var sb = "";
for (var i = 0; i < s.length; ++i) {
var c = s.charAt(i);
if (/[A-Za-z0-9]/.test(c))
sb += c;
else if (c == " ")
sb += "_";
else
sb += "-" + (c.charCodeAt(0)|0x10000).toString(16).slice(-4);
}
return sb;
}
export function idUrlUnquote(s:string)
{
var r = ""
for (var i = 0; i < s.length; ++i) {
var c = s.charAt(i);
if (c == "_") {
r += " ";
} else if (c == "/" || c == "-") {
r += String.fromCharCode(parseInt(s.slice(i + 1, i + 5), 16))
i += 4
} else {
r += c;
}
}
return r;
}
export function isProperKind(k:Kind)
{
return k && k != api.core.Unknown && !(k instanceof MultiplexKind)
}
// -------------------------------------------------------------------------------------------------------
// Visitor
// -------------------------------------------------------------------------------------------------------
export class NodeVisitor
{
public visitAstNode(node:AstNode):any { return null; }
public visitToken(tok:Token) { return this.visitAstNode(tok); }
public visitOperator(n:Operator) { return this.visitToken(n); }
public visitPropertyRef(n:PropertyRef) { return this.visitToken(n); }
public visitExpr(tok:Expr) { return this.visitToken(tok); }
public visitLiteral(n:Literal) { return this.visitExpr(n); }
public visitThingRef(n:ThingRef) { return this.visitExpr(n); }
public visitCall(n:Call) { return this.visitExpr(n); }
public visitShow(n:Call) { return this.visitCall(n); }
public visitBreak(n:Call) { return this.visitCall(n); }
public visitContinue(n:Call) { return this.visitCall(n); }
public visitReturn(n:Call) { return this.visitCall(n); }
public visitAssignment(n:Call) { return this.visitCall(n); }
public visitExprHolder(n:ExprHolder) { return this.visitAstNode(n); }
public visitStmt(n:Stmt) { return this.visitAstNode(n); }
public visitComment(n:Comment) { return this.visitStmt(n); }
public visitBlock(n:Block) { return this.visitStmt(n); }
public visitCodeBlock(n:CodeBlock) { return this.visitBlock(n); }
public visitConditionBlock(n:ConditionBlock) { return this.visitBlock(n); }
public visitParameterBlock(n:ParameterBlock) { return this.visitBlock(n); }
public visitResolveBlock(n:ResolveBlock) { return this.visitBlock(n); }
public visitBindingBlock(n:BindingBlock) { return this.visitBlock(n); }
public visitFieldBlock(n:FieldBlock) { return this.visitBlock(n); }
public visitInlineActionBlock(n:InlineActionBlock) { return this.visitBlock(n); }
public visitFor(n:For) { return this.visitStmt(n); }
public visitForeach(n:Foreach) { return this.visitStmt(n); }
public visitWhile(n:While) { return this.visitStmt(n); }
public visitBox(n:Box) { return this.visitStmt(n); }
public visitAnyIf(n:If) { return this.visitStmt(n); }
public visitIf(n:If) { return this.visitAnyIf(n); }
public visitElseIf(n:If) { return this.visitAnyIf(n); }
public visitForeachClause(n:ForeachClause) { return this.visitStmt(n); }
public visitWhere(n:Where) { return this.visitForeachClause(n); }
public visitExprStmt(n:ExprStmt) { return this.visitStmt(n); }
public visitInlineActions(n:InlineActions) { return this.visitStmt(n); }
public visitInlineAction(n:InlineAction) { return this.visitStmt(n); }
public visitOptionalParameter(n:OptionalParameter) { return this.visitStmt(n); }
public visitActionParameter(n:ActionParameter) { return this.visitStmt(n); }
public visitActionHeader(n:ActionHeader) { return this.visitStmt(n); }
public visitDecl(n:Decl) { return this.visitStmt(n); }
public visitGlobalDef(n:GlobalDef) { return this.visitDecl(n); }
public visitLibraryRef(n:LibraryRef) { return this.visitDecl(n); }
public visitRecordDef(n:RecordDef) { return this.visitDecl(n); }
public visitSingletonDef(n:SingletonDef) { return this.visitDecl(n); }
public visitAction(n:Action) { return this.visitDecl(n); }
public visitLocalDef(n:LocalDef) { return this.visitDecl(n); }
public visitApp(n:App) { return this.visitDecl(n); }
public visitKindBinding(n:KindBinding) { return this.visitStmt(n); }
public visitActionBinding(n:ActionBinding) { return this.visitStmt(n); }
public visitResolveClause(n:ResolveClause) { return this.visitStmt(n); }
public visitRecordField(n:RecordField) { return this.visitStmt(n); }
public visitFieldName(n: AST.FieldName) { return this.visitLiteral(n); }
public visitDeclName(n: AST.DeclName) { return this.visitLiteral(n); }
public visitInlineStmt(n: AST.InlineStmt) { return this.visitStmt(n); }
public dispatch(n:AstNode) { return n.accept(this); }
public visitChildren(n:AstNode)
{
n.children().forEach((c) => c.accept(this));
}
}
class SearchForStableName
extends AST.NodeVisitor
{
public found: AST.AstNode;
constructor(public name: string)
{
super()
}
visitStmt(s:AST.Stmt)
{
if (s.getStableName() == this.name)
this.found = s;
this.visitChildren(s);
}
}
class SearchForId
extends AST.NodeVisitor
{
public foundNode:AST.AstNode;
public lastDecl:AST.Decl;
public lastStmt:AST.Stmt;
constructor(public id:string)
{
super()
}
check(n:AST.AstNode)
{
if (n.stableId == this.id)
this.foundNode = n;
}
visitDecl(d:AST.Decl)
{
this.check(d);
if (!this.foundNode) {
this.lastDecl = d;
this.visitChildren(d);
}
return null;
}
visitExprHolder(eh:AST.ExprHolder)
{
if (eh.parsed) this.dispatch(eh.parsed)
this.visitAstNode(eh)
}
visitAstNode(n:AST.AstNode)
{
this.check(n);
this.visitChildren(n)
}
visitStmt(s:AST.Stmt)
{
if (!this.foundNode) {
this.lastStmt = s;
this.check(s);
this.visitChildren(s);
}
return null;
}
}
export class StatsComputer
extends NodeVisitor
{
stmtCount = 0;
weight = 0;
action:Action;
constructor() { super() }
visitAction(n:Action)
{
this.action = n;
this.visitChildren(n);
if (n.isPage()) this.weight = 2;
else if (n.isEvent()) this.weight = 1;
else if (n.isPrivate) this.weight = 0;
else if (n.isMainAction()) this.weight = 4;
else this.weight = 3;
return null
}
visitBlock(b:Block)
{
this.visitChildren(b);
return null
}
visitStmt(s:Stmt)
{
if (!s.isPlaceholder())
this.stmtCount++;
this.visitChildren(s);
return null
}
}
export class StackOp
{
public type:string;
public infixProperty:IProperty;
public propertyRef:PropertyRef;
public tokens:Token[];
public op:string;
public expr:Expr = null;
public beg = 0;
public len = 0;
public prioOverride:number = 0;
public prio()
{
if (this.prioOverride != 0) return this.prioOverride;
if (!this.infixProperty) return 0;
return this.infixProperty.getInfixPriority();
}
public markError(msg:string)
{
var i = this.beg;
if (i < 0 || i >= this.tokens.length)
i = this.tokens.length - 1;
var end = i + this.len;
if (end <= i || end > this.tokens.length)
end = this.tokens.length;
while (i < end) {
this.tokens[i].setError(msg);
i++;
}
}
public copyFrom(other:StackOp)
{
this.tokens = other.tokens;
this.beg = other.beg;
this.len = other.len;
}
}
export class VariableFinder
extends NodeVisitor
{
private readLocals0:LocalDef[];
private writtenLocals0:LocalDef[];
readLocals:LocalDef[];
writtenLocals:LocalDef[];
lastStmt:Stmt;
saveWrites = false;
// globals read or written, including both global variables and records
readGlobals: Decl[];
writtenGlobals: Decl[];
visitedActions: Action[];
getGlobals: boolean = false;
add(s:Stmt, l:Decl, lst:LocalDef[])
{
if (l instanceof LocalDef && lst.indexOf(<LocalDef>l) < 0) {
if (this.saveWrites && s)
(<LocalDef>l)._lastWriteLocation = s
lst.push(<LocalDef>l);
}
}
private getLocal(e:Token):LocalDef
{
if (e instanceof ThingRef) {
var d = (<ThingRef>e).def;
if (d instanceof LocalDef) return <LocalDef>d;
}
return null;
}
static realName(g: Decl) {
return "$" + g.getStableName();
}
public writtenGlobalNames(): string[] {
return this.writtenGlobals.map(VariableFinder.realName);
}
public readGlobalNames(): string[] {
return this.readGlobals.map(VariableFinder.realName);
}
addGlobal(l: Decl, lst:Decl[])
{
if (lst.indexOf(l) < 0) lst.push(l);
}
private getGlobal(e:AstNode)
{
if (e instanceof Call) {
var prop = (<Call>e).prop();
if (prop instanceof GlobalDef || prop instanceof RecordDef) return <PropertyDecl><any>prop;
}
return null;
}
visitAstNode(n:AstNode)
{
this.visitChildren(n);
return null;
}
visitStmt(s:Stmt)
{
this.lastStmt = s
this.visitChildren(s)
return null;
}
visitAction(n: Action) {
if (this.visitedActions && this.visitedActions.indexOf(n) < 0) {
this.visitedActions.push(n);
super.visitAction(n);
}
}
visitThingRef(n:ThingRef)
{
this.add(null, n.def, this.readLocals0);
return null;
}
visitCall(n: Call) {
var prop = n.prop();
if (prop == api.core.AssignmentProp) {
n.args[0].flatten(api.core.TupleProp).forEach((e) => {
var l = this.getLocal(e);
if (l) this.add(null, l, this.writtenLocals0);
else if (this.getGlobals) {
var g = this.getGlobal(e);
if (g) this.addGlobal(g, this.writtenGlobals);
else this.dispatch(e);
} else this.dispatch(e);
});
this.dispatch(n.args[1]);
} else if (this.getGlobals) {
var act = n.calledAction();
if (act && this.visitedActions && this.visitedActions.indexOf(act) < 0) {
var readLocals0 = this.readLocals0;
var writtenLocals0 = this.writtenLocals0;
var readLocals = this.readLocals;
var writtenLocals = this.writtenLocals;
var readGlobals = this.readGlobals;
var writtenGlobals = this.writtenGlobals;
this.traverse(act, true, this.visitedActions);
readGlobals.forEach((g) => this.addGlobal(g, this.readGlobals));
writtenGlobals.forEach((g) => this.addGlobal(g, this.writtenGlobals));
this.readLocals0 = readLocals0;
this.writtenLocals0 = writtenLocals0;
this.readLocals = readLocals;
this.writtenLocals = writtenLocals;
}
if (prop instanceof GlobalDef) {
this.addGlobal(<GlobalDef>prop, this.readGlobals);
this.addGlobal(<GlobalDef>prop, this.writtenGlobals);
} else if (prop instanceof RecordDef) {
// consider record access as both read and write.
// Will differentiate them in the future
this.addGlobal(<RecordDef>prop, this.readGlobals);
this.addGlobal(<RecordDef>prop, this.writtenGlobals);
} else {
super.visitCall(n);
}
} else {
super.visitCall(n);
}
return null;
}
visitInlineAction(n:InlineAction)
{
n.inParameters.forEach(i => this.add(n, i, this.writtenLocals))
super.visitInlineAction(n)
}
visitExprHolder(n:ExprHolder)
{
var stmt = this.lastStmt
this.readLocals0 = [];
this.writtenLocals0 = [];
if (n.parsed)
this.dispatch(n.parsed);
// maybe there were syntax errors? also look at the raw tokens just in case
n.tokens.forEach((t) => {
var l = this.getLocal(t);
if (l && this.readLocals0.indexOf(l) < 0 && this.writtenLocals0.indexOf(l) < 0)
this.add(null, l, this.readLocals0);
});
this.readLocals0.forEach((l) => this.add(null, l, this.readLocals));
this.writtenLocals0.forEach((l) => this.add(stmt, l, this.writtenLocals));
return null;
}
visitFor(n:For)
{
this.add(n, n.boundLocal, this.writtenLocals);
super.visitFor(n);
return null;
}
visitForeach(n:Foreach)
{
this.add(n, n.boundLocal, this.writtenLocals);
super.visitForeach(n);
return null;
}
traverse(node: AstNode, getGlobals: boolean = false, visitedActions: Action[] = []) {
this.readLocals = [];
this.writtenLocals = [];
this.getGlobals = getGlobals;
if (getGlobals) {
this.readGlobals = [];
this.writtenGlobals = [];
this.visitedActions = visitedActions;
}
this.dispatch(node);
}
}
export class Extractor
extends VariableFinder
{
extractedAction:Action;
numAwait = 0;
failed:Stmt[] = [];
constructor(public extracted:CodeBlock, public action:Action, public callPlaceholder:ExprStmt, public name:string)
{
super();
}
visitCall(c:Call)
{
super.visitCall(c)
if (c.awaits())
this.numAwait++;
}
run()
{
AST.visitStmtsCtx({ inLoop: false, inHandler: false }, this.extracted, (ctx, s) => {
if (s.calcNode() && s.calcNode().parsed) {
var prop = s.calcNode().parsed.calledProp()
if (!ctx.inLoop && (prop == api.core.BreakProp || prop == api.core.ContinueProp))
this.failed.push(s)
if (!ctx.inHandler && (prop == api.core.ReturnProp))
this.failed.push(s)
}
ctx = Util.jsonClone(ctx)
if (s instanceof Loop)
ctx.inLoop = true
if (s instanceof InlineAction) {
ctx.inHandler = true
ctx.inLoop = true
}
return ctx
})
if (this.failed.length > 0) return
this.saveWrites = true
this.traverse(this.extracted);
var hasAwait = this.numAwait > 0;
var readSub = this.readLocals;
var writtenSub = this.writtenLocals;
this.saveWrites = false
this.traverse(this.action.body);
this.action.getInParameters().forEach((p) => this.add(null, p.local, this.writtenLocals));
if (this.action.modelParameter)
this.add(null, this.action.modelParameter.local, this.writtenLocals)
this.action.getOutParameters().forEach((p) => this.add(null, p.local, this.readLocals));
var outgoing = writtenSub.filter((l) => this.readLocals.indexOf(l) >= 0);
var incoming = readSub.filter((l) => this.writtenLocals.indexOf(l) >= 0);
var useReturn = outgoing.length == 1
if (outgoing.length > 1) {
this.failed = outgoing.map(l => l._lastWriteLocation)
return
}
var refLocal = (l:LocalDef) => mkThing(l.getName());
var copyNames:any = {}
var extractedStmts = this.extracted.stmts.slice(0);
var extractedAction = <Action>Parser.parseDecl("action go() { meta private; }");
extractedAction.setName(this.name);
extractedAction.body = this.extracted;
extractedAction.isAtomic = !hasAwait;
extractedAction.header.inParameters.pushRange(incoming.map((l) => new ActionParameter(l)));
outgoing.forEach((l) => {
if (useReturn || incoming.indexOf(l) >= 0) {
var copy = mkLocal(this.action.nameLocal(l.getName(), copyNames), l.getKind());
copyNames[copy.getName()] = true;
var stmt = Parser.emptyExprStmt();
if (useReturn)
stmt.expr.tokens = [AST.mkOp("return"), refLocal(l)];
else
stmt.expr.tokens = [refLocal(copy), mkOp(":="), refLocal(l)];
extractedStmts.push(stmt);
l = copy;
}
extractedAction.header.outParameters.push(new ActionParameter(l, true));
});
this.extracted.setChildren(extractedStmts);
var res = Parser.parseDecl(extractedAction.serialize());
this.extractedAction = <Action>res;
var toks = this.callPlaceholder.expr.tokens;
if (outgoing.length > 0) {
outgoing.forEach((l, i) => {
if (i > 0) toks.push(mkOp(","));
toks.push(refLocal(l));
});
toks.push(mkOp(":="));
}
toks.push(mkThing("code"));
toks.push(mkPropRef(this.name));
if (incoming.length > 0) {
toks.push(mkOp("("));
incoming.forEach((l, i) => {
if (i > 0) toks.push(mkOp(","));
toks.push(refLocal(l));
});
toks.push(mkOp(")"));
}
}
}
// Find out what methods are called (transitively) from the node
export class MethodFinder
extends NodeVisitor
{
called: Action[];
visitAstNode(n: AstNode) {
this.visitChildren(n);
return null;
}
visitCall(n: Call) {
var act = n.calledAction();
if (act && this.called.indexOf(act) < 0) {
this.called.push(act);
// scan the called action
this.traverse(act, this.called);
}
super.visitCall(n);
}
visitExprHolder(n: ExprHolder) {
if (n.parsed) this.dispatch(n.parsed);
}
traverse(node: AstNode, called: Action[] = []) {
this.called = called;
this.dispatch(node);
}
}
// remove comments, skip statments, useless meta
// used for loose script equality
export class ScriptCompacter
extends TDev.AST.NodeVisitor
{
constructor () {
super()
}
static compact(s: App) {
s.setMeta("stableNames", null);
s.accept(new ScriptCompacter());
return s;
}
visitDecl(d: AST.Decl) {
this.visitChildren(d);
return null;
}
visitAction(n: TDev.AST.Action) {
this.visitChildren(n);
return null
}
visitBlock(n: TDev.AST.Block) {
n.stmts = n.stmts.filter((s) => s.nodeType() != "comment" && !s.isPlaceholder());
this.visitChildren(n);
}
visitStmt(s:TDev.AST.Stmt)
{
this.visitChildren(s);
return null
}
}
export class DeepVisitor
extends TDev.AST.NodeVisitor
{
includeUnreachable = false;
localActions:Action[] = [];
libActions:LibraryRefAction[] = [];
useBuiltinProperty(p:IProperty)
{
}
useKind(k:Kind)
{
}
useAction(a:Action)
{
if (!a) return;
if (a.visitorState) return;
a.visitorState = true;
if (a instanceof LibraryRefAction) {
this.libActions.push(<LibraryRefAction>a);
} else {
this.localActions.push(a);
}
}
static clearVisitorState(app:App)
{
app.libraries().forEach((l) => {
var pubs = l.getPublicActions();
if (pubs)
pubs.forEach((a) => a.visitorState = null);
if (l.resolved)
l.resolved.things.forEach((a) => a.visitorState = null)
})
app.things.forEach((a) => a.visitorState = null)
}
visitAstNode(n:AstNode)
{
super.visitChildren(n);
}
visitGlobalDef(g:GlobalDef)
{
this.useKind(g.getKind())
}
visitRecordField(rf:RecordField)
{
this.useKind(rf.dataKind)
}
runOnDecl(d:Decl)
{
if (d.visitorState) return;
if (d instanceof Action) this.useAction(<Action>d);
else {
d.visitorState = true;
this.dispatch(d);
}
}
visitRecordDef(r:RecordDef)
{
this.useKind(r.entryKind);
super.visitChildren(r);
}
private visitDeclOrProp(c:Call, p:IProperty)
{
var d:Decl = null
if (c)
d = c.calledExtensionAction()
if (!d)
d = p.forwardsTo();
this.useKind(p.parentKind)
if (d) {
this.runOnDecl(d);
} else {
this.useBuiltinProperty(p);
}
}
visitOperator(o:Operator)
{
var c = o.call
if (c) {
if (c._assignmentInfo && c._assignmentInfo.targets) {
c._assignmentInfo.targets.forEach(t => {
var setter = t.getLiftedSetter()
if (setter) this.visitDeclOrProp(mkFakeCall(PropertyRef.mkProp(setter), []), setter)
})
}
}
super.visitOperator(o)
}
visitPropertyRef(n:PropertyRef)
{
var p = n.prop
if (!p) return;
this.visitDeclOrProp(n.getCall(), p)
}
visitActionParameter(ap:ActionParameter)
{
this.useKind(ap.getKind());
super.visitChildren(ap);
}
visitAction(a:Action)
{
super.visitChildren(a);
}
private traverseActions()
{
while (this.localActions.length > 0) {
var a = this.localActions.pop();
this.dispatch(a);
}
}
private findActionMapping(app:App)
{
app.libraries().forEach((l) => {
if (!l.resolved) return;
var acts = this.libActions.filter((a) => a.parentLibrary() == l);
if (acts.length == 0) return;
var names = {}
acts.forEach((a) => names[a.getName()] = true)
l.resolved.allActions().forEach((a) => {
if (names.hasOwnProperty(a.getName()))
this.useAction(a);
});
});
}
secondaryRun(app: App)
{
}
run(app: App)
{
DeepVisitor.clearVisitorState(app);
app.libraries().forEach((l) => {
l.resolveClauses.forEach((r:ResolveClause) => {
r.actionBindings.forEach((b:Binding) => {
if (b instanceof ActionBinding) {
this.useAction((<ActionBinding>b).actual);
}
});
});
});
if (this.includeUnreachable)
app.things.forEach((d) => this.runOnDecl(d))
else
app.allActions().forEach((a:Action) => {
if (a.isEvent() || (!a.isPrivate || a.isTest()))
this.useAction(a);
})
this.secondaryRun(app);
this.traverseActions();
if (this.includeUnreachable) {
app.libraries().forEach((l) => {
if (!l.resolved) return;
l.resolved.things.forEach((d) => this.runOnDecl(d))
});
} else {
this.findActionMapping(app);
}
this.traverseActions();
}
}
export class PlatformDetector
extends DeepVisitor
{
propsByName:any = {};
featuresByName:any = {};
errors = "";
platform:PlatformCapability = PlatformCapability.None;
requiredPlatform:PlatformCapability = PlatformCapability.All;
compatMode = true;
useBuiltinProperty(p:IProperty)
{
var n = p.parentKind.toString() + "->" + p.getName();
if (this.propsByName[n]) return;
this.propsByName[n] = p;
var plat = this.compatMode ? p.getExplicitCapability() : p.getCapability();
if (p.parentKind.toString() == "Invalid")
plat = PlatformCapability.None;
this.useFeature(plat, n)
}
useKind(k:Kind)
{
// just using these types doesn't necessarily mean you're using caps
// for compat with C# parser
if (!this.compatMode)
this.useFeature(k.generalCapabilities, "type " + k.getName())
}
usePlatform(plat:PlatformCapability, name:string)
{
this.platform |= plat;
if ((plat & this.requiredPlatform) != plat) {
this.errors += name + " is not supported on this platform.\n";
}
}
useFeature(plat:PlatformCapability, name:string)
{
if (this.featuresByName[name]) return;
this.featuresByName[name] = true;
this.usePlatform(plat, name);
}
visitAction(a:Action)
{
super.visitAction(a);
if (a.isEvent())
this.useFeature(a.eventInfo.type.platform, a.getName())
}
visitRecordDef(r: RecordDef) {
if (r.cloudEnabled)
this.useFeature(PlatformCapability.CloudData, "cloud records")
}
visitApp(a:App)
{
super.visitApp(a)
}
}
export class DeclRefFinder
extends NodeVisitor
{
public found = false;
constructor(public decl:Decl)
{
super();
}
visitAstNode(n:AstNode)
{
if (this.found) return;
this.visitChildren(n);
}
visitToken(t:Token)
{
this.found = this.found || t.matches(this.decl);
}
}
export class ExprVisitor
extends NodeVisitor
{
visitAstNode(n:AstNode)
{
this.visitChildren(n);
}
visitExprHolder(eh:ExprHolder)
{
if (eh.parsed) this.dispatch(eh.parsed)
}
}
export class ShallowMethodFinder
extends ExprVisitor
{
called: Action[] = [];
visitCall(n: Call) {
var act = n.calledAction();
if (act && this.called.indexOf(act) < 0)
this.called.push(act);
super.visitCall(n);
}
}
class StmtVisitor<T>
extends NodeVisitor
{
t:T;
constructor(public f:(ctx:T, s:Stmt)=>T)
{
super()
}
visitStmt(s:Stmt)
{
var prev = this.t
this.t = this.f(prev, s)
this.visitChildren(s)
this.t = prev
}
}
export function visitStmts(s:Stmt, f:(s:Stmt)=>void)
{
var v = new StmtVisitor<number>((ctx, s) => { f(s); return ctx; })
v.dispatch(s)
}
export function visitStmtsCtx<T>(ctx:T, s:Stmt, f:(ctx:T, s:Stmt)=>T)
{
var v = new StmtVisitor(f)
v.t = ctx
v.dispatch(s)
}
export function visitExprHolders(s:Stmt, f:(stmt:Stmt, eh:ExprHolder)=>void)
{
visitStmts(s, stmt => {
if (stmt.calcNode()) f(stmt, stmt.calcNode())
})
}
class AllNodeVisitor
extends NodeVisitor
{
constructor(private f:(s:AstNode)=>void)
{
super()
}
visitAstNode(n:AstNode)
{
this.f(n)
this.visitChildren(n);
}
visitExprHolder(eh:ExprHolder)
{
this.f(eh)
if (eh.parsed) this.dispatch(eh.parsed)
this.visitChildren(eh)
}
}
export function visitNodes(s:Stmt, f:(s:AstNode)=>void)
{
var v = new AllNodeVisitor(f)
v.dispatch(s)
}
export interface LoopStmt {
body: CodeBlock;
}
export interface LoadScriptResult
{
numErrors:number;
status:string;
parseErrs: string[];
errLibs:App[];
prevScript:App;
numLibErrors:number;
}
export function loadScriptAsync(getText:(s:string)=>Promise, currentId = ""):Promise
{
var res:LoadScriptResult = { numErrors: 0, status: "", parseErrs: [], errLibs: [], prevScript: Script, numLibErrors: 0 }
var problem = (msg) => {
res.numErrors++;
res.status += " " + msg + "\n";
}
return getText(currentId).then((text) => {
if (!text) throw new Error("cannot get script text: " + currentId);
var app = Parser.parseScript(text, res.parseErrs);
var byId:any = {}
app.libraries().forEach((lib) => {
var id = lib.getId();
if (id)
byId[id] = getText(id)
.then(r => {
if (!r) throw new Error("empty script text: " + id)
return r
})
.then(r => r, e => {
problem("cannot fetch library: " + id + "; " + e.toString())
return "";
})
})
return Promise.join(byId).then((byId) => {
res.prevScript = Script;
setGlobalScript(app);
Script.isTopLevel = true;
var prevPlatform = Script.getPlatformRaw();
if (prevPlatform & PlatformCapability.Current)
Script.setPlatform(PlatformCapability.All);
Script.localGuid = Util.guidGen();
if (res.parseErrs.length > 0)
problem("Parse errors");
var resolved = {}
var errLibs = []
var hasEmptyLib = false;
Script.libraries().forEach((lib) => {
var id = lib.getId()
if (!id) {
lib.setError("TD131: unbound library")
problem("Library '" + lib.getName() + "' is unbound");
res.numLibErrors++;
return;
} else if (id == "sixvorgj") {
hasEmptyLib = true;
}
if (!resolved[id] && byId[id]) {
var libParseErrs = [];
var app = Parser.parseScript(byId[id], libParseErrs);
app.isTopLevel = true;
if (libParseErrs.length > 0)
problem("Parse errors in library " + id);
if (lib.guid) app.localGuid = lib.guid;
app.setPlatform(PlatformCapability.All);
var numErr = TypeChecker.tcScript(app, true);
app.things.forEach(t => { t.isExternal = true })
if (numErr > 0) {
problem("Library " + id + " has errors");
res.numLibErrors++;
res.errLibs.push(app);
}
resolved[id] = app;
}
if (resolved[id]) {
lib.resolved = resolved[id];
} else {
lib.setError("TD132: cannot bind library")
res.numLibErrors++;
problem("Library " + id + " not provided");
}
});
TypeChecker.tcScript(Script, false, false);
Script.setStableNames();
Script.things.forEach((th) => {
if (th.hasErrors())
problem("Declaration '" + th.getName() + "' has errors");
})
Script.setPlatform(prevPlatform);
if (res.numErrors && hasEmptyLib)
res.numLibErrors++;
return res;
})
})
}
class ErrorChecker
extends NodeVisitor
{
lastErrorNode:AstNode;
surplusErrors = 0;
mismatches = 0;
missingErrors = 0;
matches = 0;
resetError()
{
if (this.lastErrorNode)
this.surplusErrors++;
this.lastErrorNode = null;
}
expectError(node:Stmt, rx:string)
{
if (this.lastErrorNode) {
var err = this.lastErrorNode.getError();
if (new RegExp(rx).test(err)) {
this.lastErrorNode.errorIsOk = true;
this.matches++;
} else {
this.mismatches++;
node.setError("TD133: the error message doesn't match")
}
this.lastErrorNode = null;
} else {
this.missingErrors++;
node.setError("TD134: no error to match")
}
}
visitComment(n:Comment)
{
n.errorIsOk = false;
var m = /^E: (.*)/.exec(n.text)
if (m) {
this.expectError(n, m[1]);
} else {
super.visitComment(n);
}
}
visitBlock(n:Block)
{
// no resetError()
n.errorIsOk = false;
this.visitChildren(n);
}
visitStmt(n:Stmt)
{
n.errorIsOk = false;
if (n.parent instanceof CodeBlock || n.getError())
this.resetError();
if (n.getError())
this.lastErrorNode = n;
this.visitChildren(n);
}
visitDecl(d:Decl)
{
this.resetError();
if (d.getError())
this.lastErrorNode = d;
this.visitChildren(d);
this.resetError();
}
}
export function runErrorChecker(a:Action): boolean
{
var e = new ErrorChecker();
e.dispatch(a);
return e.surplusErrors + e.mismatches + e.missingErrors == 0;
}
export class FindErrorVisitor extends NodeVisitor
{
firstError:Stmt;
public visitStmt(s:Stmt)
{
if (this.firstError) return;
if (s.getError()) this.firstError = s
else this.visitChildren(s)
}
public visitDecl(d:Decl) { this.visitChildren(d) }
static run(n:AstNode)
{
var vis = new FindErrorVisitor()
vis.dispatch(n)
return vis.firstError
}
}
export class IntelliCollector extends NodeVisitor
{
props:any = {};
topicPath:string;
singletonOrder:StringMap<number> = {};
singletonNo = 0;
public visitAstNode(n:AstNode) {
this.visitChildren(n);
}
public visitAction(a:Action)
{
if (a._skipIntelliProfile)
return
if (a.isAtomic)
this.incr("scriptPropertiesPropertyAtomic");
a.getInParameters().forEach(ai => {
this.incr(ai.getKind().getName());
})
a.getOutParameters().forEach(ai => {
this.incr(ai.getKind().getName());
})
this.visitChildren(a);
}
private incrKind(k: Kind) {
if (k && k != api.core.Unknown)
this.incr(k.getName());
}
private incr(n:string)
{
if (!n) return;
if (!this.props.hasOwnProperty(n))
this.props[n] = 0;
this.props[n]++;
}
public visitExprHolder(eh:ExprHolder)
{
if (eh.parsed)
this.dispatch(eh.parsed)
}
public visitExpr(expr: Expr) {
this.incrKind(expr.getKind());
super.visitExpr(expr);
}
public visitCall(c:Call)
{
if (c.prop())
this.incr(c.prop().usageKey())
this.visitChildren(c);
}
public visitThingRef(t:ThingRef)
{
if (t.def)
this.incr(t.def.usageKey())
if (t.def instanceof SingletonDef) {
var n = t.def.getName()
if (!this.singletonOrder.hasOwnProperty(n))
this.singletonOrder[n] = ++this.singletonNo;
}
}
public visitGlobalDef(t: GlobalDef)
{
this.incr("addNewButton");
this.incrKind(t.getKind());
if (t.isResource) {
this.incr("artSection");
if (t.getKind() == api.core.Picture || t.getKind() == api.core.Sound) {
this.incr("calcSearchArt");
this.incr("searchArtRefactoring");
}
}
else {
this.incr("dataSection");
this.incr("promoteRefactoring");
}
super.visitGlobalDef(t);
}
public visitRecordDef(t: RecordDef)
{
this.incr("addNewButton");
this.incrKind(t.getKind());
switch (t.recordType) {
case RecordType.Decorator:
this.incr("decoratorsSection");
break;
case RecordType.Object:
this.incr("objectsSection");
break;
case RecordType.Index:
case RecordType.Table:
this.incr("persistanceRadio");
this.incr("databaseSection");
break;
}
super.visitRecordDef(t);
}
public visitComment(c:Comment)
{
var dummy = c.text.replace(/#allow:(\w+)/, (match:string, feature:string) => {
this.incr(feature)
return ""
})
// usage of comments does not imply that they are allowed so no super call
var dummy2 = c.text.replace(/\{widgets:([\w,]*)\}/, (match:string, features:string) => {
this.incr("tutorialWidgets");
features.split(',').forEach(feature => this.incr(feature));
return ""
})
var dummy2 = c.text.replace(/\{flags:([\w,]*)\}/, (match:string, features:string) => {
this.incr("tutorialFlags");
features.split(',').forEach(feature => this.incr("flag:" + feature));
return ""
})
var dummy2 = c.text.replace(/\{topic:([\w-\/@]*)\}/, (match:string, top:string) => {
this.topicPath = top;
return ""
})
}
public visitExprStmt(e:ExprStmt)
{
if (e.isVarDef()) this.incr("var");
super.visitExprStmt(e);
}
public visitStmt(s:Stmt)
{
if (!(s instanceof App))
this.incr(s.nodeType())
super.visitStmt(s)
}
}
export class IntelliProfile
{
public allowAllLibraries : boolean = true;
private properties:any; // p.helpTopic() => #occurences
private singletonOrder:StringMap<number> = {};
public merge(other : IntelliProfile)
{
this.allowAllLibraries = this.allowAllLibraries && other.allowAllLibraries;
if (other.properties) {
if (!this.properties) this.properties = Util.clone(other.properties);
else Object.keys(other.properties).forEach(k => {
if (this.properties[k]) this.properties[k] += other.properties[k];
else this.properties[k] = other.properties[k];
});
}
Object.keys(other.singletonOrder).forEach(k => {
this.singletonOrder[k] = other.singletonOrder[k];
})
}
static helpfulProperties = {
ColorsBlack: 1,
ColorsBlue: 1,
ColorsCyan: 1,
ColorsGreen: 1,
ColorsMagenta: 1,
ColorsOrange: 1,
ColorsPurple: 1,
ColorsRed: 1,
ColorsWhite: 1,
ColorsYellow: 1,
ColorsPink: 1,
//ColorsSepia: 1,
//ColorsBrown: 1,
}
public hasKey(k:string)
{
if (!k) return true;
return !this.properties || !!this.properties[k.toLowerCase()]
}
public hasTokenUsage(p:any)
{
if (!p) return true;
var tok:TokenUsage = p.getUsage ? p.getUsage() : null;
return tok && tok.localCount + tok.globalCount > 0;
}
public hasProperty(p: IProperty, strict = false) {
if (!this.properties) return true;
return (!strict && this.hasTokenUsage(p))
|| this.hasKey(p.usageKey())
|| (this.allowAllLibraries &&
(
p instanceof LibraryRefAction ||
(p instanceof MultiplexProperty && (<MultiplexProperty>p).forKind instanceof LibraryRefAbstractKind)
)
)
|| (p instanceof RecordCtorProperty && !(<RecordCtorProperty>p).from_json)
}
public hasFlag(flg:string)
{
if (!this.properties) return false;
return this.hasKey("flag:" + flg)
}
public hasKind(k: Kind): boolean {
if (!this.properties) return true;
return this.hasTokenUsage(k) || this.hasKey(k.getName());
}
public hasDecl(p:Decl)
{
if (!this.properties) return true;
if (p instanceof LocalDef) return true;
if (p.getName() == AST.libSymbol)
// needs explicit #allow:libSingleton
return this.hasKey("libSingleton");
return this.hasTokenUsage(p) || this.hasKey(p.usageKey());
}
public incr(k:string)
{
if (!this.properties) return
k = k.toLowerCase();
if (this.properties.hasOwnProperty(k)) this.properties[k]++
else this.properties[k] = 1
}
public getSingletonOrder(name:string)
{
if (this.singletonOrder.hasOwnProperty(name))
return this.singletonOrder[name]
return 0
}
public loadFrom(node:AstNode, builtin : boolean)
{
var v = new IntelliCollector()
v.props = builtin ? Util.clone(IntelliProfile.helpfulProperties) : {};
v.dispatch(node)
this.properties = {}
Object.keys(v.props).forEach(k => {
this.properties[k.toLowerCase()] = v.props[k]
})
this.singletonOrder = v.singletonOrder;
}
}
export class AtomicVisitor
extends ExprVisitor
{
private calls:StringMap<Set<Action>> = {}
private currentAction:Action;
private currentCalls:Set<Action>;
private numNonAtomic:number;
private nonAtomic = new Set<Action>();
visitCall(c:Call)
{
var act = c.calledAction() || c.calledExtensionAction()
if (act && !act.isInLibrary()) {
if (act.isPage()) this.numNonAtomic++;
else this.currentCalls.add(act)
} else {
if (c.prop().getFlags() & PropertyFlags.Async)
this.numNonAtomic++;
}
super.visitCall(c)
}
visitInlineAction(a:InlineAction)
{
// skip body
}
visitAction(a:Action)
{
if (a.isPage() || a.isEvent())
this.nonAtomic.add(a)
if (a.isActionTypeDef() || a.isAtomic)
return;
this.currentAction = a;
this.currentCalls = new Set<Action>();
this.calls[a.getName()] = this.currentCalls;
this.numNonAtomic = 0;
super.visitAction(a);
if (this.numNonAtomic > 0)
this.nonAtomic.add(a)
}
static run(app:App)
{
var v = new AtomicVisitor()
v.dispatch(app)
var nonAtomic = v.nonAtomic;
while (true) {
var prev = nonAtomic.length()
app.actions().forEach(a => {
if (nonAtomic.contains(a) || !v.calls.hasOwnProperty(a.getName())) return
if (v.calls[a.getName()].elts().some(x => nonAtomic.contains(x)))
nonAtomic.add(a)
})
if (prev == nonAtomic.length()) break;
}
return app.actions().filter(a => !nonAtomic.contains(a))
}
}
export class InitIdVisitor extends NodeVisitor {
private expectAllSet = false;
private unsetNodes:AstNode[];
private lastStmt:Stmt;
private usedIds:StringMap<AstNode> = {};
constructor(private refresh:boolean) {
super();
}
public expectSet(n:AstNode)
{
this.expectAllSet = true
this.unsetNodes = []
this.usedIds = {}
this.dispatch(n)
if (this.unsetNodes.length > 0) {
var dict = Util.toDictionary(this.unsetNodes, (n:AstNode) => n.nodeType())
Util.oops("id not set on " + Object.keys(dict).join(", "))
}
}
// these don't need IDs
public visitAstNode(node:AstNode):any { }
public visitToken(tok:Token) { }
public visitOperator(n:Operator) { }
public visitPropertyRef(n:PropertyRef) { }
public visitExpr(tok:Expr) { }
public visitLiteral(n:Literal) { }
public visitThingRef(n:ThingRef) { }
public visitCall(n:Call) { }
public visitExprHolder(eh:ExprHolder)
{
var n = this.lastStmt
var ai = eh.assignmentInfo()
if (ai)
ai.definedVars.forEach((x, i) => x.setStableName(n.getStableName() + "$l" + i));
}
// Stmt and subclasses need IDs
public visitStmt(n:Stmt) {
if (this.expectAllSet && !n.getStableName() && !n.isPlaceholder())
this.unsetNodes.push(n)
n.initStableName(this.refresh);
if (!this.refresh) {
var u = this.usedIds
var nn = n.getStableName()
if (u.hasOwnProperty(nn) && u[nn] != n) {
n.initStableName(true)
} else u[nn] = n
}
}
public visitBlock(n:Block) {
this.visitStmt(n);
/*var ch = n.children()
if (ch.length == 1 && ch[0].isPlaceholder())
// TODO XXX - this is a hack to give deterministic IDs to
// the auto-generated empty (skip) statements in new actions, etc.
this.deriveIdChildren(n)
else*/
this.visitChildren(n)
}
public visitChStmt(n:Stmt)
{
this.visitStmt(n)
this.deriveIdChildren(n)
}
private withBoundLocal(n:Stmt, loc:LocalDef)
{
this.visitChStmt(n)
if (loc)
loc.setStableName(n.getStableName() + "$l0")
}
public visitFor(n:For) { this.withBoundLocal(n, n.boundLocal); }
public visitForeach(n:Foreach) { this.withBoundLocal(n, n.boundLocal); }
public visitWhile(n:While) { this.visitChStmt(n); }
public visitBox(n:Box) { this.visitChStmt(n); }
public visitAnyIf(n:If) { this.visitChStmt(n); }
public visitInlineActions(n:InlineActions) { this.visitChStmt(n); }
public visitActionHeader(n:ActionHeader) { this.visitChStmt(n); }
public visitExprStmt(n:ExprStmt) { this.visitChStmt(n); }
public visitActionParameter(n:ActionParameter) { this.withBoundLocal(n, n.local) }
public visitInlineAction(n:InlineAction)
{
this.withBoundLocal(n, n.name);
n.inParameters.forEach((p, i) => p.setStableName(n.getStableName() + "$inlIn" + i))
n.outParameters.forEach((p, i) => p.setStableName(n.getStableName() + "$inlOut" + i))
}
public visitGlobalDef(n:GlobalDef) { this.visitChStmt(n); }
public visitRecordDef(n:RecordDef) { this.visitChStmt(n); }
public visitAction(n:Action) { this.visitChStmt(n); }
public visitLibraryRef(n:LibraryRef)
{
this.visitChStmt(n);
//n.getPublicActions().forEach(e => this.dispatch(e))
}
public visitLocalDef(n:LocalDef) { }
public visitApp(n:App) { this.visitDecl(n); this.visitChildren(n); }
public visitKindBinding(n:KindBinding) {
if (n.isExplicit)
this.visitStmt(n);
}
public visitActionBinding(n:ActionBinding) {
if (n.isExplicit)
this.visitStmt(n);
}
public visitResolveClause(n:ResolveClause) { this.visitChStmt(n); }
public visitRecordField(n:RecordField) { this.visitChStmt(n); }
public visitChildren(n:AstNode)
{
n.children().forEach(c => { if (c) c.accept(this); });
}
public deriveIdChildren(n:Stmt) {
this.lastStmt = n;
n.children().forEach((c, ix) => {
if(c) {
if(c instanceof Stmt) {
(<Stmt>c).deriveStableName(n, ix)
}
c.accept(this);
}
});
}
static ensureOK(app:App)
{
if (app.hasIds)
new InitIdVisitor(false).dispatch(app)
}
}
export function decompressStack(compressed:string):IStackFrame[]
{
var stmtById:StringMap<IStackFrame> = {}
var add = (rtid:string, rt:Stmt) => {
visitStmts(rt, s => {
stmtById[StackUtil.combineIds(s.getStableName(), rtid)] = <any> { pc: s.getStableName(), d: { libName: rtid } }
})
}
add("", Script)
Script.libraries().forEach(l => {
if (l.resolved) add(l.getStableName(), l.resolved)
})
var r = []
for (var i = 0; i < compressed.length; i += 8) {
var fr = compressed.slice(i, i + 8)
if (stmtById.hasOwnProperty(fr))
r.push(stmtById[fr])
}
return r
}
export function getEmbeddedLangaugeToken(n:Stmt):Expr
{
if (!(n instanceof ExprStmt)) return null;
var toks = (<ExprStmt>n).expr.tokens
if (toks.length == 5 &&
toks[0].getThing() == api.core.App.singleton &&
toks[1].getProperty() &&
/^thumb$/.test(toks[1].getProperty().getName()) &&
toks[2].getOperator() == "(" &&
toks[3].getStringLiteral() != null &&
toks[4].getOperator() == ")")
return <Expr>toks[3];
if (Cloud.isRestricted())
return null;
if (toks.length == 7 &&
toks[0].getThing() == api.core.App.singleton &&
toks[1].getProperty() &&
/^javascript|javascript async$/.test(toks[1].getProperty().getName()) &&
toks[2].getOperator() == "(" &&
toks[3].getStringLiteral() != null &&
toks[4].getOperator() == "," &&
toks[5].getStringLiteral() != null &&
toks[6].getOperator() == ")")
return <Expr>toks[5];
return null;
}
} | the_stack |
import { commonStartEffect, releaseAllEffect, ports } from './common/initial'
import { appInstanceMap } from '../create_app'
import { appStates, keepAliveStates } from '../constants'
import microApp, { unmountApp, unmountAllApps, getActiveApps } from '..'
describe('create_app', () => {
let appCon: Element
beforeAll(() => {
commonStartEffect(ports.create_app)
microApp.start()
appCon = document.querySelector('#app-container')!
})
afterAll(() => {
return releaseAllEffect()
})
// 在子应用加载完静态资源之前就卸载,然后重新渲染
test('unmount app before end of loading resource and remount', async () => {
const microAppElement1 = document.createElement('micro-app')
microAppElement1.setAttribute('name', 'test-app1')
microAppElement1.setAttribute('url', `http://127.0.0.1:${ports.create_app}/common/`)
let createCount = 0
await new Promise((resolve) => {
// 元素被插入到文档中,此时已经开始请求资源
// created 将会被执行两次
microAppElement1.addEventListener('created', () => {
createCount++
expect(appInstanceMap.size).toBe(1)
if (createCount === 1) {
expect(appInstanceMap.get('test-app1')!.getAppState()).toBe(appStates.LOADING_SOURCE_CODE)
} else {
// 二次渲染时会异步执行mount,所以此时仍然是UNMOUNT
expect(appInstanceMap.get('test-app1')!.getAppState()).toBe(appStates.UNMOUNT)
}
resolve(true)
}, false)
appCon.appendChild(microAppElement1)
})
await new Promise((resolve) => {
microAppElement1.addEventListener('unmount', () => {
const app = appInstanceMap.get('test-app1')!
expect(app.getAppState()).toBe(appStates.UNMOUNT)
// 因为应用还没渲染就卸载,所以active始终为false
// @ts-ignore
expect(app.sandBox!.active).toBeFalsy()
Promise.resolve().then(() => {
expect(app.container).toBeNull()
resolve(true)
})
}, false)
appCon.removeChild(microAppElement1)
})
await new Promise((resolve) => {
microAppElement1.addEventListener('mounted', () => {
expect(createCount).toBe(2)
}, false)
appCon.appendChild(microAppElement1)
resolve(true)
})
})
// 关闭沙箱
test('disableSandbox in this app', async () => {
const microAppElement2 = document.createElement('micro-app')
microAppElement2.setAttribute('name', 'test-app2')
microAppElement2.setAttribute('url', `http://127.0.0.1:${ports.create_app}/dynamic/`)
microAppElement2.setAttribute('disableSandbox', 'true')
appCon.appendChild(microAppElement2)
await new Promise((resolve) => {
microAppElement2.addEventListener('mounted', () => {
expect(appInstanceMap.get('test-app2')!.useSandbox).toBeFalsy()
resolve(true)
}, false)
})
appCon.removeChild(microAppElement2)
})
// 组件卸载后获取html失败
test('unmount app before fetch html failed', async () => {
const microAppElement3 = document.createElement('micro-app')
microAppElement3.setAttribute('name', 'test-app3')
microAppElement3.setAttribute('url', 'http://www.not-exist.com/')
const errorHandle = jest.fn()
microAppElement3.addEventListener('error', errorHandle)
appCon.appendChild(microAppElement3)
appCon.removeChild(microAppElement3)
await new Promise((resolve) => {
setTimeout(() => {
expect(errorHandle).not.toBeCalled()
resolve(true)
}, 200)
})
})
// 发送mounted事件时app已被卸载
test('coverage branch of dispatch mounted event when app has unmounted', async () => {
const microAppElement4 = document.createElement('micro-app')
microAppElement4.setAttribute('name', 'test-app4')
microAppElement4.setAttribute('url', `http://127.0.0.1:${ports.create_app}/common/`)
appCon.appendChild(microAppElement4)
const mountedHandler1 = jest.fn()
microAppElement4.addEventListener('mounted', mountedHandler1)
function unmountTestApp4 () {
appCon.removeChild(microAppElement4)
window.removeEventListener('unmount-me', unmountTestApp4)
}
window.addEventListener('unmount-me', unmountTestApp4)
// 子应用通过数据通信异步通知基座卸载自己,但异步优先于mounted执行
const microAppElement5 = document.createElement('micro-app')
microAppElement5.setAttribute('name', 'test-app5')
microAppElement5.setAttribute('url', `http://127.0.0.1:${ports.create_app}/common/`)
appCon.appendChild(microAppElement5)
const mountedHandler2 = jest.fn()
microAppElement5.addEventListener('mounted', mountedHandler2)
function unmountTestApp5 (data: Record<string, unknown>) {
if (data.unmountMeAsync === true) {
appCon.removeChild(microAppElement5)
microApp.removeDataListener('test-app5', unmountTestApp5)
}
}
microApp.addDataListener('test-app5', unmountTestApp5)
await new Promise((resolve) => {
setTimeout(() => {
// mounted 钩子不执行
expect(mountedHandler1).not.toBeCalled()
expect(mountedHandler2).not.toBeCalled()
resolve(true)
}, 200)
})
})
// 非沙箱环境的umd,在destroy卸载时,注册在window的函数应该删除
test('render umd app with disableSandbox & destroy', async () => {
const microAppElement6 = document.createElement('micro-app')
microAppElement6.setAttribute('name', 'test-app6')
microAppElement6.setAttribute('library', 'umd-app1') // 自定义umd名称
microAppElement6.setAttribute('url', `http://127.0.0.1:${ports.create_app}/umd1`)
microAppElement6.setAttribute('disableSandbox', 'true')
microAppElement6.setAttribute('destroy', 'true')
appCon.appendChild(microAppElement6)
await new Promise((resolve) => {
microAppElement6.addEventListener('mounted', () => {
// @ts-ignore
expect(window['umd-app1']).not.toBeUndefined()
appCon.removeChild(microAppElement6)
// @ts-ignore
expect(window['umd-app1']).toBeUndefined()
resolve(true)
})
})
})
// 分支覆盖 -- 返回 promise 的 mount 和 unmount 函数
test('promised mount & unmount', async () => {
const microAppElement7 = document.createElement('micro-app')
microAppElement7.setAttribute('name', 'test-app7')
microAppElement7.setAttribute('library', 'umd-app3') // 自定义umd名称
microAppElement7.setAttribute('url', `http://127.0.0.1:${ports.create_app}/umd3`)
appCon.appendChild(microAppElement7)
await new Promise((resolve) => {
microAppElement7.addEventListener('mounted', () => {
microAppElement7.addEventListener('unmount', () => {
resolve(true)
})
appCon.removeChild(microAppElement7)
})
})
// 再次渲染 -- 分支覆盖
const microAppElement8 = document.createElement('micro-app')
microAppElement8.setAttribute('name', 'test-app7')
microAppElement8.setAttribute('library', 'umd-app3') // 自定义umd名称
microAppElement8.setAttribute('url', `http://127.0.0.1:${ports.create_app}/umd3`)
appCon.appendChild(microAppElement8)
await new Promise((resolve) => {
microAppElement8.addEventListener('mounted', () => {
resolve(true)
})
})
})
// 分支覆盖 -- 抛出错误的 mount 和 unmount 函数
test('throw error mount & unmount', async () => {
const microAppElement9 = document.createElement('micro-app')
microAppElement9.setAttribute('name', 'test-app9')
microAppElement9.setAttribute('library', 'umd-app3') // 自定义umd名称
microAppElement9.setAttribute('url', `http://127.0.0.1:${ports.create_app}/umd3`)
// @ts-ignore
window.specialUmdMode = 'error-hook'
appCon.appendChild(microAppElement9)
await new Promise((resolve) => {
microAppElement9.addEventListener('mounted', () => {
// 渲染时打印错误日志
expect(console.error).toHaveBeenCalledWith('[micro-app] app test-app9: an error occurred in the mount function \n', expect.any(Error))
appCon.removeChild(microAppElement9)
// 卸载时打印错误日志
expect(console.error).toHaveBeenCalledWith('[micro-app] app test-app9: an error occurred in the unmount function \n', expect.any(Error))
resolve(true)
})
})
const microAppElement10 = document.createElement('micro-app')
microAppElement10.setAttribute('name', 'test-app9')
microAppElement10.setAttribute('library', 'umd-app3') // 自定义umd名称
microAppElement10.setAttribute('url', `http://127.0.0.1:${ports.create_app}/umd3`)
appCon.appendChild(microAppElement10)
await new Promise((resolve) => {
microAppElement10.addEventListener('mounted', () => {
// 再次渲染时打印错误日志
expect(console.error).toHaveBeenCalledWith('[micro-app] app test-app9: an error occurred in the mount function \n', expect.any(Error))
resolve(true)
})
})
// @ts-ignore
delete window.specialUmdMode
})
// 分支覆盖 -- 抛出错误promise 的 mount 和 unmount 函数
test('throw error promise mount & unmount', async () => {
const microAppElement11 = document.createElement('micro-app')
microAppElement11.setAttribute('name', 'test-app11')
microAppElement11.setAttribute('library', 'umd-app3') // 自定义umd名称
microAppElement11.setAttribute('url', `http://127.0.0.1:${ports.create_app}/umd3`)
// @ts-ignore
window.specialUmdMode = 'error-promise-hook'
appCon.appendChild(microAppElement11)
await new Promise((resolve) => {
// promise.reject 会触发error事件,不会触发mounted事件
microAppElement11.addEventListener('error', () => {
// promise.reject 会正常触发unmount事件
microAppElement11.addEventListener('unmount', () => {
resolve(true)
})
appCon.removeChild(microAppElement11)
})
})
// @ts-ignore
delete window.specialUmdMode
})
// 测试 unmountApp 方法
test('test unmountApp method', async () => {
// 场景1: 常规卸载操作
const microAppElement12 = document.createElement('micro-app')
microAppElement12.setAttribute('name', 'test-app12')
microAppElement12.setAttribute('url', `http://127.0.0.1:${ports.create_app}/common`)
appCon.appendChild(microAppElement12)
await new Promise((resolve) => {
microAppElement12.addEventListener('mounted', () => {
unmountApp('test-app12').then(resolve)
})
})
await new Promise((resolve) => {
unmountApp('not-exist').then(() => {
expect(console.warn).toHaveBeenCalledWith('[micro-app] app not-exist does not exist')
resolve(true)
})
})
// 场景2: 卸载已经卸载的应用
const microAppElement13 = document.createElement('micro-app')
microAppElement13.setAttribute('name', 'test-app13')
microAppElement13.setAttribute('url', `http://127.0.0.1:${ports.create_app}/common`)
appCon.appendChild(microAppElement13)
await new Promise((resolve) => {
microAppElement13.addEventListener('mounted', () => {
appCon.removeChild(microAppElement13)
})
// 应用已经卸载后执行unmountApp
microAppElement13.addEventListener('unmount', () => {
// 首次卸载不传 destroy,则直接返回,test-app13依然存在
unmountApp('test-app13').then(() => {
expect(appInstanceMap.has('test-app13')).toBeTruthy()
// 第二次卸载设置destroy,应用被删除
unmountApp('test-app13', {
destroy: true,
}).then(() => {
expect(appInstanceMap.has('test-app13')).toBeFalsy()
resolve(true)
})
})
})
})
// 场景3: 卸载已经推入后台的keep-alive应用
const microAppElement14 = document.createElement('micro-app')
microAppElement14.setAttribute('name', 'test-app14')
microAppElement14.setAttribute('url', `http://127.0.0.1:${ports.create_app}/common`)
microAppElement14.setAttribute('keep-alive', 'true')
appCon.appendChild(microAppElement14)
await new Promise((resolve) => {
microAppElement14.addEventListener('mounted', () => {
appCon.removeChild(microAppElement14)
})
// 应用已隐藏后执行unmountApp
microAppElement14.addEventListener('afterhidden', () => {
// 首次卸载不传 destroy,则直接返回,test-app14安然无恙
unmountApp('test-app14').then(() => {
expect(appInstanceMap.has('test-app14')).toBeTruthy()
// 第二次卸载设置clearAliveState,触发应用卸载操作,应用状态被清除
unmountApp('test-app14', {
clearAliveState: true,
}).then(() => {
expect(appInstanceMap.has('test-app14')).toBeTruthy()
expect(appInstanceMap.get('test-app14')?.getAppState()).toBe(appStates.UNMOUNT)
resolve(true)
})
})
})
})
// 场景4: 强制删除已经推入后台的keep-alive应用
const microAppElement15 = document.createElement('micro-app')
microAppElement15.setAttribute('name', 'test-app15')
microAppElement15.setAttribute('url', `http://127.0.0.1:${ports.create_app}/umd1`)
microAppElement15.setAttribute('keep-alive', 'true')
appCon.appendChild(microAppElement15)
await new Promise((resolve) => {
microAppElement15.addEventListener('mounted', () => {
appCon.removeChild(microAppElement15)
})
// 应用已隐藏后执行unmountApp
microAppElement15.addEventListener('afterhidden', () => {
unmountApp('test-app15', {
destroy: true,
}).then(() => {
expect(appInstanceMap.has('test-app15')).toBeFalsy()
resolve(true)
})
})
})
// 场景5: 强制删除正在运行的app
const microAppElement16 = document.createElement('micro-app')
microAppElement16.setAttribute('name', 'test-app16')
microAppElement16.setAttribute('url', `http://127.0.0.1:${ports.create_app}/common`)
microAppElement16.setAttribute('destroy', 'attr-of-destroy')
microAppElement16.setAttribute('destory', 'attr-of-destory')
appCon.appendChild(microAppElement16)
await new Promise((resolve) => {
microAppElement16.addEventListener('mounted', () => {
unmountApp('test-app16', {
destroy: true,
}).then(() => {
expect(appInstanceMap.has('test-app16')).toBeFalsy()
expect(microAppElement16.getAttribute('destroy')).toBe('attr-of-destroy')
expect(microAppElement16.getAttribute('destory')).toBe('attr-of-destory')
resolve(true)
})
})
})
// 场景6: 卸载正在运行的keep-alive应用并清空状态
const microAppElement17 = document.createElement('micro-app')
microAppElement17.setAttribute('name', 'test-app17')
microAppElement17.setAttribute('url', `http://127.0.0.1:${ports.create_app}/common`)
microAppElement17.setAttribute('keep-alive', 'attr-of-keep-alive')
appCon.appendChild(microAppElement17)
await new Promise((resolve) => {
microAppElement17.addEventListener('mounted', () => {
unmountApp('test-app17', {
clearAliveState: true,
}).then(() => {
expect(appInstanceMap.get('test-app17')?.getAppState()).toBe(appStates.UNMOUNT)
expect(microAppElement17.getAttribute('keep-alive')).toBe('attr-of-keep-alive')
resolve(true)
})
})
})
// 场景7: 正常卸载一个keep-alive应用,保留状态
const microAppElement18 = document.createElement('micro-app')
microAppElement18.setAttribute('name', 'test-app18')
microAppElement18.setAttribute('url', `http://127.0.0.1:${ports.create_app}/common`)
microAppElement18.setAttribute('keep-alive', 'true')
appCon.appendChild(microAppElement18)
await new Promise((resolve) => {
microAppElement18.addEventListener('mounted', () => {
unmountApp('test-app18').then(() => {
expect(appInstanceMap.get('test-app18')?.getKeepAliveState()).toBe(keepAliveStates.KEEP_ALIVE_HIDDEN)
resolve(true)
})
})
})
})
// 测试 unmountAllApps 方法
test('test unmountAllApps method', async () => {
const microAppElement19 = document.createElement('micro-app')
microAppElement19.setAttribute('name', 'test-app19')
microAppElement19.setAttribute('url', `http://127.0.0.1:${ports.create_app}/common`)
microAppElement19.setAttribute('destroy', 'true')
appCon.appendChild(microAppElement19)
await new Promise((resolve) => {
microAppElement19.addEventListener('mounted', () => {
unmountAllApps().then(() => {
expect(appInstanceMap.has('test-app19')).toBeFalsy()
resolve(true)
})
})
})
})
// 分支覆盖之prefetchResolve为空
test('coverage: undefined prefetchResolve', async () => {
const microAppElement20 = document.createElement('micro-app')
microAppElement20.setAttribute('name', 'test-app20')
microAppElement20.setAttribute('url', `http://127.0.0.1:${ports.create_app}/common`)
appCon.appendChild(microAppElement20)
appInstanceMap.get('test-app20')!.isPrefetch = true
const mountedHandler = jest.fn()
microAppElement20.addEventListener('mounted', mountedHandler)
await new Promise((resolve) => {
setTimeout(() => {
expect(mountedHandler).not.toBeCalled()
resolve(true)
}, 100)
})
})
// 测试getActiveApps方法
test('test getActiveApps method', async () => {
// 因为上面已经执行unmountAllApps卸载了所有应用,所以这里长度为0
expect(getActiveApps(true).length).toBe(0)
})
}) | the_stack |
// some helpers
const toSafeArray = <T>(...items: T[]): SafeArray<T> => {
const dict: Scripting.Dictionary<number, T> = new ActiveXObject('Scripting.Dictionary');
items.forEach((x, index) => dict.Add(index, x));
return dict.Items();
};
const inCollection = <T = any>(collection: { Item(index: any): T }, index: string | number): T | undefined => {
let item: T | undefined;
try {
item = collection.Item(index);
} catch (error) { }
return item;
};
{
let app1: Excel.Application | null = new ActiveXObject('Excel.Application');
app1.Visible = true;
const book1 = app1.Workbooks.Add();
app1.Quit();
app1 = null;
WScript.Quit();
}
const app = new ActiveXObject('Excel.Application');
// create a workbook -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/create-a-workbook
const newBook = app.Workbooks.Add();
newBook.Title = 'All Sales';
newBook.Subject = 'Sales';
newBook.SaveAs('allsales.xls');
// create or replace a worksheet -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/create-or-replace-a-worksheet
const newOrExistingWorksheet = () => {
const mySheetName = 'Sheet4';
let mySheet = inCollection<Excel.Worksheet>(newBook.Worksheets, mySheetName);
if (!mySheet) {
WScript.Echo(`The sheet named "${mySheetName} doesn't exist, but will be created.`);
mySheet = app.Worksheets.Add() as Excel.Worksheet;
mySheet.Name = mySheetName;
}
};
const replaceWorksheet = () => {
const mySheetName = 'Sheet4';
app.DisplayAlerts = false;
let mySheet = inCollection<Excel.Worksheet>(app.Worksheets, mySheetName);
if (mySheet) { mySheet.Delete(); }
app.DisplayAlerts = true;
mySheet = app.Worksheets.Add() as Excel.Worksheet;
mySheet.Name = mySheetName;
WScript.Echo(`The sheet named "${mySheetName} has been replaced.`);
};
// referencing multiple sheets -- https://msdn.microsoft.com/VBA/Excel-VBA/articles/sheets-object-excel
const moveMultipleSheets = () => app.Worksheets(toSafeArray<string | number>(1, 'Sheet2')).Move(4);
// sort worksheets alphanumerically by name -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/sort-worksheets-alphanumerically-by-name
const sortSheetsTabName = () => {
app.ScreenUpdating = false;
const sheets = app.ActiveWorkbook.Sheets;
const sheetCount = sheets.Count;
for (let i = 0; i < sheetCount; i += 1) {
const sheetI = sheets(i);
for (let j = i; j < sheetCount; j += 1) {
const sheetJ = sheets(j);
if (sheetJ.Name < sheetI.Name) { sheetJ.Move(sheetI); }
}
}
app.ScreenUpdating = true;
};
// fill a value down into blank cells in a column -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/fill-a-value-down-into-blank-cells-in-a-column
const fillCellsFromAbove = () => {
app.ScreenUpdating = false;
const columnA = app.Columns(1);
try {
columnA.SpecialCells(Excel.XlCellType.xlCellTypeBlanks).Formula = '=R[-1]C';
columnA.Value = columnA.Value;
} catch (error) { }
app.ScreenUpdating = true;
};
// hide and unhide columns -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/hide-and-unhide-columns
const setColumnVisibility = (visible: boolean) => {
const book = app.Workbooks(1);
const sheet = inCollection<Excel.Worksheet | Excel.Chart | Excel.DialogSheet>(book.Worksheets, 'Sheet1');
if (!sheet) { return; }
// search the four columns for any constants
const checkWithin = (sheet as Excel.Worksheet).Range('A1:D1').SpecialCells(Excel.XlCellType.xlCellTypeConstants);
let find = checkWithin.Find('X');
if (!find) { return; }
const address = find.Address();
// hide the column, and then find the next X
do {
find.EntireColumn.Hidden = visible;
find = checkWithin.FindNext(find);
} while (find && find.Address() !== address);
};
// highlighting the active cell, row, or column -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/highlight-the-active-cell-row-or-column
{
const wks = app.ActiveSheet as Excel.Worksheet;
// highlight active cell
ActiveXObject.on(wks, 'SelectionChange', ['Target'], function(this: Excel.Worksheet, prm) {
app.ScreenUpdating = false;
// clear the color of all the cells
this.Cells.Interior.ColorIndex = 0;
// highlight the actie cell
prm.Target.Interior.ColorIndex = 8;
app.ScreenUpdating = true;
});
// highlight entire row and column that contain active cell
ActiveXObject.on(wks, 'SelectionChange', ['Target'], function(this: Excel.Worksheet, prm) {
if (prm.Target.Cells.Count > 1) { return; }
app.ScreenUpdating = false;
// clear the color of all the cells in the row and column of the active cell
this.Cells.Interior.ColorIndex = 0;
prm.Target.EntireRow.Interior.ColorIndex = 8;
prm.Target.EntireColumn.Interior.ColorIndex = 8;
app.ScreenUpdating = true;
});
}
// referencing cells -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/reference-cells-and-ranges
{
const wks = app.ActiveSheet as Excel.Worksheet;
// all the cells on a worksheet
wks.Cells.ClearContents();
// using A1 notation
wks.Range('A1').Font.Bold = true;
wks.Range('A1:D5').Font.Bold = true;
wks.Range('C5:D9,G9:H16').Font.Bold = true;
wks.Range('A:A').Font.Bold = true;
wks.Range('1:1').Font.Bold = true;
wks.Range('A:C').Font.Bold = true;
wks.Range('1:5').Font.Bold = true;
wks.Range('1:1,3:3,8:8').Font.Bold = true;
wks.Range('A:A,C:C,F:F').Font.Bold = true;
// using index numbers
wks.Cells(6, 1).Value2 = 10;
wks.Cells(6, 1).Value = 10;
// iterating through cells using index numbers
for (let counter = 1; counter < 20; counter += 1) {
wks.Cells(counter, 1).Value = 10;
}
// relative to other cells
wks.Cells(1, 1).Font.Underline = Excel.XlUnderlineStyle.xlUnderlineStyleDouble;
// using a Range object
const rng = wks.Cells('A1:D5');
rng.Formula = '=RAND()';
rng.Font.Bold = true;
// refer to multiple ranges, using Union
const r1 = wks.Range('A1:A10');
const r2 = wks.Range('B4:B20');
const union = app.Union(r1, r2);
union.Font.Bold = true;
// refer to multiple ranges using Areas
WScript.Echo(union.Areas.Count);
}
// looping through a range of cells -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/looping-through-a-range-of-cells
{
const wks = app.ActiveSheet as Excel.Worksheet;
// using for
for (let x = 1; x < 20; x++) {
const currentCell = wks.Cells(x, 1);
if (Math.abs(currentCell.Value) < 0.01) {
currentCell.Value = 0;
}
}
// using Enumerator
let enumerator = new Enumerator(wks.Cells('A1:D10'));
enumerator.moveFirst();
while (!enumerator.atEnd()) {
const currentCell = enumerator.item();
if (Math.abs(currentCell.Value) < 0.01) {
currentCell.Value = 0;
}
enumerator.moveNext();
}
// using CurrentRegion
enumerator = new Enumerator(app.ActiveCell.CurrentRegion);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
const cell = enumerator.item();
if (Math.abs(cell.Value) < 0.01) {
cell.Value = 0;
}
enumerator.moveNext();
}
}
// using selection -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/selecting-and-activating-cells
{
const wks = app.ActiveWorkbook.Worksheets(1);
// make a worksheet the active worksheet; otherwise code which uses the selection will fail
wks.Select();
// select a cell
wks.Range("A1").Select();
app.ActiveCell.Font.Bold = true;
// activate a cell; only a single cell can be active at any given time
wks.Range("B1").Activate();
// working with 3-D ranges -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/working-with-3-d-ranges
app.Sheets(toSafeArray("Sheet2", "Sheet3", "Sheet4")).Select();
app.Range("A1:H1").Select();
(app.Selection as Excel.Range).Borders(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlDouble;
// alternatively, use FillAcrossSheets to fill formatting and data across sheets
const book = app.ActiveWorkbook;
const wks2 = book.Worksheets("Sheet2");
const rng = wks2.Range("A1:H1");
rng.Borders(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlDouble;
book.Sheets.FillAcrossSheets(rng);
}
// prevent duplicate entry -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/prevent-duplicate-entries-in-a-range
{
const book = app.Workbooks(1);
ActiveXObject.on(book, 'SheetChange', ['Sh', 'Target'], function(this, prm) {
const EvalRange = (this.ActiveSheet as Excel.Worksheet).Range("A1:B20");
// If the cell where the value was entered is not in the defined range, if the value pasted is larger than a single cell, or if no value was entered in the cell, then exit the macro
if (
(app.Intersect(prm.Target, EvalRange) == null) ||
(prm.Target.Cells.Count > 1)
// VBA has a function called IsEmpty; not sure what the equivalent is in Javascript
) { return; }
// If the value entered already exists in the defined range on the current worksheet, undo and exit
if (app.WorksheetFunction.CountIf(EvalRange, prm.Target.Value()) > 1) {
app.EnableEvents = false;
app.Undo();
app.EnableEvents = true;
return;
}
// const enumerator = new Enumerator<Excel.Worksheet | Excel.Chart | Excel.DialogSheet>(book.Worksheets);
const enumerator = new Enumerator(book.Worksheets);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
const wks = enumerator.item();
if (wks.Name === prm.Target.Name) { continue; }
// If the value entered already exists in the defined range on the current worksheet, undo the entry.
if (app.WorksheetFunction.CountIf(wks.Range('A1:B20'), prm.Target.Value()) === 0) { continue; }
app.EnableEvents = false;
app.Undo();
app.EnableEvents = true;
}
});
}
// add a unique list of values to a combobox -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/add-a-unique-list-of-values-to-a-combo-box
{
{
// using the AdvancedFilter property
const book = app.ThisWorkbook;
const sheet = book.Worksheets("Sheet1");
const dataRange = sheet.Range('A1', sheet.Range("A100").End(Excel.XlDirection.xlUp));
dataRange.AdvancedFilter(Excel.XlFilterAction.xlFilterCopy, undefined, sheet.Range('L1'), true);
const data = sheet.Range("L2", sheet.Range('L100').End(Excel.XlDirection.xlUp)).Value() as SafeArray;
sheet.Range('L1', sheet.Range('L100').End(Excel.XlDirection.xlUp)).ClearContents();
const combobox = sheet.OLEObjects('ComboBox1').Object as MSForms.ComboBox;
combobox.Clear();
ActiveXObject.set(combobox, 'List', [], data);
combobox.ListIndex = -1;
}
{
// using a Dictionary
const sheet = app.ThisWorkbook.Sheets('Sheet2') as Excel.Worksheet;
const data = sheet.Range('A2', sheet.Range('A100').End(Excel.XlDirection.xlUp)).Value2 as SafeArray;
const arr = new VBArray(data).toArray();
const dict = new ActiveXObject('Scripting.Dictionary');
for (const x of arr) {
ActiveXObject.set(dict, 'Item', [x], true);
}
const combobox = sheet.OLEObjects('ComboBox1').Object as MSForms.ComboBox;
combobox.Clear();
// iterate over keys using Enumerator
const enumerator = new Enumerator(dict);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
combobox.AddItem(enumerator.item());
enumerator.moveNext();
}
// alternatively, make a JS array out of the keys, and iterate using forEach
// new VBArray(dict.Keys()).toArray().forEach(x => combobox.AddItem(x));
}
// animating a sparkline -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/animate-a-sparkline
{
const wks = app.ActiveSheet as Excel.Worksheet;
const oSparkGroup = wks.Cells.SparklineGroups(1);
// Set the data source to the first year of data
oSparkGroup.ModifySourceData('B2:M4');
// Loop through the data points for the subsequent two years
for (let i = 1; i <= 24; i++) {
// Move the reference for the sparkline group over one cell
oSparkGroup.ModifySourceData(wks.Range(oSparkGroup.SourceData).Offset(0, 1).Address());
WScript.Sleep(1000);
}
}
{
const formats = new VBArray(app.ClipboardFormats).toArray();
for (const format of formats) {
WScript.Echo(format);
}
}
} | the_stack |
import { ChangeDetectorRef } from '@angular/core';
import { WidgetImplementationComponent } from '../widgetimplementation.component';
import { WidgetService } from '../../widget.service';
import { NotificationService, Base64Service, WidgetEventBusService, Principal } from '../../../../shared';
import { DataSourceService } from '../../../data-source/data-source.service';
import { JhiEventManager } from 'ng-jhipster';
import { BsModalService } from 'ngx-bootstrap/modal';
import { DataSource } from '../../../data-source/data-source.model';
import { Subject, Subscription } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { Router } from '@angular/router';
export abstract class DataWidgetComponent extends WidgetImplementationComponent {
// datasource
dataSource: DataSource;
dataSourceMetadata: Object;
// time window for datasource indexing status check
DATASOURCE_INDEXING_CHECK_WINDOW = 10 * 1000;
dashboardPanelResizedSubscriber: Subscription;
// full text search
searchTerm = new Subject<string>();
searchTermObserver; // observer to search
lastEmittedSearchTerm: string;
renderFullTextSearchView: boolean = false;
// search
inputSearch: string;
// user role
userAuthorities: string[];
userIsAdmin: boolean;
maxElementsByContract: number;
maxNumberOfElementsReachedAlert: string = `The maximum number of elements for the current widget was already reached.
If you want to load some fresh data you have to delete some elements.`;
// messages
datasourceAlertMessage: string = `No index is defined over the datasource the widget is connected with.
The widget will not work properly till an index will be defined.`;
datasourceAlertMessageMustBeShown: boolean = false;
constructor(protected principal: Principal,
protected widgetService: WidgetService,
protected notificationService: NotificationService,
protected dataSourceService: DataSourceService,
protected eventManager: JhiEventManager,
protected cdr: ChangeDetectorRef,
protected modalService: BsModalService,
protected base64Service: Base64Service,
protected widgetEventBusService: WidgetEventBusService,
protected router: Router) {
super(principal, widgetService, notificationService, dataSourceService, eventManager, cdr, modalService, base64Service, router);
}
/*
* Methods
*/
initParamsDependingOnUserIdentities() {
// user role init
this.userAuthorities = this.principal['userIdentity']['authorities'];
if (this.userAuthorities.indexOf('ROLE_ADMIN') >= 0) {
this.userIsAdmin = true;
} else {
this.userIsAdmin = false;
}
// updating datasource indexing message according to current user authorities
if (this.userAuthorities.indexOf('ROLE_EDITOR') >= 0 || this.userAuthorities.indexOf('ROLE_ADMIN') >= 0) {
this.datasourceAlertMessage += '<br/><br/>';
this.datasourceAlertMessage += '<button type="button" class="btn btn-sm btn-primary indexDatasourceButton">';
this.datasourceAlertMessage += '<i class="fa fa-refresh" aria-hidden="true"></i> ';
this.datasourceAlertMessage += '<span>Index Datasource</span>';
this.datasourceAlertMessage += '</button>';
} else {
this.datasourceAlertMessage += '<br/><br/>';
this.datasourceAlertMessage += '<button type="button" class="btn btn-sm btn-primary" disabled>';
this.datasourceAlertMessage += '<i class="fa fa-refresh" aria-hidden="true"></i> ';
this.datasourceAlertMessage += '<span>Index Datasource</span>';
this.datasourceAlertMessage += '</button>';
}
// max elements init
this.maxElementsByContract = this.principal['userIdentity']['contract']['maxElements'];
}
callDatasourceIndexing() {
this.widgetService.callDatasourceIndexing(this.dataSource['id']).subscribe((res: Object) => {
const message: string = 'Indexing started.\nYou can perform a search also during the indexing process on the partial indexed data.';
this.notificationService.push('success', 'Full Text Index', message);
this.checkDatasourceIndexingStatus();
}, (error: HttpErrorResponse) => {
this.handleError(error.error, 'Datasource indexing');
});
}
checkDatasourceIndexingStatus() {
this.dataSourceService.find(this.widget['dataSourceId']).subscribe((dataSource: DataSource) => {
this.dataSource = dataSource;
if (this.dataSource['indexing'].toString() !== 'INDEXED') {
// wait for a while and check again
setTimeout(() => {
this.checkDatasourceIndexingStatus();
}, this.DATASOURCE_INDEXING_CHECK_WINDOW);
} else {
// check completed, notify the user about the new datasource indexing status
const message: string = 'Datasource indexing completed.';
this.notificationService.push('success', 'Full Text Index', message);
this.performOperationsAfterIndexingComplete();
}
});
}
checkDatasourceIndexingAlert() {
if (!this.dataSource.indexing) {
this.datasourceAlertMessageMustBeShown = true;
} else {
if (this.dataSource.indexing.toString() === 'NOT_INDEXED') {
this.datasourceAlertMessageMustBeShown = true;
} else {
this.datasourceAlertMessageMustBeShown = false;
}
}
if (!this.minimizedView && this.datasourceAlertMessageMustBeShown) {
const notification = this.notificationService.push('warning', 'DataSource Index', this.datasourceAlertMessage);
// adding button reaction if button is enabled
$('.indexDatasourceButton').fadeIn(() => {
(<any>$('.indexDatasourceButton')).click(() => {
notification.close();
this.callDatasourceIndexing();
});
});
}
}
/**
* Search functions
*/
// FULL TEXT SEARCH (ELASTIC SEARCH ON DATASOURCE)
renderFullTextSearch() {
if (!this.renderFullTextSearchView) {
this.renderFullTextSearchView = true;
}
}
updateFullTextSearchRendering() {
if (!this.lastEmittedSearchTerm) {
this.renderFullTextSearchView = false;
} else if (this.lastEmittedSearchTerm.length === 0) {
this.renderFullTextSearchView = false;
}
}
resetFullTextSearch(buttonFocus?: boolean) {
// cleaning the searchTerm subject
this.searchTerm.next('');
// cleaning the input value
(<any>$('#fullTextSearchInput')).val('');
this.updateFullTextSearchRendering();
if (buttonFocus) {
(<any>$('#fullTextSearchClear')).blur(); // taking fous out of search input text
(<any>$('#indexButton')).focus(); // focusing on the 'index datasource' button
}
}
/**
* Abstract method implemented by each specific widget performing all the operations that must be performed after the indexing process completion.
*/
abstract performOperationsAfterIndexingComplete(): void;
cleanDatasourceMetadataForSecondaryWidget(dataSourceMetadata: Object, elements: Object[]): Object {
const cleanedDatasourceMetadata: Object = {
nodesClasses: {},
edgesClasses: {}
};
if (elements && elements.length > 0) {
if (!dataSourceMetadata['nodesClasses'] && !dataSourceMetadata['edgesClasses']) {
console.log('WARNING: No nodesClasses or edgesClasses are present in the metadata.');
return cleanedDatasourceMetadata;
}
if (dataSourceMetadata['nodesClasses']) {
for (const currNodeClassName of Object.keys(dataSourceMetadata['nodesClasses'])) {
// filtering elements of the current class names and filtering out all the hidden elements
const currClassElements = elements.filter((currElement) => {
if (currElement['classes'].indexOf(currNodeClassName) >= 0 && !currElement['data']['hidden']) {
return true;
}
return false;
});
const currClassCardinality = currClassElements.length;
if (currClassCardinality > 0) {
const currNodeClassMetadata = dataSourceMetadata['nodesClasses'][currNodeClassName];
const currNodeClassMetadataCopy = Object.assign({}, currNodeClassMetadata);
currNodeClassMetadataCopy['cardinality'] = currClassCardinality;
cleanedDatasourceMetadata['nodesClasses'][currNodeClassName] = currNodeClassMetadataCopy;
}
}
}
if (dataSourceMetadata['edgesClasses']) {
for (const currEdgeClassName of Object.keys(dataSourceMetadata['edgesClasses'])) {
// filtering elements of the current class names and filtering out all the hidden elements
const currClassElements = elements.filter((currElement) => {
if (currElement['classes'].indexOf(currEdgeClassName) >= 0 && !currElement['data']['hidden']) {
return true;
}
return false;
});
const currClassCardinality = currClassElements.length;
if (currClassCardinality > 0) {
const currEdgeClassMetadata = dataSourceMetadata['edgesClasses'][currEdgeClassName];
const currEdgeClassMetadataCopy = Object.assign({}, currEdgeClassMetadata);
currEdgeClassMetadataCopy['cardinality'] = currClassCardinality;
cleanedDatasourceMetadata['edgesClasses'][currEdgeClassName] = currEdgeClassMetadataCopy;
}
}
}
}
return cleanedDatasourceMetadata;
}
}
export const enum FetchingMode {
LOAD_FROM_CLASS,
TRAVERSE,
LOAD_FROM_IDS,
QUERY
} | the_stack |
import assert from "assert";
import { Command } from "commander";
import fs from "fs";
import path from "path";
import plist from "simple-plist";
import { Access, Characteristic, Formats, Units } from "../Characteristic";
import { toLongForm } from "../util/uuid";
import {
CharacteristicClassAdditions,
CharacteristicDeprecatedNames,
CharacteristicHidden,
CharacteristicManualAdditions,
CharacteristicNameOverrides,
CharacteristicOverriding,
CharacteristicSinceInformation,
CharacteristicValidValuesOverride,
ServiceCharacteristicConfigurationOverrides,
ServiceDeprecatedNames,
ServiceManualAdditions,
ServiceNameOverrides,
ServiceSinceInformation
} from "./generator-configuration";
// noinspection JSUnusedLocalSymbols
const temp = Characteristic; // this to have "../Characteristic" not being only type import, otherwise this would not result in a require statement
const command = new Command("generate-definitions")
.version("1.0.0")
.option("-f, --force")
.option("-m, --metadata <path>", "Define a custom location for the plain-metadata.config file",
"/System/Library/PrivateFrameworks/HomeKitDaemon.framework/Resources/plain-metadata.config")
.requiredOption("-s, --simulator <path>", "Define the path to the accessory simulator.");
command.parse(process.argv);
const options = command.opts();
const metadataFile: string = options.metadata;
const simulator: string = options.simulator;
if (!fs.existsSync(metadataFile)) {
console.warn(`The metadata file at '${metadataFile}' does not exist!`);
process.exit(1);
}
if (!fs.existsSync(simulator)) {
console.warn(`The simulator app directory '${simulator}' does not exist!`);
process.exit(1);
}
const defaultPlist: string = path.resolve(simulator, "Contents/Frameworks/HAPAccessoryKit.framework/Resources/default.metadata.plist");
const defaultMfiPlist: string = path.resolve(simulator, "Contents/Frameworks/HAPAccessoryKit.framework/Resources/default_mfi.metadata.plist");
interface CharacteristicDefinition {
DefaultDescription: string,
Format: string,
LocalizationKey: string,
Properties: number,
ShortUUID: string,
MaxValue?: number,
MinValue?: number,
MaxLength?: number,
// MinLength is another property present on the SerialNumber characteristic. Though we already have a special check for that
StepValue?: number,
Units?: string,
}
interface SimulatorCharacteristicDefinition {
UUID: string;
Name: string;
Format: string;
Constraints?: Constraints;
Permissions: string[]; // stuff like "securedRead", "securedWrite", "writeResponse" or "timedWrite"
Properties: string[]; // stuff like "read", "write", "cnotify", "uncnotify"
}
interface Constraints {
StepValue?: number;
MaximumValue?: number;
MinimumValue?: number;
ValidValues?: Record<string, string>;
ValidBits?: Record<number, string>;
}
interface ServiceDefinition {
Characteristics: {
Optional: string[],
Required: string[]
},
DefaultDescription: string,
LocalizationKey: string,
ShortUUID: string,
}
interface PropertyDefinition {
DefaultDescription: string;
LocalizationKey: string;
Position: number;
}
interface UnitDefinition {
DefaultDescription: string,
LocalizationKey: string;
}
interface CategoryDefinition {
DefaultDescription: string;
Identifier: number;
UUID: string;
}
export interface GeneratedCharacteristic {
id: string;
UUID: string,
name: string,
className: string,
deprecatedClassName?: string;
since?: string,
deprecatedNotice?: string;
format: string,
units?: string,
properties: number,
maxValue?: number,
minValue?: number,
stepValue?: number,
maxLength?: number,
validValues?: Record<string, string>; // <value, key>
validBitMasks?: Record<string, string>;
adminOnlyAccess?: Access[],
classAdditions?: string[],
}
export interface GeneratedService {
id: string,
UUID: string,
name: string,
className: string,
deprecatedClassName?: string,
since?: string,
deprecatedNotice?: string,
requiredCharacteristics: string[];
optionalCharacteristics?: string[];
}
const plistData = plist.readFileSync(metadataFile);
const simulatorPlistData = plist.readFileSync(defaultPlist);
const simulatorMfiPlistData = fs.existsSync(defaultMfiPlist)? plist.readFileSync(defaultMfiPlist): undefined;
if (plistData.SchemaVersion !== 1) {
console.warn(`Detected unsupported schema version ${plistData.SchemaVersion}!`);
}
if (plistData.PlistDictionary.SchemaVersion !== 1) {
console.warn(`Detect unsupported PlistDictionary schema version ${plistData.PlistDictionary.SchemaVersion}!`);
}
console.log(`Parsing version ${plistData.Version}...`);
const shouldParseCharacteristics = checkWrittenVersion("./CharacteristicDefinitions.ts", plistData.Version);
const shouldParseServices = checkWrittenVersion("./ServiceDefinitions.ts", plistData.Version);
if (!options.force && (!shouldParseCharacteristics || !shouldParseServices)) {
console.log("Parsed schema version " + plistData.Version + " is older than what's already generated. " +
"User --force option to generate and overwrite nonetheless!");
process.exit(1);
}
const undefinedUnits: string[] = ["micrograms/m^3", "ppm"];
let characteristics: Record<string, CharacteristicDefinition>;
const simulatorCharacteristics: Map<string, SimulatorCharacteristicDefinition> = new Map();
let services: Record<string, ServiceDefinition>;
let units: Record<string, UnitDefinition>;
let categories: Record<string, CategoryDefinition>;
const properties: Map<number, string> = new Map();
try {
characteristics = checkDefined(plistData.PlistDictionary.HAP.Characteristics);
services = checkDefined(plistData.PlistDictionary.HAP.Services);
units = checkDefined(plistData.PlistDictionary.HAP.Units);
categories = checkDefined(plistData.PlistDictionary.HomeKit.Categories);
const props: Record<string, PropertyDefinition> = checkDefined(plistData.PlistDictionary.HAP.Properties);
// noinspection JSUnusedLocalSymbols
for (const [id, definition] of Object.entries(props).sort(([a, aDef], [b, bDef]) => aDef.Position - bDef.Position)) {
const perm = characteristicPerm(id);
if (perm) {
const num = 1 << definition.Position;
properties.set(num, perm);
}
}
for (const characteristic of (simulatorPlistData.Characteristics as SimulatorCharacteristicDefinition[])) {
simulatorCharacteristics.set(characteristic.UUID, characteristic);
}
if (simulatorMfiPlistData) {
for (const characteristic of (simulatorMfiPlistData.Characteristics as SimulatorCharacteristicDefinition[])) {
simulatorCharacteristics.set(characteristic.UUID, characteristic);
}
}
} catch (error) {
console.log("Unexpected structure of the plist file!");
throw error;
}
// first step is to check if we are up to date on categories
for (const definition of Object.values(categories)) {
if (definition.Identifier > 36) {
console.log(`Detected a new category '${definition.DefaultDescription}' with id ${definition.Identifier}`);
}
}
const characteristicOutput = fs.createWriteStream(path.join(__dirname, "CharacteristicDefinitions.ts"));
characteristicOutput.write("// THIS FILE IS AUTO-GENERATED - DO NOT MODIFY\n");
characteristicOutput.write(`// V=${plistData.Version}\n`);
characteristicOutput.write("\n");
characteristicOutput.write("import { Access, Characteristic, Formats, Perms, Units } from \"../Characteristic\";\n\n");
/**
* Characteristics
*/
const generatedCharacteristics: Record<string, GeneratedCharacteristic> = {}; // indexed by id
const writtenCharacteristicEntries: Record<string, GeneratedCharacteristic> = {}; // indexed by class name
for (const [id, definition] of Object.entries(characteristics)) {
try {
if (CharacteristicHidden.has(id)) {
continue;
}
// "Carbon dioxide Detected" -> "Carbon Dioxide Detected"
const name = (CharacteristicNameOverrides.get(id) ?? definition.DefaultDescription).split(" ").map(entry => entry[0].toUpperCase() + entry.slice(1)).join(" ");
const deprecatedName = CharacteristicDeprecatedNames.get(id);
// "Target Door State" -> "TargetDoorState", "PM2.5" -> "PM2_5"
const className = name.replace(/[\s-]/g, "").replace(/[.]/g, "_");
const deprecatedClassName = deprecatedName?.replace(/[\s-]/g, "").replace(/[.]/g, "_");
const longUUID = toLongForm(definition.ShortUUID);
const simulatorCharacteristic = simulatorCharacteristics.get(longUUID);
const validValues = simulatorCharacteristic?.Constraints?.ValidValues || {};
const validValuesOverride = CharacteristicValidValuesOverride.get(id);
if (validValuesOverride) {
for (const [key, value] of Object.entries(validValuesOverride)) {
validValues[key] = value;
}
}
for (const [value, name] of Object.entries(validValues)) {
let constName = name.toUpperCase().replace(/[^\w]+/g, "_");
if (/^[1-9]/.test(constName)) {
constName = "_" + constName; // variables can't start with a number
}
validValues[value] = constName;
}
const validBits = simulatorCharacteristic?.Constraints?.ValidBits;
let validBitMasks: Record<string, string> | undefined = undefined;
if (validBits) {
validBitMasks = {};
for (const [value, name] of Object.entries(validBits)) {
let constName = name.toUpperCase().replace(/[^\w]+/g, "_");
if (/^[1-9]/.test(constName)) {
constName = "_" + constName; // variables can't start with a number
}
validBitMasks["" + (1 << parseInt(value, 10))] = constName + "_BIT_MASK";
}
}
const generatedCharacteristic: GeneratedCharacteristic = {
id: id,
UUID: longUUID,
name: name,
className: className,
deprecatedClassName: deprecatedClassName,
since: CharacteristicSinceInformation.get(id),
format: definition.Format,
units: definition.Units,
properties: definition.Properties,
minValue: definition.MinValue,
maxValue: definition.MaxValue,
stepValue: definition.StepValue,
maxLength: definition.MaxLength,
validValues: validValues,
validBitMasks: validBitMasks,
classAdditions: CharacteristicClassAdditions.get(id),
};
// call any handler which wants to manually override properties of the generated characteristic
CharacteristicOverriding.get(id)?.(generatedCharacteristic)
generatedCharacteristics[id] = generatedCharacteristic;
writtenCharacteristicEntries[className] = generatedCharacteristic;
if (deprecatedClassName) {
writtenCharacteristicEntries[deprecatedClassName] = generatedCharacteristic;
}
} catch (error) {
throw new Error("Error thrown generating characteristic '" + id + "' (" + definition.DefaultDescription + "): " + error.message);
}
}
for (const [id, generated] of CharacteristicManualAdditions) {
generatedCharacteristics[id] = generated;
writtenCharacteristicEntries[generated.className] = generated;
if (generated.deprecatedClassName) {
writtenCharacteristicEntries[generated.deprecatedClassName] = generated;
}
}
for (const generated of Object.values(generatedCharacteristics)
.sort((a, b) => a.className.localeCompare(b.className))) {
try {
characteristicOutput.write("/**\n");
characteristicOutput.write(" * Characteristic \"" + generated.name + "\"\n");
if (generated.since) {
characteristicOutput.write(" * @since iOS " + generated.since + "\n");
}
if (generated.deprecatedNotice) {
characteristicOutput.write(" * @deprecated " + generated.deprecatedNotice + "\n");
}
characteristicOutput.write(" */\n");
characteristicOutput.write("export class " + generated.className + " extends Characteristic {\n\n");
characteristicOutput.write(" public static readonly UUID: string = \"" + generated.UUID + "\";\n\n");
const classAdditions = generated.classAdditions;
if (classAdditions) {
characteristicOutput.write(classAdditions.map(line => " " + line + "\n").join("") + "\n");
}
let validValuesEntries = Object.entries(generated.validValues ?? {})
if (validValuesEntries.length) {
for (let [value, name] of validValuesEntries) {
if (!name) {
continue
}
characteristicOutput.write(` public static readonly ${name} = ${value};\n`);
}
characteristicOutput.write("\n");
}
if (generated.validBitMasks) {
for (let [value, name] of Object.entries(generated.validBitMasks)) {
characteristicOutput.write(` public static readonly ${name} = ${value};\n`);
}
characteristicOutput.write("\n");
}
characteristicOutput.write(" constructor() {\n");
characteristicOutput.write(" super(\"" + generated.name + "\", " + generated.className + ".UUID, {\n");
characteristicOutput.write(" format: Formats." + characteristicFormat(generated.format) + ",\n");
characteristicOutput.write(" perms: [" + generatePermsString(generated.id, generated.properties) + "],\n")
if (generated.units && !undefinedUnits.includes(generated.units)) {
characteristicOutput.write(" unit: Units." + characteristicUnit(generated.units) + ",\n");
}
if (generated.minValue != null) {
characteristicOutput.write(" minValue: " + generated.minValue + ",\n");
}
if (generated.maxValue != null) {
characteristicOutput.write(" maxValue: " + generated.maxValue + ",\n");
}
if (generated.stepValue != null) {
characteristicOutput.write(" minStep: " + generated.stepValue + ",\n");
}
if (generated.maxLength != null) {
characteristicOutput.write(" maxLen: " + generated.maxLength + ",\n");
}
if (validValuesEntries.length) {
characteristicOutput.write(" validValues: [" + Object.keys(generated.validValues!).join(", ") + "],\n")
}
if (generated.adminOnlyAccess) {
characteristicOutput.write(" adminOnlyAccess: ["
+ generated.adminOnlyAccess.map(value => "Access." + characteristicAccess(value)).join(", ") + "],\n")
}
characteristicOutput.write(" });\n");
characteristicOutput.write(" this.value = this.getDefaultValue();\n");
characteristicOutput.write(" }\n");
characteristicOutput.write("}\n");
if (generated.deprecatedClassName) {
characteristicOutput.write("// noinspection JSDeprecatedSymbols\n");
characteristicOutput.write("Characteristic." + generated.deprecatedClassName + " = " + generated.className + ";\n");
}
if (generated.deprecatedNotice) {
characteristicOutput.write("// noinspection JSDeprecatedSymbols\n");
}
characteristicOutput.write("Characteristic." + generated.className + " = " + generated.className + ";\n\n");
} catch (error) {
throw new Error("Error thrown writing characteristic '" + generated.id + "' (" + generated.className + "): " + error.message);
}
}
characteristicOutput.end();
const characteristicProperties = Object.entries(writtenCharacteristicEntries).sort(([a], [b]) => a.localeCompare(b));
rewriteProperties("Characteristic", characteristicProperties);
writeCharacteristicTestFile();
/**
* Services
*/
const serviceOutput = fs.createWriteStream(path.join(__dirname, "ServiceDefinitions.ts"));
serviceOutput.write("// THIS FILE IS AUTO-GENERATED - DO NOT MODIFY\n");
serviceOutput.write(`// V=${plistData.Version}\n`);
serviceOutput.write("\n");
serviceOutput.write("import { Characteristic } from \"../Characteristic\";\n");
serviceOutput.write("import { Service } from \"../Service\";\n\n");
const generatedServices: Record<string, GeneratedService> = {}; // indexed by id
const writtenServiceEntries: Record<string, GeneratedService> = {}; // indexed by class name
for (const [id, definition] of Object.entries(services)) {
try {
// "Carbon dioxide Sensor" -> "Carbon Dioxide Sensor"
const name = (ServiceNameOverrides.get(id) ?? definition.DefaultDescription).split(" ").map(entry => entry[0].toUpperCase() + entry.slice(1)).join(" ");
const deprecatedName = ServiceDeprecatedNames.get(id);
const className = name.replace(/[\s-]/g, "").replace(/[.]/g, "_");
const deprecatedClassName = deprecatedName?.replace(/[\s-]/g, "").replace(/[.]/g, "_");
const longUUID = toLongForm(definition.ShortUUID);
const requiredCharacteristics = definition.Characteristics.Required;
const optionalCharacteristics = definition.Characteristics.Optional;
const configurationOverride = ServiceCharacteristicConfigurationOverrides.get(id);
if (configurationOverride) {
if (configurationOverride.removedRequired) {
for (const entry of configurationOverride.removedRequired) {
const index = requiredCharacteristics.indexOf(entry);
if (index !== -1) {
requiredCharacteristics.splice(index, 1);
}
}
}
if (configurationOverride.removedOptional) {
for (const entry of configurationOverride.removedOptional) {
const index = optionalCharacteristics.indexOf(entry);
if (index !== -1) {
optionalCharacteristics.splice(index, 1);
}
}
}
if (configurationOverride.addedRequired) {
for (const entry of configurationOverride.addedRequired) {
if (!requiredCharacteristics.includes(entry)) {
requiredCharacteristics.push(entry);
}
}
}
if (configurationOverride.addedOptional) {
for (const entry of configurationOverride.addedOptional) {
if (!optionalCharacteristics.includes(entry)) {
optionalCharacteristics.push(entry);
}
}
}
}
const generatedService: GeneratedService = {
id: id,
UUID: longUUID,
name: name,
className: className,
deprecatedClassName: deprecatedClassName,
since: ServiceSinceInformation.get(id),
requiredCharacteristics: requiredCharacteristics,
optionalCharacteristics: optionalCharacteristics,
};
generatedServices[id] = generatedService;
writtenServiceEntries[className] = generatedService;
if (deprecatedClassName) {
writtenServiceEntries[deprecatedClassName] = generatedService;
}
} catch (error) {
throw new Error("Error thrown generating service '" + id + "' (" + definition.DefaultDescription + "): " + error.message);
}
}
for (const [id, generated] of ServiceManualAdditions) {
generatedServices[id] = generated;
writtenServiceEntries[generated.className] = generated;
if (generated.deprecatedClassName) {
writtenServiceEntries[generated.deprecatedClassName] = generated;
}
}
for (const generated of Object.values(generatedServices)
.sort((a, b) => a.className.localeCompare(b.className))) {
try {
serviceOutput.write("/**\n");
serviceOutput.write(" * Service \"" + generated.name + "\"\n");
if (generated.since) {
serviceOutput.write(" * @since iOS " + generated.since + "\n");
}
if (generated.deprecatedNotice) {
serviceOutput.write(" * @deprecated " + generated.deprecatedNotice + "\n");
}
serviceOutput.write(" */\n");
serviceOutput.write("export class " + generated.className + " extends Service {\n\n");
serviceOutput.write(" public static readonly UUID: string = \"" + generated.UUID + "\";\n\n");
serviceOutput.write(" constructor(displayName?: string, subtype?: string) {\n");
serviceOutput.write(" super(displayName, " + generated.className + ".UUID, subtype);\n\n");
serviceOutput.write(" // Required Characteristics\n");
for (const required of generated.requiredCharacteristics) {
const characteristic = generatedCharacteristics[required];
if (!characteristic) {
console.warn("Could not find required characteristic " + required + " for " + generated.className);
continue;
}
if (required === "name") {
serviceOutput.write(" if (!this.testCharacteristic(Characteristic.Name)) { // workaround for Name characteristic collision in constructor\n");
serviceOutput.write(" this.addCharacteristic(Characteristic.Name).updateValue(\"Unnamed Service\");\n");
serviceOutput.write(" }\n");
} else {
serviceOutput.write(" this.addCharacteristic(Characteristic." + characteristic.className + ");\n");
}
}
if (generated.optionalCharacteristics?.length) {
serviceOutput.write("\n // Optional Characteristics\n");
for (const optional of generated.optionalCharacteristics) {
const characteristic = generatedCharacteristics[optional];
if (!characteristic) {
console.warn("Could not find optional characteristic " + optional + " for " + generated.className);
continue;
}
serviceOutput.write(" this.addOptionalCharacteristic(Characteristic." + characteristic.className + ");\n");
}
}
serviceOutput.write(" }\n}\n");
if (generated.deprecatedClassName) {
serviceOutput.write("// noinspection JSDeprecatedSymbols\n");
serviceOutput.write("Service." + generated.deprecatedClassName + " = " + generated.className + ";\n");
}
if (generated.deprecatedNotice) {
serviceOutput.write("// noinspection JSDeprecatedSymbols\n");
}
serviceOutput.write("Service." + generated.className + " = " + generated.className + ";\n\n");
} catch (error) {
throw new Error("Error thrown writing service '" + generated.id + "' (" + generated.className + "): " + error.message);
}
}
serviceOutput.end();
const serviceProperties = Object.entries(writtenServiceEntries).sort(([a], [b]) => a.localeCompare(b));
rewriteProperties("Service", serviceProperties);
writeServicesTestFile();
// ------------------------ utils ------------------------
function checkDefined<T>(input: T): T {
if (!input) {
throw new Error("value is undefined!");
}
return input;
}
function characteristicFormat(format: string): string {
// @ts-expect-error
for (const [key, value] of Object.entries(Formats)) {
if (value === format) {
return key;
}
}
throw new Error("Unknown characteristic format '" + format + "'");
}
function characteristicUnit(unit: string): string {
// @ts-expect-error
for (const [key, value] of Object.entries(Units)) {
if (value === unit) {
return key;
}
}
throw new Error("Unknown characteristic format '" + unit + "'");
}
function characteristicAccess(access: number): string {
// @ts-expect-error
for (const [key, value] of Object.entries(Access)) {
if (value === access) {
return key;
}
}
throw new Error("Unknown access for '" + access + "'");
}
function characteristicPerm(id: string): string | undefined {
switch (id) {
case "aa":
return "ADDITIONAL_AUTHORIZATION";
case "hidden":
return "HIDDEN";
case "notify":
return "NOTIFY";
case "read":
return "PAIRED_READ";
case "timedWrite":
return "TIMED_WRITE";
case "write":
return "PAIRED_WRITE";
case "writeResponse":
return "WRITE_RESPONSE";
case "broadcast": // used for bluetooth
return undefined;
default:
throw new Error("Received unknown perms id: " + id);
}
}
function generatePermsString(id: string, propertiesBitMap: number): string {
const perms: string [] = [];
for (const [bitMap, name] of properties) {
if (name === "ADDITIONAL_AUTHORIZATION") {
// aa set by homed just signals that aa may be supported. Setting up aa will always require a custom made app though
continue;
}
if ((propertiesBitMap | bitMap) === propertiesBitMap) { // if it stays the same the bit is set
perms.push("Perms." + name);
}
}
const result = perms.join(", ");
assert(result != "", "perms string cannot be empty (" + propertiesBitMap + ")");
return result;
}
function checkWrittenVersion(filePath: string, parsingVersion: number): boolean {
filePath = path.resolve(__dirname, filePath);
const content = fs.readFileSync(filePath, { encoding: "utf8" }).split("\n", 3);
const v = content[1];
if (!v.startsWith("// V=")) {
throw new Error("Could not detect definition version for '" + filePath + "'");
}
const version = parseInt(v.replace("// V=", ""), 10);
return parsingVersion >= version;
}
function rewriteProperties(className: string, properties: [key: string, value: GeneratedCharacteristic | GeneratedService][]): void {
const filePath = path.resolve(__dirname, "../" + className + ".ts");
if (!fs.existsSync(filePath)) {
throw new Error("File '" + filePath + "' does not exist!");
}
const file = fs.readFileSync(filePath, { encoding: "utf8"});
const lines = file.split("\n");
let i = 0;
let importStart = -1;
let importEnd = -1;
let foundImport = false;
for (; i < lines.length; i++) {
const line = lines[i];
if (line === "import {") {
importStart = i; // save last import start;
} else if (line === "} from \"./definitions\";") {
importEnd = i;
foundImport = true;
break;
}
}
if (!foundImport) {
throw new Error("Could not find import section!");
}
let startIndex = -1;
let stopIndex = -1;
for (; i < lines.length; i++) {
if (lines[i] === " // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-") {
startIndex = i;
break;
}
}
if (startIndex === -1) {
throw new Error("Could not find start pattern in file!");
}
for (; i < lines.length; i++) {
if (lines[i] === " // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=") {
stopIndex = i;
break;
}
}
if (stopIndex === -1) {
throw new Error("Could not find stop pattern in file!");
}
const importSize = importEnd - importStart - 1;
const newImports = properties
.filter(([key, value]) => key === value.className)
.map(([key]) => " " + key + ",");
lines.splice(importStart + 1, importSize, ...newImports); // remove current imports
const importDelta = newImports.length - importSize;
startIndex += importDelta;
stopIndex += importDelta;
const amount = stopIndex - startIndex - 1;
const newContentLines = properties.map(([key, value]) => {
let line = "";
let deprecatedNotice = value.deprecatedNotice;
if (key !== value.className) {
deprecatedNotice = "Please use {@link " + className + "." + value.className + "}." // prepend deprecated notice
+ (deprecatedNotice? " " + deprecatedNotice: "");
}
if (deprecatedNotice) {
line += " /**\n";
line += " * @deprecated " + deprecatedNotice + "\n";
line += " */\n";
}
line += " public static " + key + ": typeof " + value.className + ";";
return line;
});
lines.splice(startIndex + 1, amount, ...newContentLines); // insert new lines
const resultContent = lines.join("\n");
fs.writeFileSync(filePath, resultContent, { encoding: "utf8" });
}
function writeCharacteristicTestFile(): void {
const characteristics = Object.values(generatedCharacteristics).sort((a, b) => a.className.localeCompare(b.className));
const testOutput = fs.createWriteStream(path.resolve(__dirname, "./CharacteristicDefinitions.spec.ts"), { encoding: "utf8" });
testOutput.write("// THIS FILE IS AUTO-GENERATED - DO NOT MODIFY\n");
testOutput.write("import \"./\";\n\n");
testOutput.write("import { Characteristic } from \"../Characteristic\";\n\n");
testOutput.write("describe(\"CharacteristicDefinitions\", () => {");
for (const generated of characteristics) {
testOutput.write("\n");
testOutput.write(" describe(\"" + generated.className + "\", () => {\n");
// first test is just calling the constructor
testOutput.write(" it(\"should be able to construct\", () => {\n");
testOutput.write(" new Characteristic." + generated.className + "();\n");
if (generated.deprecatedClassName) {
testOutput.write(" // noinspection JSDeprecatedSymbols\n");
testOutput.write(" new Characteristic." + generated.deprecatedClassName + "();\n");
}
testOutput.write(" });\n");
testOutput.write(" });\n");
}
testOutput.write("});\n");
testOutput.end();
}
function writeServicesTestFile(): void {
const services = Object.values(generatedServices).sort((a, b) => a.className.localeCompare(b.className));
const testOutput = fs.createWriteStream(path.resolve(__dirname, "./ServiceDefinitions.spec.ts"), { encoding: "utf8" });
testOutput.write("// THIS FILE IS AUTO-GENERATED - DO NOT MODIFY\n");
testOutput.write("import \"./\";\n\n");
testOutput.write("import { Characteristic } from \"../Characteristic\";\n");
testOutput.write("import { Service } from \"../Service\";\n\n");
testOutput.write("describe(\"ServiceDefinitions\", () => {");
for (const generated of services) {
testOutput.write("\n");
testOutput.write(" describe(\"" + generated.className + "\", () => {\n");
// first test is just calling the constructor
testOutput.write(" it(\"should be able to construct\", () => {\n");
testOutput.write(" const service0 = new Service." + generated.className + "();\n");
testOutput.write(" const service1 = new Service." + generated.className + "(\"test name\");\n");
testOutput.write(" const service2 = new Service." + generated.className + "(\"test name\", \"test sub type\");\n\n");
testOutput.write(" expect(service0.displayName).toBe(\"\");\n");
testOutput.write(" expect(service0.testCharacteristic(Characteristic.Name)).toBe(" + generated.requiredCharacteristics.includes("name") + ");\n");
testOutput.write(" expect(service0.subtype).toBeUndefined();\n\n");
testOutput.write(" expect(service1.displayName).toBe(\"test name\");\n");
testOutput.write(" expect(service1.testCharacteristic(Characteristic.Name)).toBe(true);\n");
testOutput.write(" expect(service1.getCharacteristic(Characteristic.Name).value).toBe(\"test name\");\n");
testOutput.write(" expect(service1.subtype).toBeUndefined();\n\n");
testOutput.write(" expect(service2.displayName).toBe(\"test name\");\n");
testOutput.write(" expect(service2.testCharacteristic(Characteristic.Name)).toBe(true);\n");
testOutput.write(" expect(service2.getCharacteristic(Characteristic.Name).value).toBe(\"test name\");\n");
testOutput.write(" expect(service2.subtype).toBe(\"test sub type\");\n");
if (generated.deprecatedClassName) {
testOutput.write(" // noinspection JSDeprecatedSymbols\n");
testOutput.write("\n new Service." + generated.deprecatedClassName + "();\n");
}
testOutput.write(" });\n");
testOutput.write(" });\n");
}
testOutput.write("});\n");
testOutput.end();
} | the_stack |
import {
ExceptionLogItem,
ExternalLinkLogItem,
InspectableObjectLogItem,
LogEntry as ILogEntry,
LogItem,
LogItemType,
LogLevel,
LuisEditorDeepLinkLogItem,
NetworkRequestLogItem,
NetworkResponseLogItem,
NgrokExpirationLogItem,
OpenAppSettingsLogItem,
TextLogItem,
} from '@bfemulator/sdk-shared';
import * as React from 'react';
import { ExtensionManager, InspectorAPI } from '../../../../../extensions';
import * as styles from './log.scss';
export interface LogEntryProps {
document: any;
entry: ILogEntry;
currentlyInspectedActivity?: any;
launchLuisEditor?: () => void;
setInspectorObjects?: (documentId: string, objs: any) => void;
setHighlightedObjects?: (documentId: string, objs: any) => void;
reconnectNgrok?: () => void;
showAppSettings?: () => void;
trackEvent?: (name: string, properties?: { [key: string]: any }) => void;
}
export class LogEntry extends React.Component<LogEntryProps> {
/** Allows <LogEntry />'s to highlight themselves based on their log item children */
private inspectableObjects: { [id: string]: boolean };
/** Sends obj to the inspector panel
* @param obj Can be a conversation activity or network request
*/
inspect(obj: Record<string, unknown> = {}) {
this.props.setInspectorObjects(this.props.document.documentId, { ...obj, showInInspector: true });
}
highlight(obj: Record<string, unknown> = {}) {
this.props.setHighlightedObjects(this.props.document.documentId, obj);
}
/** Sends obj to the inspector panel and highlights the activity in Webchat
* (triggered by click in log)
* @param obj Conversation activity to be highlighted in the WebChat control
*/
inspectAndHighlightInWebchat(obj: any) {
this.inspect(obj);
this.props.trackEvent('log_inspectActivity', { type: obj.type || '' });
}
render() {
// reset the inspectable objects lookup
this.inspectableObjects = {};
// render the timestamp and any items to be displayed within the entry;
// any rendered inspectable items will add themselves to this.inspectableObjects
const innerJsx = (
<>
{this.renderTimestamp(this.props.entry.timestamp)}
{this.props.entry.items.map((item, key) => this.renderItem(item, '' + key))}
</>
);
// if the currently inspected activity matches any of this item's inner inspectable
// objects, append an 'inspected' class name to the log entry to highlight it
const currentlyInspectedActivity = this.props.currentlyInspectedActivity || {};
let inspectedActivityClass = '';
const targetId = currentlyInspectedActivity.id;
if (this.inspectableObjects[targetId]) {
inspectedActivityClass = styles.inspected;
}
return (
<div key="entry" className={[styles.entry, inspectedActivityClass].join(' ')}>
{innerJsx}
</div>
);
}
renderTimestamp(t: number) {
return (
<span key="timestamp" className={'timestamp ' + styles.spaced}>
[<span className={styles.timestamp}>{timestamp(t)}</span>]
</span>
);
}
renderItem(item: LogItem, key: string) {
switch (item.type) {
case LogItemType.Text: {
const { level, text } = item.payload as TextLogItem;
return this.renderTextItem(level, text, key);
}
case LogItemType.ExternalLink: {
const { text, hyperlink } = item.payload as ExternalLinkLogItem;
return this.renderExternalLinkItem(text, hyperlink, key);
}
case LogItemType.OpenAppSettings: {
const { text } = item.payload as OpenAppSettingsLogItem;
return this.renderAppSettingsItem(text, key);
}
case LogItemType.Exception: {
const { err } = item.payload as ExceptionLogItem;
return this.renderExceptionItem(err, key);
}
case LogItemType.InspectableObject: {
const { obj } = item.payload as InspectableObjectLogItem;
return this.renderInspectableItem(obj, key);
}
case LogItemType.NetworkRequest: {
const { facility, body, headers, method, url } = item.payload as NetworkRequestLogItem;
return this.renderNetworkRequestItem(facility, body, headers, method, url, key);
}
case LogItemType.LuisEditorDeepLink: {
const { text } = item.payload as LuisEditorDeepLinkLogItem;
return this.renderLuisEditorDeepLinkItem(text, key);
}
case LogItemType.NetworkResponse: {
const { body, headers, statusCode, statusMessage, srcUrl } = item.payload as NetworkResponseLogItem;
return this.renderNetworkResponseItem(body, headers, statusCode, statusMessage, srcUrl, key);
}
case LogItemType.NgrokExpiration: {
const { text } = item.payload as NgrokExpirationLogItem;
return this.renderNgrokExpirationItem(text, key);
}
default:
return false;
}
}
renderTextItem(level: LogLevel, text: string, key: string) {
return (
<span key={key} className={`text-item ${styles.spaced} ${logLevelToClassName(level)}`}>
{text}
</span>
);
}
renderExternalLinkItem(text: string, hyperlink: string, key: string) {
return (
<span key={key} className={styles.spaced}>
<button className={styles.link} onClick={() => window.open(hyperlink, '_blank')}>
{text}
</button>
</span>
);
}
renderAppSettingsItem(text: string, key: string) {
return (
<span key={key} className={styles.spaced}>
<button className={styles.link} onClick={() => this.props.showAppSettings()}>
{text}
</button>
</span>
);
}
renderExceptionItem(err: Error, key: string) {
return (
<span key={key} className={`${styles.spaced} ${styles.level3}`}>
{err && err.message ? err.message : ''}
</span>
);
}
renderInspectableItem(obj: any, key: string) {
// add self to inspectable object lookup
if (obj.id) {
this.inspectableObjects[obj.id] = true;
}
let title = 'inspect';
if (typeof obj.type === 'string') {
title = obj.type;
}
const summaryText = this.summaryText(obj) || '';
return (
<span key={key} onMouseOver={() => this.highlight(obj)} onMouseLeave={() => this.highlight({})}>
<span className={`inspectable-item ${styles.spaced} ${styles.level0}`}>
<button className={styles.link} onClick={() => this.inspectAndHighlightInWebchat(obj)}>
{title}
</button>
</span>
<span className={`${styles.spaced} ${styles.level0}`}>{summaryText}</span>
</span>
);
}
renderNetworkRequestItem(_facility: any, body: any, _headers: any, method: any, _url: string, key: string) {
let obj;
if (typeof body === 'string') {
try {
obj = JSON.parse(body);
} catch (e) {
obj = body;
}
} else {
obj = body;
}
if (obj) {
return (
<span key={key} className={`network-req-item ${styles.spaced} ${styles.level0}`}>
<button className={styles.link} onClick={() => this.inspect(obj)}>
{method}
</button>
</span>
);
} else {
return (
<span key={key} className={`network-req-item ${styles.spaced} ${styles.level0}`}>
{method}
</span>
);
}
}
renderNetworkResponseItem(
body: any,
_headers: any,
statusCode: number,
_statusMessage: string,
_srcUrl: string,
key: string
) {
let obj;
if (typeof body === 'string') {
try {
obj = JSON.parse(body);
// html responses come over as doubly stringified e.g.: ""<some html>"" and
// calling JSON.parse will turn them into a standard string;
// we want to assign the html to a property so that the string isn't expanded
// out into a giant object with one key per character
if (typeof obj === 'string') {
obj = { value: obj };
}
} catch (e) {
obj = body;
}
} else {
obj = body;
}
if (obj) {
return (
<span key={key} className={`network-res-item ${styles.spaced} ${styles.level0}`}>
<button className={styles.link} onClick={() => this.inspect(obj)}>
{statusCode}
</button>
</span>
);
} else {
return (
<span key={key} className={`network-res-item ${styles.spaced} ${styles.level0}`}>
{statusCode}
</span>
);
}
}
renderNgrokExpirationItem(text: string, key: string): JSX.Element {
return (
<span key={key} className={`${styles.spaced} ${styles.level3}`}>
{text + ' '}
<button className={styles.link} onClick={() => this.props.reconnectNgrok()}>
Please reconnect.
</button>
</span>
);
}
renderLuisEditorDeepLinkItem(text: string, key: string): JSX.Element {
return (
<span key={key} className={`text-item ${styles.spaced} ${styles.level3}`}>
{`${text} Please `}
<a className={styles.link} onClick={() => this.props.launchLuisEditor()}>
connect your bot to LUIS
</a>
{` using the services pane.`}
</span>
);
}
summaryText(obj: any): string {
const inspResult = ExtensionManager.inspectorForObject(obj, true);
if (inspResult && inspResult.inspector) {
return InspectorAPI.summaryText(inspResult.inspector, obj);
} else {
return undefined;
}
}
}
export function number2(n: number) {
return ('0' + n).slice(-2);
}
export function timestamp(t: number) {
const timestamp1 = new Date(t);
const hours = number2(timestamp1.getHours());
const minutes = number2(timestamp1.getMinutes());
const seconds = number2(timestamp1.getSeconds());
return `${hours}:${minutes}:${seconds}`;
}
function logLevelToClassName(level: LogLevel): string {
switch (level) {
case LogLevel.Debug:
return styles.level1;
case LogLevel.Info:
return styles.level0;
case LogLevel.Warn:
return styles.level2;
case LogLevel.Error:
return styles.level3;
default:
return '';
}
} | the_stack |
import * as express from 'express';
import { wrap, requireAuth, requireCustomToken } from '../middleware';
import { Runner } from '../../lib/Runner';
import { Logger } from '../../lib/Logger';
import { BitbucketClient } from '../../bitbucket/BitbucketClient';
import { AccountService } from '../../lib/AccountService';
import { permissionService } from '../../lib/PermissionService';
import { Config, LandRequestOptions } from '../../types';
import { eventEmitter } from '../../lib/Events';
import { LandRequest } from '../../db';
const landKidTag = process.env.LANDKID_TAG || 'Unknown';
export function apiRoutes(runner: Runner, client: BitbucketClient, config: Config) {
const router = express();
const easterEggText = config.easterEgg || 'There is no cow level';
router.get(
'/meta',
wrap(async (req, res) => {
Logger.verbose('Requesting meta information', { namespace: 'routes:api:meta' });
const install = await runner.getInstallationIfExists();
const isInstalled = !!install;
const { customChecks, ...prSettings } = config.prSettings;
res.header('Access-Control-Allow-Origin', '*').json({
meta: {
'tag-version': landKidTag,
easterEgg: easterEggText,
targetRepo: config.repoConfig.repoName,
prSettings,
maxConcurrentBuilds: runner.getMaxConcurrentBuilds(),
},
isInstalled,
});
}),
);
router.get(
'/current-state',
requireAuth('read'),
wrap(async (req, res) => {
try {
Logger.info('Requesting current state', { namespace: 'routes:api:current-state' });
const state = await runner.getState(req.user!);
eventEmitter.emit('GET_STATE.SUCCESS');
res.header('Access-Control-Allow-Origin', '*').json(state);
} catch {
Logger.error('Error getting current state', { namespace: 'routes:api:current-state' });
eventEmitter.emit('GET_STATE.FAIL');
res.sendStatus(500);
}
}),
);
router.get(
'/history',
requireAuth('land'),
wrap(async (req, res) => {
const page = parseInt((req.query.page as string) || '0', 10);
const history = await runner.getHistory(page);
Logger.info('Requesting history', { namespace: 'routes:api:history', page });
res.header('Access-Control-Allow-Origin', '*').json(history);
}),
);
router.get(
'/user/:aaid',
requireAuth('read'),
wrap(async (req, res) => {
const aaid = req.params.aaid;
Logger.verbose('Requesting user', { namespace: 'routes:api:user', aaid });
res.json(await AccountService.get(client).getAccountInfo(aaid));
}),
);
router.patch(
'/permission/:aaid',
requireAuth('admin'),
wrap(async (req, res) => {
const aaid = req.params.aaid;
const mode = req.body.mode;
Logger.verbose('Setting user permission', { namespace: 'routes:api:permission', aaid, mode });
if (['read', 'land', 'admin'].indexOf(mode) === -1) {
return res.status(400).json({ error: 'Invalid permission mode' });
}
res.json(await permissionService.setPermissionForUser(aaid, mode, req.user!));
}),
);
router.patch(
'/note/:aaid',
requireAuth('admin'),
wrap(async (req, res) => {
const aaid = req.params.aaid;
const note = req.body.note;
Logger.verbose('Setting user note', { namespace: 'routes:api:note', aaid, note });
if (!note) {
return res.status(400).json({ error: 'Note can not be empty' });
}
await permissionService.setNoteForUser(aaid, note, req.user!);
res.json({ message: `Added note to user ${aaid}` });
}),
);
router.delete(
'/note/:aaid',
requireAuth('admin'),
wrap(async (req, res) => {
const aaid = req.params.aaid;
Logger.verbose('Removing user note', { namespace: 'routes:api:note', aaid });
await permissionService.removeUserNote(aaid);
res.json({ message: `Removed note from user ${aaid}` });
}),
);
router.post(
'/pause',
requireAuth('admin'),
wrap(async (req, res) => {
let pausedReason = 'Paused via API';
if (req && req.body && req.body.reason) {
pausedReason = String(req.body.reason);
}
Logger.verbose('Pausing', { namespace: 'routes:api:pause', pausedReason });
runner.pause(pausedReason, req.user!);
res.json({ paused: true, pausedReason });
}),
);
router.post(
'/unpause',
requireAuth('admin'),
wrap(async (req, res) => {
Logger.verbose('Unpausing', { namespace: 'routes:api:unpause' });
await runner.unpause();
res.json({ paused: false });
}),
);
/**
* This is a magic endpoint that allows us to call next() if landkid hangs
*/
router.post(
'/next',
requireAuth('admin'),
wrap(async (req, res) => {
Logger.verbose('Calling next', { namespace: 'routes:api:next' });
await runner.next();
res.json({ message: 'Called next()' });
}),
);
router.post(
'/uninstall',
requireAuth('admin'),
wrap(async (req, res) => {
Logger.verbose('Uninstalling', { namespace: 'routes:api:uninstall' });
await runner.deleteInstallation();
res.json({ message: 'Installation deleted' });
}),
);
router.post(
'/remove/:id',
requireAuth('admin'),
wrap(async (req, res) => {
const requestId = req.params.id;
Logger.verbose('Removing landrequest from queue', {
namespace: 'routes:api:remove',
requestId,
});
const success = await runner.removeLandRequestFromQueue(requestId, req.user!);
if (success) {
res.json({ message: 'Request removed from queue' });
} else {
res.status(400).json({ error: 'Request either does not exist or is not queued' });
}
}),
);
router.post(
'/cancel/:id',
requireAuth('admin'),
wrap(async (req, res) => {
const requestId = req.params.id;
Logger.verbose('Cancelling running landrequest', {
namespace: 'routes:api:cancel',
requestId,
});
const success = await runner.cancelRunningBuild(requestId, req.user!);
if (success) {
res.json({ message: 'Running build cancelled' });
} else {
res.status(400).json({ error: 'Request either does not exist or is not running' });
}
}),
);
router.post(
'/message',
requireAuth('admin'),
wrap(async (req, res) => {
let message = '';
let type = '';
if (req && req.body && req.body.message && req.body.type) {
message = String(req.body.message);
type = String(req.body.type);
}
Logger.verbose('Setting message', { namespace: 'routes:api:message', message, type });
if (!message) {
return res.status(400).json({ error: 'Cannot send an empty message' });
}
if (!['default', 'warning', 'error'].includes(type)) {
return res
.status(400)
.json({ error: 'Message type must be one of: default, warning, error' });
}
// @ts-ignore -- checks value of type above
runner.addBannerMessage(message, type, req.user!);
res.json({ message });
}),
);
router.post(
'/remove-message',
requireAuth('admin'),
wrap(async (req, res) => {
Logger.verbose('Removing message', { namespace: 'routes:api:remove-message' });
await runner.removeBannerMessage();
res.json({ removed: true });
}),
);
router.get(
'/landrequests',
requireAuth('land'),
wrap(async (req, res) => {
const ids = (req.query.ids as string).split(',');
Logger.verbose('Requesting landrequests', { namespace: 'routes:api:landrequests', ids });
res.json({ statuses: await runner.getStatusesForLandRequests(ids) });
}),
);
router.post(
'/create-landrequest',
requireCustomToken,
wrap(async (req, res) => {
if (!req.body || !req.body.prId) {
return res.status(400).json({ err: 'req.body.prId expected' });
}
const prId = parseInt(req.body.prId, 10);
const prInfo = await client.bitbucket.getPullRequest(prId);
if (!prInfo) {
return res.status(400).json({ err: 'Could not find PR with that ID' });
}
const landRequestOptions: LandRequestOptions = {
prId,
// Must always have a valid aaid, so lets set it to Luke's aaid
triggererAaid: req.user ? req.user.aaid : '557057:9512f4e4-3319-4d30-a78d-7d5f8ed243ae',
commit: prInfo.commit,
prTitle: prInfo.title,
prAuthorAaid: prInfo.authorAaid,
prSourceBranch: prInfo.sourceBranch,
prTargetBranch: prInfo.targetBranch,
};
let request: LandRequest | undefined;
if (req.body.entryPoint === 'land-when-able') {
request = await runner.addToWaitingToLand(landRequestOptions);
} else {
request = await runner.enqueue(landRequestOptions);
}
if (req.body.priority === 'low' && request) {
await request.decrementPriority();
} else if (req.body.priority === 'high' && request) {
await request.incrementPriority();
}
Logger.info('Land request created', {
namespace: 'routes:api:create-landrequest',
landRequestOptions,
});
res.sendStatus(200);
}),
);
router.delete(
'/delete-history',
requireAuth('admin'),
wrap(async (req, res) => {
Logger.verbose('Deleting history', { namespace: 'routes:api:delete-history' });
await runner.clearHistory();
res.json({ response: 'You better be sure about this captain... Done!' });
}),
);
router.delete(
'/clear-land-when-able-queue',
requireAuth('admin'),
wrap(async (req, res) => {
Logger.verbose('Deleting land-when-able queue', {
namespace: 'routes:api:clear-land-when-able-queue',
});
await runner.clearLandWhenAbleQueue();
res.json({
response: 'You may not be a threat, but you better stop pretending to be a hero... Done!',
});
}),
);
router.post(
'/priority/:id',
requireAuth('admin'),
wrap(async (req, res) => {
const requestId = req.params.id;
if (!req.body) {
return res.status(400).json({ err: 'body expected' });
}
const priority = parseInt(req.body.priority, 10);
if (isNaN(priority)) {
return res.status(400).json({ err: 'body.priority is required and needs to be a number ' });
}
Logger.verbose('Updating priority of land request', {
namespace: 'routes:api:priority',
requestId,
priority,
});
const success = await runner.updateLandRequestPriority(requestId, priority);
if (success) {
res.json({ message: 'Updated priority of request' });
} else {
res.status(404).json({ error: 'Land request does not exist' });
}
}),
);
return router;
} | the_stack |
import * as vscode from 'vscode'
import * as path from 'path'
import ARMParser from './lib/arm-parser'
import TelemetryReporter from 'vscode-extension-telemetry'
import * as NodeCache from 'node-cache'
// Set up telemetry logging
// eslint-disable-next-line @typescript-eslint/no-var-requires
const packageJson = require('../package.json')
const telemetryExtensionId = packageJson.publisher + '.' + packageJson.name
const telemetryExtensionVersion = packageJson.version
const telemetryKey = '0e2a6ba6-6c52-4e94-86cf-8dc87830e82e'
// Main globals
let panel: vscode.WebviewPanel | undefined
let extensionPath: string
let themeName: string
let editor: vscode.TextEditor
let paramFileContent: string
let filters: string
let reporter: TelemetryReporter
let cache: NodeCache
// Used to buffer/delay updates when typing
let refreshedTime: number = Date.now()
let typingTimeout: NodeJS.Timeout | undefined
//
// Main extension activation
//
export function activate(context: vscode.ExtensionContext): void {
extensionPath = context.extensionPath
context.subscriptions.push(
vscode.commands.registerCommand('armView.start', () => {
// Check for open editors that are showing JSON
// These are safe guards, the `when` clauses in package.json should prevent this
if (!vscode.window.activeTextEditor) {
vscode.window.showErrorMessage('No editor active, open a ARM template JSON file in the editor')
return
} else {
if (!(vscode.window.activeTextEditor.document.languageId === 'json' ||
vscode.window.activeTextEditor.document.languageId === 'arm-template')) {
vscode.window.showErrorMessage('Current file is not JSON')
return
}
}
// Store the active editor at start
editor = vscode.window.activeTextEditor
paramFileContent = ''
themeName = vscode.workspace.getConfiguration('armView').get('iconTheme', 'original')
console.log(`### ArmView: Activating ${extensionPath} with theme ${themeName}`)
const cacheTime = vscode.workspace.getConfiguration('armView').get<number>('linkedUrlCacheTime', 120)
cache = new NodeCache({ stdTTL: cacheTime })
if (panel) {
// If we already have a panel, show it
panel.reveal()
return
}
// Create the panel (held globally)
panel = vscode.window.createWebviewPanel(
'armViewer',
'ARM Viewer',
{
preserveFocus: false,
viewColumn: vscode.ViewColumn.Beside
},
{
enableScripts: true,
localResourceRoots: [vscode.Uri.file(path.join(extensionPath, 'assets'))],
},
)
// Give panel a custom icon
panel.iconPath = {
dark: vscode.Uri.file(`${extensionPath}/assets/img/icons/eye-dark.svg`),
light: vscode.Uri.file(`${extensionPath}/assets/img/icons/eye-light.svg`),
}
reporter = new TelemetryReporter(telemetryExtensionId, telemetryExtensionVersion, telemetryKey)
context.subscriptions.push(reporter)
// Load the webview HTML/JS
panel.webview.html = getWebviewContent()
// Listen for active document changes, i.e. user typing
vscode.workspace.onDidChangeTextDocument(() => {
// console.log("### onDidChangeTextDocument");
// If an update is scheduled, then skip
if (typingTimeout) { return }
// Buffer/delay updates by 2 seconds
if (Date.now() - refreshedTime < 2000) {
typingTimeout = setTimeout(refreshView, 2000)
return
}
try {
refreshView()
} catch (err) {
// Nadda
}
})
// Listen for active editor changes
vscode.window.onDidChangeActiveTextEditor(() => {
// console.log("### onDidChangeActiveTextEditor");
try {
// Switch editor and refresh
if (vscode.window.activeTextEditor) {
if (editor.document.fileName !== vscode.window.activeTextEditor.document.fileName) {
// Wipe param file on switch
paramFileContent = ''
if (panel) { panel.webview.postMessage({ command: 'paramFile', payload: '' }) }
editor = vscode.window.activeTextEditor
refreshView()
}
}
} catch (err) {
// Nadda
}
})
// Handle messages from the webview
panel.webview.onDidReceiveMessage(
message => {
// Initial load of content, done at startup
if (message.command === 'initialized') {
console.log('### ArmView: Initialization of WebView complete, now parsing template...')
refreshView()
}
// Message from webview - user clicked 'Params' button
if (message.command === 'paramsClicked') {
pickParamsFile()
}
// Message from webview - user clicked 'Filters' button
if (message.command === 'filtersClicked') {
pickFilters()
}
// Message from webview - user clicked 'Filters' button
if (message.command === 'exportPNG') {
savePNG(message.payload)
}
},
undefined,
context.subscriptions,
)
// Dispose/cleanup
panel.onDidDispose(
() => {
reporter.dispose()
panel = undefined
if (typingTimeout) {
clearTimeout(typingTimeout)
}
},
null,
context.subscriptions,
)
}),
)
}
async function savePNG(pngBase64: string): Promise<any> {
const saveAs = await vscode.window.showSaveDialog({ saveLabel: 'Save PNG', filters: { Images: ['png'] } })
if (saveAs) {
const buf = Buffer.from(pngBase64, 'base64')
vscode.workspace.fs.writeFile(saveAs, buf)
}
}
//
// Prompt user for parameter file and apply it to the parser
//
async function pickParamsFile(): Promise<any> {
const wsLocalDir = path.dirname(editor.document.fileName)
if (wsLocalDir) {
const paramFile = await vscode.window.showOpenDialog({
canSelectMany: false,
defaultUri: vscode.Uri.file(wsLocalDir),
filters: { JSON: ['json'] },
})
if (paramFile) {
const res = await vscode.workspace.fs.readFile(paramFile[0])
if (res) {
paramFileContent = res.toString()
const paramFileName = vscode.workspace.asRelativePath(paramFile[0])
if (panel) { panel.webview.postMessage({ command: 'paramFile', payload: paramFileName }) }
}
}
}
refreshView()
}
//
// Prompt user for resource filters
//
async function pickFilters(): Promise<any> {
const res = await vscode.window.showInputBox({ prompt: 'Comma separated list of resource types to filter out. Can be partial strings. Empty string will remove all filters', value: filters, placeHolder: 'e.g. vaults/secrets, securityRules' })
// Res will be undefined if the user cancels (hits escape)
if (res !== undefined) { filters = res.toString().toLowerCase() }
if (panel) { panel.webview.postMessage({ command: 'filtersApplied', payload: filters }) }
refreshView()
}
//
// Refresh contents of the view
//
async function refreshView(): Promise<any> {
// Reset timers for typing updates
refreshedTime = Date.now()
if (typingTimeout) {
clearTimeout(typingTimeout)
}
typingTimeout = undefined
if (!panel) {
return
}
if (editor) {
// Skip non-JSON
if (!(editor.document.languageId === 'json' || editor.document.languageId === 'arm-template')) {
return
}
// Parse the source template JSON
const templateJSON = editor.document.getText()
// Create a new ARM parser, giving icon prefix based on theme, and name it "main"
// Additionally passing reporter and editor enables telemetry and linked template discovery in VS Code workspace
const parser = new ARMParser(`${extensionPath}/assets/img/azure/${themeName}`, 'main', reporter, editor, cache)
try {
const start = Date.now()
const result = await parser.parse(templateJSON, paramFileContent)
console.log(`### ArmView: Parsing took ${Date.now() - start} ms`)
reporter.sendTelemetryEvent('parsedOK', {
filename: editor.document.fileName,
nodeCount: result.length.toString(),
})
panel.webview.postMessage({ command: 'newData', payload: result })
panel.webview.postMessage({ command: 'resCount', payload: result.length.toString() })
} catch (err) {
// Disable logging and telemetry for now
// console.log('### ArmView: ERROR STACK: ' + err.stack)
// reporter.sendTelemetryEvent('parseError', {'error': err, 'filename': editor.document.fileName});
panel.webview.postMessage({ command: 'error', payload: err.message })
}
} else {
vscode.window.showErrorMessage('No editor active, open a ARM template JSON file in the editor')
}
}
//
// Initialize the contents of the webview - called at startup
//
function getWebviewContent(): string {
// Send telemetry for activation
const wsname: string = vscode.workspace.name || 'unknown'
reporter.sendTelemetryEvent('activated', { workspace: wsname })
// Just in case, shouldn't happen
if (!panel) {
return ''
}
const assetsPath = panel.webview.asWebviewUri(vscode.Uri.file(path.join(extensionPath, 'assets')))
const iconThemeBase = panel.webview.asWebviewUri(
vscode.Uri.file(path.join(extensionPath, 'assets', 'img', 'azure', themeName)),
).toString()
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="${assetsPath}/js/vendor/jquery-3.4.1.slim.min.js"></script>
<script src="${assetsPath}/js/vendor/cytoscape.min.js"></script>
<script src="${assetsPath}/js/vendor/cytoscape-snap-to-grid.js"></script>
<script src="${assetsPath}/js/main.js"></script>
<link href="${assetsPath}/css/main.css" rel="stylesheet" type="text/css">
<title>ARM Viewer</title>
</head>
<body>
<div id="error">
<div id="errortitle">⚠️ Parser Error</div>
<div id="errormsg"></div>
</div>
<div id="buttons">
<button onclick="toggleLabels()" title="Toggle Labels"><img src="${assetsPath}/img/toolbar/labels.svg"><span class="lab"> Labels</span></button>
<button onclick="cy.fit()" title="Zoom to fit"><img src="${assetsPath}/img/toolbar/fit.svg"><span class="lab"> Re-fit</span></button>
<button onclick="toggleSnap()" id="snapbut" title="Toggle snap to grid"><img src="${assetsPath}/img/toolbar/snap.svg"><span class="lab"> Snap</span></button>
<span class="lab">Layout:</span>
<button onclick="reLayout('breadthfirst', true)" title="Relayout as tree"><img src="${assetsPath}/img/toolbar/tree.svg"></button>
<button onclick="reLayout('grid', true)" title="Relayout as grid"><img src="${assetsPath}/img/toolbar/grid.svg"></button>
<!--button onclick="reLayout('cose', true)"><img src="${assetsPath}/img/toolbar/cose.svg"></button-->
<button onclick="sendMessage('paramsClicked')" title="Apply parameters file"><img src="${assetsPath}/img/toolbar/params.svg"><span class="lab"> Params</span></button>
<button onclick="sendMessage('filtersClicked')" title="Filter out resource types"><img src="${assetsPath}/img/toolbar/filter.svg"><span class="lab"> Filter</span></button>
<button onclick="sendMessage('initialized')" title="Reload/reset"><img src="${assetsPath}/img/toolbar/reload.svg"><span class="lab"> Reload</span></button>
<button onclick="exportPNG()" title="Export view as PNG"><img src="${assetsPath}/img/toolbar/export.svg"><span class="lab"> Export</span></button>
</div>
<div class="loader"></div>
<div id="mainview"></div>
<div id="statusbar">
Objects: <span id="statusResCount">0</span>   |  
Snap to grid: <span id="statusSnap">Off</span>   |  
Parameters: <span id="statusParams">none</span>   |  
Filters: <span id="statusFilters">none</span>
</div>
<div id="infobox">
<div class="panel-heading" onclick="hideInfo()"><img id="infoimg" src=''/> Resource Details</div>
<div class="panel-body">
<table id="infotable"></table>
</div>
</div>
<script>
// **** Init Cytoscape and canvas (function in main.js) ****
init("${iconThemeBase}");
</script>
</body>
</html>`
} | the_stack |
import { enable, disable } from 'farrow-pipeline/asyncHooks.node';
import {
createPipeline,
createAsyncPipeline,
createContext,
createContainer,
} from 'farrow-pipeline';
import { createManager, createAsyncManager, useRunner } from '../src/manager';
import { createWaterfall, createAsyncWaterfall } from '../src/waterfall';
import {
createWorkflow,
createAsyncWorkflow,
createParallelWorkflow,
} from '../src/workflow';
import { main } from './fixtures/async/core';
import foo from './fixtures/async/base/foo';
import bar, { getBar } from './fixtures/async/base/bar';
import dFoo from './fixtures/async/dynamic/foo';
import dBar, { getNumber } from './fixtures/async/dynamic/bar';
import { sleep } from './helpers';
describe('async manager', () => {
it('base usage', async () => {
const manager = main.clone().usePlugin(foo).usePlugin(bar);
expect(getBar()).toBe(0);
const runner = await manager.init({});
expect(getBar()).toBe(1);
runner.preDev();
expect(getBar()).toBe(2);
runner.postDev();
expect(getBar()).toBe(3);
});
it('should support async initializer', async () => {
const manager = createAsyncManager();
const countContext = createContext(0);
const useCount = () => countContext.use().value;
const plugin = manager.createPlugin(async () => {
await sleep(0);
expect(useCount()).toBe(1);
});
manager.usePlugin(plugin);
manager.run(() => {
countContext.set(1);
});
enable();
await manager.init();
disable();
const result0 = manager.run(() => countContext.get());
expect(result0).toBe(1);
});
it('support support dynamicly register', async () => {
const manager = main.clone().usePlugin(dFoo).usePlugin(dBar);
expect(getNumber()).toBe(0);
const runner = await manager.init();
expect(getNumber()).toBe(1);
runner.preDev();
expect(getNumber()).toBe(2);
});
it('could without progress hook in plugin', async () => {
// eslint-disable-next-line @typescript-eslint/no-shadow
const foo = createWaterfall<number>();
const manager = createAsyncManager({ foo });
// eslint-disable-next-line @typescript-eslint/no-empty-function
const plugin = manager.createPlugin(() => {});
manager.usePlugin(plugin);
const runner = await manager.init();
expect(runner.foo(0)).toBe(0);
});
describe('pre order plugin', () => {
it('default order is right order', async () => {
const manager = createAsyncManager();
const list: number[] = [];
const plugin0 = manager.createPlugin(
() => {
list.push(0);
},
{ name: 'plugin0' },
);
const plugin1 = manager.createPlugin(
() => {
list.push(1);
},
{
name: 'plugin1',
pre: ['plugin0'],
},
);
const plugin2 = manager.createPlugin(
() => {
list.push(2);
},
{ name: 'plugin2' },
);
manager.usePlugin(plugin0, plugin1, plugin2);
await manager.init();
expect(list).toStrictEqual([0, 1, 2]);
});
it('default order is incorrect order', async () => {
const manager = createAsyncManager();
const list: number[] = [];
const plugin0 = manager.createPlugin(
() => {
list.push(0);
},
{
name: 'plugin0',
pre: ['plugin1'],
},
);
const plugin1 = manager.createPlugin(
() => {
list.push(1);
},
{ name: 'plugin1' },
);
const plugin2 = manager.createPlugin(
() => {
list.push(2);
},
{ name: 'plugin2' },
);
manager.usePlugin(plugin0, plugin1, plugin2);
await manager.init();
expect(list).toStrictEqual([1, 0, 2]);
});
});
describe('post order plugin', () => {
it('default order is right order', async () => {
const manager = createAsyncManager();
const list: number[] = [];
const plugin0 = manager.createPlugin(
() => {
list.push(0);
},
{
name: 'plugin0',
post: ['plugin1'],
},
);
const plugin1 = manager.createPlugin(
() => {
list.push(1);
},
{ name: 'plugin1' },
);
const plugin2 = manager.createPlugin(
() => {
list.push(2);
},
{ name: 'plugin2' },
);
manager.usePlugin(plugin0, plugin1, plugin2);
await manager.init();
expect(list).toStrictEqual([0, 1, 2]);
});
it('default order is incorrect order', async () => {
const manager = createAsyncManager();
const list: number[] = [];
const plugin0 = manager.createPlugin(
() => {
list.push(0);
},
{ name: 'plugin0' },
);
const plugin1 = manager.createPlugin(
() => {
list.push(1);
},
{
name: 'plugin1',
post: ['plugin0'],
},
);
const plugin2 = manager.createPlugin(
() => {
list.push(2);
},
{ name: 'plugin2' },
);
manager.usePlugin(plugin0, plugin1, plugin2);
await manager.init();
expect(list).toStrictEqual([1, 0, 2]);
});
it('should support more plugin', async () => {
const manager = createAsyncManager();
let status = 0;
const plugin1 = manager.createPlugin(
() => {
status = 1;
},
{ name: 'plugin1' },
);
const plugin2 = manager.createPlugin(() => {
status = 2;
});
const plugin3 = manager.createPlugin(() => {
status = 3;
});
const plugin4 = manager.createPlugin(
() => {
status = 4;
},
{ post: ['plugin1'] },
);
manager.usePlugin(plugin1);
manager.usePlugin(plugin2);
manager.usePlugin(plugin3);
manager.usePlugin(plugin4);
await manager.init({});
expect(status).toBe(1);
});
});
describe('rival plugin', () => {
it('should throw error when attaching rival plugin', async () => {
const manager = createAsyncManager();
let count = 0;
const plugin0 = manager.createPlugin(
() => {
count = 0;
},
{ name: 'plugin0' },
);
const plugin1 = manager.createPlugin(
() => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
count += 1;
},
{
name: 'plugin1',
rivals: ['plugin0'],
},
);
manager.usePlugin(plugin0, plugin1);
await expect(manager.init).rejects.toThrowError();
});
it('should not throw error without attaching rival plugin', async () => {
const manager = createAsyncManager();
let count = 0;
const plugin0 = manager.createPlugin(
() => {
count = 0;
},
{ name: 'plugin0' },
);
const plugin1 = manager.createPlugin(
() => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
count += 1;
},
{
name: 'plugin1',
rivals: ['plugin2'],
},
);
manager.usePlugin(plugin0, plugin1);
await manager.init();
});
});
describe('required plugin', () => {
it('should throw error when it is without required plugin', async () => {
const manager = createAsyncManager();
// eslint-disable-next-line @typescript-eslint/no-empty-function
const plugin0 = manager.createPlugin(() => {}, {
name: 'plugin0',
required: ['plugin1'],
});
manager.usePlugin(plugin0);
await expect(manager.init).rejects.toThrowError();
});
it('should not throw error without attaching rival plugin', async () => {
const manager = createAsyncManager();
let count = 0;
const plugin0 = manager.createPlugin(
() => {
count = 0;
},
{
name: 'plugin0',
required: ['plugin1'],
},
);
const plugin1 = manager.createPlugin(
() => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
count += 1;
},
{ name: 'plugin1' },
);
manager.usePlugin(plugin0, plugin1);
await manager.init();
});
});
it('should de-duplicate plugins', async () => {
const manager = createAsyncManager();
let count = 0;
const plugin = manager.createPlugin(() => {
count += 1;
});
manager.usePlugin(plugin, plugin);
manager.usePlugin(plugin);
await manager.init();
expect(count).toBe(1);
});
it('should support manager clone', async () => {
const manager0 = createAsyncManager();
let count = 0;
const plugin = manager0.createPlugin(() => {
count += 1;
});
manager0.usePlugin(plugin);
await manager0.init();
expect(count).toBe(1);
const manager1 = manager0.clone();
manager1.usePlugin(plugin);
await manager1.init();
expect(count).toBe(2);
});
it('isPlugin if exclusive plugins of manager', () => {
const manager0 = createManager();
const manager1 = createAsyncManager();
// eslint-disable-next-line @typescript-eslint/no-empty-function
const plugin = manager0.createPlugin(() => {});
expect(manager0.isPlugin(plugin)).toBeTruthy();
expect(manager1.isPlugin(plugin)).toBeFalsy();
expect(manager1.isPlugin({})).toBeFalsy();
expect(manager1.isPlugin('' as any)).toBeFalsy();
});
it('usePlugin should only add exclusive plugins of manager', async () => {
const manager0 = createManager();
const manager1 = createAsyncManager();
let count = 0;
const plugin = manager0.createPlugin(() => {
count += 1;
});
manager1.usePlugin(plugin as any);
await manager1.init();
expect(count).toBe(0);
});
it('should support clear plugins', async () => {
const manager = createAsyncManager();
let count = 0;
const plugin = manager.createPlugin(() => {
count += 1;
});
manager.usePlugin(plugin);
manager.clear();
await manager.init();
expect(count).toBe(0);
});
it('should run under the internal container', async () => {
const manager = createAsyncManager();
const Count = createContext(0);
const plugin = manager.createPlugin(() => {
Count.set(1);
});
manager.usePlugin(plugin);
await manager.init();
expect(manager.run(Count.get)).toBe(1);
const container = createContainer();
await manager.init({ container });
expect(manager.run(Count.get, { container })).toBe(1);
});
it('should support all progress', async () => {
const manager = createAsyncManager({
pipeline: createPipeline(),
asyncPipeline: createAsyncPipeline(),
waterfall: createWaterfall(),
asyncWaterfall: createAsyncWaterfall(),
workflow: createWorkflow(),
asyncWorkflow: createAsyncWorkflow(),
parallelWorkflow: createParallelWorkflow(),
});
const list: string[] = [];
const plugin = manager.createPlugin(() => ({
pipeline: () => {
list.push('pipeline');
},
asyncPipeline: () => {
list.push('asyncPipeline');
},
waterfall: () => {
list.push('waterfall');
},
asyncWaterfall: () => {
list.push('asyncWaterfall');
},
workflow: () => {
list.push('workflow');
},
asyncWorkflow: () => {
list.push('asyncWorkflow');
},
parallelWorkflow: () => {
list.push('parallelWorkflow');
},
}));
manager.usePlugin(plugin);
const runner = await manager.init();
runner.pipeline({});
await runner.asyncPipeline({});
runner.waterfall({});
await runner.asyncWaterfall({});
runner.workflow({});
await runner.asyncWorkflow({});
await runner.parallelWorkflow({});
expect(list).toStrictEqual([
'pipeline',
'asyncPipeline',
'waterfall',
'asyncWaterfall',
'workflow',
'asyncWorkflow',
'parallelWorkflow',
]);
});
describe('useRunner', () => {
it('should work well', async () => {
// eslint-disable-next-line @typescript-eslint/no-shadow
const foo = createAsyncPipeline();
// eslint-disable-next-line @typescript-eslint/no-shadow
const bar = createAsyncPipeline();
const manager = createAsyncManager({ foo, bar });
let count = 0;
const plugin = manager.createPlugin(() => ({
foo: async () => {
await sleep(0);
const runner = manager.useRunner();
runner.bar({});
},
bar: () => {
count = 1;
},
}));
manager.usePlugin(plugin);
const runner = await manager.init();
enable();
await runner.foo({});
disable();
expect(count).toBe(1);
});
it('should throw error useRunner out plugin hook', async () => {
// eslint-disable-next-line @typescript-eslint/no-shadow
const foo = createAsyncPipeline();
// eslint-disable-next-line @typescript-eslint/no-shadow
const bar = createAsyncPipeline();
const manager = createAsyncManager({ foo, bar });
let count = 0;
const plugin = manager.createPlugin(() => {
const runner = manager.useRunner();
return {
foo: async () => {
await sleep(0);
runner.bar({});
},
bar: () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
count = 1;
},
};
});
manager.usePlugin(plugin);
await expect(manager.init).rejects.toThrowError(
new Error(
`Can't call useRunner out of scope, it should be placed in hooks of plugin`,
),
);
});
it('should throw error useRunner out plugin', () => {
expect(useRunner).toThrowError(
new Error(
`Can't call useContainer out of scope, it should be placed on top of the function`,
),
);
});
});
}); | the_stack |
import * as t from './types';
import {SerialDriver} from './uart';
import {COMMANDS, ZDO_COMMANDS} from './commands';
import {
EmberStatus,
EmberOutgoingMessageType,
EzspPolicyId,
EzspDecisionId,
EzspDecisionBitmask,
EmberConcentratorType,
EzspConfigId,
EmberZdoConfigurationFlags
} from './types/named';
import {EventEmitter} from 'events';
import {EmberApsFrame} from './types/struct';
import {Queue, Waitress} from '../../../utils';
import Debug from "debug";
const debug = {
error: Debug('zigbee-herdsman:adapter:ezsp:error'),
log: Debug('zigbee-herdsman:adapter:ezsp:log'),
};
const MTOR_MIN_INTERVAL = 10;
const MTOR_MAX_INTERVAL = 90;
const MTOR_ROUTE_ERROR_THRESHOLD = 4;
const MTOR_DELIVERY_FAIL_THRESHOLD = 3;
const MAX_WATCHDOG_FAILURES = 4;
//const RESET_ATTEMPT_BACKOFF_TIME = 5;
const WATCHDOG_WAKE_PERIOD = 10; // in sec
//const EZSP_COUNTER_CLEAR_INTERVAL = 180; // Clear counters every n * WATCHDOG_WAKE_PERIOD
const EZSP_DEFAULT_RADIUS = 0;
const EZSP_MULTICAST_NON_MEMBER_RADIUS = 3;
type EZSPFrame = {
sequence: number,
frameId: number,
frameName: string,
/* eslint-disable-next-line @typescript-eslint/no-explicit-any*/
payload: any
};
type EZSPWaitressMatcher = {
sequence: number | null,
frameId: number
};
export class Ezsp extends EventEmitter {
ezspV = 4;
cmdSeq = 0; // command sequence
/* eslint-disable-next-line @typescript-eslint/no-explicit-any*/
COMMANDS_BY_ID = new Map<number, { name: string, inArgs: any[], outArgs: any[] }>();
private serialDriver: SerialDriver;
private waitress: Waitress<EZSPFrame, EZSPWaitressMatcher>;
private queue: Queue;
private watchdogTimer: NodeJS.Timeout;
private failures = 0;
constructor() {
super();
for (const name in COMMANDS) {
const details = COMMANDS[name];
this.COMMANDS_BY_ID.set(details[0], {name, inArgs: details[1], outArgs: details[2]});
}
this.queue = new Queue();
this.waitress = new Waitress<EZSPFrame, EZSPWaitressMatcher>(
this.waitressValidator, this.waitressTimeoutFormatter);
this.serialDriver = new SerialDriver();
this.serialDriver.on('received', this.onFrameReceived.bind(this));
}
public async connect(path: string, options: Record<string, number|boolean>): Promise<void> {
await this.serialDriver.connect(path, options);
this.watchdogTimer = setInterval(
this.watchdogHandler.bind(this),
WATCHDOG_WAKE_PERIOD*1000
);
}
public async close(): Promise<void> {
debug.log('Stop ezsp');
clearTimeout(this.watchdogTimer);
await this.serialDriver.close();
}
private onFrameReceived(data: Buffer): void {
/*Handle a received EZSP frame
The protocol has taken care of UART specific framing etc, so we should
just have EZSP application stuff here, with all escaping/stuffing and
data randomization removed.
*/
debug.log(`<=== Frame: ${data.toString('hex')}`);
let frame_id: number, result, sequence;
if ((this.ezspV < 8)) {
[sequence, frame_id, data] = [data[0], data[2], data.slice(3)];
} else {
sequence = data[0];
[[frame_id], data] = t.deserialize(data.slice(3), [t.uint16_t]);
}
if ((frame_id === 255)) {
frame_id = 0;
if ((data.length > 1)) {
frame_id = data[1];
data = data.slice(2);
}
}
const cmd = this.COMMANDS_BY_ID.get(frame_id);
if (!cmd) throw new Error('Unrecognized command from FrameID' + frame_id);
const frameName = cmd.name;
debug.log("<=== Application frame %s (%s) received: %s", frame_id, frameName, data.toString('hex'));
const schema = cmd.outArgs;
[result, data] = t.deserialize(data, schema);
debug.log(`<=== Application frame ${frame_id} (${frameName}) parsed: ${result}`);
const handled = this.waitress.resolve({
frameId: frame_id,
frameName: frameName,
sequence: sequence,
payload: result
});
if (!handled) this.emit('frame', frameName, ...result);
if ((frame_id === 0)) {
this.ezspV = result[0];
}
}
async version(): Promise<number> {
const version = this.ezspV;
const result = await this.command("version", version);
if ((result[0] !== version)) {
debug.log("Switching to eszp version %d", result[0]);
await this.command("version", result[0]);
}
return result[0];
}
async networkInit(): Promise<boolean> {
const waiter = this.waitFor(COMMANDS["stackStatusHandler"][0], null).start();
const [result] = await this.command("networkInit");
debug.log('network init result', result);
if ((result !== EmberStatus.SUCCESS)) {
this.waitress.remove(waiter.ID);
debug.log("Failure to init network:" + result);
return false;
}
const response = await waiter.promise;
return response.payload[0] == EmberStatus.NETWORK_UP;
}
async leaveNetwork(): Promise<number> {
const waiter = this.waitFor(COMMANDS["stackStatusHandler"][0], null).start();
const [result] = await this.command("leaveNetwork");
debug.log('network init result', result);
if ((result !== EmberStatus.SUCCESS)) {
this.waitress.remove(waiter.ID);
debug.log("Failure to leave network:" + result);
throw new Error(("Failure to leave network:" + result));
}
const response = await waiter.promise;
if ((response.payload[0] !== EmberStatus.NETWORK_DOWN)) {
debug.log("Wrong network status:" + response.payload);
throw new Error(("Wrong network status:" + response.payload));
}
return response.payload[0];
}
/* eslint-disable-next-line @typescript-eslint/no-explicit-any*/
async setConfigurationValue(configId: number, value: any): Promise<void> {
debug.log('Set %s = %s', EzspConfigId.valueToName(EzspConfigId, configId), value);
const [ret] = await this.execCommand('setConfigurationValue', configId, value);
console.assert(ret === EmberStatus.SUCCESS);
}
async getConfigurationValue(configId: number): Promise<number> {
debug.log('Get %s', EzspConfigId.valueToName(EzspConfigId, configId));
const [ret, value] = await this.execCommand('getConfigurationValue', configId);
console.assert(ret === EmberStatus.SUCCESS);
debug.log('Got %s = %s', EzspConfigId.valueToName(EzspConfigId, configId), value);
return value;
}
async getMulticastTableEntry(index: number): Promise<t.EmberMulticastTableEntry> {
const [value] = await this.execCommand('getMulticastTableEntry', index);
//console.assert(ret === EmberStatus.SUCCESS);
return value;
}
async setMulticastTableEntry(index: number, entry: t.EmberMulticastTableEntry): Promise<number[]> {
const [ret] = await this.execCommand('setMulticastTableEntry', index, entry);
console.assert(ret === EmberStatus.SUCCESS);
return [ret];
}
async setInitialSecurityState(entry: t.EmberInitialSecurityState): Promise<number[]>{
const [ret] = await this.execCommand('setInitialSecurityState', entry);
console.assert(ret === EmberStatus.SUCCESS);
return [ret];
}
/* eslint-disable-next-line @typescript-eslint/no-explicit-any*/
async getCurrentSecurityState(): Promise<any[]> {
const [ret, res] = await this.execCommand('getCurrentSecurityState');
console.assert(ret === EmberStatus.SUCCESS);
return [ret, res];
}
/* eslint-disable-next-line @typescript-eslint/no-explicit-any*/
async setValue(valueId: t.EzspValueId, value: any): Promise<number[]> {
debug.log('Set %s = %s', t.EzspValueId.valueToName(t.EzspValueId, valueId), value);
const [ret] = await this.execCommand('setValue', valueId, value);
console.assert(ret === EmberStatus.SUCCESS);
return [ret];
}
async getValue(valueId: t.EzspValueId): Promise<Buffer> {
debug.log('Get %s', t.EzspValueId.valueToName(t.EzspValueId, valueId));
const [ret, value] = await this.execCommand('getValue', valueId);
console.assert(ret === EmberStatus.SUCCESS);
debug.log('Got %s = %s', t.EzspValueId.valueToName(t.EzspValueId, valueId), value);
return value;
}
/* eslint-disable-next-line @typescript-eslint/no-explicit-any*/
async setPolicy(policyId: EzspPolicyId, value: any): Promise<number[]> {
debug.log('Set %s = %s', EzspPolicyId.valueToName(EzspPolicyId, policyId), value);
const [ret] = await this.execCommand('setPolicy', policyId, value);
console.assert(ret === EmberStatus.SUCCESS);
return [ret];
}
async updateConfig(): Promise<void> {
const config = [
[EzspConfigId.CONFIG_FRAGMENT_DELAY_MS, 50],
[EzspConfigId.CONFIG_TX_POWER_MODE, 3],
[EzspConfigId.CONFIG_FRAGMENT_WINDOW_SIZE, 1],
//[EzspConfigId.CONFIG_BEACON_JITTER_DURATION, 0],
[EzspConfigId.CONFIG_NEIGHBOR_TABLE_SIZE, 16],
[EzspConfigId.CONFIG_ROUTE_TABLE_SIZE, 16],
[EzspConfigId.CONFIG_BINDING_TABLE_SIZE, 32],
[EzspConfigId.CONFIG_KEY_TABLE_SIZE, 12],
[EzspConfigId.CONFIG_ZLL_GROUP_ADDRESSES, 0],
[EzspConfigId.CONFIG_ZLL_RSSI_THRESHOLD, 215], // -40
[EzspConfigId.CONFIG_TRANSIENT_KEY_TIMEOUT_S, 300],
[EzspConfigId.CONFIG_APS_UNICAST_MESSAGE_COUNT, 255],
[EzspConfigId.CONFIG_BROADCAST_TABLE_SIZE, 15],
[EzspConfigId.CONFIG_MAX_HOPS, 30],
[EzspConfigId.CONFIG_INDIRECT_TRANSMISSION_TIMEOUT, 7680], // 30000
[EzspConfigId.CONFIG_SOURCE_ROUTE_TABLE_SIZE, 16], // 61
[EzspConfigId.CONFIG_MULTICAST_TABLE_SIZE, 16],
[EzspConfigId.CONFIG_ADDRESS_TABLE_SIZE, 16], // 8
[EzspConfigId.CONFIG_TRUST_CENTER_ADDRESS_CACHE_SIZE, 2],
[EzspConfigId.CONFIG_SUPPORTED_NETWORKS, 1],
[EzspConfigId.CONFIG_TC_REJOINS_USING_WELL_KNOWN_KEY_TIMEOUT_S, 90],
[EzspConfigId.CONFIG_APPLICATION_ZDO_FLAGS,
EmberZdoConfigurationFlags.APP_RECEIVES_SUPPORTED_ZDO_REQUESTS
| EmberZdoConfigurationFlags.APP_HANDLES_UNSUPPORTED_ZDO_REQUESTS],
[EzspConfigId.CONFIG_SECURITY_LEVEL, 5],
[EzspConfigId.CONFIG_END_DEVICE_POLL_TIMEOUT, 8], // 14
[EzspConfigId.CONFIG_PAN_ID_CONFLICT_REPORT_THRESHOLD, 2],
[EzspConfigId.CONFIG_MAX_END_DEVICE_CHILDREN, 32],
[EzspConfigId.CONFIG_STACK_PROFILE, 2],
[EzspConfigId.CONFIG_PACKET_BUFFER_COUNT, 255],
];
for (const [confName, value] of config) {
await this.setConfigurationValue(confName, value);
}
}
async updatePolicies(): Promise<void> {
// Set up the policies for what the NCP should do.
const policies = [
[EzspPolicyId.BINDING_MODIFICATION_POLICY,
EzspDecisionId.CHECK_BINDING_MODIFICATIONS_ARE_VALID_ENDPOINT_CLUSTERS],
[EzspPolicyId.UNICAST_REPLIES_POLICY, EzspDecisionId.HOST_WILL_NOT_SUPPLY_REPLY],
[EzspPolicyId.POLL_HANDLER_POLICY, EzspDecisionId.POLL_HANDLER_IGNORE],
[EzspPolicyId.MESSAGE_CONTENTS_IN_CALLBACK_POLICY,
EzspDecisionId.MESSAGE_TAG_ONLY_IN_CALLBACK],
[EzspPolicyId.PACKET_VALIDATE_LIBRARY_POLICY,
EzspDecisionId.PACKET_VALIDATE_LIBRARY_CHECKS_DISABLED],
[EzspPolicyId.ZLL_POLICY, EzspDecisionId.ALLOW_JOINS],
[EzspPolicyId.TC_REJOINS_USING_WELL_KNOWN_KEY_POLICY, EzspDecisionId.ALLOW_JOINS],
[EzspPolicyId.APP_KEY_REQUEST_POLICY, EzspDecisionId.DENY_APP_KEY_REQUESTS],
[EzspPolicyId.TRUST_CENTER_POLICY, EzspDecisionBitmask.ALLOW_UNSECURED_REJOINS
| EzspDecisionBitmask.ALLOW_JOINS],
[EzspPolicyId.TC_KEY_REQUEST_POLICY, EzspDecisionId.ALLOW_TC_KEY_REQUESTS],
];
for (const [policy, value] of policies) {
await this.setPolicy(policy, value);
}
}
/* eslint-disable-next-line @typescript-eslint/no-explicit-any*/
public makeZDOframe(name: string, ...args: any[]): Buffer {
const c = ZDO_COMMANDS[name];
const data = t.serialize(args, c[1]);
return data;
}
/* eslint-disable-next-line @typescript-eslint/no-explicit-any*/
private makeFrame(name: string, ...args: any[]): Buffer {
const c = COMMANDS[name];
const data = t.serialize(args, c[1]);
const frame = [(this.cmdSeq & 255)];
if ((this.ezspV < 8)) {
if ((this.ezspV >= 5)) {
frame.push(0x00, 0xFF, 0x00, c[0]);
} else {
frame.push(0x00, c[0]);
}
} else {
const cmd_id = t.serialize([c[0]], [t.uint16_t]);
frame.push(0x00, 0x01, ...cmd_id);
}
return Buffer.concat([Buffer.from(frame), data]);
}
/* eslint-disable-next-line @typescript-eslint/no-explicit-any*/
private command(name: string, ...args: any[]): Promise<Buffer> {
debug.log(`===> Send command ${name}: (${args})`);
return this.queue.execute<Buffer>(async (): Promise<Buffer> => {
const data = this.makeFrame(name, ...args);
debug.log(`===> Send data ${name}: (${data.toString('hex')})`);
/* eslint-disable-next-line @typescript-eslint/no-explicit-any*/
const c = COMMANDS[name];
const waiter = this.waitFor(c[0], this.cmdSeq).start();
this.cmdSeq = (this.cmdSeq + 1) & 255;
this.serialDriver.sendDATA(data);
const response = await waiter.promise;
return response.payload;
});
}
/* eslint-disable-next-line @typescript-eslint/no-explicit-any*/
async formNetwork(...args: any[]): Promise<number> {
const waiter = this.waitFor(COMMANDS["stackStatusHandler"][0], null).start();
const v = await this.command("formNetwork", ...args);
if ((v[0] !== EmberStatus.SUCCESS)) {
this.waitress.remove(waiter.ID);
debug.error("Failure forming network:" + v);
throw new Error(("Failure forming network:" + v));
}
const response = await waiter.promise;
if ((response.payload[0] !== EmberStatus.NETWORK_UP)) {
debug.error("Wrong network status:" + response.payload);
throw new Error(("Wrong network status:" + response.payload));
}
return response.payload[0];
}
/* eslint-disable-next-line @typescript-eslint/no-explicit-any*/
execCommand(name: string, ...args: any[]): any {
if (Object.keys(COMMANDS).indexOf(name) < 0) {
throw new Error('Unknown command: ' + name);
}
return this.command(name, ...args);
}
/* eslint-disable-next-line @typescript-eslint/no-explicit-any*/
public parse_frame_payload(name: string, data: Buffer): any[] {
if (Object.keys(ZDO_COMMANDS).indexOf(name) < 0) {
throw new Error('Unknown ZDO command: ' + name);
}
/* eslint-disable-next-line @typescript-eslint/no-explicit-any*/
const c = ZDO_COMMANDS[name];
const result = t.deserialize(data, c[1])[0];
return result;
}
/* eslint-disable @typescript-eslint/no-explicit-any*/
public sendUnicast(direct: EmberOutgoingMessageType, nwk: number, apsFrame:
EmberApsFrame, seq: number, data: Buffer): any {
return this.execCommand('sendUnicast', direct, nwk, apsFrame, seq, data);
}
/* eslint-enable @typescript-eslint/no-explicit-any*/
/* eslint-disable @typescript-eslint/no-explicit-any*/
public sendMulticast(apsFrame: EmberApsFrame, seq: number, data: Buffer): any {
return this.execCommand('sendMulticast', apsFrame, EZSP_DEFAULT_RADIUS,
EZSP_MULTICAST_NON_MEMBER_RADIUS, seq, data);
}
/* eslint-enable @typescript-eslint/no-explicit-any*/
public async setSourceRouting(): Promise<void> {
const [res] = await this.execCommand('setConcentrator',
true,
EmberConcentratorType.HIGH_RAM_CONCENTRATOR,
MTOR_MIN_INTERVAL,
MTOR_MAX_INTERVAL,
MTOR_ROUTE_ERROR_THRESHOLD,
MTOR_DELIVERY_FAIL_THRESHOLD,
0,
);
debug.log("Set concentrator type: %s", res);
if (res != EmberStatus.SUCCESS) {
debug.log("Couldn't set concentrator type %s: %s", true, res);
}
// await this.execCommand('setSourceRouteDiscoveryMode', 1);
}
public waitFor(frameId: number, sequence: number | null, timeout = 10000)
: { start: () => { promise: Promise<EZSPFrame>; ID: number }; ID: number } {
return this.waitress.waitFor({frameId, sequence}, timeout);
}
private waitressTimeoutFormatter(matcher: EZSPWaitressMatcher, timeout: number): string {
return `${JSON.stringify(matcher)} after ${timeout}ms`;
}
private waitressValidator(payload: EZSPFrame, matcher: EZSPWaitressMatcher): boolean {
return (
(matcher.sequence == null || payload.sequence === matcher.sequence) &&
payload.frameId === matcher.frameId
);
}
private async watchdogHandler(): Promise<void> {
debug.log(`Time to watchdog ... ${this.failures}`);
try {
await this.execCommand('nop');
} catch (error) {
debug.error(`Watchdog heartbeat timeout ${error.stack}`);
this.failures += 1;
if (this.failures > MAX_WATCHDOG_FAILURES) {
this.failures = 0;
this.emit('reset');
}
}
}
} | the_stack |
import * as assert from 'assert';
import {describe, it, beforeEach, afterEach} from 'mocha';
import * as nock from 'nock';
import * as sinon from 'sinon';
import {GaxiosError, GaxiosOptions, GaxiosPromise} from 'gaxios';
import {Credentials} from '../src/auth/credentials';
import {StsSuccessfulResponse} from '../src/auth/stscredentials';
import {
DownscopedClient,
CredentialAccessBoundary,
MAX_ACCESS_BOUNDARY_RULES_COUNT,
} from '../src/auth/downscopedclient';
import {AuthClient} from '../src/auth/authclient';
import {mockStsTokenExchange} from './externalclienthelper';
import {
OAuthErrorResponse,
getErrorFromOAuthErrorResponse,
} from '../src/auth/oauth2common';
import {GetAccessTokenResponse, Headers} from '../src/auth/oauth2client';
nock.disableNetConnect();
/** A dummy class used as source credential for testing. */
class TestAuthClient extends AuthClient {
public throwError = false;
private counter = 0;
async getAccessToken(): Promise<GetAccessTokenResponse> {
if (!this.throwError) {
// Increment subject_token counter each time this is called.
return {
token: `subject_token_${this.counter++}`,
};
}
throw new Error('Cannot get subject token.');
}
set expirationTime(expirationTime: number | undefined | null) {
this.credentials.expiry_date = expirationTime;
}
async getRequestHeaders(url?: string): Promise<Headers> {
throw new Error('Not implemented.');
}
request<T>(opts: GaxiosOptions): GaxiosPromise<T> {
throw new Error('Not implemented.');
}
}
interface SampleResponse {
foo: string;
bar: number;
}
describe('DownscopedClient', () => {
let clock: sinon.SinonFakeTimers;
let client: TestAuthClient;
const ONE_HOUR_IN_SECS = 3600;
const testAvailableResource =
'//storage.googleapis.com/projects/_/buckets/bucket-123';
const testAvailablePermission1 = 'inRole:roles/storage.objectViewer';
const testAvailablePermission2 = 'inRole:roles/storage.objectAdmin';
const testAvailabilityConditionExpression =
"resource.name.startsWith('projects/_/buckets/bucket-123/objects/prefix')";
const testAvailabilityConditionTitle = 'Test availability condition title.';
const testAvailabilityConditionDescription =
'Test availability condition description.';
const testClientAccessBoundary = {
accessBoundary: {
accessBoundaryRules: [
{
availableResource: testAvailableResource,
availablePermissions: [testAvailablePermission1],
availabilityCondition: {
expression: testAvailabilityConditionExpression,
},
},
],
},
};
const stsSuccessfulResponse: StsSuccessfulResponse = {
access_token: 'DOWNSCOPED_CLIENT_ACCESS_TOKEN_0',
issued_token_type: 'urn:ietf:params:oauth:token-type:access_token',
token_type: 'Bearer',
expires_in: ONE_HOUR_IN_SECS,
};
/**
* Offset to take into account network delays and server clock skews.
*/
const EXPIRATION_TIME_OFFSET = 5 * 60 * 1000;
beforeEach(async () => {
client = new TestAuthClient();
});
afterEach(() => {
nock.cleanAll();
if (clock) {
clock.restore();
}
});
describe('Constructor', () => {
it('should throw on empty access boundary rule', () => {
const expectedError = new Error(
'At least one access boundary rule needs to be defined.'
);
const cabWithEmptyAccessBoundaryRules = {
accessBoundary: {
accessBoundaryRules: [],
},
};
assert.throws(() => {
return new DownscopedClient(client, cabWithEmptyAccessBoundaryRules);
}, expectedError);
});
it('should throw when number of access boundary rules is exceeded', () => {
const expectedError = new Error(
'The provided access boundary has more than ' +
`${MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`
);
const cabWithExceedingAccessBoundaryRules: CredentialAccessBoundary = {
accessBoundary: {
accessBoundaryRules: [],
},
};
const testAccessBoundaryRule = {
availableResource: testAvailableResource,
availablePermissions: [testAvailablePermission1],
availabilityCondition: {
expression: testAvailabilityConditionExpression,
},
};
for (let num = 0; num <= MAX_ACCESS_BOUNDARY_RULES_COUNT; num++) {
cabWithExceedingAccessBoundaryRules.accessBoundary.accessBoundaryRules.push(
testAccessBoundaryRule
);
}
assert.throws(() => {
return new DownscopedClient(
client,
cabWithExceedingAccessBoundaryRules
);
}, expectedError);
});
it('should throw on no permissions are defined in access boundary rules', () => {
const expectedError = new Error(
'At least one permission should be defined in access boundary rules.'
);
const cabWithNoPermissionIncluded = {
accessBoundary: {
accessBoundaryRules: [
{
availableResource: testAvailableResource,
availablePermissions: [],
availabilityCondition: {
expression: testAvailabilityConditionExpression,
},
},
],
},
};
assert.throws(() => {
return new DownscopedClient(client, cabWithNoPermissionIncluded);
}, expectedError);
});
it('should not throw on one access boundary rule with all fields included', () => {
const cabWithOneAccessBoundaryRule = {
accessBoundary: {
accessBoundaryRules: [
{
availableResource: testAvailableResource,
availablePermissions: [testAvailablePermission1],
availabilityCondition: {
expression: testAvailabilityConditionExpression,
},
},
],
},
};
assert.doesNotThrow(() => {
return new DownscopedClient(client, cabWithOneAccessBoundaryRule);
});
});
it('should not throw with multiple permissions defined', () => {
const cabWithTwoAvailblePermissions = {
accessBoundary: {
accessBoundaryRules: [
{
availableResource: testAvailableResource,
availablePermissions: [
testAvailablePermission1,
testAvailablePermission2,
],
availabilityCondition: {
expression: testAvailabilityConditionExpression,
title: testAvailabilityConditionTitle,
description: testAvailabilityConditionDescription,
},
},
],
},
};
assert.doesNotThrow(() => {
return new DownscopedClient(client, cabWithTwoAvailblePermissions);
});
});
it('should not throw with empty available condition', () => {
const cabWithNoAvailabilityCondition = {
accessBoundary: {
accessBoundaryRules: [
{
availableResource: testAvailableResource,
availablePermissions: [testAvailablePermission1],
},
],
},
};
assert.doesNotThrow(() => {
return new DownscopedClient(client, cabWithNoAvailabilityCondition);
});
});
it('should not throw with only expression setup in available condition', () => {
const cabWithOnlyAvailabilityConditionExpression = {
accessBoundary: {
accessBoundaryRules: [
{
availableResource: testAvailableResource,
availablePermissions: [
testAvailablePermission1,
testAvailablePermission2,
],
availabilityCondition: {
expression: testAvailabilityConditionExpression,
},
},
],
},
};
assert.doesNotThrow(() => {
return new DownscopedClient(
client,
cabWithOnlyAvailabilityConditionExpression
);
});
});
it('should not throw with an optional quota_project_id', () => {
const quotaProjectId = 'quota_project_id';
const cabWithOneAccessBoundaryRule = {
accessBoundary: {
accessBoundaryRules: [
{
availableResource: testAvailableResource,
availablePermissions: [testAvailablePermission1],
availabilityCondition: {
expression: testAvailabilityConditionExpression,
},
},
],
},
};
assert.doesNotThrow(() => {
return new DownscopedClient(
client,
cabWithOneAccessBoundaryRule,
undefined,
quotaProjectId
);
});
});
it('should set custom RefreshOptions', () => {
const refreshOptions = {
eagerRefreshThresholdMillis: 5000,
forceRefreshOnFailure: true,
};
const cabWithOneAccessBoundaryRules = {
accessBoundary: {
accessBoundaryRules: [
{
availableResource: testAvailableResource,
availablePermissions: [testAvailablePermission1],
availabilityCondition: {
expression: testAvailabilityConditionExpression,
},
},
],
},
};
const downscopedClient = new DownscopedClient(
client,
cabWithOneAccessBoundaryRules,
refreshOptions
);
assert.strictEqual(
downscopedClient.forceRefreshOnFailure,
refreshOptions.forceRefreshOnFailure
);
assert.strictEqual(
downscopedClient.eagerRefreshThresholdMillis,
refreshOptions.eagerRefreshThresholdMillis
);
});
});
describe('setCredential()', () => {
it('should throw error if no expire time is set in credential', async () => {
const credentials = {
access_token: 'DOWNSCOPED_CLIENT_ACCESS_TOKEN',
};
const expectedError = new Error(
'The access token expiry_date field is missing in the provided ' +
'credentials.'
);
const downscopedClient = new DownscopedClient(
client,
testClientAccessBoundary
);
assert.throws(() => {
downscopedClient.setCredentials(credentials);
}, expectedError);
});
it('should not throw error if expire time is set in credential', async () => {
const now = new Date().getTime();
const credentials = {
access_token: 'DOWNSCOPED_CLIENT_ACCESS_TOKEN',
expiry_date: now + ONE_HOUR_IN_SECS * 1000,
};
const downscopedClient = new DownscopedClient(
client,
testClientAccessBoundary
);
assert.doesNotThrow(() => {
downscopedClient.setCredentials(credentials);
});
const tokenResponse = await downscopedClient.getAccessToken();
assert.deepStrictEqual(tokenResponse.token, credentials.access_token);
assert.deepStrictEqual(
tokenResponse.expirationTime,
credentials.expiry_date
);
});
});
describe('getAccessToken()', () => {
it('should return current unexpired cached DownscopedClient access token', async () => {
const now = new Date().getTime();
clock = sinon.useFakeTimers(now);
const credentials = {
access_token: 'DOWNSCOPED_CLIENT_ACCESS_TOKEN',
expiry_date: now + ONE_HOUR_IN_SECS * 1000,
};
const downscopedClient = new DownscopedClient(
client,
testClientAccessBoundary
);
downscopedClient.setCredentials(credentials);
const tokenResponse = await downscopedClient.getAccessToken();
assert.deepStrictEqual(tokenResponse.token, credentials.access_token);
assert.deepStrictEqual(
tokenResponse.expirationTime,
credentials.expiry_date
);
assert.deepStrictEqual(
tokenResponse.token,
downscopedClient.credentials.access_token
);
assert.deepStrictEqual(
tokenResponse.expirationTime,
downscopedClient.credentials.expiry_date
);
clock.tick(ONE_HOUR_IN_SECS * 1000 - EXPIRATION_TIME_OFFSET - 1);
const cachedTokenResponse = await downscopedClient.getAccessToken();
assert.deepStrictEqual(
cachedTokenResponse.token,
credentials.access_token
);
assert.deepStrictEqual(
cachedTokenResponse.expirationTime,
credentials.expiry_date
);
});
it('should refresh a new DownscopedClient access when cached one gets expired', async () => {
const now = new Date().getTime();
clock = sinon.useFakeTimers(now);
const emittedEvents: Credentials[] = [];
const credentials = {
access_token: 'DOWNSCOPED_CLIENT_ACCESS_TOKEN',
expiry_date: now + ONE_HOUR_IN_SECS * 1000,
};
const scope = mockStsTokenExchange([
{
statusCode: 200,
response: stsSuccessfulResponse,
request: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
requested_token_type:
'urn:ietf:params:oauth:token-type:access_token',
subject_token: 'subject_token_0',
subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',
options: JSON.stringify(testClientAccessBoundary),
},
},
]);
const downscopedClient = new DownscopedClient(
client,
testClientAccessBoundary
);
// Listen to tokens events. On every event, push to list of
// emittedEvents.
downscopedClient.on('tokens', tokens => {
emittedEvents.push(tokens);
});
downscopedClient.setCredentials(credentials);
clock.tick(ONE_HOUR_IN_SECS * 1000 - EXPIRATION_TIME_OFFSET - 1);
const tokenResponse = await downscopedClient.getAccessToken();
// No new event should be triggered since the cached access token is
// returned.
assert.strictEqual(emittedEvents.length, 0);
assert.deepStrictEqual(tokenResponse.token, credentials.access_token);
clock.tick(1);
const refreshedTokenResponse = await downscopedClient.getAccessToken();
const responseExpiresIn = stsSuccessfulResponse.expires_in as number;
const expectedExpirationTime =
credentials.expiry_date +
responseExpiresIn * 1000 -
EXPIRATION_TIME_OFFSET;
// tokens event should be triggered once with expected event.
assert.strictEqual(emittedEvents.length, 1);
assert.deepStrictEqual(emittedEvents[0], {
refresh_token: null,
expiry_date: expectedExpirationTime,
access_token: stsSuccessfulResponse.access_token,
token_type: 'Bearer',
id_token: null,
});
assert.deepStrictEqual(
refreshedTokenResponse.token,
stsSuccessfulResponse.access_token
);
assert.deepStrictEqual(
refreshedTokenResponse.expirationTime,
expectedExpirationTime
);
assert.deepStrictEqual(
refreshedTokenResponse.token,
downscopedClient.credentials.access_token
);
assert.deepStrictEqual(
refreshedTokenResponse.expirationTime,
downscopedClient.credentials.expiry_date
);
scope.done();
});
it('should return new access token when no cached token is available', async () => {
const scope = mockStsTokenExchange([
{
statusCode: 200,
response: stsSuccessfulResponse,
request: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
requested_token_type:
'urn:ietf:params:oauth:token-type:access_token',
subject_token: 'subject_token_0',
subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',
options: JSON.stringify(testClientAccessBoundary),
},
},
]);
const downscopedClient = new DownscopedClient(
client,
testClientAccessBoundary
);
assert.deepStrictEqual(downscopedClient.credentials, {});
const tokenResponse = await downscopedClient.getAccessToken();
assert.deepStrictEqual(
tokenResponse.token,
stsSuccessfulResponse.access_token
);
assert.deepStrictEqual(
tokenResponse.token,
downscopedClient.credentials.access_token
);
assert.deepStrictEqual(
tokenResponse.expirationTime,
downscopedClient.credentials.expiry_date
);
scope.done();
});
it('should handle underlying token exchange errors', async () => {
const errorResponse: OAuthErrorResponse = {
error: 'invalid_request',
error_description: 'Invalid subject token',
error_uri: 'https://tools.ietf.org/html/rfc6749#section-5.2',
};
const scope = mockStsTokenExchange([
{
statusCode: 400,
response: errorResponse,
request: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
requested_token_type:
'urn:ietf:params:oauth:token-type:access_token',
subject_token: 'subject_token_0',
subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',
options: JSON.stringify(testClientAccessBoundary),
},
},
{
statusCode: 200,
response: stsSuccessfulResponse,
request: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
requested_token_type:
'urn:ietf:params:oauth:token-type:access_token',
subject_token: 'subject_token_1',
subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',
options: JSON.stringify(testClientAccessBoundary),
},
},
]);
const downscopedClient = new DownscopedClient(
client,
testClientAccessBoundary
);
assert.deepStrictEqual(downscopedClient.credentials, {});
await assert.rejects(
downscopedClient.getAccessToken(),
getErrorFromOAuthErrorResponse(errorResponse)
);
assert.deepStrictEqual(downscopedClient.credentials, {});
// Next try should succeed.
const actualResponse = await downscopedClient.getAccessToken();
delete actualResponse.res;
assert.deepStrictEqual(
actualResponse.token,
stsSuccessfulResponse.access_token
);
assert.deepStrictEqual(
actualResponse.token,
downscopedClient.credentials.access_token
);
assert.deepStrictEqual(
actualResponse.expirationTime,
downscopedClient.credentials.expiry_date
);
scope.done();
});
it('should throw when the source AuthClient rejects on token request', async () => {
const expectedError = new Error('Cannot get subject token.');
client.throwError = true;
const downscopedClient = new DownscopedClient(
client,
testClientAccessBoundary
);
await assert.rejects(downscopedClient.getAccessToken(), expectedError);
});
it('should copy source cred expiry time if STS response does not return expiry time', async () => {
const now = new Date().getTime();
const expireDate = now + ONE_HOUR_IN_SECS * 1000;
const stsSuccessfulResponseWithoutExpireInField = Object.assign(
{},
stsSuccessfulResponse
);
const emittedEvents: Credentials[] = [];
delete stsSuccessfulResponseWithoutExpireInField.expires_in;
const scope = mockStsTokenExchange([
{
statusCode: 200,
response: stsSuccessfulResponseWithoutExpireInField,
request: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
requested_token_type:
'urn:ietf:params:oauth:token-type:access_token',
subject_token: 'subject_token_0',
subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',
options: JSON.stringify(testClientAccessBoundary),
},
},
]);
client.expirationTime = expireDate;
const downscopedClient = new DownscopedClient(
client,
testClientAccessBoundary
);
// Listen to tokens events. On every event, push to list of
// emittedEvents.
downscopedClient.on('tokens', tokens => {
emittedEvents.push(tokens);
});
const tokenResponse = await downscopedClient.getAccessToken();
// tokens event should be triggered once with expected event.
assert.strictEqual(emittedEvents.length, 1);
assert.deepStrictEqual(emittedEvents[0], {
refresh_token: null,
expiry_date: expireDate,
access_token: stsSuccessfulResponseWithoutExpireInField.access_token,
token_type: 'Bearer',
id_token: null,
});
assert.deepStrictEqual(tokenResponse.expirationTime, expireDate);
assert.deepStrictEqual(
tokenResponse.token,
stsSuccessfulResponseWithoutExpireInField.access_token
);
assert.strictEqual(downscopedClient.credentials.expiry_date, expireDate);
assert.strictEqual(
downscopedClient.credentials.access_token,
stsSuccessfulResponseWithoutExpireInField.access_token
);
scope.done();
});
it('should have no expiry date if source cred has no expiry time and STS response does not return one', async () => {
const stsSuccessfulResponseWithoutExpireInField = Object.assign(
{},
stsSuccessfulResponse
);
const emittedEvents: Credentials[] = [];
delete stsSuccessfulResponseWithoutExpireInField.expires_in;
const scope = mockStsTokenExchange([
{
statusCode: 200,
response: stsSuccessfulResponseWithoutExpireInField,
request: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
requested_token_type:
'urn:ietf:params:oauth:token-type:access_token',
subject_token: 'subject_token_0',
subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',
options: JSON.stringify(testClientAccessBoundary),
},
},
]);
const downscopedClient = new DownscopedClient(
client,
testClientAccessBoundary
);
// Listen to tokens events. On every event, push to list of
// emittedEvents.
downscopedClient.on('tokens', tokens => {
emittedEvents.push(tokens);
});
const tokenResponse = await downscopedClient.getAccessToken();
// tokens event should be triggered once with expected event.
assert.strictEqual(emittedEvents.length, 1);
assert.deepStrictEqual(emittedEvents[0], {
refresh_token: null,
expiry_date: null,
access_token: stsSuccessfulResponseWithoutExpireInField.access_token,
token_type: 'Bearer',
id_token: null,
});
assert.deepStrictEqual(
tokenResponse.token,
stsSuccessfulResponseWithoutExpireInField.access_token
);
assert.deepStrictEqual(tokenResponse.expirationTime, null);
assert.deepStrictEqual(downscopedClient.credentials.expiry_date, null);
scope.done();
});
});
describe('getRequestHeader()', () => {
it('should inject the authorization headers', async () => {
const expectedHeaders = {
Authorization: `Bearer ${stsSuccessfulResponse.access_token}`,
};
const scope = mockStsTokenExchange([
{
statusCode: 200,
response: stsSuccessfulResponse,
request: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
requested_token_type:
'urn:ietf:params:oauth:token-type:access_token',
subject_token: 'subject_token_0',
subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',
options: JSON.stringify(testClientAccessBoundary),
},
},
]);
const cabClient = new DownscopedClient(client, testClientAccessBoundary);
const actualHeaders = await cabClient.getRequestHeaders();
assert.deepStrictEqual(actualHeaders, expectedHeaders);
scope.done();
});
it('should inject the authorization and metadata headers', async () => {
const quotaProjectId = 'QUOTA_PROJECT_ID';
const expectedHeaders = {
Authorization: `Bearer ${stsSuccessfulResponse.access_token}`,
'x-goog-user-project': quotaProjectId,
};
const scope = mockStsTokenExchange([
{
statusCode: 200,
response: stsSuccessfulResponse,
request: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
requested_token_type:
'urn:ietf:params:oauth:token-type:access_token',
subject_token: 'subject_token_0',
subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',
options: JSON.stringify(testClientAccessBoundary),
},
},
]);
const cabClient = new DownscopedClient(
client,
testClientAccessBoundary,
undefined,
quotaProjectId
);
const actualHeaders = await cabClient.getRequestHeaders();
assert.deepStrictEqual(expectedHeaders, actualHeaders);
scope.done();
});
it('should reject when error occurs during token retrieval', async () => {
const errorResponse: OAuthErrorResponse = {
error: 'invalid_request',
error_description: 'Invalid subject token',
error_uri: 'https://tools.ietf.org/html/rfc6749#section-5.2',
};
const scope = mockStsTokenExchange([
{
statusCode: 400,
response: errorResponse,
request: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
requested_token_type:
'urn:ietf:params:oauth:token-type:access_token',
subject_token: 'subject_token_0',
subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',
options: JSON.stringify(testClientAccessBoundary),
},
},
]);
const cabClient = new DownscopedClient(client, testClientAccessBoundary);
await assert.rejects(
cabClient.getRequestHeaders(),
getErrorFromOAuthErrorResponse(errorResponse)
);
scope.done();
});
});
describe('request()', () => {
it('should process HTTP request with authorization header', async () => {
const quotaProjectId = 'QUOTA_PROJECT_ID';
const authHeaders = {
Authorization: `Bearer ${stsSuccessfulResponse.access_token}`,
'x-goog-user-project': quotaProjectId,
};
const exampleRequest = {
key1: 'value1',
key2: 'value2',
};
const exampleResponse: SampleResponse = {
foo: 'a',
bar: 1,
};
const exampleHeaders = {
custom: 'some-header-value',
other: 'other-header-value',
};
const scopes = [
mockStsTokenExchange([
{
statusCode: 200,
response: stsSuccessfulResponse,
request: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
requested_token_type:
'urn:ietf:params:oauth:token-type:access_token',
subject_token: 'subject_token_0',
subject_token_type:
'urn:ietf:params:oauth:token-type:access_token',
options: JSON.stringify(testClientAccessBoundary),
},
},
]),
nock('https://example.com')
.post('/api', exampleRequest, {
reqheaders: Object.assign({}, exampleHeaders, authHeaders),
})
.reply(200, Object.assign({}, exampleResponse)),
];
const cabClient = new DownscopedClient(
client,
testClientAccessBoundary,
undefined,
quotaProjectId
);
const actualResponse = await cabClient.request<SampleResponse>({
url: 'https://example.com/api',
method: 'POST',
headers: exampleHeaders,
data: exampleRequest,
responseType: 'json',
});
assert.deepStrictEqual(actualResponse.data, exampleResponse);
scopes.forEach(scope => scope.done());
});
it('should process headerless HTTP request', async () => {
const quotaProjectId = 'QUOTA_PROJECT_ID';
const authHeaders = {
Authorization: `Bearer ${stsSuccessfulResponse.access_token}`,
'x-goog-user-project': quotaProjectId,
};
const exampleRequest = {
key1: 'value1',
key2: 'value2',
};
const exampleResponse: SampleResponse = {
foo: 'a',
bar: 1,
};
const scopes = [
mockStsTokenExchange([
{
statusCode: 200,
response: stsSuccessfulResponse,
request: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
requested_token_type:
'urn:ietf:params:oauth:token-type:access_token',
subject_token: 'subject_token_0',
subject_token_type:
'urn:ietf:params:oauth:token-type:access_token',
options: JSON.stringify(testClientAccessBoundary),
},
},
]),
nock('https://example.com')
.post('/api', exampleRequest, {
reqheaders: Object.assign({}, authHeaders),
})
.reply(200, Object.assign({}, exampleResponse)),
];
const cabClient = new DownscopedClient(
client,
testClientAccessBoundary,
undefined,
quotaProjectId
);
// Send request with no headers.
const actualResponse = await cabClient.request<SampleResponse>({
url: 'https://example.com/api',
method: 'POST',
data: exampleRequest,
responseType: 'json',
});
assert.deepStrictEqual(actualResponse.data, exampleResponse);
scopes.forEach(scope => scope.done());
});
it('should reject when error occurs during token retrieval', async () => {
const errorResponse: OAuthErrorResponse = {
error: 'invalid_request',
error_description: 'Invalid subject token',
error_uri: 'https://tools.ietf.org/html/rfc6749#section-5.2',
};
const exampleRequest = {
key1: 'value1',
key2: 'value2',
};
const scope = mockStsTokenExchange([
{
statusCode: 400,
response: errorResponse,
request: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
requested_token_type:
'urn:ietf:params:oauth:token-type:access_token',
subject_token: 'subject_token_0',
subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',
options: JSON.stringify(testClientAccessBoundary),
},
},
]);
const cabClient = new DownscopedClient(client, testClientAccessBoundary);
await assert.rejects(
cabClient.request<SampleResponse>({
url: 'https://example.com/api',
method: 'POST',
data: exampleRequest,
responseType: 'json',
}),
getErrorFromOAuthErrorResponse(errorResponse)
);
scope.done();
});
it('should trigger callback on success when provided', done => {
const authHeaders = {
Authorization: `Bearer ${stsSuccessfulResponse.access_token}`,
};
const exampleRequest = {
key1: 'value1',
key2: 'value2',
};
const exampleResponse: SampleResponse = {
foo: 'a',
bar: 1,
};
const exampleHeaders = {
custom: 'some-header-value',
other: 'other-header-value',
};
const scopes = [
mockStsTokenExchange([
{
statusCode: 200,
response: stsSuccessfulResponse,
request: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
requested_token_type:
'urn:ietf:params:oauth:token-type:access_token',
subject_token: 'subject_token_0',
subject_token_type:
'urn:ietf:params:oauth:token-type:access_token',
options: JSON.stringify(testClientAccessBoundary),
},
},
]),
nock('https://example.com')
.post('/api', exampleRequest, {
reqheaders: Object.assign({}, exampleHeaders, authHeaders),
})
.reply(200, Object.assign({}, exampleResponse)),
];
const cabClient = new DownscopedClient(client, testClientAccessBoundary);
cabClient.request<SampleResponse>(
{
url: 'https://example.com/api',
method: 'POST',
headers: exampleHeaders,
data: exampleRequest,
responseType: 'json',
},
(err, result) => {
assert.strictEqual(err, null);
assert.deepStrictEqual(result?.data, exampleResponse);
scopes.forEach(scope => scope.done());
done();
}
);
});
it('should trigger callback on error when provided', done => {
const errorMessage = 'Bad Request';
const authHeaders = {
Authorization: `Bearer ${stsSuccessfulResponse.access_token}`,
};
const exampleRequest = {
key1: 'value1',
key2: 'value2',
};
const exampleHeaders = {
custom: 'some-header-value',
other: 'other-header-value',
};
const scopes = [
mockStsTokenExchange([
{
statusCode: 200,
response: stsSuccessfulResponse,
request: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
requested_token_type:
'urn:ietf:params:oauth:token-type:access_token',
subject_token: 'subject_token_0',
subject_token_type:
'urn:ietf:params:oauth:token-type:access_token',
options: JSON.stringify(testClientAccessBoundary),
},
},
]),
nock('https://example.com')
.post('/api', exampleRequest, {
reqheaders: Object.assign({}, exampleHeaders, authHeaders),
})
.reply(400, errorMessage),
];
const cabClient = new DownscopedClient(client, testClientAccessBoundary);
cabClient.request<SampleResponse>(
{
url: 'https://example.com/api',
method: 'POST',
headers: exampleHeaders,
data: exampleRequest,
responseType: 'json',
},
(err, result) => {
assert.strictEqual(err!.message, errorMessage);
assert.deepStrictEqual(result, (err as GaxiosError)!.response);
scopes.forEach(scope => scope.done());
done();
}
);
});
it('should retry on 401 on forceRefreshOnFailure=true', async () => {
const stsSuccessfulResponse2 = Object.assign({}, stsSuccessfulResponse);
stsSuccessfulResponse2.access_token = 'DOWNSCOPED_CLIENT_ACCESS_TOKEN_1';
const authHeaders = {
Authorization: `Bearer ${stsSuccessfulResponse.access_token}`,
};
const authHeaders2 = {
Authorization: `Bearer ${stsSuccessfulResponse2.access_token}`,
};
const exampleRequest = {
key1: 'value1',
key2: 'value2',
};
const exampleResponse: SampleResponse = {
foo: 'a',
bar: 1,
};
const exampleHeaders = {
custom: 'some-header-value',
other: 'other-header-value',
};
const scopes = [
mockStsTokenExchange([
{
statusCode: 200,
response: stsSuccessfulResponse,
request: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
requested_token_type:
'urn:ietf:params:oauth:token-type:access_token',
subject_token: 'subject_token_0',
subject_token_type:
'urn:ietf:params:oauth:token-type:access_token',
options: JSON.stringify(testClientAccessBoundary),
},
},
{
statusCode: 200,
response: stsSuccessfulResponse2,
request: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
requested_token_type:
'urn:ietf:params:oauth:token-type:access_token',
subject_token: 'subject_token_1',
subject_token_type:
'urn:ietf:params:oauth:token-type:access_token',
options: JSON.stringify(testClientAccessBoundary),
},
},
]),
nock('https://example.com')
.post('/api', exampleRequest, {
reqheaders: Object.assign({}, exampleHeaders, authHeaders),
})
.reply(401)
.post('/api', exampleRequest, {
reqheaders: Object.assign({}, exampleHeaders, authHeaders2),
})
.reply(200, Object.assign({}, exampleResponse)),
];
const cabClient = new DownscopedClient(client, testClientAccessBoundary, {
forceRefreshOnFailure: true,
});
const actualResponse = await cabClient.request<SampleResponse>({
url: 'https://example.com/api',
method: 'POST',
headers: exampleHeaders,
data: exampleRequest,
responseType: 'json',
});
assert.deepStrictEqual(actualResponse.data, exampleResponse);
scopes.forEach(scope => scope.done());
});
it('should not retry on 401 on forceRefreshOnFailure=false', async () => {
const authHeaders = {
Authorization: `Bearer ${stsSuccessfulResponse.access_token}`,
};
const exampleRequest = {
key1: 'value1',
key2: 'value2',
};
const exampleHeaders = {
custom: 'some-header-value',
other: 'other-header-value',
};
const scopes = [
mockStsTokenExchange([
{
statusCode: 200,
response: stsSuccessfulResponse,
request: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
requested_token_type:
'urn:ietf:params:oauth:token-type:access_token',
subject_token: 'subject_token_0',
subject_token_type:
'urn:ietf:params:oauth:token-type:access_token',
options: JSON.stringify(testClientAccessBoundary),
},
},
]),
nock('https://example.com')
.post('/api', exampleRequest, {
reqheaders: Object.assign({}, exampleHeaders, authHeaders),
})
.reply(401),
];
const cabClient = new DownscopedClient(client, testClientAccessBoundary, {
forceRefreshOnFailure: false,
});
await assert.rejects(
cabClient.request<SampleResponse>({
url: 'https://example.com/api',
method: 'POST',
headers: exampleHeaders,
data: exampleRequest,
responseType: 'json',
}),
{
code: '401',
}
);
scopes.forEach(scope => scope.done());
});
it('should not retry more than once', async () => {
const stsSuccessfulResponse2 = Object.assign({}, stsSuccessfulResponse);
stsSuccessfulResponse2.access_token = 'DOWNSCOPED_CLIENT_ACCESS_TOKEN_1';
const authHeaders = {
Authorization: `Bearer ${stsSuccessfulResponse.access_token}`,
};
const authHeaders2 = {
Authorization: `Bearer ${stsSuccessfulResponse2.access_token}`,
};
const exampleRequest = {
key1: 'value1',
key2: 'value2',
};
const exampleHeaders = {
custom: 'some-header-value',
other: 'other-header-value',
};
const scopes = [
mockStsTokenExchange([
{
statusCode: 200,
response: stsSuccessfulResponse,
request: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
requested_token_type:
'urn:ietf:params:oauth:token-type:access_token',
subject_token: 'subject_token_0',
subject_token_type:
'urn:ietf:params:oauth:token-type:access_token',
options: JSON.stringify(testClientAccessBoundary),
},
},
{
statusCode: 200,
response: stsSuccessfulResponse2,
request: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
requested_token_type:
'urn:ietf:params:oauth:token-type:access_token',
subject_token: 'subject_token_1',
subject_token_type:
'urn:ietf:params:oauth:token-type:access_token',
options: JSON.stringify(testClientAccessBoundary),
},
},
]),
nock('https://example.com')
.post('/api', exampleRequest, {
reqheaders: Object.assign({}, exampleHeaders, authHeaders),
})
.reply(403)
.post('/api', exampleRequest, {
reqheaders: Object.assign({}, exampleHeaders, authHeaders2),
})
.reply(403),
];
const cabClient = new DownscopedClient(client, testClientAccessBoundary, {
forceRefreshOnFailure: true,
});
await assert.rejects(
cabClient.request<SampleResponse>({
url: 'https://example.com/api',
method: 'POST',
headers: exampleHeaders,
data: exampleRequest,
responseType: 'json',
}),
{
code: '403',
}
);
scopes.forEach(scope => scope.done());
});
});
}); | the_stack |
import { createCommentVNode, defineComponent, h, ref, Ref, PropType, inject, nextTick, ComputedRef, onBeforeUnmount, onMounted } from 'vue'
import XEUtils from 'xe-utils'
import GlobalConfig from '../../v-x-e-table/src/conf'
import { VXETable } from '../../v-x-e-table'
import { mergeBodyMethod, getRowid, getPropClass, removeScrollListener, restoreScrollListener, XEBodyScrollElement } from './util'
import { browse, updateCellTitle } from '../../tools/dom'
import { isEnableConf } from '../../tools/utils'
import { VxeTablePrivateMethods, VxeTableConstructor, VxeTableDefines, VxeTableMethods, VxeGlobalRendererHandles, VxeColumnPropTypes, SizeType } from '../../../types/all'
const renderType = 'body'
const lineOffsetSizes = {
mini: 3,
small: 2,
medium: 1
}
export default defineComponent({
name: 'VxeTableBody',
props: {
tableData: Array as PropType<any[]>,
tableColumn: Array as PropType<VxeTableDefines.ColumnInfo[]>,
fixedColumn: Array as PropType<VxeTableDefines.ColumnInfo[]>,
fixedType: { type: String as PropType<VxeColumnPropTypes.Fixed>, default: null }
},
setup (props) {
const $xetable = inject('$xetable', {} as VxeTableConstructor & VxeTableMethods & VxeTablePrivateMethods)
const xesize = inject('xesize', null as ComputedRef<SizeType> | null)
const { xID, props: tableProps, context: tableContext, reactData: tableReactData, internalData: tableInternalData } = $xetable
const { refTableHeader, refTableBody, refTableFooter, refTableLeftBody, refTableRightBody, refValidTooltip } = $xetable.getRefMaps()
const { computeEditOpts, computeMouseOpts, computeSYOpts, computeEmptyOpts, computeKeyboardOpts, computeTooltipOpts, computeRadioOpts, computeTreeOpts, computeCheckboxOpts, computeValidOpts } = $xetable.getComputeMaps()
const refElem = ref() as Ref<XEBodyScrollElement>
const refBodyTable = ref() as Ref<HTMLTableElement>
const refBodyColgroup = ref() as Ref<HTMLTableColElement>
const refBodyTBody = ref() as Ref<HTMLTableSectionElement>
const refBodyXSpace = ref() as Ref<HTMLDivElement>
const refBodyYSpace = ref() as Ref<HTMLDivElement>
const refBodyEmptyBlock = ref() as Ref<HTMLDivElement>
const getOffsetSize = () => {
if (xesize) {
const vSize = xesize.value
if (vSize) {
return lineOffsetSizes[vSize] || 0
}
}
return 0
}
const countTreeExpand = (prevRow: any, params: any) => {
const treeOpts = computeTreeOpts.value
const rowChildren = prevRow[treeOpts.children]
let count = 1
if ($xetable.isTreeExpandByRow(prevRow)) {
for (let index = 0; index < rowChildren.length; index++) {
count += countTreeExpand(rowChildren[index], params)
}
}
return count
}
const calcTreeLine = (params: any, items: any[]) => {
const { $rowIndex } = params
let expandSize = 1
if ($rowIndex) {
expandSize = countTreeExpand(items[$rowIndex - 1], params)
}
return tableReactData.rowHeight * expandSize - ($rowIndex ? 1 : (12 - getOffsetSize()))
}
// 滚动、拖动过程中不需要触发
const isOperateMouse = () => {
const { delayHover } = tableProps
const { lastScrollTime, _isResize } = tableInternalData
return _isResize || (lastScrollTime && Date.now() < lastScrollTime + (delayHover as number))
}
const renderLine = (rowLevel: number, items: any[], params: any) => {
const { column } = params
const { treeConfig } = tableProps
const treeOpts = computeTreeOpts.value
const { slots, treeNode } = column
if (slots && slots.line) {
return $xetable.callSlot(slots.line, params)
}
if (treeConfig && treeNode && treeOpts.line) {
return [
h('div', {
class: 'vxe-tree--line-wrapper'
}, [
h('div', {
class: 'vxe-tree--line',
style: {
height: `${calcTreeLine(params, items)}px`,
left: `${(rowLevel * treeOpts.indent) + (rowLevel ? 2 - getOffsetSize() : 0) + 16}px`
}
})
])
]
}
return []
}
/**
* 渲染列
*/
const renderColumn = ($seq: string, seq: number, rowid: string, fixedType: any, rowLevel: number, row: any, rowIndex: number, $rowIndex: number, _rowIndex: number, column: any, $columnIndex: number, columns: any, items: any[]) => {
const { columnKey, height, showOverflow: allColumnOverflow, cellClassName, cellStyle, align: allAlign, spanMethod, mouseConfig, editConfig, editRules, tooltipConfig } = tableProps
const { tableData, overflowX, scrollXLoad, scrollYLoad, currentColumn, mergeList, editStore, validStore, isAllOverflow } = tableReactData
const { afterFullData } = tableInternalData
const validOpts = computeValidOpts.value
const checkboxOpts = computeCheckboxOpts.value
const editOpts = computeEditOpts.value
const tooltipOpts = computeTooltipOpts.value
const sYOpts = computeSYOpts.value
const { type, cellRender, editRender, align, showOverflow, className, treeNode } = column
const { actived } = editStore
const { rHeight } = sYOpts
const showAllTip = tooltipOpts.showAll
const columnIndex = $xetable.getColumnIndex(column)
const _columnIndex = $xetable.getVTColumnIndex(column)
const isEdit = isEnableConf(editRender)
let fixedHiddenColumn = fixedType ? column.fixed !== fixedType : column.fixed && overflowX
const cellOverflow = (XEUtils.isUndefined(showOverflow) || XEUtils.isNull(showOverflow)) ? allColumnOverflow : showOverflow
let showEllipsis = cellOverflow === 'ellipsis'
const showTitle = cellOverflow === 'title'
const showTooltip = cellOverflow === true || cellOverflow === 'tooltip'
let hasEllipsis = showTitle || showTooltip || showEllipsis
let isDirty
const tdOns: any = {}
const cellAlign = align || allAlign
const hasValidError = validStore.row === row && validStore.column === column
const showValidTip = editRules && validOpts.showMessage && (validOpts.message === 'default' ? (height || tableData.length > 1) : validOpts.message === 'inline')
const attrs: any = { colid: column.id }
const params: VxeTableDefines.CellRenderBodyParams = { $table: $xetable, $seq, seq, rowid, row, rowIndex, $rowIndex, _rowIndex, column, columnIndex, $columnIndex, _columnIndex, fixed: fixedType, type: renderType, isHidden: fixedHiddenColumn, level: rowLevel, visibleData: afterFullData, data: tableData, items }
// 虚拟滚动不支持动态高度
if ((scrollXLoad || scrollYLoad) && !hasEllipsis) {
showEllipsis = hasEllipsis = true
}
// hover 进入事件
if (showTitle || showTooltip || showAllTip || tooltipConfig) {
tdOns.onMouseenter = (evnt: MouseEvent) => {
if (isOperateMouse()) {
return
}
if (showTitle) {
updateCellTitle(evnt.currentTarget, column)
} else if (showTooltip || showAllTip) {
// 如果配置了显示 tooltip
$xetable.triggerBodyTooltipEvent(evnt, params)
}
$xetable.dispatchEvent('cell-mouseenter', Object.assign({ cell: evnt.currentTarget }, params), evnt)
}
}
// hover 退出事件
if (showTooltip || showAllTip || tooltipConfig) {
tdOns.onMouseleave = (evnt: MouseEvent) => {
if (isOperateMouse()) {
return
}
if (showTooltip || showAllTip) {
$xetable.handleTargetLeaveEvent(evnt)
}
$xetable.dispatchEvent('cell-mouseleave', Object.assign({ cell: evnt.currentTarget }, params), evnt)
}
}
// 按下事件处理
if (checkboxOpts.range || mouseConfig) {
tdOns.onMousedown = (evnt: MouseEvent) => {
$xetable.triggerCellMousedownEvent(evnt, params)
}
}
// 点击事件处理
tdOns.onClick = (evnt: MouseEvent) => {
$xetable.triggerCellClickEvent(evnt, params)
}
// 双击事件处理
tdOns.onDblclick = (evnt: MouseEvent) => {
$xetable.triggerCellDblclickEvent(evnt, params)
}
// 合并行或列
if (mergeList.length) {
const spanRest = mergeBodyMethod(mergeList, _rowIndex, _columnIndex)
if (spanRest) {
const { rowspan, colspan } = spanRest
if (!rowspan || !colspan) {
return null
}
if (rowspan > 1) {
attrs.rowspan = rowspan
}
if (colspan > 1) {
attrs.colspan = colspan
}
}
} else if (spanMethod) {
// 自定义合并行或列的方法
const { rowspan = 1, colspan = 1 } = spanMethod(params) || {}
if (!rowspan || !colspan) {
return null
}
if (rowspan > 1) {
attrs.rowspan = rowspan
}
if (colspan > 1) {
attrs.colspan = colspan
}
}
// 如果被合并不可隐藏
if (fixedHiddenColumn && mergeList) {
if (attrs.colspan > 1 || attrs.rowspan > 1) {
fixedHiddenColumn = false
}
}
// 如果编辑列开启显示状态
if (!fixedHiddenColumn && editConfig && (editRender || cellRender) && (editOpts.showStatus || editOpts.showUpdateStatus)) {
isDirty = $xetable.isUpdateByRow(row, column.property)
}
const tdVNs = []
if (fixedHiddenColumn && (allColumnOverflow ? isAllOverflow : allColumnOverflow)) {
tdVNs.push(
h('div', {
class: ['vxe-cell', {
'c--title': showTitle,
'c--tooltip': showTooltip,
'c--ellipsis': showEllipsis
}],
style: {
maxHeight: hasEllipsis && rHeight ? `${rHeight}px` : ''
}
})
)
} else {
// 渲染单元格
tdVNs.push(
...renderLine(rowLevel, items, params),
h('div', {
class: ['vxe-cell', {
'c--title': showTitle,
'c--tooltip': showTooltip,
'c--ellipsis': showEllipsis
}],
style: {
maxHeight: hasEllipsis && rHeight ? `${rHeight}px` : ''
},
title: showTitle ? $xetable.getCellLabel(row, column) : null
}, column.renderCell(params))
)
if (showValidTip && hasValidError) {
tdVNs.push(
h('div', {
class: 'vxe-cell--valid',
style: validStore.rule && validStore.rule.maxWidth ? {
width: `${validStore.rule.maxWidth}px`
} : null
}, [
h('span', {
class: 'vxe-cell--valid-msg'
}, validStore.content)
])
)
}
}
return h('td', {
class: ['vxe-body--column', column.id, {
[`col--${cellAlign}`]: cellAlign,
[`col--${type}`]: type,
'col--last': $columnIndex === columns.length - 1,
'col--tree-node': treeNode,
'col--edit': isEdit,
'col--ellipsis': hasEllipsis,
'fixed--hidden': fixedHiddenColumn,
'col--dirty': isDirty,
'col--actived': editConfig && isEdit && (actived.row === row && (actived.column === column || editOpts.mode === 'row')),
'col--valid-error': hasValidError,
'col--current': currentColumn === column
}, getPropClass(className, params), getPropClass(cellClassName, params)],
key: columnKey ? column.id : $columnIndex,
...attrs,
style: Object.assign({
height: hasEllipsis && rHeight ? `${rHeight}px` : ''
}, cellStyle ? (XEUtils.isFunction(cellStyle) ? cellStyle(params) : cellStyle) : null),
...tdOns
}, tdVNs)
}
const renderRows = ($seq: string, rowLevel: any, fixedType: any, tableData: any, tableColumn: any) => {
const { stripe, rowKey, highlightHoverRow, rowClassName, rowStyle, showOverflow: allColumnOverflow, editConfig, treeConfig } = tableProps
const { hasFixedColumn, treeExpandeds, scrollYLoad, editStore, rowExpandeds, expandColumn, selectRow } = tableReactData
const { scrollYStore } = tableInternalData
const checkboxOpts = computeCheckboxOpts.value
const radioOpts = computeRadioOpts.value
const treeOpts = computeTreeOpts.value
const editOpts = computeEditOpts.value
const rows: any[] = []
tableData.forEach((row: any, $rowIndex: any) => {
const trOn: any = {}
let rowIndex = $rowIndex
let seq = rowIndex + 1
if (scrollYLoad) {
seq += scrollYStore.startIndex
}
const _rowIndex = $xetable.getVTRowIndex(row)
// 确保任何情况下 rowIndex 都精准指向真实 data 索引
rowIndex = $xetable.getRowIndex(row)
// 事件绑定
if (highlightHoverRow) {
trOn.onMouseenter = (evnt: any) => {
if (isOperateMouse()) {
return
}
$xetable.triggerHoverEvent(evnt, { row, rowIndex })
}
trOn.onMouseleave = () => {
if (isOperateMouse()) {
return
}
$xetable.clearHoverRow()
}
}
const rowid = getRowid($xetable, row)
const params = { $table: $xetable, $seq, seq, rowid, fixed: fixedType, type: renderType, level: rowLevel, row, rowIndex, $rowIndex, _rowIndex }
let isNewRow = false
if (editConfig) {
isNewRow = $xetable.findRowIndexOf(editStore.insertList, row) > -1
}
rows.push(
h('tr', {
class: ['vxe-body--row', {
'row--stripe': stripe && ($xetable.getVTRowIndex(row) + 1) % 2 === 0,
'is--new': isNewRow,
'row--new': isNewRow && (editOpts.showStatus || editOpts.showInsertStatus),
'row--radio': radioOpts.highlight && selectRow === row,
'row--checked': checkboxOpts.highlight && $xetable.isCheckedByCheckboxRow(row)
}, rowClassName ? (XEUtils.isFunction(rowClassName) ? rowClassName(params) : rowClassName) : ''],
rowid: rowid,
style: rowStyle ? (XEUtils.isFunction(rowStyle) ? rowStyle(params) : rowStyle) : null,
key: rowKey || treeConfig ? rowid : $rowIndex,
...trOn
}, tableColumn.map((column: any, $columnIndex: any) => {
return renderColumn($seq, seq, rowid, fixedType, rowLevel, row, rowIndex, $rowIndex, _rowIndex, column, $columnIndex, tableColumn, tableData)
}))
)
// 如果行被展开了
if (expandColumn && rowExpandeds.length && $xetable.findRowIndexOf(rowExpandeds, row) > -1) {
let cellStyle
if (treeConfig) {
cellStyle = {
paddingLeft: `${(rowLevel * treeOpts.indent) + 30}px`
}
}
const { showOverflow } = expandColumn
const hasEllipsis = (XEUtils.isUndefined(showOverflow) || XEUtils.isNull(showOverflow)) ? allColumnOverflow : showOverflow
const expandParams = { $table: $xetable, $seq, seq, column: expandColumn, fixed: fixedType, type: renderType, level: rowLevel, row, rowIndex, $rowIndex, _rowIndex }
rows.push(
h('tr', {
class: 'vxe-body--expanded-row',
key: `expand_${rowid}`,
style: rowStyle ? (XEUtils.isFunction(rowStyle) ? rowStyle(expandParams) : rowStyle) : null,
...trOn
}, [
h('td', {
class: ['vxe-body--expanded-column', {
'fixed--hidden': fixedType && !hasFixedColumn,
'col--ellipsis': hasEllipsis
}],
colspan: tableColumn.length
}, [
h('div', {
class: 'vxe-body--expanded-cell',
style: cellStyle
}, [
expandColumn.renderData(expandParams)
])
])
])
)
}
// 如果是树形表格
if (treeConfig && treeExpandeds.length) {
const rowChildren = row[treeOpts.children]
if (rowChildren && rowChildren.length && $xetable.findRowIndexOf(treeExpandeds, row) > -1) {
rows.push(...renderRows($seq ? `${$seq}.${seq}` : `${seq}`, rowLevel + 1, fixedType, rowChildren, tableColumn))
}
}
})
return rows
}
/**
* 同步滚动条
*/
let scrollProcessTimeout: any
const syncBodyScroll = (scrollTop: number, elem1: XEBodyScrollElement | null, elem2: XEBodyScrollElement | null) => {
if (elem1 || elem2) {
if (elem1) {
removeScrollListener(elem1)
elem1.scrollTop = scrollTop
}
if (elem2) {
removeScrollListener(elem2)
elem2.scrollTop = scrollTop
}
clearTimeout(scrollProcessTimeout)
scrollProcessTimeout = setTimeout(function () {
restoreScrollListener(elem1)
restoreScrollListener(elem2)
}, 300)
}
}
/**
* 滚动处理
* 如果存在列固定左侧,同步更新滚动状态
* 如果存在列固定右侧,同步更新滚动状态
*/
const scrollEvent = (evnt: Event) => {
const { fixedType } = props
const { highlightHoverRow } = tableProps
const { scrollXLoad, scrollYLoad } = tableReactData
const { elemStore, lastScrollTop, lastScrollLeft } = tableInternalData
const tableHeader = refTableHeader.value
const tableBody = refTableBody.value
const tableFooter = refTableFooter.value
const leftBody = refTableLeftBody.value
const rightBody = refTableRightBody.value
const validTip = refValidTooltip.value
const scrollBodyElem = refElem.value
const headerElem = tableHeader ? tableHeader.$el as HTMLDivElement : null
const footerElem = tableFooter ? tableFooter.$el as HTMLDivElement : null
const bodyElem = tableBody.$el as XEBodyScrollElement
const leftElem = leftBody ? leftBody.$el as XEBodyScrollElement : null
const rightElem = rightBody ? rightBody.$el as XEBodyScrollElement : null
const bodyYElem = elemStore['main-body-ySpace']
const bodyXElem = elemStore['main-body-xSpace']
const bodyHeight = bodyYElem ? bodyYElem.clientHeight : 0
const bodyWidth = bodyXElem ? bodyXElem.clientWidth : 0
let scrollTop = scrollBodyElem.scrollTop
const scrollLeft = bodyElem.scrollLeft
const isRollX = scrollLeft !== lastScrollLeft
const isRollY = scrollTop !== lastScrollTop
tableInternalData.lastScrollTop = scrollTop
tableInternalData.lastScrollLeft = scrollLeft
tableInternalData.lastScrollTime = Date.now()
if (highlightHoverRow) {
$xetable.clearHoverRow()
}
if (leftElem && fixedType === 'left') {
scrollTop = leftElem.scrollTop
syncBodyScroll(scrollTop, bodyElem, rightElem)
} else if (rightElem && fixedType === 'right') {
scrollTop = rightElem.scrollTop
syncBodyScroll(scrollTop, bodyElem, leftElem)
} else {
if (isRollX) {
if (headerElem) {
headerElem.scrollLeft = bodyElem.scrollLeft
}
if (footerElem) {
footerElem.scrollLeft = bodyElem.scrollLeft
}
}
if (leftElem || rightElem) {
$xetable.checkScrolling()
if (isRollY) {
syncBodyScroll(scrollTop, leftElem, rightElem)
}
}
}
if (scrollXLoad && isRollX) {
$xetable.triggerScrollXEvent(evnt)
}
if (scrollYLoad && isRollY) {
$xetable.triggerScrollYEvent(evnt)
}
if (isRollX && validTip && validTip.reactData.visible) {
validTip.updatePlacement()
}
$xetable.dispatchEvent('scroll', { type: renderType, fixed: fixedType, scrollTop, scrollLeft, bodyHeight, bodyWidth, isX: isRollX, isY: isRollY }, evnt)
}
let wheelTime: any
let wheelYSize = 0
let wheelYInterval = 0
let wheelYTotal = 0
let isPrevWheelTop = false
const handleWheel = (evnt: WheelEvent, isTopWheel: boolean, deltaTop: number, isRollX: boolean, isRollY: boolean) => {
const { elemStore } = tableInternalData
const tableBody = refTableBody.value
const leftBody = refTableLeftBody.value
const rightBody = refTableRightBody.value
const leftElem = leftBody ? leftBody.$el as HTMLDivElement : null
const rightElem = rightBody ? rightBody.$el as HTMLDivElement : null
const bodyElem = tableBody.$el as HTMLDivElement
const bodyYElem = elemStore['main-body-ySpace']
const bodyXElem = elemStore['main-body-xSpace']
const bodyHeight = bodyYElem ? bodyYElem.clientHeight : 0
const bodyWidth = bodyXElem ? bodyXElem.clientWidth : 0
const remainSize = isPrevWheelTop === isTopWheel ? Math.max(0, wheelYSize - wheelYTotal) : 0
isPrevWheelTop = isTopWheel
wheelYSize = Math.abs(isTopWheel ? deltaTop - remainSize : deltaTop + remainSize)
wheelYInterval = 0
wheelYTotal = 0
clearTimeout(wheelTime)
const handleSmooth = () => {
if (wheelYTotal < wheelYSize) {
const { fixedType } = props
wheelYInterval = Math.max(5, Math.floor(wheelYInterval * 1.5))
wheelYTotal = wheelYTotal + wheelYInterval
if (wheelYTotal > wheelYSize) {
wheelYInterval = wheelYInterval - (wheelYTotal - wheelYSize)
}
const { scrollTop, clientHeight, scrollHeight } = bodyElem
const targerTop = scrollTop + (wheelYInterval * (isTopWheel ? -1 : 1))
bodyElem.scrollTop = targerTop
if (leftElem) {
leftElem.scrollTop = targerTop
}
if (rightElem) {
rightElem.scrollTop = targerTop
}
if (isTopWheel ? targerTop < scrollHeight - clientHeight : targerTop >= 0) {
wheelTime = setTimeout(handleSmooth, 10)
}
$xetable.dispatchEvent('scroll', { type: renderType, fixed: fixedType, scrollTop: bodyElem.scrollTop, scrollLeft: bodyElem.scrollLeft, bodyHeight, bodyWidth, isX: isRollX, isY: isRollY }, evnt)
}
}
handleSmooth()
}
/**
* 滚轮处理
*/
const wheelEvent = (evnt: WheelEvent) => {
const { deltaY, deltaX } = evnt
const { highlightHoverRow } = tableProps
const { scrollYLoad } = tableReactData
const { lastScrollTop, lastScrollLeft } = tableInternalData
const tableBody = refTableBody.value
const scrollBodyElem = refElem.value
const bodyElem = tableBody.$el as HTMLDivElement
const deltaTop = browse.firefox ? deltaY * 40 : deltaY
const deltaLeft = browse.firefox ? deltaX * 40 : deltaX
const isTopWheel = deltaTop < 0
// 如果滚动位置已经是顶部或底部,则不需要触发
if (isTopWheel ? scrollBodyElem.scrollTop <= 0 : scrollBodyElem.scrollTop >= scrollBodyElem.scrollHeight - scrollBodyElem.clientHeight) {
return
}
const scrollTop = scrollBodyElem.scrollTop + deltaTop
const scrollLeft = bodyElem.scrollLeft + deltaLeft
const isRollX = scrollLeft !== lastScrollLeft
const isRollY = scrollTop !== lastScrollTop
// 用于鼠标纵向滚轮处理
if (isRollY) {
evnt.preventDefault()
tableInternalData.lastScrollTop = scrollTop
tableInternalData.lastScrollLeft = scrollLeft
tableInternalData.lastScrollTime = Date.now()
if (highlightHoverRow) {
$xetable.clearHoverRow()
}
handleWheel(evnt, isTopWheel, deltaTop, isRollX, isRollY)
if (scrollYLoad) {
$xetable.triggerScrollYEvent(evnt)
}
}
}
onMounted(() => {
nextTick(() => {
const { fixedType } = props
const { elemStore } = tableInternalData
const prefix = `${fixedType || 'main'}-body-`
const el = refElem.value
elemStore[`${prefix}wrapper`] = refElem.value
elemStore[`${prefix}table`] = refBodyTable.value
elemStore[`${prefix}colgroup`] = refBodyColgroup.value
elemStore[`${prefix}list`] = refBodyTBody.value
elemStore[`${prefix}xSpace`] = refBodyXSpace.value
elemStore[`${prefix}ySpace`] = refBodyYSpace.value
elemStore[`${prefix}emptyBlock`] = refBodyEmptyBlock.value
el.onscroll = scrollEvent
el._onscroll = scrollEvent
})
})
onBeforeUnmount(() => {
const el = refElem.value
clearTimeout(wheelTime)
el._onscroll = null
el.onscroll = null
})
const renderVN = () => {
let { fixedColumn, fixedType, tableColumn } = props
const { keyboardConfig, showOverflow: allColumnOverflow, spanMethod, mouseConfig } = tableProps
const { tableData, mergeList, scrollXLoad, scrollYLoad, isAllOverflow } = tableReactData
const { visibleColumn } = tableInternalData
const { slots } = tableContext
const sYOpts = computeSYOpts.value
const emptyOpts = computeEmptyOpts.value
const keyboardOpts = computeKeyboardOpts.value
const mouseOpts = computeMouseOpts.value
// const isMergeLeftFixedExceeded = computeIsMergeLeftFixedExceeded.value
// const isMergeRightFixedExceeded = computeIsMergeRightFixedExceeded.value
// 如果是使用优化模式
if (fixedType) {
if (scrollXLoad || scrollYLoad || (allColumnOverflow ? isAllOverflow : allColumnOverflow)) {
if (!mergeList.length && !spanMethod && !(keyboardConfig && keyboardOpts.isMerge)) {
tableColumn = fixedColumn
} else {
tableColumn = visibleColumn
// 检查固定列是否被合并,合并范围是否超出固定列
// if (mergeList.length && !isMergeLeftFixedExceeded && fixedType === 'left') {
// tableColumn = fixedColumn
// } else if (mergeList.length && !isMergeRightFixedExceeded && fixedType === 'right') {
// tableColumn = fixedColumn
// } else {
// tableColumn = visibleColumn
// }
}
} else {
tableColumn = visibleColumn
}
}
let emptyContent: string | VxeGlobalRendererHandles.RenderResult
if (slots.empty) {
emptyContent = $xetable.callSlot(slots.empty, { $table: $xetable })
} else {
const compConf = emptyOpts.name ? VXETable.renderer.get(emptyOpts.name) : null
const renderEmpty = compConf ? compConf.renderEmpty : null
if (renderEmpty) {
emptyContent = renderEmpty(emptyOpts, { $table: $xetable })
} else {
emptyContent = tableProps.emptyText || GlobalConfig.i18n('vxe.table.emptyText')
}
}
return h('div', {
ref: refElem,
class: ['vxe-table--body-wrapper', fixedType ? `fixed-${fixedType}--wrapper` : 'body--wrapper'],
xid: xID,
...(scrollYLoad && sYOpts.mode === 'wheel' ? { onWheel: wheelEvent } : {})
}, [
fixedType ? createCommentVNode() : h('div', {
ref: refBodyXSpace,
class: 'vxe-body--x-space'
}),
h('div', {
ref: refBodyYSpace,
class: 'vxe-body--y-space'
}),
h('table', {
ref: refBodyTable,
class: 'vxe-table--body',
xid: xID,
cellspacing: 0,
cellpadding: 0,
border: 0
}, [
/**
* 列宽
*/
h('colgroup', {
ref: refBodyColgroup
}, (tableColumn as any[]).map((column, $columnIndex) => {
return h('col', {
name: column.id,
key: $columnIndex
})
})),
/**
* 内容
*/
h('tbody', {
ref: refBodyTBody
}, renderRows('', 0, fixedType, tableData, tableColumn))
]),
h('div', {
class: 'vxe-table--checkbox-range'
}),
mouseConfig && mouseOpts.area ? h('div', {
class: 'vxe-table--cell-area'
}, [
h('span', {
class: 'vxe-table--cell-main-area'
}, mouseOpts.extension ? [
h('span', {
class: 'vxe-table--cell-main-area-btn',
onMousedown (evnt: any) {
$xetable.triggerCellExtendMousedownEvent(evnt, { $table: $xetable, fixed: fixedType, type: renderType })
}
})
] : []),
h('span', {
class: 'vxe-table--cell-copy-area'
}),
h('span', {
class: 'vxe-table--cell-extend-area'
}),
h('span', {
class: 'vxe-table--cell-multi-area'
}),
h('span', {
class: 'vxe-table--cell-active-area'
})
]) : null,
!fixedType ? h('div', {
class: 'vxe-table--empty-block',
ref: refBodyEmptyBlock
}, [
h('div', {
class: 'vxe-table--empty-content'
}, emptyContent)
]) : null
])
}
return renderVN
}
}) | the_stack |
import * as assert from 'assert';
import {describe, it, after, afterEach, before} from 'mocha';
// This is imported only for types. Generated .js file should NOT load 'http2'
// in this place. It is dynamically loaded later from each test suite below.
// eslint-disable-next-line node/no-unsupported-features/node-builtins
import * as http2Types from 'http2';
import * as semver from 'semver';
import * as stream from 'stream';
import {Constants, SpanType} from '../../src/constants';
import {TraceLabels} from '../../src/trace-labels';
import * as traceTestModule from '../trace';
import {
assertSpanDuration,
DEFAULT_SPAN_DURATION,
hasContext,
SERVER_CERT,
SERVER_KEY,
} from '../utils';
const serverRes = '1729';
const serverPort = 9042;
const maybeSkipHttp2 = semver.satisfies(process.version, '<8')
? describe.skip
: describe;
maybeSkipHttp2('Trace Agent integration with http2', () => {
let http2: typeof http2Types;
before(() => {
traceTestModule.setPluginLoaderForTest();
traceTestModule.setCLSForTest();
traceTestModule.start();
// eslint-disable-next-line node/no-unsupported-features/node-builtins
http2 = require('http2');
});
after(() => {
traceTestModule.setPluginLoaderForTest(traceTestModule.TestPluginLoader);
traceTestModule.setCLSForTest(traceTestModule.TestCLS);
});
afterEach(() => {
traceTestModule.clearTraceData();
});
describe('test-trace-http2', () => {
let server: http2Types.Http2Server;
before(() => {
server = http2.createServer();
server.on('stream', s => {
setTimeout(() => {
s.respond({':status': 200});
s.end(serverRes);
}, DEFAULT_SPAN_DURATION);
});
});
afterEach(done => {
if (server.listening) {
server.close(done);
} else {
done();
}
});
it('should patch the necessary functions', () => {
assert.strictEqual(http2.connect['__wrapped'], true);
});
it('should accurately measure request time', done => {
server.listen(serverPort, () => {
traceTestModule.get().runInRootSpan({name: 'outer'}, rootSpan => {
assert.ok(rootSpan.type === SpanType.ROOT);
const start = Date.now();
const session = http2.connect(`http://localhost:${serverPort}`);
const s = session.request({':path': '/'});
s.setEncoding('utf8');
let result = '';
s.on('data', (data: string) => {
result += data;
}).on('end', () => {
rootSpan.endSpan();
assert.strictEqual(result, serverRes);
assertSpanDuration(
traceTestModule.getOneSpan(span => span.name !== 'outer'),
[DEFAULT_SPAN_DURATION, Date.now() - start]
);
session.destroy();
done();
});
s.end();
});
});
});
it('should propagate context', done => {
server.listen(serverPort, () => {
traceTestModule.get().runInRootSpan({name: 'outer'}, rootSpan => {
assert.ok(rootSpan.type === SpanType.ROOT);
const session = http2.connect(`http://localhost:${serverPort}`);
const s = session.request({':path': '/'});
s.on('data', () => {
assert.ok(hasContext());
}).on('end', () => {
assert.ok(hasContext());
rootSpan.endSpan();
session.destroy();
done();
});
s.end();
});
});
});
it('should not trace api requests', done => {
server.listen(serverPort, () => {
traceTestModule.get().runInRootSpan({name: 'outer'}, rootSpan => {
assert.ok(rootSpan.type === SpanType.ROOT);
const session = http2.connect(`http://localhost:${serverPort}`);
const headers: http2Types.OutgoingHttpHeaders = {':path': '/'};
headers[Constants.TRACE_AGENT_REQUEST_HEADER] = 'yay';
const s = session.request(headers);
s.end();
setTimeout(() => {
rootSpan.endSpan();
const traces = traceTestModule.getTraces();
assert.strictEqual(traces.length, 1);
// The only span present should be the outer span.
assert.strictEqual(traces[0].spans.length, 1);
assert.strictEqual(traces[0].spans[0].name, 'outer');
session.destroy();
done();
}, DEFAULT_SPAN_DURATION * 1.5);
});
});
});
it('should not break with no headers', done => {
server.listen(serverPort, () => {
traceTestModule.get().runInRootSpan({name: 'outer'}, rootSpan => {
assert.ok(rootSpan.type === SpanType.ROOT);
const session = http2.connect(`http://localhost:${serverPort}`);
// `headers` are not passed
const s = session.request();
s.setEncoding('utf8');
// eslint-disable-next-line @typescript-eslint/no-unused-vars
s.on('data', (data: string) => {}).on('end', () => {
rootSpan.endSpan();
const traces = traceTestModule.getTraces();
assert.strictEqual(traces.length, 1);
// /http/method and /http/url must be set correctly even when the
// `headers` argument is not passed to the request() call.
assert.strictEqual(
traces[0].spans[1].labels['/http/method'],
'GET'
);
assert.strictEqual(
traces[0].spans[1].labels['/http/url'],
`http://localhost:${serverPort}/`
);
session.destroy();
done();
});
s.end();
});
});
});
it('should leave request streams in paused mode', done => {
server.listen(serverPort, () => {
traceTestModule.get().runInRootSpan({name: 'outer'}, rootSpan => {
assert.ok(rootSpan.type === SpanType.ROOT);
const start = Date.now();
const session = http2.connect(`http://localhost:${serverPort}`);
const s = session.request({':path': '/'});
let result = '';
const writable = new stream.Writable();
writable._write = (chunk, encoding, next) => {
result += chunk;
next();
};
writable.on('finish', () => {
rootSpan.endSpan();
assert.strictEqual(result, serverRes);
assertSpanDuration(
traceTestModule.getOneSpan(span => span.name !== 'outer'),
[DEFAULT_SPAN_DURATION, Date.now() - start]
);
session.destroy();
done();
});
setImmediate(() => {
s.pipe(writable);
});
s.end();
});
});
});
it('should not include query parameters in span name', done => {
server.listen(serverPort, () => {
traceTestModule.get().runInRootSpan({name: 'outer'}, rootSpan => {
assert.ok(rootSpan.type === SpanType.ROOT);
const session = http2.connect(`http://localhost:${serverPort}`);
const s = session.request({':path': '/?foo=bar'});
s.on('data', () => {}); // enter flowing mode
s.end();
setTimeout(() => {
rootSpan.endSpan();
const traces = traceTestModule.getTraces();
assert.strictEqual(traces.length, 1);
assert.strictEqual(traces[0].spans[1].name, 'localhost');
session.destroy();
done();
}, DEFAULT_SPAN_DURATION * 1.5);
});
});
});
it('custom port number must be included in the url label', done => {
server.listen(serverPort, () => {
traceTestModule.get().runInRootSpan({name: 'outer'}, rootSpan => {
assert.ok(rootSpan.type === SpanType.ROOT);
const session = http2.connect(`http://localhost:${serverPort}`);
const s = session.request({':path': '/'});
s.on('data', () => {}); // enter flowing mode
s.end();
setTimeout(() => {
rootSpan.endSpan();
const traces = traceTestModule.getTraces();
assert.strictEqual(traces.length, 1);
assert.strictEqual(
traces[0].spans[1].labels['/http/url'],
`http://localhost:${serverPort}/`
);
session.destroy();
done();
}, DEFAULT_SPAN_DURATION * 1.5);
});
});
});
it('should accurately measure request time, error', done => {
const server: http2Types.Http2Server = http2.createServer();
server.on(
'stream',
(
s: http2Types.ServerHttp2Stream & {rstWithInternalError: () => void}
) => {
// In Node 9.9+, the error handler is not added by default.
s.on('error', () => {});
setTimeout(() => {
if (semver.satisfies(process.version, '^8.11||>=9.4')) {
// Node 8.11/9.4 removed rstWithInternalError() in favor of new
// close() function.
s.close(http2.constants.NGHTTP2_INTERNAL_ERROR);
} else {
s.rstWithInternalError();
}
}, DEFAULT_SPAN_DURATION / 2);
}
);
server.listen(serverPort, () => {
traceTestModule.get().runInRootSpan({name: 'outer'}, rootSpan => {
assert.ok(rootSpan.type === SpanType.ROOT);
const start = Date.now();
const session = http2.connect(`http://localhost:${serverPort}`);
const s = session.request({':path': '/'});
s.on('error', () => {
rootSpan.endSpan();
const span = traceTestModule.getOneSpan(
span => span.name !== 'outer'
);
assertSpanDuration(span, [
DEFAULT_SPAN_DURATION / 2,
Date.now() - start,
]);
if (semver.satisfies(process.version, '>=12')) {
assert.strictEqual(
span.labels[TraceLabels.ERROR_DETAILS_NAME],
'Error'
);
} else {
assert.strictEqual(
span.labels[TraceLabels.ERROR_DETAILS_NAME],
'Error [ERR_HTTP2_STREAM_ERROR]'
);
}
if (semver.satisfies(process.version, '>=9.11 || >=8.12')) {
assert.strictEqual(
span.labels[TraceLabels.ERROR_DETAILS_MESSAGE],
'Stream closed with error code NGHTTP2_INTERNAL_ERROR'
);
} else {
assert.strictEqual(
span.labels[TraceLabels.ERROR_DETAILS_MESSAGE],
'Stream closed with error code 2'
);
}
session.destroy();
server.close();
done();
});
s.end();
});
});
});
it('should accurately measure request time, event emitter', done => {
server.listen(serverPort, () => {
traceTestModule.get().runInRootSpan({name: 'outer'}, rootSpan => {
assert.ok(rootSpan.type === SpanType.ROOT);
const start = Date.now();
const session = http2.connect(`http://localhost:${serverPort}`);
const s: http2Types.ClientHttp2Stream = session.request({
':path': '/',
});
s.setEncoding('utf8');
s.on('response', () => {
let result = '';
s.on('data', data => {
result += data;
}).on('end', () => {
rootSpan.endSpan();
assert.strictEqual(result, serverRes);
assertSpanDuration(
traceTestModule.getOneSpan(span => span.name !== 'outer'),
[DEFAULT_SPAN_DURATION, Date.now() - start]
);
session.destroy();
done();
});
});
});
});
});
it('should handle concurrent requests', function (done) {
this.timeout(10000); // this test takes a long time
let count = 200;
const slowServer: http2Types.Http2Server = http2.createServer();
slowServer.on('stream', s => {
setTimeout(() => {
s.respond({':status': count++});
s.end();
}, 5000);
});
slowServer.listen(serverPort, () => {
traceTestModule.get().runInRootSpan({name: 'outer'}, rootSpan => {
assert.ok(rootSpan.type === SpanType.ROOT);
let completed = 0;
for (let i = 0; i < 5; i++) {
const session = http2.connect(`http://localhost:${serverPort}`);
const s = session.request({':path': '/'});
s.on('data', () => {}).on('end', () => {
if (++completed === 5) {
rootSpan.endSpan();
const spans = traceTestModule.getSpans(
span => span.name !== 'outer'
);
assert.strictEqual(spans.length, 5);
// We need to check a property attached at the end of a span.
const statusCodes: number[] = [];
for (let j = 0; j < spans.length; j++) {
const code = Number(
spans[j].labels[TraceLabels.HTTP_RESPONSE_CODE_LABEL_KEY]
);
assert.strictEqual(statusCodes.indexOf(code), -1);
statusCodes.push(code);
}
assert.strictEqual(
statusCodes.reduce((a, b) => a + b),
1010
);
slowServer.close();
done();
}
session.destroy();
});
s.end();
}
});
});
});
});
describe('Secure HTTP2', () => {
it('should accurately measure request time', done => {
const options: http2Types.SecureServerOptions = {
key: SERVER_KEY,
cert: SERVER_CERT,
};
const secureServer: http2Types.Http2SecureServer =
http2.createSecureServer(options);
secureServer.on('stream', s => {
setTimeout(() => {
s.respond({':status': 200});
s.end(serverRes);
}, DEFAULT_SPAN_DURATION);
});
secureServer.listen(serverPort, () => {
traceTestModule.get().runInRootSpan({name: 'outer'}, rootSpan => {
assert.ok(rootSpan.type === SpanType.ROOT);
const start = Date.now();
const session = http2.connect(`https://localhost:${serverPort}`, {
rejectUnauthorized: false,
});
const s = session.request({':path': '/'});
s.setEncoding('utf8');
let result = '';
s.on('data', (data: string) => {
result += data;
}).on('end', () => {
rootSpan.endSpan();
assert.strictEqual(result, serverRes);
assertSpanDuration(
traceTestModule.getOneSpan(span => span.name !== 'outer'),
[DEFAULT_SPAN_DURATION, Date.now() - start]
);
session.destroy();
secureServer.close();
done();
});
s.end();
});
});
});
});
}); | the_stack |
import { GlobalProps } from 'ojs/ojvcomponent';
import { ComponentChildren } from 'preact';
import { DvtTimeComponentScale } from '../ojdvttimecomponentscale';
import { ojTimeAxis } from '../ojtimeaxis';
import Converter = require('../ojconverter');
import { DataProvider } from '../ojdataprovider';
import { dvtTimeComponent, dvtTimeComponentEventMap, dvtTimeComponentSettableProperties } from '../ojtime-base';
import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojTimeline<K, D extends ojTimeline.DataItem | any> extends dvtTimeComponent<ojTimelineSettableProperties<K, D>> {
animationOnDataChange: 'auto' | 'none';
animationOnDisplay: 'auto' | 'none';
data?: (DataProvider<K, D>);
end: string;
majorAxis: {
converter?: (ojTimeAxis.Converters | Converter<string>);
scale?: (string | DvtTimeComponentScale);
svgStyle?: Partial<CSSStyleDeclaration>;
};
minorAxis: {
converter?: (ojTimeAxis.Converters | Converter<string>);
scale?: (string | DvtTimeComponentScale);
svgStyle?: Partial<CSSStyleDeclaration>;
zoomOrder?: Array<string | DvtTimeComponentScale>;
};
orientation: 'vertical' | 'horizontal';
overview: {
rendered?: 'on' | 'off';
svgStyle?: Partial<CSSStyleDeclaration>;
};
referenceObjects: ojTimeline.ReferenceObject[];
selection: K[];
selectionMode: 'none' | 'single' | 'multiple';
start: string;
styleDefaults: {
animationDuration?: number;
borderColor?: string;
item?: {
backgroundColor?: string;
borderColor?: string;
descriptionStyle?: Partial<CSSStyleDeclaration>;
hoverBackgroundColor?: string;
hoverBorderColor?: string;
selectedBackgroundColor?: string;
selectedBorderColor?: string;
titleStyle?: Partial<CSSStyleDeclaration>;
};
majorAxis?: {
labelStyle?: Partial<CSSStyleDeclaration>;
separatorColor?: string;
};
minorAxis?: {
backgroundColor?: string;
borderColor?: string;
labelStyle?: Partial<CSSStyleDeclaration>;
separatorColor?: string;
};
overview?: {
backgroundColor?: string;
labelStyle?: Partial<CSSStyleDeclaration>;
window?: {
backgroundColor?: string;
borderColor?: string;
};
};
referenceObject?: {
color?: string;
};
series?: {
backgroundColor?: string;
colors?: string[];
emptyTextStyle?: Partial<CSSStyleDeclaration>;
labelStyle?: Partial<CSSStyleDeclaration>;
};
};
tooltip: {
renderer: ((context: ojTimeline.TooltipContext<K, D>) => ({
insert: Element | string;
} | {
preventDefault: boolean;
}));
};
valueFormats: {
date?: {
converter?: (Converter<string>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
description?: {
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
end?: {
converter?: (Converter<string>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
series?: {
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
start?: {
converter?: (Converter<string>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
title?: {
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
};
viewportEnd: string;
viewportNavigationMode: 'continuous' | 'discrete';
viewportStart: string;
translations: {
accessibleItemDesc?: string;
accessibleItemEnd?: string;
accessibleItemStart?: string;
accessibleItemTitle?: string;
componentName?: string;
labelAccNavNextPage?: string;
labelAccNavPreviousPage?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelDate?: string;
labelDescription?: string;
labelEnd?: string;
labelInvalidData?: string;
labelNoData?: string;
labelSeries?: string;
labelStart?: string;
labelTitle?: string;
navArrowDisabledState?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
tipArrowNextPage?: string;
tipArrowPreviousPage?: string;
tooltipZoomIn?: string;
tooltipZoomOut?: string;
};
addEventListener<T extends keyof ojTimelineEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojTimelineEventMap<K, D>[T]) => any, options?: (boolean | AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojTimelineSettableProperties<K, D>>(property: T): ojTimeline<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojTimelineSettableProperties<K, D>>(property: T, value: ojTimelineSettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojTimelineSettableProperties<K, D>>): void;
setProperties(properties: ojTimelineSettablePropertiesLenient<K, D>): void;
getContextByNode(node: Element): ojTimeline.NodeContext | null;
}
export namespace ojTimeline {
interface ojViewportChange extends CustomEvent<{
minorAxisScale: string;
viewportEnd: string;
viewportStart: string;
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type animationOnDataChangeChanged<K, D extends DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["animationOnDataChange"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDisplayChanged<K, D extends DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["animationOnDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type dataChanged<K, D extends DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["data"]>;
// tslint:disable-next-line interface-over-type-literal
type endChanged<K, D extends DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["end"]>;
// tslint:disable-next-line interface-over-type-literal
type majorAxisChanged<K, D extends DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["majorAxis"]>;
// tslint:disable-next-line interface-over-type-literal
type minorAxisChanged<K, D extends DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["minorAxis"]>;
// tslint:disable-next-line interface-over-type-literal
type orientationChanged<K, D extends DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["orientation"]>;
// tslint:disable-next-line interface-over-type-literal
type overviewChanged<K, D extends DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["overview"]>;
// tslint:disable-next-line interface-over-type-literal
type referenceObjectsChanged<K, D extends DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["referenceObjects"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionChanged<K, D extends DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["selection"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionModeChanged<K, D extends DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["selectionMode"]>;
// tslint:disable-next-line interface-over-type-literal
type startChanged<K, D extends DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["start"]>;
// tslint:disable-next-line interface-over-type-literal
type styleDefaultsChanged<K, D extends DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["styleDefaults"]>;
// tslint:disable-next-line interface-over-type-literal
type tooltipChanged<K, D extends DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["tooltip"]>;
// tslint:disable-next-line interface-over-type-literal
type valueFormatsChanged<K, D extends DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["valueFormats"]>;
// tslint:disable-next-line interface-over-type-literal
type viewportEndChanged<K, D extends DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["viewportEnd"]>;
// tslint:disable-next-line interface-over-type-literal
type viewportNavigationModeChanged<K, D extends DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["viewportNavigationMode"]>;
// tslint:disable-next-line interface-over-type-literal
type viewportStartChanged<K, D extends DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["viewportStart"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type trackResizeChanged<K, D extends DataItem | any> = dvtTimeComponent.trackResizeChanged<ojTimelineSettableProperties<K, D>>;
// tslint:disable-next-line interface-over-type-literal
type DataItem<K = any, D = any> = {
description?: string;
durationFillColor?: string;
end?: string;
seriesId: string;
shortDesc?: (string | ((context: ItemShortDescContext<K, D>) => string));
start: string;
svgStyle?: Partial<CSSStyleDeclaration>;
thumbnail?: string;
title?: string;
};
// tslint:disable-next-line interface-over-type-literal
type itemBubbleTemplateContext<K, D> = {
data: SeriesItem<K>;
itemData: D;
previousState: {
focused: boolean;
hovered: boolean;
selected: boolean;
};
seriesData: Series<K>;
state: {
focused: boolean;
hovered: boolean;
selected: boolean;
};
};
// tslint:disable-next-line interface-over-type-literal
type ItemShortDescContext<K, D> = {
data: SeriesItem<K>;
itemData: D;
seriesData: Series<K>;
};
// tslint:disable-next-line interface-over-type-literal
type ItemTemplateContext = {
componentElement: Element;
data: object;
index: number;
key: any;
};
// tslint:disable-next-line interface-over-type-literal
type NodeContext = {
itemIndex: number;
seriesIndex: number;
subId: string;
};
// tslint:disable-next-line interface-over-type-literal
type ReferenceObject = {
value?: string;
};
// tslint:disable-next-line interface-over-type-literal
type Series<K> = {
emptyText?: string;
id: string;
itemLayout?: 'auto' | 'bottomToTop' | 'topToBottom';
items?: Array<SeriesItem<K>>;
label?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type SeriesItem<K, D = any> = {
description?: string;
durationFillColor?: string;
end?: string;
id: K;
shortDesc?: (string | ((context: ItemShortDescContext<K, D>) => string));
start: string;
svgStyle?: Partial<CSSStyleDeclaration>;
thumbnail?: string;
title?: string;
};
// tslint:disable-next-line interface-over-type-literal
type SeriesTemplateContext = {
componentElement: Element;
id: any;
index: number;
items: Array<{
data: object;
index: number;
key: any;
}>;
};
// tslint:disable-next-line interface-over-type-literal
type TooltipContext<K, D> = {
color: string;
componentElement: Element;
data: SeriesItem<K>;
itemData: D;
parentElement: Element;
seriesData: Series<K>;
};
}
export interface ojTimelineEventMap<K, D extends ojTimeline.DataItem | any> extends dvtTimeComponentEventMap<ojTimelineSettableProperties<K, D>> {
'ojViewportChange': ojTimeline.ojViewportChange;
'animationOnDataChangeChanged': JetElementCustomEvent<ojTimeline<K, D>["animationOnDataChange"]>;
'animationOnDisplayChanged': JetElementCustomEvent<ojTimeline<K, D>["animationOnDisplay"]>;
'dataChanged': JetElementCustomEvent<ojTimeline<K, D>["data"]>;
'endChanged': JetElementCustomEvent<ojTimeline<K, D>["end"]>;
'majorAxisChanged': JetElementCustomEvent<ojTimeline<K, D>["majorAxis"]>;
'minorAxisChanged': JetElementCustomEvent<ojTimeline<K, D>["minorAxis"]>;
'orientationChanged': JetElementCustomEvent<ojTimeline<K, D>["orientation"]>;
'overviewChanged': JetElementCustomEvent<ojTimeline<K, D>["overview"]>;
'referenceObjectsChanged': JetElementCustomEvent<ojTimeline<K, D>["referenceObjects"]>;
'selectionChanged': JetElementCustomEvent<ojTimeline<K, D>["selection"]>;
'selectionModeChanged': JetElementCustomEvent<ojTimeline<K, D>["selectionMode"]>;
'startChanged': JetElementCustomEvent<ojTimeline<K, D>["start"]>;
'styleDefaultsChanged': JetElementCustomEvent<ojTimeline<K, D>["styleDefaults"]>;
'tooltipChanged': JetElementCustomEvent<ojTimeline<K, D>["tooltip"]>;
'valueFormatsChanged': JetElementCustomEvent<ojTimeline<K, D>["valueFormats"]>;
'viewportEndChanged': JetElementCustomEvent<ojTimeline<K, D>["viewportEnd"]>;
'viewportNavigationModeChanged': JetElementCustomEvent<ojTimeline<K, D>["viewportNavigationMode"]>;
'viewportStartChanged': JetElementCustomEvent<ojTimeline<K, D>["viewportStart"]>;
'trackResizeChanged': JetElementCustomEvent<ojTimeline<K, D>["trackResize"]>;
}
export interface ojTimelineSettableProperties<K, D extends ojTimeline.DataItem | any> extends dvtTimeComponentSettableProperties {
animationOnDataChange: 'auto' | 'none';
animationOnDisplay: 'auto' | 'none';
data?: (DataProvider<K, D>);
end: string;
majorAxis: {
converter?: (ojTimeAxis.Converters | Converter<string>);
scale?: (string | DvtTimeComponentScale);
svgStyle?: Partial<CSSStyleDeclaration>;
};
minorAxis: {
converter?: (ojTimeAxis.Converters | Converter<string>);
scale?: (string | DvtTimeComponentScale);
svgStyle?: Partial<CSSStyleDeclaration>;
zoomOrder?: Array<string | DvtTimeComponentScale>;
};
orientation: 'vertical' | 'horizontal';
overview: {
rendered?: 'on' | 'off';
svgStyle?: Partial<CSSStyleDeclaration>;
};
referenceObjects: ojTimeline.ReferenceObject[];
selection: K[];
selectionMode: 'none' | 'single' | 'multiple';
start: string;
styleDefaults: {
animationDuration?: number;
borderColor?: string;
item?: {
backgroundColor?: string;
borderColor?: string;
descriptionStyle?: Partial<CSSStyleDeclaration>;
hoverBackgroundColor?: string;
hoverBorderColor?: string;
selectedBackgroundColor?: string;
selectedBorderColor?: string;
titleStyle?: Partial<CSSStyleDeclaration>;
};
majorAxis?: {
labelStyle?: Partial<CSSStyleDeclaration>;
separatorColor?: string;
};
minorAxis?: {
backgroundColor?: string;
borderColor?: string;
labelStyle?: Partial<CSSStyleDeclaration>;
separatorColor?: string;
};
overview?: {
backgroundColor?: string;
labelStyle?: Partial<CSSStyleDeclaration>;
window?: {
backgroundColor?: string;
borderColor?: string;
};
};
referenceObject?: {
color?: string;
};
series?: {
backgroundColor?: string;
colors?: string[];
emptyTextStyle?: Partial<CSSStyleDeclaration>;
labelStyle?: Partial<CSSStyleDeclaration>;
};
};
tooltip: {
renderer: ((context: ojTimeline.TooltipContext<K, D>) => ({
insert: Element | string;
} | {
preventDefault: boolean;
}));
};
valueFormats: {
date?: {
converter?: (Converter<string>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
description?: {
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
end?: {
converter?: (Converter<string>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
series?: {
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
start?: {
converter?: (Converter<string>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
title?: {
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
};
viewportEnd: string;
viewportNavigationMode: 'continuous' | 'discrete';
viewportStart: string;
translations: {
accessibleItemDesc?: string;
accessibleItemEnd?: string;
accessibleItemStart?: string;
accessibleItemTitle?: string;
componentName?: string;
labelAccNavNextPage?: string;
labelAccNavPreviousPage?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelDate?: string;
labelDescription?: string;
labelEnd?: string;
labelInvalidData?: string;
labelNoData?: string;
labelSeries?: string;
labelStart?: string;
labelTitle?: string;
navArrowDisabledState?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
tipArrowNextPage?: string;
tipArrowPreviousPage?: string;
tooltipZoomIn?: string;
tooltipZoomOut?: string;
};
}
export interface ojTimelineSettablePropertiesLenient<K, D extends ojTimeline.DataItem | any> extends Partial<ojTimelineSettableProperties<K, D>> {
[key: string]: any;
}
export interface ojTimelineItem<K = any, D = any> extends dvtTimeComponent<ojTimelineItemSettableProperties<K, D>> {
description?: string;
durationFillColor?: string | null;
end?: string;
itemType?: 'event' | 'duration-bar' | 'duration-event' | 'auto';
label?: string;
seriesId: string;
shortDesc?: (string | ((context: ojTimeline.ItemShortDescContext<K, D>) => string));
start: string;
svgStyle?: Partial<CSSStyleDeclaration>;
thumbnail?: string;
addEventListener<T extends keyof ojTimelineItemEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojTimelineItemEventMap<K, D>[T]) => any, options?: (boolean |
AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojTimelineItemSettableProperties<K, D>>(property: T): ojTimelineItem<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojTimelineItemSettableProperties<K, D>>(property: T, value: ojTimelineItemSettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojTimelineItemSettableProperties<K, D>>): void;
setProperties(properties: ojTimelineItemSettablePropertiesLenient<K, D>): void;
}
export namespace ojTimelineItem {
// tslint:disable-next-line interface-over-type-literal
type descriptionChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["description"]>;
// tslint:disable-next-line interface-over-type-literal
type durationFillColorChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["durationFillColor"]>;
// tslint:disable-next-line interface-over-type-literal
type endChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["end"]>;
// tslint:disable-next-line interface-over-type-literal
type itemTypeChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["itemType"]>;
// tslint:disable-next-line interface-over-type-literal
type labelChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["label"]>;
// tslint:disable-next-line interface-over-type-literal
type seriesIdChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["seriesId"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type startChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["start"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type thumbnailChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["thumbnail"]>;
}
export interface ojTimelineItemEventMap<K = any, D = any> extends dvtTimeComponentEventMap<ojTimelineItemSettableProperties<K, D>> {
'descriptionChanged': JetElementCustomEvent<ojTimelineItem<K, D>["description"]>;
'durationFillColorChanged': JetElementCustomEvent<ojTimelineItem<K, D>["durationFillColor"]>;
'endChanged': JetElementCustomEvent<ojTimelineItem<K, D>["end"]>;
'itemTypeChanged': JetElementCustomEvent<ojTimelineItem<K, D>["itemType"]>;
'labelChanged': JetElementCustomEvent<ojTimelineItem<K, D>["label"]>;
'seriesIdChanged': JetElementCustomEvent<ojTimelineItem<K, D>["seriesId"]>;
'shortDescChanged': JetElementCustomEvent<ojTimelineItem<K, D>["shortDesc"]>;
'startChanged': JetElementCustomEvent<ojTimelineItem<K, D>["start"]>;
'svgStyleChanged': JetElementCustomEvent<ojTimelineItem<K, D>["svgStyle"]>;
'thumbnailChanged': JetElementCustomEvent<ojTimelineItem<K, D>["thumbnail"]>;
}
export interface ojTimelineItemSettableProperties<K = any, D = any> extends dvtTimeComponentSettableProperties {
description?: string;
durationFillColor?: string | null;
end?: string;
itemType?: 'event' | 'duration-bar' | 'duration-event' | 'auto';
label?: string;
seriesId: string;
shortDesc?: (string | ((context: ojTimeline.ItemShortDescContext<K, D>) => string));
start: string;
svgStyle?: Partial<CSSStyleDeclaration>;
thumbnail?: string;
}
export interface ojTimelineItemSettablePropertiesLenient<K = any, D = any> extends Partial<ojTimelineItemSettableProperties<K, D>> {
[key: string]: any;
}
export interface ojTimelineSeries extends JetElement<ojTimelineSeriesSettableProperties> {
emptyText?: string;
itemLayout?: 'auto' | 'bottomToTop' | 'topToBottom';
label?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
addEventListener<T extends keyof ojTimelineSeriesEventMap>(type: T, listener: (this: HTMLElement, ev: ojTimelineSeriesEventMap[T]) => any, options?: (boolean | AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojTimelineSeriesSettableProperties>(property: T): ojTimelineSeries[T];
getProperty(property: string): any;
setProperty<T extends keyof ojTimelineSeriesSettableProperties>(property: T, value: ojTimelineSeriesSettableProperties[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojTimelineSeriesSettableProperties>): void;
setProperties(properties: ojTimelineSeriesSettablePropertiesLenient): void;
}
export namespace ojTimelineSeries {
// tslint:disable-next-line interface-over-type-literal
type emptyTextChanged = JetElementCustomEvent<ojTimelineSeries["emptyText"]>;
// tslint:disable-next-line interface-over-type-literal
type itemLayoutChanged = JetElementCustomEvent<ojTimelineSeries["itemLayout"]>;
// tslint:disable-next-line interface-over-type-literal
type labelChanged = JetElementCustomEvent<ojTimelineSeries["label"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged = JetElementCustomEvent<ojTimelineSeries["svgStyle"]>;
}
export interface ojTimelineSeriesEventMap extends HTMLElementEventMap {
'emptyTextChanged': JetElementCustomEvent<ojTimelineSeries["emptyText"]>;
'itemLayoutChanged': JetElementCustomEvent<ojTimelineSeries["itemLayout"]>;
'labelChanged': JetElementCustomEvent<ojTimelineSeries["label"]>;
'svgStyleChanged': JetElementCustomEvent<ojTimelineSeries["svgStyle"]>;
}
export interface ojTimelineSeriesSettableProperties extends JetSettableProperties {
emptyText?: string;
itemLayout?: 'auto' | 'bottomToTop' | 'topToBottom';
label?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
}
export interface ojTimelineSeriesSettablePropertiesLenient extends Partial<ojTimelineSeriesSettableProperties> {
[key: string]: any;
}
export type TimelineElement<K, D extends ojTimeline.DataItem | any> = ojTimeline<K, D>;
export type TimelineItemElement<K = any, D = any> = ojTimelineItem<K, D>;
export type TimelineSeriesElement = ojTimelineSeries;
export namespace TimelineElement {
interface ojViewportChange extends CustomEvent<{
minorAxisScale: string;
viewportEnd: string;
viewportStart: string;
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type animationOnDataChangeChanged<K, D extends ojTimeline.DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["animationOnDataChange"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDisplayChanged<K, D extends ojTimeline.DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["animationOnDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type dataChanged<K, D extends ojTimeline.DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["data"]>;
// tslint:disable-next-line interface-over-type-literal
type endChanged<K, D extends ojTimeline.DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["end"]>;
// tslint:disable-next-line interface-over-type-literal
type majorAxisChanged<K, D extends ojTimeline.DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["majorAxis"]>;
// tslint:disable-next-line interface-over-type-literal
type minorAxisChanged<K, D extends ojTimeline.DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["minorAxis"]>;
// tslint:disable-next-line interface-over-type-literal
type orientationChanged<K, D extends ojTimeline.DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["orientation"]>;
// tslint:disable-next-line interface-over-type-literal
type overviewChanged<K, D extends ojTimeline.DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["overview"]>;
// tslint:disable-next-line interface-over-type-literal
type referenceObjectsChanged<K, D extends ojTimeline.DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["referenceObjects"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionChanged<K, D extends ojTimeline.DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["selection"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionModeChanged<K, D extends ojTimeline.DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["selectionMode"]>;
// tslint:disable-next-line interface-over-type-literal
type startChanged<K, D extends ojTimeline.DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["start"]>;
// tslint:disable-next-line interface-over-type-literal
type styleDefaultsChanged<K, D extends ojTimeline.DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["styleDefaults"]>;
// tslint:disable-next-line interface-over-type-literal
type tooltipChanged<K, D extends ojTimeline.DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["tooltip"]>;
// tslint:disable-next-line interface-over-type-literal
type valueFormatsChanged<K, D extends ojTimeline.DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["valueFormats"]>;
// tslint:disable-next-line interface-over-type-literal
type viewportEndChanged<K, D extends ojTimeline.DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["viewportEnd"]>;
// tslint:disable-next-line interface-over-type-literal
type viewportNavigationModeChanged<K, D extends ojTimeline.DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["viewportNavigationMode"]>;
// tslint:disable-next-line interface-over-type-literal
type viewportStartChanged<K, D extends ojTimeline.DataItem | any> = JetElementCustomEvent<ojTimeline<K, D>["viewportStart"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type trackResizeChanged<K, D extends ojTimeline.DataItem | any> = dvtTimeComponent.trackResizeChanged<ojTimelineSettableProperties<K, D>>;
// tslint:disable-next-line interface-over-type-literal
type DataItem<K = any, D = any> = {
description?: string;
durationFillColor?: string;
end?: string;
seriesId: string;
shortDesc?: (string | ((context: ojTimeline.ItemShortDescContext<K, D>) => string));
start: string;
svgStyle?: Partial<CSSStyleDeclaration>;
thumbnail?: string;
title?: string;
};
// tslint:disable-next-line interface-over-type-literal
type ItemShortDescContext<K, D> = {
data: ojTimeline.SeriesItem<K>;
itemData: D;
seriesData: ojTimeline.Series<K>;
};
// tslint:disable-next-line interface-over-type-literal
type NodeContext = {
itemIndex: number;
seriesIndex: number;
subId: string;
};
// tslint:disable-next-line interface-over-type-literal
type Series<K> = {
emptyText?: string;
id: string;
itemLayout?: 'auto' | 'bottomToTop' | 'topToBottom';
items?: Array<ojTimeline.SeriesItem<K>>;
label?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type SeriesTemplateContext = {
componentElement: Element;
id: any;
index: number;
items: Array<{
data: object;
index: number;
key: any;
}>;
};
}
export namespace TimelineItemElement {
// tslint:disable-next-line interface-over-type-literal
type descriptionChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["description"]>;
// tslint:disable-next-line interface-over-type-literal
type durationFillColorChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["durationFillColor"]>;
// tslint:disable-next-line interface-over-type-literal
type endChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["end"]>;
// tslint:disable-next-line interface-over-type-literal
type itemTypeChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["itemType"]>;
// tslint:disable-next-line interface-over-type-literal
type labelChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["label"]>;
// tslint:disable-next-line interface-over-type-literal
type seriesIdChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["seriesId"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type startChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["start"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type thumbnailChanged<K = any, D = any> = JetElementCustomEvent<ojTimelineItem<K, D>["thumbnail"]>;
}
export namespace TimelineSeriesElement {
// tslint:disable-next-line interface-over-type-literal
type emptyTextChanged = JetElementCustomEvent<ojTimelineSeries["emptyText"]>;
// tslint:disable-next-line interface-over-type-literal
type itemLayoutChanged = JetElementCustomEvent<ojTimelineSeries["itemLayout"]>;
// tslint:disable-next-line interface-over-type-literal
type labelChanged = JetElementCustomEvent<ojTimelineSeries["label"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged = JetElementCustomEvent<ojTimelineSeries["svgStyle"]>;
}
export interface TimelineIntrinsicProps extends Partial<Readonly<ojTimelineSettableProperties<any, any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onojViewportChange?: (value: ojTimelineEventMap<any, any>['ojViewportChange']) => void;
onanimationOnDataChangeChanged?: (value: ojTimelineEventMap<any, any>['animationOnDataChangeChanged']) => void;
onanimationOnDisplayChanged?: (value: ojTimelineEventMap<any, any>['animationOnDisplayChanged']) => void;
ondataChanged?: (value: ojTimelineEventMap<any, any>['dataChanged']) => void;
onendChanged?: (value: ojTimelineEventMap<any, any>['endChanged']) => void;
onmajorAxisChanged?: (value: ojTimelineEventMap<any, any>['majorAxisChanged']) => void;
onminorAxisChanged?: (value: ojTimelineEventMap<any, any>['minorAxisChanged']) => void;
onorientationChanged?: (value: ojTimelineEventMap<any, any>['orientationChanged']) => void;
onoverviewChanged?: (value: ojTimelineEventMap<any, any>['overviewChanged']) => void;
onreferenceObjectsChanged?: (value: ojTimelineEventMap<any, any>['referenceObjectsChanged']) => void;
onselectionChanged?: (value: ojTimelineEventMap<any, any>['selectionChanged']) => void;
onselectionModeChanged?: (value: ojTimelineEventMap<any, any>['selectionModeChanged']) => void;
onstartChanged?: (value: ojTimelineEventMap<any, any>['startChanged']) => void;
onstyleDefaultsChanged?: (value: ojTimelineEventMap<any, any>['styleDefaultsChanged']) => void;
ontooltipChanged?: (value: ojTimelineEventMap<any, any>['tooltipChanged']) => void;
onvalueFormatsChanged?: (value: ojTimelineEventMap<any, any>['valueFormatsChanged']) => void;
onviewportEndChanged?: (value: ojTimelineEventMap<any, any>['viewportEndChanged']) => void;
onviewportNavigationModeChanged?: (value: ojTimelineEventMap<any, any>['viewportNavigationModeChanged']) => void;
onviewportStartChanged?: (value: ojTimelineEventMap<any, any>['viewportStartChanged']) => void;
ontrackResizeChanged?: (value: ojTimelineEventMap<any, any>['trackResizeChanged']) => void;
children?: ComponentChildren;
}
export interface TimelineItemIntrinsicProps extends Partial<Readonly<ojTimelineItemSettableProperties<any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
ondescriptionChanged?: (value: ojTimelineItemEventMap<any, any>['descriptionChanged']) => void;
ondurationFillColorChanged?: (value: ojTimelineItemEventMap<any, any>['durationFillColorChanged']) => void;
onendChanged?: (value: ojTimelineItemEventMap<any, any>['endChanged']) => void;
onitemTypeChanged?: (value: ojTimelineItemEventMap<any, any>['itemTypeChanged']) => void;
onlabelChanged?: (value: ojTimelineItemEventMap<any, any>['labelChanged']) => void;
onseriesIdChanged?: (value: ojTimelineItemEventMap<any, any>['seriesIdChanged']) => void;
onshortDescChanged?: (value: ojTimelineItemEventMap<any, any>['shortDescChanged']) => void;
onstartChanged?: (value: ojTimelineItemEventMap<any, any>['startChanged']) => void;
onsvgStyleChanged?: (value: ojTimelineItemEventMap<any, any>['svgStyleChanged']) => void;
onthumbnailChanged?: (value: ojTimelineItemEventMap<any, any>['thumbnailChanged']) => void;
children?: ComponentChildren;
}
export interface TimelineSeriesIntrinsicProps extends Partial<Readonly<ojTimelineSeriesSettableProperties>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onemptyTextChanged?: (value: ojTimelineSeriesEventMap['emptyTextChanged']) => void;
onitemLayoutChanged?: (value: ojTimelineSeriesEventMap['itemLayoutChanged']) => void;
onlabelChanged?: (value: ojTimelineSeriesEventMap['labelChanged']) => void;
onsvgStyleChanged?: (value: ojTimelineSeriesEventMap['svgStyleChanged']) => void;
children?: ComponentChildren;
}
declare global {
namespace preact.JSX {
interface IntrinsicElements {
"oj-timeline": TimelineIntrinsicProps;
"oj-timeline-item": TimelineItemIntrinsicProps;
"oj-timeline-series": TimelineSeriesIntrinsicProps;
}
}
} | the_stack |
import type {
AnySchema,
AnySchemaObject,
AnyValidateFunction,
AsyncValidateFunction,
EvaluatedProperties,
EvaluatedItems,
} from "../types"
import type Ajv from "../core"
import type {InstanceOptions} from "../core"
import {CodeGen, _, nil, stringify, Name, Code, ValueScopeName} from "./codegen"
import {ValidationError} from "./error_classes"
import N from "./names"
import {LocalRefs, getFullPath, _getFullPath, inlineRef, normalizeId, resolveUrl} from "./resolve"
import {schemaHasRulesButRef, unescapeFragment} from "./util"
import {validateFunctionCode} from "./validate"
import URI = require("uri-js")
import {JSONType} from "./rules"
export type SchemaRefs = {
[Ref in string]?: SchemaEnv | AnySchema
}
export interface SchemaCxt {
readonly gen: CodeGen
readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error
readonly data: Name // Name with reference to the current part of data instance
readonly parentData: Name // should be used in keywords modifying data
readonly parentDataProperty: Code | number // should be used in keywords modifying data
readonly dataNames: Name[]
readonly dataPathArr: (Code | number)[]
readonly dataLevel: number // the level of the currently validated data,
// it can be used to access both the property names and the data on all levels from the top.
dataTypes: JSONType[] // data types applied to the current part of data instance
readonly topSchemaRef: Code
readonly validateName: Name
evaluated?: Name
readonly ValidationError?: Name
readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt
readonly schemaEnv: SchemaEnv
readonly rootId: string
baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\$ref)
readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema
readonly errSchemaPath: string // this is actual string, should not be changed to Code
readonly errorPath: Code
readonly propertyName?: Name
readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword,
// where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`).
// This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true.
// You only need to use it if you have many steps in your keywords and potentially can define multiple errors.
props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function
items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function
jtdDiscriminator?: string
jtdMetadata?: boolean
readonly createErrors?: boolean
readonly opts: InstanceOptions // Ajv instance option.
readonly self: Ajv // current Ajv instance
}
export interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
}
interface SchemaEnvArgs {
readonly schema: AnySchema
readonly root?: SchemaEnv
readonly baseId?: string
readonly localRefs?: LocalRefs
readonly meta?: boolean
}
export class SchemaEnv implements SchemaEnvArgs {
readonly schema: AnySchema
readonly root: SchemaEnv
baseId: string // TODO possibly, it should be readonly
localRefs?: LocalRefs
readonly meta?: boolean
readonly $async?: boolean // true if the current schema is asynchronous.
readonly refs: SchemaRefs = {}
readonly dynamicAnchors: {[Ref in string]?: true} = {}
validate?: AnyValidateFunction
validateName?: ValueScopeName
constructor(env: SchemaEnvArgs) {
let schema: AnySchemaObject | undefined
if (typeof env.schema == "object") schema = env.schema
this.schema = env.schema
this.root = env.root || this
this.baseId = env.baseId ?? normalizeId(schema?.$id)
this.localRefs = env.localRefs
this.meta = env.meta
this.$async = schema?.$async
this.refs = {}
}
}
// let codeSize = 0
// let nodeCount = 0
// Compiles schema in SchemaEnv
export function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv {
// TODO refactor - remove compilations
const _sch = getCompilingSchema.call(this, sch)
if (_sch) return _sch
const rootId = getFullPath(sch.root.baseId) // TODO if getFullPath removed 1 tests fails
const {es5, lines} = this.opts.code
const {ownProperties} = this.opts
const gen = new CodeGen(this.scope, {es5, lines, ownProperties})
let _ValidationError
if (sch.$async) {
_ValidationError = gen.scopeValue("Error", {
ref: ValidationError,
code: _`require("ajv/dist/compile/error_classes").ValidationError`,
})
}
const validateName = gen.scopeName("validate")
sch.validateName = validateName
const schemaCxt: SchemaCxt = {
gen,
allErrors: this.opts.allErrors,
data: N.data,
parentData: N.parentData,
parentDataProperty: N.parentDataProperty,
dataNames: [N.data],
dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed?
dataLevel: 0,
dataTypes: [],
topSchemaRef: gen.scopeValue(
"schema",
this.opts.code.source === true
? {ref: sch.schema, code: stringify(sch.schema)}
: {ref: sch.schema}
),
validateName,
ValidationError: _ValidationError,
schema: sch.schema,
schemaEnv: sch,
rootId,
baseId: sch.baseId || rootId,
schemaPath: nil,
errSchemaPath: this.opts.jtd ? "" : "#",
errorPath: _`""`,
opts: this.opts,
self: this,
}
let sourceCode: string | undefined
try {
this._compilations.add(sch)
validateFunctionCode(schemaCxt)
gen.optimize(this.opts.code.optimize)
// gen.optimize(1)
const validateCode = gen.toString()
sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}`
// console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))
if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch)
// console.log("\n\n\n *** \n", sourceCode)
const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode)
const validate: AnyValidateFunction = makeValidate(this, this.scope.get())
this.scope.value(validateName, {ref: validate})
validate.errors = null
validate.schema = sch.schema
validate.schemaEnv = sch
if (sch.$async) (validate as AsyncValidateFunction).$async = true
if (this.opts.code.source === true) {
validate.source = {validateName, validateCode, scopeValues: gen._values}
}
if (this.opts.unevaluated) {
const {props, items} = schemaCxt
validate.evaluated = {
props: props instanceof Name ? undefined : props,
items: items instanceof Name ? undefined : items,
dynamicProps: props instanceof Name,
dynamicItems: items instanceof Name,
}
if (validate.source) validate.source.evaluated = stringify(validate.evaluated)
}
sch.validate = validate
return sch
} catch (e) {
delete sch.validate
delete sch.validateName
if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode)
// console.log("\n\n\n *** \n", sourceCode, this.opts)
throw e
} finally {
this._compilations.delete(sch)
}
}
export function resolveRef(
this: Ajv,
root: SchemaEnv,
baseId: string,
ref: string
): AnySchema | SchemaEnv | undefined {
ref = resolveUrl(baseId, ref)
const schOrFunc = root.refs[ref]
if (schOrFunc) return schOrFunc
let _sch = resolve.call(this, root, ref)
if (_sch === undefined) {
const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv
if (schema) _sch = new SchemaEnv({schema, root, baseId})
}
if (_sch === undefined) return
return (root.refs[ref] = inlineOrCompile.call(this, _sch))
}
function inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv {
if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema
return sch.validate ? sch : compileSchema.call(this, sch)
}
// Index of schema compilation in the currently compiled list
function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void {
for (const sch of this._compilations) {
if (sameSchemaEnv(sch, schEnv)) return sch
}
}
function sameSchemaEnv(s1: SchemaEnv, s2: SchemaEnv): boolean {
return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId
}
// resolve and compile the references ($ref)
// TODO returns AnySchemaObject (if the schema can be inlined) or validation function
function resolve(
this: Ajv,
root: SchemaEnv, // information about the root schema for the current schema
ref: string // reference to resolve
): SchemaEnv | undefined {
let sch
while (typeof (sch = this.refs[ref]) == "string") ref = sch
return sch || this.schemas[ref] || resolveSchema.call(this, root, ref)
}
// Resolve schema, its root and baseId
export function resolveSchema(
this: Ajv,
root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
ref: string // reference to resolve
): SchemaEnv | undefined {
const p = URI.parse(ref)
const refPath = _getFullPath(p)
let baseId = getFullPath(root.baseId)
// TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
if (Object.keys(root.schema).length > 0 && refPath === baseId) {
return getJsonPointer.call(this, p, root)
}
const id = normalizeId(refPath)
const schOrRef = this.refs[id] || this.schemas[id]
if (typeof schOrRef == "string") {
const sch = resolveSchema.call(this, root, schOrRef)
if (typeof sch?.schema !== "object") return
return getJsonPointer.call(this, p, sch)
}
if (typeof schOrRef?.schema !== "object") return
if (!schOrRef.validate) compileSchema.call(this, schOrRef)
if (id === normalizeId(ref)) {
const {schema} = schOrRef
if (schema.$id) baseId = resolveUrl(baseId, schema.$id)
return new SchemaEnv({schema, root, baseId})
}
return getJsonPointer.call(this, p, schOrRef)
}
const PREVENT_SCOPE_CHANGE = new Set([
"properties",
"patternProperties",
"enum",
"dependencies",
"definitions",
])
function getJsonPointer(
this: Ajv,
parsedRef: URI.URIComponents,
{baseId, schema, root}: SchemaEnv
): SchemaEnv | undefined {
if (parsedRef.fragment?.[0] !== "/") return
for (const part of parsedRef.fragment.slice(1).split("/")) {
if (typeof schema == "boolean") return
schema = schema[unescapeFragment(part)]
if (schema === undefined) return
// TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?
if (!PREVENT_SCOPE_CHANGE.has(part) && typeof schema == "object" && schema.$id) {
baseId = resolveUrl(baseId, schema.$id)
}
}
let env: SchemaEnv | undefined
if (typeof schema != "boolean" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) {
const $ref = resolveUrl(baseId, schema.$ref)
env = resolveSchema.call(this, root, $ref)
}
// even though resolution failed we need to return SchemaEnv to throw exception
// so that compileAsync loads missing schema.
env = env || new SchemaEnv({schema, root, baseId})
if (env.schema !== env.root.schema) return env
return undefined
} | the_stack |
import { SvgIconComponent } from "@material-ui/icons";
import { RenNetwork } from "@renproject/interfaces";
import {
ArbitrumBlackIcon,
ArbitrumCircleIcon,
ArbitrumColorIcon,
AvaFullIcon,
AvaIcon,
AvalancheChainCircleIcon,
BchDashedIcon,
BchFullIcon,
BchGreyIcon,
BchIcon,
BinanceChainFullIcon,
BinanceChainIcon,
BitcoinIcon,
BtcDashedIcon,
BtcFullIcon,
BtcGreyIcon,
BtcIcon,
CustomSvgIconComponent,
DgbDashedIcon,
DgbFullIcon,
DgbGreyIcon,
DgbIcon,
DogeDashedIcon,
DogeFullIcon,
DogeGreyIcon,
DogeIcon,
DotsFullIcon,
DotsGreyIcon,
DotsIcon,
EthereumChainFullIcon,
EthereumIcon,
FantomCircleIcon,
FantomFullIcon,
FantomGreyIcon,
FilDashedIcon,
FilFullIcon,
FilGreyIcon,
FilIcon,
LunaDashedIcon,
LunaFullIcon,
LunaGreyIcon,
LunaIcon,
MetamaskFullIcon,
MewFullIcon,
PhantomFullIcon,
PolygonCircleIcon,
PolygonFullIcon,
PolygonGreyIcon,
SolanaCircleIcon,
SolanaGreyIcon,
SolletFullIcon,
TooltipIcon as NotSetIcon,
WalletConnectFullIcon,
ZecDashedIcon,
ZecFullIcon,
ZecGreyIcon,
ZecIcon,
} from "../components/icons/RenIcons";
import { env } from "../constants/environmentVariables";
import * as customColors from "../theme/colors";
// TODO: replace everywhere
export enum RenChain {
arbitrum = "arbitrum",
avalanche = "avalanche",
binanceSmartChain = "binanceSmartChain",
ethereum = "ethereum",
fantom = "fantom",
polygon = "polygon",
solana = "solana",
bitcoin = "bitcoin",
zcash = "zcash",
bitcoinCash = "bitcoinCash",
dogecoin = "dogecoin",
digibyte = "digibyte",
terra = "terra",
filecoin = "filecoin",
unknown = "unknown",
}
export enum BridgeCurrency {
BTC = "BTC",
BCH = "BCH",
DOTS = "DOTS",
DOGE = "DOGE",
ZEC = "ZEC",
DGB = "DGB",
LUNA = "LUNA",
FIL = "FIL",
RENBTC = "RENBTC",
RENBCH = "RENBCH",
RENDOGE = "RENDOGE",
RENZEC = "RENZEC",
RENDGB = "RENDGB",
RENLUNA = "RENLUNA",
RENFIL = "RENFIL",
ETH = "ETH",
FTM = "FTM",
MATIC = "MATIC",
BNB = "BNB",
AVAX = "AVAX",
SOL = "SOL",
ARBETH = "ARBETH",
UNKNOWN = "UNKNOWN",
}
export enum BridgeChain {
BTCC = "BTCC",
BCHC = "BCHC",
ZECC = "ZECC",
DOGC = "DOGC",
DGBC = "DGBC",
FILC = "FILC",
LUNAC = "LUNAC",
BSCC = "BSCC",
ETHC = "ETHC",
MATICC = "MATICC",
FTMC = "FTMC",
AVAXC = "AVAXC",
SOLC = "SOLC",
ARBITRUMC = "ARBITRUMC",
UNKNOWNC = "UNKNOWNC",
}
export enum BridgeNetwork {
MAINNET = "MAINNET",
TESTNET = "TESTNET",
UNKNOWN = "UNKNOWN",
}
export enum EthTestnet {
KOVAN = "Kovan",
RINKEBY = "Rinkeby",
UNKNOWNT = "Unknown",
}
export enum BridgeWallet {
METAMASKW = "METAMASKW",
WALLETCONNECTW = "WALLETCONNECTW",
MEWCONNECTW = "MEWCONNECTW",
BINANCESMARTW = "BINANCESMARTW",
SOLLETW = "SOLLETW",
PHANTOMW = "PHANTOMW",
UNKNOWNW = "UNKNOWNW",
}
export type NetworkMapping = {
testnet: RenNetwork;
mainnet: RenNetwork;
};
export type ChainToNetworkMappings = Record<
RenChain.ethereum | RenChain.binanceSmartChain | string,
NetworkMapping
>;
const unknownLabel = "unknown";
export type LabelsConfig = {
short: string;
full: string;
};
export type ColorsConfig = {
color?: string;
};
export type MainIconConfig = {
Icon: CustomSvgIconComponent | SvgIconComponent;
MainIcon: CustomSvgIconComponent | SvgIconComponent;
};
export type IconsConfig = MainIconConfig & {
FullIcon: CustomSvgIconComponent | SvgIconComponent;
GreyIcon: CustomSvgIconComponent | SvgIconComponent;
};
export type BridgeCurrencyConfig = LabelsConfig &
ColorsConfig &
IconsConfig & {
symbol: BridgeCurrency;
sourceChain: BridgeChain;
rentxName: string;
destinationChains?: Array<BridgeChain>;
bandchainSymbol?: string;
coingeckoSymbol?: string;
networkMappings: ChainToNetworkMappings;
decimals?: number;
ethTestnet?: EthTestnet | null;
};
const networkMappingLegacy: NetworkMapping = {
mainnet: RenNetwork.Mainnet,
testnet: RenNetwork.Testnet,
};
const networkMappingVDot3: NetworkMapping = {
mainnet: RenNetwork.MainnetVDot3,
testnet: RenNetwork.TestnetVDot3,
};
const oldNetworkMappings: ChainToNetworkMappings = {
[RenChain.ethereum]: networkMappingLegacy,
// BinanceSmartChain only has 1 network for testnet/mainnet
// so vDot3 is equavelent to "legacy" mappings
[RenChain.binanceSmartChain]: networkMappingLegacy,
[RenChain.fantom]: networkMappingLegacy,
[RenChain.polygon]: networkMappingLegacy,
[RenChain.avalanche]: networkMappingLegacy,
[RenChain.solana]: networkMappingLegacy,
[RenChain.arbitrum]: networkMappingLegacy,
};
const newNetworkMappings: ChainToNetworkMappings = {
[RenChain.ethereum]: networkMappingVDot3,
// BinanceSmartChain only has 1 network for testnet/mainnet
// so vDot3 is equavelent to "legacy" mappings
[RenChain.binanceSmartChain]: networkMappingLegacy,
[RenChain.fantom]: networkMappingLegacy,
[RenChain.polygon]: networkMappingLegacy,
[RenChain.avalanche]: networkMappingLegacy,
[RenChain.solana]: networkMappingLegacy,
[RenChain.arbitrum]: networkMappingLegacy,
};
export const currenciesConfig: Record<BridgeCurrency, BridgeCurrencyConfig> = {
[BridgeCurrency.BTC]: {
symbol: BridgeCurrency.BTC,
short: "BTC",
full: "Bitcoin",
color: customColors.bitcoinOrange,
FullIcon: BtcFullIcon,
GreyIcon: BtcGreyIcon,
Icon: BtcIcon,
MainIcon: BtcFullIcon,
rentxName: "btc",
sourceChain: BridgeChain.BTCC,
networkMappings: oldNetworkMappings,
},
[BridgeCurrency.RENBTC]: {
symbol: BridgeCurrency.RENBTC,
short: "renBTC",
full: "Ren Bitcoin",
FullIcon: BtcFullIcon,
GreyIcon: BtcGreyIcon,
Icon: BtcIcon,
MainIcon: BtcDashedIcon,
rentxName: "renBTC",
sourceChain: BridgeChain.ETHC,
bandchainSymbol: BridgeCurrency.BTC,
networkMappings: oldNetworkMappings,
},
[BridgeCurrency.BCH]: {
symbol: BridgeCurrency.BCH,
short: "BCH",
full: "Bitcoin Cash",
color: customColors.bitcoinCashGreen,
FullIcon: BchFullIcon,
GreyIcon: BchGreyIcon,
Icon: BchIcon,
MainIcon: BchFullIcon,
rentxName: "BCH",
sourceChain: BridgeChain.BCHC,
networkMappings: oldNetworkMappings,
},
[BridgeCurrency.RENBCH]: {
symbol: BridgeCurrency.RENBCH,
short: "renBCH",
full: "Bitcoin Cash",
FullIcon: BchFullIcon,
GreyIcon: BchGreyIcon,
Icon: BchIcon,
MainIcon: BchDashedIcon,
rentxName: "renBCH",
sourceChain: BridgeChain.ETHC,
bandchainSymbol: BridgeCurrency.BCH,
networkMappings: oldNetworkMappings,
},
[BridgeCurrency.DOTS]: {
symbol: BridgeCurrency.DOTS,
short: "DOTS",
full: "Polkadot",
FullIcon: DotsFullIcon,
GreyIcon: DotsGreyIcon,
Icon: DotsIcon,
MainIcon: DotsFullIcon,
sourceChain: BridgeChain.UNKNOWNC, // TODO:
rentxName: "dots",
bandchainSymbol: "DOT",
networkMappings: newNetworkMappings,
},
[BridgeCurrency.DOGE]: {
symbol: BridgeCurrency.DOGE,
short: "DOGE",
full: "Dogecoin",
FullIcon: DogeFullIcon,
GreyIcon: DogeGreyIcon,
Icon: DogeIcon,
MainIcon: DogeFullIcon,
sourceChain: BridgeChain.DOGC,
rentxName: "doge",
networkMappings: newNetworkMappings,
},
[BridgeCurrency.RENDOGE]: {
symbol: BridgeCurrency.RENDOGE,
short: "renDOGE",
full: "Dogecoin",
FullIcon: DogeFullIcon,
GreyIcon: DogeGreyIcon,
Icon: DogeIcon,
MainIcon: DogeDashedIcon,
rentxName: "renDOGE",
sourceChain: BridgeChain.ETHC,
bandchainSymbol: BridgeCurrency.DOGE,
ethTestnet: EthTestnet.KOVAN,
networkMappings: newNetworkMappings,
},
[BridgeCurrency.ZEC]: {
symbol: BridgeCurrency.ZEC,
short: "ZEC",
full: "Zcash",
FullIcon: ZecFullIcon,
GreyIcon: ZecGreyIcon,
Icon: ZecIcon,
MainIcon: ZecFullIcon,
rentxName: "zec",
sourceChain: BridgeChain.ZECC,
networkMappings: oldNetworkMappings,
},
[BridgeCurrency.RENZEC]: {
symbol: BridgeCurrency.RENZEC,
short: "renZEC",
full: "Zcash",
FullIcon: ZecFullIcon,
GreyIcon: ZecGreyIcon,
Icon: ZecIcon,
MainIcon: ZecDashedIcon,
rentxName: "renZEC",
sourceChain: BridgeChain.ETHC,
bandchainSymbol: BridgeCurrency.ZEC,
networkMappings: oldNetworkMappings,
},
[BridgeCurrency.DGB]: {
symbol: BridgeCurrency.DGB,
short: "DGB",
full: "DigiByte",
FullIcon: DgbFullIcon,
GreyIcon: DgbGreyIcon,
Icon: DgbIcon,
MainIcon: DgbFullIcon,
sourceChain: BridgeChain.DGBC,
rentxName: "DGB",
networkMappings: newNetworkMappings,
},
[BridgeCurrency.RENDGB]: {
symbol: BridgeCurrency.RENDGB,
short: "renDGB",
full: "DigiByte",
FullIcon: DgbFullIcon,
GreyIcon: DgbGreyIcon,
Icon: DgbIcon,
MainIcon: DgbDashedIcon,
rentxName: "renDGB",
sourceChain: BridgeChain.ETHC,
bandchainSymbol: BridgeCurrency.DGB,
networkMappings: newNetworkMappings,
},
[BridgeCurrency.FIL]: {
symbol: BridgeCurrency.FIL,
short: "FIL",
full: "Filecoin",
FullIcon: FilFullIcon,
GreyIcon: FilGreyIcon,
Icon: FilIcon,
MainIcon: FilFullIcon,
sourceChain: BridgeChain.FILC,
rentxName: "FIL",
networkMappings: newNetworkMappings,
},
[BridgeCurrency.RENFIL]: {
symbol: BridgeCurrency.RENFIL,
short: "renFIL",
full: "Filecoin",
FullIcon: FilFullIcon,
GreyIcon: FilGreyIcon,
Icon: FilIcon,
MainIcon: FilDashedIcon,
rentxName: "renFIL",
sourceChain: BridgeChain.ETHC,
bandchainSymbol: BridgeCurrency.FIL,
networkMappings: newNetworkMappings,
},
[BridgeCurrency.LUNA]: {
symbol: BridgeCurrency.LUNA,
short: "LUNA",
full: "Luna",
FullIcon: LunaFullIcon,
GreyIcon: LunaGreyIcon,
Icon: LunaIcon,
MainIcon: LunaFullIcon,
sourceChain: BridgeChain.LUNAC,
rentxName: "LUNA",
networkMappings: newNetworkMappings,
},
[BridgeCurrency.RENLUNA]: {
symbol: BridgeCurrency.RENLUNA,
short: "renLUNA",
full: "Luna",
FullIcon: LunaFullIcon,
GreyIcon: LunaGreyIcon,
Icon: LunaIcon,
MainIcon: LunaDashedIcon,
rentxName: "renLUNA",
sourceChain: BridgeChain.ETHC,
bandchainSymbol: BridgeCurrency.LUNA,
networkMappings: newNetworkMappings,
},
[BridgeCurrency.ETH]: {
symbol: BridgeCurrency.ETH,
short: "ETH",
full: "Ether",
FullIcon: EthereumIcon,
GreyIcon: NotSetIcon,
Icon: EthereumIcon,
MainIcon: BtcFullIcon,
rentxName: "eth",
sourceChain: BridgeChain.ETHC,
networkMappings: newNetworkMappings,
},
[BridgeCurrency.AVAX]: {
symbol: BridgeCurrency.AVAX,
short: "AVAX",
full: "Avalanche",
FullIcon: AvaIcon,
GreyIcon: NotSetIcon,
Icon: AvaIcon,
MainIcon: AvaFullIcon,
rentxName: "ava",
coingeckoSymbol: "avalanche-2",
sourceChain: BridgeChain.AVAXC,
networkMappings: newNetworkMappings,
decimals: 18,
},
[BridgeCurrency.MATIC]: {
symbol: BridgeCurrency.MATIC,
short: "MATIC",
full: "Matic",
FullIcon: PolygonFullIcon,
GreyIcon: NotSetIcon,
Icon: PolygonFullIcon,
MainIcon: PolygonFullIcon,
rentxName: "matic",
sourceChain: BridgeChain.MATICC,
networkMappings: newNetworkMappings,
decimals: 18,
},
[BridgeCurrency.FTM]: {
symbol: BridgeCurrency.FTM,
short: "FTM",
full: "Fantom",
FullIcon: FantomFullIcon,
GreyIcon: NotSetIcon,
Icon: FantomFullIcon,
MainIcon: BtcFullIcon,
rentxName: "ftm",
sourceChain: BridgeChain.FTMC,
networkMappings: newNetworkMappings,
decimals: 18,
},
[BridgeCurrency.BNB]: {
symbol: BridgeCurrency.BNB,
short: "BNB",
full: "Binance Coin",
FullIcon: EthereumIcon,
GreyIcon: NotSetIcon,
Icon: EthereumIcon,
MainIcon: BtcFullIcon,
rentxName: "eth",
sourceChain: BridgeChain.BSCC,
networkMappings: newNetworkMappings,
decimals: 18,
},
[BridgeCurrency.SOL]: {
symbol: BridgeCurrency.SOL,
short: "SOL",
full: "Solana",
FullIcon: EthereumIcon,
GreyIcon: NotSetIcon,
Icon: EthereumIcon,
MainIcon: BtcFullIcon,
rentxName: "sol",
sourceChain: BridgeChain.SOLC,
networkMappings: newNetworkMappings,
decimals: 9,
},
[BridgeCurrency.ARBETH]: {
symbol: BridgeCurrency.ARBETH,
short: "arbETH",
full: "Arbitrum ETH",
FullIcon: ArbitrumBlackIcon,
GreyIcon: NotSetIcon,
Icon: ArbitrumBlackIcon,
MainIcon: BtcFullIcon,
rentxName: "sol",
sourceChain: BridgeChain.ARBITRUMC,
bandchainSymbol: "ETH",
networkMappings: newNetworkMappings,
decimals: 18,
},
[BridgeCurrency.UNKNOWN]: {
symbol: BridgeCurrency.UNKNOWN,
short: "UNKNOWN",
full: "Unknown",
FullIcon: NotSetIcon,
GreyIcon: NotSetIcon,
Icon: NotSetIcon,
MainIcon: NotSetIcon,
rentxName: "unknown",
sourceChain: BridgeChain.UNKNOWNC,
networkMappings: newNetworkMappings,
},
};
const unknownCurrencyConfig = currenciesConfig[BridgeCurrency.UNKNOWN];
export const getCurrencyConfig = (symbol: BridgeCurrency) =>
currenciesConfig[symbol] || unknownCurrencyConfig;
export const getCurrencyShortLabel = (symbol: BridgeCurrency) =>
currenciesConfig[symbol].short || unknownLabel;
export const getCurrencyConfigByRentxName = (name: string) =>
Object.values(currenciesConfig).find(
(currency) => currency.rentxName === name
) || unknownCurrencyConfig;
export const getCurrencyConfigByBandchainSymbol = (symbol: string) =>
Object.values(currenciesConfig).find(
(config) => config.bandchainSymbol === symbol || config.symbol === symbol
) || unknownCurrencyConfig;
export const getCurrencyRentxName = (symbol: BridgeCurrency) =>
currenciesConfig[symbol].rentxName || unknownLabel;
export const getCurrencySourceChain = (symbol: BridgeCurrency) =>
currenciesConfig[symbol].sourceChain || BridgeChain.UNKNOWNC;
export const getCurrencyRentxSourceChain = (symbol: BridgeCurrency) => {
const bridgeChain = getCurrencySourceChain(symbol);
if (bridgeChain) {
return getChainRentxName(bridgeChain);
}
return BridgeChain.UNKNOWNC;
};
export type BridgeChainConfig = LabelsConfig &
IconsConfig & {
symbol: BridgeChain;
rentxName: RenChain;
blockTime: number;
nativeCurrency: BridgeCurrency;
targetConfirmations: number;
memo?: boolean;
};
export const chainsConfig: Record<BridgeChain, BridgeChainConfig> = {
[BridgeChain.BTCC]: {
symbol: BridgeChain.BTCC,
short: "BTC",
full: "Bitcoin",
FullIcon: NotSetIcon,
Icon: BitcoinIcon,
MainIcon: BitcoinIcon,
GreyIcon: NotSetIcon,
rentxName: RenChain.bitcoin,
blockTime: 10,
nativeCurrency: BridgeCurrency.BTC,
targetConfirmations: 6,
},
[BridgeChain.BCHC]: {
symbol: BridgeChain.BCHC,
short: "BCH",
full: "Bitcoin Cash",
FullIcon: BchFullIcon,
GreyIcon: BchGreyIcon,
Icon: BchIcon,
MainIcon: BchFullIcon,
rentxName: RenChain.bitcoinCash,
blockTime: 10,
targetConfirmations: 6,
nativeCurrency: BridgeCurrency.BCH,
},
[BridgeChain.ZECC]: {
symbol: BridgeChain.ZECC,
short: "ZEC",
full: "Zcash",
FullIcon: ZecFullIcon,
GreyIcon: ZecGreyIcon,
Icon: ZecIcon,
MainIcon: ZecFullIcon,
rentxName: RenChain.zcash,
blockTime: 2.5,
nativeCurrency: BridgeCurrency.ZEC,
targetConfirmations: 24,
},
[BridgeChain.DOGC]: {
symbol: BridgeChain.DOGC,
short: "DOGE",
full: "Dogecoin",
FullIcon: DogeFullIcon,
GreyIcon: DogeGreyIcon,
Icon: DogeIcon,
MainIcon: DogeFullIcon,
rentxName: RenChain.dogecoin,
blockTime: 1,
targetConfirmations: 40,
nativeCurrency: BridgeCurrency.DOGE,
},
[BridgeChain.DGBC]: {
symbol: BridgeChain.DGBC,
short: "DGB",
full: "DigiByte",
FullIcon: DgbFullIcon,
GreyIcon: DgbGreyIcon,
Icon: DgbIcon,
MainIcon: DgbFullIcon,
rentxName: RenChain.digibyte,
blockTime: 1,
targetConfirmations: 40,
nativeCurrency: BridgeCurrency.DGB,
},
[BridgeChain.FILC]: {
symbol: BridgeChain.FILC,
short: "FIL",
full: "Filecoin",
FullIcon: FilFullIcon,
GreyIcon: FilGreyIcon,
Icon: FilIcon,
MainIcon: FilFullIcon,
rentxName: RenChain.filecoin,
blockTime: 1,
targetConfirmations: 40,
nativeCurrency: BridgeCurrency.FIL,
},
[BridgeChain.LUNAC]: {
symbol: BridgeChain.LUNAC,
short: "LUNA",
full: "Luna",
FullIcon: LunaFullIcon,
GreyIcon: LunaGreyIcon,
Icon: LunaIcon,
MainIcon: LunaFullIcon,
rentxName: RenChain.terra,
blockTime: 1,
targetConfirmations: 40,
nativeCurrency: BridgeCurrency.LUNA,
memo: true,
},
[BridgeChain.BSCC]: {
symbol: BridgeChain.BSCC,
short: "BSC",
full: "Binance Smart Chain",
FullIcon: BinanceChainFullIcon,
Icon: BinanceChainIcon,
MainIcon: BinanceChainFullIcon,
GreyIcon: NotSetIcon,
rentxName: RenChain.binanceSmartChain,
blockTime: 3,
targetConfirmations: 30,
nativeCurrency: BridgeCurrency.BNB,
},
[BridgeChain.FTMC]: {
symbol: BridgeChain.FTMC,
short: "FTM",
full: "Fantom",
FullIcon: FantomCircleIcon,
Icon: FantomGreyIcon,
MainIcon: FantomCircleIcon,
GreyIcon: NotSetIcon,
rentxName: RenChain.fantom,
blockTime: 3,
targetConfirmations: 30,
nativeCurrency: BridgeCurrency.FTM,
},
[BridgeChain.MATICC]: {
symbol: BridgeChain.MATICC,
short: "MATIC",
full: "Polygon",
FullIcon: PolygonCircleIcon,
Icon: PolygonGreyIcon,
MainIcon: PolygonCircleIcon,
GreyIcon: NotSetIcon,
rentxName: RenChain.polygon,
blockTime: 3,
targetConfirmations: 30,
nativeCurrency: BridgeCurrency.MATIC,
},
[BridgeChain.AVAXC]: {
symbol: BridgeChain.AVAXC,
short: "AVAX",
full: "Avalanche",
FullIcon: AvalancheChainCircleIcon,
Icon: AvalancheChainCircleIcon,
MainIcon: AvalancheChainCircleIcon,
GreyIcon: NotSetIcon,
rentxName: RenChain.avalanche,
blockTime: 3,
targetConfirmations: 30,
nativeCurrency: BridgeCurrency.AVAX,
},
[BridgeChain.ETHC]: {
symbol: BridgeChain.ETHC,
short: "ETH",
full: "Ethereum",
FullIcon: EthereumChainFullIcon,
Icon: EthereumIcon,
MainIcon: EthereumChainFullIcon,
GreyIcon: NotSetIcon,
rentxName: RenChain.ethereum,
blockTime: 0.25,
targetConfirmations: 30,
nativeCurrency: BridgeCurrency.ETH,
},
[BridgeChain.SOLC]: {
symbol: BridgeChain.SOLC,
short: "SOL",
full: "Solana",
FullIcon: SolanaCircleIcon,
Icon: SolanaGreyIcon,
MainIcon: SolanaCircleIcon,
GreyIcon: NotSetIcon,
rentxName: RenChain.solana,
blockTime: 0.25,
targetConfirmations: 30,
nativeCurrency: BridgeCurrency.SOL,
},
[BridgeChain.ARBITRUMC]: {
symbol: BridgeChain.ARBITRUMC,
short: "ARB",
full: "Arbitrum",
FullIcon: ArbitrumCircleIcon,
Icon: ArbitrumColorIcon,
MainIcon: ArbitrumCircleIcon,
GreyIcon: NotSetIcon,
rentxName: RenChain.arbitrum,
blockTime: 0.25,
targetConfirmations: 30,
nativeCurrency: BridgeCurrency.ARBETH,
},
[BridgeChain.UNKNOWNC]: {
symbol: BridgeChain.UNKNOWNC,
short: "UNKNOWNC",
full: "Unknown",
FullIcon: NotSetIcon,
GreyIcon: NotSetIcon,
Icon: NotSetIcon,
MainIcon: NotSetIcon,
rentxName: RenChain.unknown,
blockTime: 1e6,
targetConfirmations: 1e6,
nativeCurrency: BridgeCurrency.UNKNOWN,
},
};
const unknownChainConfig = chainsConfig[BridgeChain.UNKNOWNC];
export const getChainConfig = (symbol: BridgeChain) =>
chainsConfig[symbol] || unknownChainConfig;
export const getChainRentxName = (symbol: BridgeChain) =>
chainsConfig[symbol].rentxName || unknownLabel;
export const getChainConfigByRentxName = (name: string) =>
Object.values(chainsConfig).find((chain) => chain.rentxName === name) ||
unknownChainConfig;
type NetworkConfig = LabelsConfig & {
rentxName: string;
symbol: BridgeNetwork;
};
export const networksConfig: Record<BridgeNetwork, NetworkConfig> = {
[BridgeNetwork.MAINNET]: {
symbol: BridgeNetwork.MAINNET,
short: "MAINNET",
full: "Mainnet",
rentxName: RenNetwork.Mainnet,
},
[BridgeNetwork.TESTNET]: {
symbol: BridgeNetwork.TESTNET,
short: "TESTNET",
full: "Testnet",
rentxName: RenNetwork.Testnet,
},
[BridgeNetwork.UNKNOWN]: {
symbol: BridgeNetwork.UNKNOWN,
short: "UNKNOWN",
full: "Unknown",
rentxName: "unknown",
},
};
const unknownNetworkConfig = networksConfig[BridgeNetwork.UNKNOWN];
export const isTestnetNetwork = (name: string) => name.indexOf("testnet") > -1;
export const isMainnetNetwork = (name: string) => name.indexOf("mainnet") > -1;
export const getNetworkConfigByRentxName = (name: string) => {
if (isTestnetNetwork(name)) {
return networksConfig[BridgeNetwork.TESTNET];
}
if (isMainnetNetwork(name)) {
return networksConfig[BridgeNetwork.MAINNET];
}
return (
Object.values(networksConfig).find(
(network) => network.rentxName === name
) || unknownNetworkConfig
);
};
export const supportedLockCurrencies =
env.ENABLED_CURRENCIES[0] === "*"
? [
BridgeCurrency.BTC,
BridgeCurrency.BCH,
BridgeCurrency.DGB,
BridgeCurrency.DOGE,
BridgeCurrency.FIL,
BridgeCurrency.LUNA,
BridgeCurrency.ZEC,
]
: env.ENABLED_CURRENCIES.filter((x) => {
const included = Object.keys(BridgeCurrency).includes(x);
if (!included) {
console.error("unknown currency:", x);
}
return included;
}).map((x) => x as BridgeCurrency);
export const supportedMintDestinationChains = [
BridgeChain.ETHC,
BridgeChain.BSCC,
BridgeChain.MATICC,
BridgeChain.FTMC,
BridgeChain.AVAXC,
BridgeChain.SOLC,
BridgeChain.ARBITRUMC,
];
export const supportedBurnChains = [
BridgeChain.ETHC,
BridgeChain.MATICC,
BridgeChain.FTMC,
BridgeChain.AVAXC,
BridgeChain.SOLC,
BridgeChain.BSCC,
BridgeChain.ARBITRUMC,
];
export const supportedReleaseCurrencies = supportedLockCurrencies.map(
(x) => ("REN" + x) as BridgeCurrency
);
export const toMintedCurrency = (lockedCurrency: BridgeCurrency) => {
switch (lockedCurrency) {
case BridgeCurrency.BTC:
return BridgeCurrency.RENBTC;
case BridgeCurrency.BCH:
return BridgeCurrency.RENBCH;
case BridgeCurrency.DOGE:
return BridgeCurrency.RENDOGE;
case BridgeCurrency.ZEC:
return BridgeCurrency.RENZEC;
default:
const fallback =
BridgeCurrency[("REN" + lockedCurrency) as BridgeCurrency];
if (fallback) return fallback;
return BridgeCurrency.UNKNOWN;
}
};
export const toReleasedCurrency = (burnedCurrency: BridgeCurrency) => {
switch (burnedCurrency) {
case BridgeCurrency.RENBTC:
return BridgeCurrency.BTC;
case BridgeCurrency.RENBCH:
return BridgeCurrency.BCH;
case BridgeCurrency.RENDOGE:
return BridgeCurrency.DOGE;
case BridgeCurrency.RENZEC:
return BridgeCurrency.ZEC;
default:
const fallback = BridgeCurrency[getNativeCurrency(burnedCurrency)];
if (fallback) return fallback;
return BridgeCurrency.UNKNOWN;
}
};
export type BridgeWalletConfig = LabelsConfig &
ColorsConfig &
MainIconConfig & {
rentxName: string;
symbol: BridgeWallet;
chain: BridgeChain;
};
export const walletsConfig: Record<BridgeWallet, BridgeWalletConfig> = {
[BridgeWallet.METAMASKW]: {
symbol: BridgeWallet.METAMASKW,
short: "MetaMask",
full: "MetaMask Wallet",
Icon: NotSetIcon,
MainIcon: MetamaskFullIcon,
chain: BridgeChain.ETHC,
rentxName: "Metamask",
},
[BridgeWallet.WALLETCONNECTW]: {
symbol: BridgeWallet.WALLETCONNECTW,
short: "MetaMask",
full: "MetaMask Wallet",
Icon: NotSetIcon,
MainIcon: WalletConnectFullIcon,
chain: BridgeChain.ETHC,
rentxName: "WalletConnect",
},
[BridgeWallet.BINANCESMARTW]: {
symbol: BridgeWallet.BINANCESMARTW,
short: "Binance Wallet",
full: "Binance Chain Wallet",
Icon: NotSetIcon,
MainIcon: BinanceChainFullIcon,
chain: BridgeChain.BSCC,
rentxName: "BinanceSmartWallet",
},
[BridgeWallet.MEWCONNECTW]: {
symbol: BridgeWallet.UNKNOWNW,
short: "MEW",
full: "MEW Wallet",
Icon: NotSetIcon,
MainIcon: MewFullIcon,
chain: BridgeChain.ETHC,
rentxName: "MEW",
},
[BridgeWallet.SOLLETW]: {
symbol: BridgeWallet.SOLLETW,
short: "Sollet.io",
full: "Sollet Wallet",
Icon: NotSetIcon,
MainIcon: SolletFullIcon,
chain: BridgeChain.SOLC,
rentxName: "Sollet.io",
},
[BridgeWallet.PHANTOMW]: {
symbol: BridgeWallet.PHANTOMW,
short: "Phantom",
full: "Phantom Wallet",
Icon: NotSetIcon,
MainIcon: PhantomFullIcon,
chain: BridgeChain.SOLC,
rentxName: "Phantom",
},
[BridgeWallet.UNKNOWNW]: {
symbol: BridgeWallet.UNKNOWNW,
short: "Unknown",
full: "Unknown Wallet",
Icon: NotSetIcon,
MainIcon: NotSetIcon,
chain: BridgeChain.UNKNOWNC,
rentxName: "unknown",
},
};
const unknownWalletConfig = walletsConfig[BridgeWallet.UNKNOWNW];
export const getWalletConfig = (symbol: BridgeWallet) =>
walletsConfig[symbol] || unknownWalletConfig;
export const getWalletConfigByRentxName = (name: string) =>
Object.values(walletsConfig).find((wallet) => wallet.rentxName === name) ||
unknownWalletConfig;
// FIXME: hacky, lets not have two different enums for the same things (supported networks)
// Maybe we should raise the enum into ren-js, just like we have RenNetwork
export const bridgeChainToRenChain = (bridgeChain: BridgeChain): RenChain => {
switch (bridgeChain) {
case BridgeChain.ETHC:
return RenChain.ethereum;
case BridgeChain.BSCC:
return RenChain.binanceSmartChain;
case BridgeChain.FTMC:
return RenChain.fantom;
case BridgeChain.MATICC:
return RenChain.polygon;
case BridgeChain.SOLC:
return RenChain.solana;
case BridgeChain.ARBITRUMC:
return RenChain.arbitrum;
default:
return RenChain.unknown;
}
};
export const getNativeCurrency = (renAsset: string) => {
return renAsset.split("REN").pop() as BridgeCurrency;
}; | the_stack |
// Builder
// -------
import assert from '../deps/@jspm/core@1.1.0/nodelibs/assert.js';
import inherits from '../deps/inherits@2.0.4/inherits.js';
import { EventEmitter } from '../deps/@jspm/core@1.1.0/nodelibs/events.js';
import Raw from '../raw.js';
import helpers from '../helpers.js';
import JoinClause from './joinclause.js';
import _ from '../deps/lodash@4.17.15/index.js';
const assign = _.assign;
const clone = _.clone;
const each = _.each;
const isBoolean = _.isBoolean;
const isEmpty = _.isEmpty;
const isFunction = _.isFunction;
const isNumber = _.isNumber;
const isObject = _.isObject;
const isPlainObject = _.isPlainObject;
const isString = _.isString;
const last = _.last;
const reject = _.reject;
const tail = _.tail;
const toArray = _.toArray;
import saveAsyncStack from '../util/save-async-stack.js';
import { lockMode, waitMode } from './constants.js';
// Typically called from `knex.builder`,
// start a new query building chain.
function Builder(client) {
this.client = client;
this.and = this;
this._single = {};
this._statements = [];
this._method = 'select';
if (client.config) {
saveAsyncStack(this, 5);
this._debug = client.config.debug;
}
// Internal flags used in the builder.
this._joinFlag = 'inner';
this._boolFlag = 'and';
this._notFlag = false;
this._asColumnFlag = false;
}
inherits(Builder, EventEmitter);
const validateWithArgs = function (alias, statement, method) {
if (typeof alias !== 'string') {
throw new Error(`${method}() first argument must be a string`);
}
if (
typeof statement === 'function' ||
statement instanceof Builder ||
statement instanceof Raw
) {
return;
}
throw new Error(
`${method}() second argument must be a function / QueryBuilder or a raw`
);
};
assign(Builder.prototype, {
toString() {
return this.toQuery();
},
// Convert the current query "toSQL"
toSQL(method, tz) {
return this.client.queryCompiler(this).toSQL(method || this._method, tz);
},
// Create a shallow clone of the current query builder.
clone() {
const cloned = new this.constructor(this.client);
cloned._method = this._method;
cloned._single = clone(this._single);
cloned._statements = clone(this._statements);
cloned._debug = this._debug;
// `_option` is assigned by the `Interface` mixin.
if (this._options !== undefined) {
cloned._options = clone(this._options);
}
if (this._queryContext !== undefined) {
cloned._queryContext = clone(this._queryContext);
}
if (this._connection !== undefined) {
cloned._connection = this._connection;
}
return cloned;
},
timeout(ms, { cancel } = {}) {
if (isNumber(ms) && ms > 0) {
this._timeout = ms;
if (cancel) {
this.client.assertCanCancelQuery();
this._cancelOnTimeout = true;
}
}
return this;
},
// With
// ------
with(alias, statement) {
validateWithArgs(alias, statement, 'with');
return this.withWrapped(alias, statement);
},
// Helper for compiling any advanced `with` queries.
withWrapped(alias, query) {
this._statements.push({
grouping: 'with',
type: 'withWrapped',
alias: alias,
value: query,
});
return this;
},
// With Recursive
// ------
withRecursive(alias, statement) {
validateWithArgs(alias, statement, 'withRecursive');
return this.withRecursiveWrapped(alias, statement);
},
// Helper for compiling any advanced `withRecursive` queries.
withRecursiveWrapped(alias, query) {
this.withWrapped(alias, query);
this._statements[this._statements.length - 1].recursive = true;
return this;
},
// Select
// ------
// Adds a column or columns to the list of "columns"
// being selected on the query.
columns(column) {
if (!column && column !== 0) return this;
this._statements.push({
grouping: 'columns',
value: helpers.normalizeArr.apply(null, arguments),
});
return this;
},
// Allow for a sub-select to be explicitly aliased as a column,
// without needing to compile the query in a where.
as(column) {
this._single.as = column;
return this;
},
// Prepends the `schemaName` on `tableName` defined by `.table` and `.join`.
withSchema(schemaName) {
this._single.schema = schemaName;
return this;
},
// Sets the `tableName` on the query.
// Alias to "from" for select and "into" for insert statements
// e.g. builder.insert({a: value}).into('tableName')
// `options`: options object containing keys:
// - `only`: whether the query should use SQL's ONLY to not return
// inheriting table data. Defaults to false.
table(tableName, options = {}) {
this._single.table = tableName;
this._single.only = options.only === true;
return this;
},
// Adds a `distinct` clause to the query.
distinct() {
this._statements.push({
grouping: 'columns',
value: helpers.normalizeArr.apply(null, arguments),
distinct: true,
});
return this;
},
distinctOn() {
const value = helpers.normalizeArr.apply(null, arguments);
if (isEmpty(value)) {
throw new Error('distinctOn requires atleast on argument');
}
this._statements.push({
grouping: 'columns',
value,
distinctOn: true,
});
return this;
},
// Adds a join clause to the query, allowing for advanced joins
// with an anonymous function as the second argument.
// function(table, first, operator, second)
join(table, first) {
let join;
const { schema } = this._single;
const joinType = this._joinType();
if (typeof first === 'function') {
join = new JoinClause(table, joinType, schema);
first.call(join, join);
} else if (joinType === 'raw') {
join = new JoinClause(this.client.raw(table, first), 'raw');
} else {
join = new JoinClause(
table,
joinType,
table instanceof Builder ? undefined : schema
);
if (arguments.length > 1) {
join.on.apply(join, toArray(arguments).slice(1));
}
}
this._statements.push(join);
return this;
},
// JOIN blocks:
innerJoin() {
return this._joinType('inner').join.apply(this, arguments);
},
leftJoin() {
return this._joinType('left').join.apply(this, arguments);
},
leftOuterJoin() {
return this._joinType('left outer').join.apply(this, arguments);
},
rightJoin() {
return this._joinType('right').join.apply(this, arguments);
},
rightOuterJoin() {
return this._joinType('right outer').join.apply(this, arguments);
},
outerJoin() {
return this._joinType('outer').join.apply(this, arguments);
},
fullOuterJoin() {
return this._joinType('full outer').join.apply(this, arguments);
},
crossJoin() {
return this._joinType('cross').join.apply(this, arguments);
},
joinRaw() {
return this._joinType('raw').join.apply(this, arguments);
},
// The where function can be used in several ways:
// The most basic is `where(key, value)`, which expands to
// where key = value.
where(column, operator, value) {
// Support "where true || where false"
if (column === false || column === true) {
return this.where(1, '=', column ? 1 : 0);
}
// Check if the column is a function, in which case it's
// a where statement wrapped in parens.
if (typeof column === 'function') {
return this.whereWrapped(column);
}
// Allow a raw statement to be passed along to the query.
if (column instanceof Raw && arguments.length === 1)
return this.whereRaw(column);
// Allows `where({id: 2})` syntax.
if (isObject(column) && !(column instanceof Raw))
return this._objectWhere(column);
// Enable the where('key', value) syntax, only when there
// are explicitly two arguments passed, so it's not possible to
// do where('key', '!=') and have that turn into where key != null
if (arguments.length === 2) {
value = operator;
operator = '=';
// If the value is null, and it's a two argument query,
// we assume we're going for a `whereNull`.
if (value === null) {
return this.whereNull(column);
}
}
// lower case the operator for comparison purposes
const checkOperator = `${operator}`.toLowerCase().trim();
// If there are 3 arguments, check whether 'in' is one of them.
if (arguments.length === 3) {
if (checkOperator === 'in' || checkOperator === 'not in') {
return this._not(checkOperator === 'not in').whereIn(
arguments[0],
arguments[2]
);
}
if (checkOperator === 'between' || checkOperator === 'not between') {
return this._not(checkOperator === 'not between').whereBetween(
arguments[0],
arguments[2]
);
}
}
// If the value is still null, check whether they're meaning
// where value is null
if (value === null) {
// Check for .where(key, 'is', null) or .where(key, 'is not', 'null');
if (checkOperator === 'is' || checkOperator === 'is not') {
return this._not(checkOperator === 'is not').whereNull(column);
}
}
// Push onto the where statement stack.
this._statements.push({
grouping: 'where',
type: 'whereBasic',
column,
operator,
value,
not: this._not(),
bool: this._bool(),
asColumn: this._asColumnFlag,
});
return this;
},
whereColumn(column, operator, rightColumn) {
this._asColumnFlag = true;
this.where.apply(this, arguments);
this._asColumnFlag = false;
return this;
},
// Adds an `or where` clause to the query.
orWhere() {
this._bool('or');
const obj = arguments[0];
if (isObject(obj) && !isFunction(obj) && !(obj instanceof Raw)) {
return this.whereWrapped(function () {
for (const key in obj) {
this.andWhere(key, obj[key]);
}
});
}
return this.where.apply(this, arguments);
},
orWhereColumn() {
this._bool('or');
const obj = arguments[0];
if (isObject(obj) && !isFunction(obj) && !(obj instanceof Raw)) {
return this.whereWrapped(function () {
for (const key in obj) {
this.andWhereColumn(key, '=', obj[key]);
}
});
}
return this.whereColumn.apply(this, arguments);
},
// Adds an `not where` clause to the query.
whereNot() {
return this._not(true).where.apply(this, arguments);
},
whereNotColumn() {
return this._not(true).whereColumn.apply(this, arguments);
},
// Adds an `or not where` clause to the query.
orWhereNot() {
return this._bool('or').whereNot.apply(this, arguments);
},
orWhereNotColumn() {
return this._bool('or').whereNotColumn.apply(this, arguments);
},
// Processes an object literal provided in a "where" clause.
_objectWhere(obj) {
const boolVal = this._bool();
const notVal = this._not() ? 'Not' : '';
for (const key in obj) {
this[boolVal + 'Where' + notVal](key, obj[key]);
}
return this;
},
// Adds a raw `where` clause to the query.
whereRaw(sql, bindings) {
const raw = sql instanceof Raw ? sql : this.client.raw(sql, bindings);
this._statements.push({
grouping: 'where',
type: 'whereRaw',
value: raw,
not: this._not(),
bool: this._bool(),
});
return this;
},
orWhereRaw(sql, bindings) {
return this._bool('or').whereRaw(sql, bindings);
},
// Helper for compiling any advanced `where` queries.
whereWrapped(callback) {
this._statements.push({
grouping: 'where',
type: 'whereWrapped',
value: callback,
not: this._not(),
bool: this._bool(),
});
return this;
},
// Adds a `where exists` clause to the query.
whereExists(callback) {
this._statements.push({
grouping: 'where',
type: 'whereExists',
value: callback,
not: this._not(),
bool: this._bool(),
});
return this;
},
// Adds an `or where exists` clause to the query.
orWhereExists(callback) {
return this._bool('or').whereExists(callback);
},
// Adds a `where not exists` clause to the query.
whereNotExists(callback) {
return this._not(true).whereExists(callback);
},
// Adds a `or where not exists` clause to the query.
orWhereNotExists(callback) {
return this._bool('or').whereNotExists(callback);
},
// Adds a `where in` clause to the query.
whereIn(column, values) {
if (Array.isArray(values) && isEmpty(values))
return this.where(this._not());
this._statements.push({
grouping: 'where',
type: 'whereIn',
column,
value: values,
not: this._not(),
bool: this._bool(),
});
return this;
},
// Adds a `or where in` clause to the query.
orWhereIn(column, values) {
return this._bool('or').whereIn(column, values);
},
// Adds a `where not in` clause to the query.
whereNotIn(column, values) {
return this._not(true).whereIn(column, values);
},
// Adds a `or where not in` clause to the query.
orWhereNotIn(column, values) {
return this._bool('or')._not(true).whereIn(column, values);
},
// Adds a `where null` clause to the query.
whereNull(column) {
this._statements.push({
grouping: 'where',
type: 'whereNull',
column,
not: this._not(),
bool: this._bool(),
});
return this;
},
// Adds a `or where null` clause to the query.
orWhereNull(column) {
return this._bool('or').whereNull(column);
},
// Adds a `where not null` clause to the query.
whereNotNull(column) {
return this._not(true).whereNull(column);
},
// Adds a `or where not null` clause to the query.
orWhereNotNull(column) {
return this._bool('or').whereNotNull(column);
},
// Adds a `where between` clause to the query.
whereBetween(column, values) {
assert(
Array.isArray(values),
'The second argument to whereBetween must be an array.'
);
assert(
values.length === 2,
'You must specify 2 values for the whereBetween clause'
);
this._statements.push({
grouping: 'where',
type: 'whereBetween',
column,
value: values,
not: this._not(),
bool: this._bool(),
});
return this;
},
// Adds a `where not between` clause to the query.
whereNotBetween(column, values) {
return this._not(true).whereBetween(column, values);
},
// Adds a `or where between` clause to the query.
orWhereBetween(column, values) {
return this._bool('or').whereBetween(column, values);
},
// Adds a `or where not between` clause to the query.
orWhereNotBetween(column, values) {
return this._bool('or').whereNotBetween(column, values);
},
// Adds a `group by` clause to the query.
groupBy(item) {
if (item instanceof Raw) {
return this.groupByRaw.apply(this, arguments);
}
this._statements.push({
grouping: 'group',
type: 'groupByBasic',
value: helpers.normalizeArr.apply(null, arguments),
});
return this;
},
// Adds a raw `group by` clause to the query.
groupByRaw(sql, bindings) {
const raw = sql instanceof Raw ? sql : this.client.raw(sql, bindings);
this._statements.push({
grouping: 'group',
type: 'groupByRaw',
value: raw,
});
return this;
},
// Adds a `order by` clause to the query.
orderBy(column, direction) {
if (Array.isArray(column)) {
return this._orderByArray(column);
}
this._statements.push({
grouping: 'order',
type: 'orderByBasic',
value: column,
direction,
});
return this;
},
// Adds a `order by` with multiple columns to the query.
_orderByArray(columnDefs) {
for (let i = 0; i < columnDefs.length; i++) {
const columnInfo = columnDefs[i];
if (isObject(columnInfo)) {
this._statements.push({
grouping: 'order',
type: 'orderByBasic',
value: columnInfo['column'],
direction: columnInfo['order'],
});
} else if (isString(columnInfo)) {
this._statements.push({
grouping: 'order',
type: 'orderByBasic',
value: columnInfo,
});
}
}
return this;
},
// Add a raw `order by` clause to the query.
orderByRaw(sql, bindings) {
const raw = sql instanceof Raw ? sql : this.client.raw(sql, bindings);
this._statements.push({
grouping: 'order',
type: 'orderByRaw',
value: raw,
});
return this;
},
_union(clause, args) {
let callbacks = args[0];
let wrap = args[1];
if (args.length === 1 || (args.length === 2 && isBoolean(wrap))) {
if (!Array.isArray(callbacks)) {
callbacks = [callbacks];
}
for (let i = 0, l = callbacks.length; i < l; i++) {
this._statements.push({
grouping: 'union',
clause: clause,
value: callbacks[i],
wrap: wrap || false,
});
}
} else {
callbacks = toArray(args).slice(0, args.length - 1);
wrap = args[args.length - 1];
if (!isBoolean(wrap)) {
callbacks.push(wrap);
wrap = false;
}
this._union(clause, [callbacks, wrap]);
}
return this;
},
// Add a union statement to the query.
union(...args) {
return this._union('union', args);
},
// Adds a union all statement to the query.
unionAll(...args) {
return this._union('union all', args);
},
// Adds an intersect statement to the query
intersect(callbacks, wrap) {
if (arguments.length === 1 || (arguments.length === 2 && isBoolean(wrap))) {
if (!Array.isArray(callbacks)) {
callbacks = [callbacks];
}
for (let i = 0, l = callbacks.length; i < l; i++) {
this._statements.push({
grouping: 'union',
clause: 'intersect',
value: callbacks[i],
wrap: wrap || false,
});
}
} else {
callbacks = toArray(arguments).slice(0, arguments.length - 1);
wrap = arguments[arguments.length - 1];
if (!isBoolean(wrap)) {
callbacks.push(wrap);
wrap = false;
}
this.intersect(callbacks, wrap);
}
return this;
},
// Adds a `having` clause to the query.
having(column, operator, value) {
if (column instanceof Raw && arguments.length === 1) {
return this.havingRaw(column);
}
// Check if the column is a function, in which case it's
// a having statement wrapped in parens.
if (typeof column === 'function') {
return this.havingWrapped(column);
}
this._statements.push({
grouping: 'having',
type: 'havingBasic',
column,
operator,
value,
bool: this._bool(),
not: this._not(),
});
return this;
},
orHaving: function orHaving() {
this._bool('or');
const obj = arguments[0];
if (isObject(obj) && !isFunction(obj) && !(obj instanceof Raw)) {
return this.havingWrapped(function () {
for (const key in obj) {
this.andHaving(key, obj[key]);
}
});
}
return this.having.apply(this, arguments);
},
// Helper for compiling any advanced `having` queries.
havingWrapped(callback) {
this._statements.push({
grouping: 'having',
type: 'havingWrapped',
value: callback,
bool: this._bool(),
not: this._not(),
});
return this;
},
havingNull(column) {
this._statements.push({
grouping: 'having',
type: 'havingNull',
column,
not: this._not(),
bool: this._bool(),
});
return this;
},
orHavingNull(callback) {
return this._bool('or').havingNull(callback);
},
havingNotNull(callback) {
return this._not(true).havingNull(callback);
},
orHavingNotNull(callback) {
return this._not(true)._bool('or').havingNull(callback);
},
havingExists(callback) {
this._statements.push({
grouping: 'having',
type: 'havingExists',
value: callback,
not: this._not(),
bool: this._bool(),
});
return this;
},
orHavingExists(callback) {
return this._bool('or').havingExists(callback);
},
havingNotExists(callback) {
return this._not(true).havingExists(callback);
},
orHavingNotExists(callback) {
return this._not(true)._bool('or').havingExists(callback);
},
havingBetween(column, values) {
assert(
Array.isArray(values),
'The second argument to havingBetween must be an array.'
);
assert(
values.length === 2,
'You must specify 2 values for the havingBetween clause'
);
this._statements.push({
grouping: 'having',
type: 'havingBetween',
column,
value: values,
not: this._not(),
bool: this._bool(),
});
return this;
},
orHavingBetween(column, values) {
return this._bool('or').havingBetween(column, values);
},
havingNotBetween(column, values) {
return this._not(true).havingBetween(column, values);
},
orHavingNotBetween(column, values) {
return this._not(true)._bool('or').havingBetween(column, values);
},
havingIn(column, values) {
if (Array.isArray(values) && isEmpty(values))
return this.where(this._not());
this._statements.push({
grouping: 'having',
type: 'havingIn',
column,
value: values,
not: this._not(),
bool: this._bool(),
});
return this;
},
// Adds a `or where in` clause to the query.
orHavingIn(column, values) {
return this._bool('or').havingIn(column, values);
},
// Adds a `where not in` clause to the query.
havingNotIn(column, values) {
return this._not(true).havingIn(column, values);
},
// Adds a `or where not in` clause to the query.
orHavingNotIn(column, values) {
return this._bool('or')._not(true).havingIn(column, values);
},
// Adds a raw `having` clause to the query.
havingRaw(sql, bindings) {
const raw = sql instanceof Raw ? sql : this.client.raw(sql, bindings);
this._statements.push({
grouping: 'having',
type: 'havingRaw',
value: raw,
bool: this._bool(),
not: this._not(),
});
return this;
},
orHavingRaw(sql, bindings) {
return this._bool('or').havingRaw(sql, bindings);
},
// Only allow a single "offset" to be set for the current query.
offset(value) {
if (value == null || value instanceof Raw || value instanceof Builder) {
// Builder for backward compatibility
this._single.offset = value;
} else {
const val = parseInt(value, 10);
if (isNaN(val)) {
this.client.logger.warn('A valid integer must be provided to offset');
} else {
this._single.offset = val;
}
}
return this;
},
// Only allow a single "limit" to be set for the current query.
limit(value) {
const val = parseInt(value, 10);
if (isNaN(val)) {
this.client.logger.warn('A valid integer must be provided to limit');
} else {
this._single.limit = val;
}
return this;
},
// Retrieve the "count" result of the query.
count(column, options) {
return this._aggregate('count', column || '*', options);
},
// Retrieve the minimum value of a given column.
min(column, options) {
return this._aggregate('min', column, options);
},
// Retrieve the maximum value of a given column.
max(column, options) {
return this._aggregate('max', column, options);
},
// Retrieve the sum of the values of a given column.
sum(column, options) {
return this._aggregate('sum', column, options);
},
// Retrieve the average of the values of a given column.
avg(column, options) {
return this._aggregate('avg', column, options);
},
// Retrieve the "count" of the distinct results of the query.
countDistinct() {
let columns = helpers.normalizeArr.apply(null, arguments);
let options;
if (columns.length > 1 && isPlainObject(last(columns))) {
[options] = columns.splice(columns.length - 1, 1);
}
if (!columns.length) {
columns = '*';
} else if (columns.length === 1) {
columns = columns[0];
}
return this._aggregate('count', columns, { ...options, distinct: true });
},
// Retrieve the sum of the distinct values of a given column.
sumDistinct(column, options) {
return this._aggregate('sum', column, { ...options, distinct: true });
},
// Retrieve the vg of the distinct results of the query.
avgDistinct(column, options) {
return this._aggregate('avg', column, { ...options, distinct: true });
},
// Increments a column's value by the specified amount.
increment(column, amount = 1) {
if (isObject(column)) {
for (const key in column) {
this._counter(key, column[key]);
}
return this;
}
return this._counter(column, amount);
},
// Decrements a column's value by the specified amount.
decrement(column, amount = 1) {
if (isObject(column)) {
for (const key in column) {
this._counter(key, -column[key]);
}
return this;
}
return this._counter(column, -amount);
},
// Clears increments/decrements
clearCounters() {
this._single.counter = {};
return this;
},
// Sets the values for a `select` query, informing that only the first
// row should be returned (limit 1).
first() {
if (!this._isSelectQuery()) {
throw new Error(`Cannot chain .first() on "${this._method}" query!`);
}
const args = new Array(arguments.length);
for (let i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
this.select.apply(this, args);
this._method = 'first';
this.limit(1);
return this;
},
// Use existing connection to execute the query
// Same value that client.acquireConnection() for an according client returns should be passed
connection(_connection) {
this._connection = _connection;
return this;
},
// Pluck a column from a query.
pluck(column) {
this._method = 'pluck';
this._single.pluck = column;
this._statements.push({
grouping: 'columns',
type: 'pluck',
value: column,
});
return this;
},
// Remove everything from select clause
clearSelect() {
this._clearGrouping('columns');
return this;
},
// Remove everything from where clause
clearWhere() {
this._clearGrouping('where');
return this;
},
// Remove everything from group clause
clearGroup() {
this._clearGrouping('group');
return this;
},
// Remove everything from order clause
clearOrder() {
this._clearGrouping('order');
return this;
},
// Remove everything from having clause
clearHaving() {
this._clearGrouping('having');
return this;
},
// Insert & Update
// ------
// Sets the values for an `insert` query.
insert(values, returning) {
this._method = 'insert';
if (!isEmpty(returning)) this.returning(returning);
this._single.insert = values;
return this;
},
// Sets the values for an `update`, allowing for both
// `.update(key, value, [returning])` and `.update(obj, [returning])` syntaxes.
update(values, returning) {
let ret;
const obj = this._single.update || {};
this._method = 'update';
if (isString(values)) {
obj[values] = returning;
if (arguments.length > 2) {
ret = arguments[2];
}
} else {
const keys = Object.keys(values);
if (this._single.update) {
this.client.logger.warn('Update called multiple times with objects.');
}
let i = -1;
while (++i < keys.length) {
obj[keys[i]] = values[keys[i]];
}
ret = arguments[1];
}
if (!isEmpty(ret)) this.returning(ret);
this._single.update = obj;
return this;
},
// Sets the returning value for the query.
returning(returning) {
this._single.returning = returning;
return this;
},
// Delete
// ------
// Executes a delete statement on the query;
delete(ret) {
this._method = 'del';
if (!isEmpty(ret)) this.returning(ret);
return this;
},
// Truncates a table, ends the query chain.
truncate(tableName) {
this._method = 'truncate';
if (tableName) {
this._single.table = tableName;
}
return this;
},
// Retrieves columns for the table specified by `knex(tableName)`
columnInfo(column) {
this._method = 'columnInfo';
this._single.columnInfo = column;
return this;
},
// Set a lock for update constraint.
forUpdate() {
this._single.lock = lockMode.forUpdate;
this._single.lockTables = helpers.normalizeArr.apply(null, arguments);
return this;
},
// Set a lock for share constraint.
forShare() {
this._single.lock = lockMode.forShare;
this._single.lockTables = helpers.normalizeArr.apply(null, arguments);
return this;
},
// Skips locked rows when using a lock constraint.
skipLocked() {
if (!this._isSelectQuery()) {
throw new Error(`Cannot chain .skipLocked() on "${this._method}" query!`);
}
if (!this._hasLockMode()) {
throw new Error(
'.skipLocked() can only be used after a call to .forShare() or .forUpdate()!'
);
}
if (this._single.waitMode === waitMode.noWait) {
throw new Error('.skipLocked() cannot be used together with .noWait()!');
}
this._single.waitMode = waitMode.skipLocked;
return this;
},
// Causes error when acessing a locked row instead of waiting for it to be released.
noWait() {
if (!this._isSelectQuery()) {
throw new Error(`Cannot chain .noWait() on "${this._method}" query!`);
}
if (!this._hasLockMode()) {
throw new Error(
'.noWait() can only be used after a call to .forShare() or .forUpdate()!'
);
}
if (this._single.waitMode === waitMode.skipLocked) {
throw new Error('.noWait() cannot be used together with .skipLocked()!');
}
this._single.waitMode = waitMode.noWait;
return this;
},
// Takes a JS object of methods to call and calls them
fromJS(obj) {
each(obj, (val, key) => {
if (typeof this[key] !== 'function') {
this.client.logger.warn(`Knex Error: unknown key ${key}`);
}
if (Array.isArray(val)) {
this[key].apply(this, val);
} else {
this[key](val);
}
});
return this;
},
// Passes query to provided callback function, useful for e.g. composing
// domain-specific helpers
modify(callback) {
callback.apply(this, [this].concat(tail(arguments)));
return this;
},
// ----------------------------------------------------------------------
// Helper for the incrementing/decrementing queries.
_counter(column, amount) {
amount = parseFloat(amount);
this._method = 'update';
this._single.counter = this._single.counter || {};
this._single.counter[column] = amount;
return this;
},
// Helper to get or set the "boolFlag" value.
_bool(val) {
if (arguments.length === 1) {
this._boolFlag = val;
return this;
}
const ret = this._boolFlag;
this._boolFlag = 'and';
return ret;
},
// Helper to get or set the "notFlag" value.
_not(val) {
if (arguments.length === 1) {
this._notFlag = val;
return this;
}
const ret = this._notFlag;
this._notFlag = false;
return ret;
},
// Helper to get or set the "joinFlag" value.
_joinType(val) {
if (arguments.length === 1) {
this._joinFlag = val;
return this;
}
const ret = this._joinFlag || 'inner';
this._joinFlag = 'inner';
return ret;
},
// Helper for compiling any aggregate queries.
_aggregate(method, column, options = {}) {
this._statements.push({
grouping: 'columns',
type: column instanceof Raw ? 'aggregateRaw' : 'aggregate',
method,
value: column,
aggregateDistinct: options.distinct || false,
alias: options.as,
});
return this;
},
// Helper function for clearing or reseting a grouping type from the builder
_clearGrouping(grouping) {
this._statements = reject(this._statements, { grouping });
},
// Helper function that checks if the builder will emit a select query
_isSelectQuery() {
return ['pluck', 'first', 'select'].includes(this._method);
},
// Helper function that checks if the query has a lock mode set
_hasLockMode() {
return [lockMode.forShare, lockMode.forUpdate].includes(this._single.lock);
},
});
Object.defineProperty(Builder.prototype, 'or', {
get() {
return this._bool('or');
},
});
Object.defineProperty(Builder.prototype, 'not', {
get() {
return this._not(true);
},
});
Builder.prototype.select = Builder.prototype.columns;
Builder.prototype.column = Builder.prototype.columns;
Builder.prototype.andWhereNot = Builder.prototype.whereNot;
Builder.prototype.andWhereNotColumn = Builder.prototype.whereNotColumn;
Builder.prototype.andWhere = Builder.prototype.where;
Builder.prototype.andWhereColumn = Builder.prototype.whereColumn;
Builder.prototype.andWhereRaw = Builder.prototype.whereRaw;
Builder.prototype.andWhereBetween = Builder.prototype.whereBetween;
Builder.prototype.andWhereNotBetween = Builder.prototype.whereNotBetween;
Builder.prototype.andHaving = Builder.prototype.having;
Builder.prototype.andHavingIn = Builder.prototype.havingIn;
Builder.prototype.andHavingNotIn = Builder.prototype.havingNotIn;
Builder.prototype.andHavingNull = Builder.prototype.havingNull;
Builder.prototype.andHavingNotNull = Builder.prototype.havingNotNull;
Builder.prototype.andHavingExists = Builder.prototype.havingExists;
Builder.prototype.andHavingNotExists = Builder.prototype.havingNotExists;
Builder.prototype.andHavingBetween = Builder.prototype.havingBetween;
Builder.prototype.andHavingNotBetween = Builder.prototype.havingNotBetween;
Builder.prototype.from = Builder.prototype.table;
Builder.prototype.into = Builder.prototype.table;
Builder.prototype.del = Builder.prototype.delete;
// Attach all of the top level promise methods that should be chainable.
import interfacelib from '../interface.js';
interfacelib(Builder);
helpers.addQueryContext(Builder);
Builder.extend = (methodName, fn) => {
if (Object.prototype.hasOwnProperty.call(Builder.prototype, methodName)) {
throw new Error(
`Can't extend QueryBuilder with existing method ('${methodName}').`
);
}
assign(Builder.prototype, { [methodName]: fn });
};
export default Builder; | the_stack |
import React, { createRef } from 'react';
import { _t } from "../../../languageHandler";
import { MatrixClientPeg } from "../../../MatrixClientPeg";
import Field from "../elements/Field";
import { replaceableComponent } from "../../../utils/replaceableComponent";
import { mediaFromMxc } from "../../../customisations/Media";
import AccessibleButton from "../elements/AccessibleButton";
import AvatarSetting from "../settings/AvatarSetting";
interface IProps {
roomId: string;
}
interface IState {
originalDisplayName: string;
displayName: string;
originalAvatarUrl: string;
avatarUrl: string;
avatarFile: File;
originalTopic: string;
topic: string;
profileFieldsTouched: Record<string, boolean>;
canSetName: boolean;
canSetTopic: boolean;
canSetAvatar: boolean;
}
// TODO: Merge with ProfileSettings?
@replaceableComponent("views.room_settings.RoomProfileSettings")
export default class RoomProfileSettings extends React.Component<IProps, IState> {
private avatarUpload = createRef<HTMLInputElement>();
constructor(props: IProps) {
super(props);
const client = MatrixClientPeg.get();
const room = client.getRoom(props.roomId);
if (!room) throw new Error(`Expected a room for ID: ${props.roomId}`);
const avatarEvent = room.currentState.getStateEvents("m.room.avatar", "");
let avatarUrl = avatarEvent && avatarEvent.getContent() ? avatarEvent.getContent()["url"] : null;
if (avatarUrl) avatarUrl = mediaFromMxc(avatarUrl).getSquareThumbnailHttp(96);
const topicEvent = room.currentState.getStateEvents("m.room.topic", "");
const topic = topicEvent && topicEvent.getContent() ? topicEvent.getContent()['topic'] : '';
const nameEvent = room.currentState.getStateEvents('m.room.name', '');
const name = nameEvent && nameEvent.getContent() ? nameEvent.getContent()['name'] : '';
this.state = {
originalDisplayName: name,
displayName: name,
originalAvatarUrl: avatarUrl,
avatarUrl: avatarUrl,
avatarFile: null,
originalTopic: topic,
topic: topic,
profileFieldsTouched: {},
canSetName: room.currentState.maySendStateEvent('m.room.name', client.getUserId()),
canSetTopic: room.currentState.maySendStateEvent('m.room.topic', client.getUserId()),
canSetAvatar: room.currentState.maySendStateEvent('m.room.avatar', client.getUserId()),
};
}
private uploadAvatar = (): void => {
this.avatarUpload.current.click();
};
private removeAvatar = (): void => {
// clear file upload field so same file can be selected
this.avatarUpload.current.value = "";
this.setState({
avatarUrl: null,
avatarFile: null,
profileFieldsTouched: {
...this.state.profileFieldsTouched,
avatar: true,
},
});
};
private isSaveEnabled = () => {
return Boolean(Object.values(this.state.profileFieldsTouched).length);
};
private cancelProfileChanges = async (e: React.MouseEvent): Promise<void> => {
e.stopPropagation();
e.preventDefault();
if (!this.isSaveEnabled()) return;
this.setState({
profileFieldsTouched: {},
displayName: this.state.originalDisplayName,
topic: this.state.originalTopic,
avatarUrl: this.state.originalAvatarUrl,
avatarFile: null,
});
};
private saveProfile = async (e: React.FormEvent): Promise<void> => {
e.stopPropagation();
e.preventDefault();
if (!this.isSaveEnabled()) return;
this.setState({ profileFieldsTouched: {} });
const client = MatrixClientPeg.get();
const newState: Partial<IState> = {};
// TODO: What do we do about errors?
const displayName = this.state.displayName.trim();
if (this.state.originalDisplayName !== this.state.displayName) {
await client.setRoomName(this.props.roomId, displayName);
newState.originalDisplayName = displayName;
newState.displayName = displayName;
}
if (this.state.avatarFile) {
const uri = await client.uploadContent(this.state.avatarFile);
await client.sendStateEvent(this.props.roomId, 'm.room.avatar', { url: uri }, '');
newState.avatarUrl = mediaFromMxc(uri).getSquareThumbnailHttp(96);
newState.originalAvatarUrl = newState.avatarUrl;
newState.avatarFile = null;
} else if (this.state.originalAvatarUrl !== this.state.avatarUrl) {
await client.sendStateEvent(this.props.roomId, 'm.room.avatar', {}, '');
}
if (this.state.originalTopic !== this.state.topic) {
await client.setRoomTopic(this.props.roomId, this.state.topic);
newState.originalTopic = this.state.topic;
}
this.setState(newState as IState);
};
private onDisplayNameChanged = (e: React.ChangeEvent<HTMLInputElement>): void => {
this.setState({ displayName: e.target.value });
if (this.state.originalDisplayName === e.target.value) {
this.setState({
profileFieldsTouched: {
...this.state.profileFieldsTouched,
name: false,
},
});
} else {
this.setState({
profileFieldsTouched: {
...this.state.profileFieldsTouched,
name: true,
},
});
}
};
private onTopicChanged = (e: React.ChangeEvent<HTMLTextAreaElement>): void => {
this.setState({ topic: e.target.value });
if (this.state.originalTopic === e.target.value) {
this.setState({
profileFieldsTouched: {
...this.state.profileFieldsTouched,
topic: false,
},
});
} else {
this.setState({
profileFieldsTouched: {
...this.state.profileFieldsTouched,
topic: true,
},
});
}
};
private onAvatarChanged = (e: React.ChangeEvent<HTMLInputElement>): void => {
if (!e.target.files || !e.target.files.length) {
this.setState({
avatarUrl: this.state.originalAvatarUrl,
avatarFile: null,
profileFieldsTouched: {
...this.state.profileFieldsTouched,
avatar: false,
},
});
return;
}
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = (ev) => {
this.setState({
avatarUrl: String(ev.target.result),
avatarFile: file,
profileFieldsTouched: {
...this.state.profileFieldsTouched,
avatar: true,
},
});
};
reader.readAsDataURL(file);
};
public render(): JSX.Element {
let profileSettingsButtons;
if (
this.state.canSetName ||
this.state.canSetTopic ||
this.state.canSetAvatar
) {
profileSettingsButtons = (
<div className="mx_ProfileSettings_buttons">
<AccessibleButton
onClick={this.cancelProfileChanges}
kind="link"
disabled={!this.isSaveEnabled()}
>
{ _t("Cancel") }
</AccessibleButton>
<AccessibleButton
onClick={this.saveProfile}
kind="primary"
disabled={!this.isSaveEnabled()}
>
{ _t("Save") }
</AccessibleButton>
</div>
);
}
return (
<form
onSubmit={this.saveProfile}
autoComplete="off"
noValidate={true}
className="mx_ProfileSettings_profileForm"
>
<input
type="file"
ref={this.avatarUpload}
className="mx_ProfileSettings_avatarUpload"
onChange={this.onAvatarChanged}
accept="image/*"
/>
<div className="mx_ProfileSettings_profile">
<div className="mx_ProfileSettings_controls">
<Field
label={_t("Room Name")}
type="text"
value={this.state.displayName}
autoComplete="off"
onChange={this.onDisplayNameChanged}
disabled={!this.state.canSetName}
/>
<Field
className="mx_ProfileSettings_controls_topic"
id="profileTopic"
label={_t("Room Topic")}
disabled={!this.state.canSetTopic}
type="text"
value={this.state.topic}
autoComplete="off"
onChange={this.onTopicChanged}
element="textarea"
/>
</div>
<AvatarSetting
avatarUrl={this.state.avatarUrl}
avatarName={this.state.displayName || this.props.roomId}
avatarAltText={_t("Room avatar")}
uploadAvatar={this.state.canSetAvatar ? this.uploadAvatar : undefined}
removeAvatar={this.state.canSetAvatar ? this.removeAvatar : undefined} />
</div>
{ profileSettingsButtons }
</form>
);
}
} | the_stack |
export class MimeTypeNames {
/**
* @description Used to denote the encoding necessary for files containing JavaScript source code.
* @description The alternative MIME type for this file type is text/javascript.
*/
public static ApplicationXJavascript = 'application/x-javascript';
/**
* @description 24bit Linear PCM audio at 8-48kHz, 1-N channels; Defined in RFC 3190
*/
public static AudioL24 = 'audio/L24';
/**
* @description Adobe Flash files for example with the extension .swf
*/
public static ApplicationXShockwaveFlash = 'application/x-shockwave-flash';
/**
* @description Arbitrary binary data.[5] Generally speaking this type identifies files that are not associated with a specific application.
* @description Contrary to past assumptions by software packages such as Apache this is not a type that should be applied to unknown files.
* @description In such a case, a server or application should not indicate a content type, as it may be incorrect, but rather,
* @description should omit the type in order to allow the recipient to guess the type.[6]
*/
public static ApplicationOctetStream = 'application/octet-stream';
/**
* @description Atom feeds
*/
public static ApplicationAtomXml = 'application/atom+xml';
/**
* @description Cascading Style Sheets; Defined in RFC 2318
*/
public static TextCss = 'text/css';
/**
* @description commands; subtype resident in Gecko browsers like Firefox 3.5
*/
public static TextCmd = 'text/cmd';
/**
* @description Comma-separated values; Defined in RFC 4180
*/
public static TextCsv = 'text/csv';
/**
* @description deb (file format), a software package format used by the Debian project
*/
public static ApplicationXDeb = 'application/x-deb';
/**
* @description Defined in RFC 1847
*/
public static MultipartEncrypted = 'multipart/encrypted';
/**
* @description Defined in RFC 1847
*/
public static MultipartSigned = 'multipart/signed';
/**
* @description Defined in RFC 2616
*/
public static MessageHttp = 'message/http';
/**
* @description Defined in RFC 4735
*/
public static ModelExample = 'model/example';
/**
* @description device-independent document in DVI format
*/
public static ApplicationXDvi = 'application/x-dvi';
/**
* @description DTD files; Defined by RFC 3023
*/
public static ApplicationXmlDtd = 'application/xml-dtd';
/**
* @description ECMAScript/JavaScript; Defined in RFC 4329 (equivalent to application/ecmascript but with looser processing rules)
* @description It is not accepted in IE 8 or earlier - text/javascript is accepted but it is defined as obsolete in RFC 4329.
* @description The "type" attribute of the <script> tag in HTML5 is optional and in practice omitting the media type of JavaScript
* @description programs is the most interoperable solution since all browsers have always assumed the correct default even before HTML5.
*/
public static ApplicationJavascript = 'application/javascript';
/**
* @description ECMAScript/JavaScript; Defined in RFC 4329 (equivalent to application/javascript but with stricter processing rules)
*/
public static ApplicationEcmascript = 'application/ecmascript';
/**
* @description EDI EDIFACT data; Defined in RFC 1767
*/
public static ApplicationEdifact = 'application/EDIFACT';
/**
* @description EDI X12 data; Defined in RFC 1767
*/
public static ApplicationEdiX12 = 'application/EDI-X12';
/**
* @description Email; Defined in RFC 2045 and RFC 2046
*/
public static MessagePartial = 'message/partial';
/**
* @description Email; EML files, MIME files, MHT files, MHTML files; Defined in RFC 2045 and RFC 2046
*/
public static MessageRfc822 = 'message/rfc822';
/**
* @description Extensible Markup Language; Defined in RFC 3023
*/
public static TextXml = 'text/xml';
/**
* @description Flash video (FLV files)
*/
public static VideoXFlv = 'video/x-flv';
/**
* @description GIF image; Defined in RFC 2045 and RFC 2046
*/
public static ImageGif = 'image/gif';
/**
* @description GoogleWebToolkit data
*/
public static TextXGwtRpc = 'text/x-gwt-rpc';
/**
* @description Gzip
*/
public static ApplicationXGzip = 'application/x-gzip';
/**
* @description HTML; Defined in RFC 2854
*/
public static TextHtml = 'text/html';
/**
* @description ICO image; Registered[9]
*/
public static ImageVndMicrosoftIcon = 'image/vnd.microsoft.icon';
/**
* @description IGS files, IGES files; Defined in RFC 2077
*/
public static ModelIges = 'model/iges';
/**
* @description IMDN Instant Message Disposition Notification; Defined in RFC 5438
*/
public static MessageImdnXml = 'message/imdn+xml';
/**
* @description JavaScript Object Notation JSON; Defined in RFC 4627
*/
public static ApplicationJson = 'application/json';
/**
* @description JavaScript Object Notation (JSON) Patch; Defined in RFC 6902
*/
public static ApplicationJsonPatch = 'application/json-patch+json';
/**
* @description JavaScript - Defined in and obsoleted by RFC 4329 in order to discourage its usage in favor of application/javascript.
* @description However,text/javascript is allowed in HTML 4 and 5 and, unlike application/javascript, has cross-browser support.
* @description The "type" attribute of the <script> tag in HTML5 is optional and there is no need to use it at all since all browsers
* @description have always assumed the correct default (even in HTML 4 where it was required by the specification).
*/
public static TextJavascript = 'text/javascript';
/**
* @description JPEG JFIF image; Associated with Internet Explorer; Listed in ms775147(v=vs.85) - Progressive JPEG,
* @description initiated before global browser support for progressive JPEGs (Microsoft and Firefox).
*/
public static ImagePjpeg = 'image/pjpeg';
/**
* @description JPEG JFIF image; Defined in RFC 2045 and RFC 2046
*/
public static ImageJpeg = 'image/jpeg';
/**
* @description jQuery template data
*/
public static TextXJqueryTmpl = 'text/x-jquery-tmpl';
/**
* @description KML files (e.g. for Google Earth)
*/
public static ApplicationVndGoogleEarthKmlXml =
'application/vnd.google-earth.kml+xml';
/**
* @description LaTeX files
*/
public static ApplicationXLatex = 'application/x-latex';
/**
* @description Matroska open media format
*/
public static VideoXMatroska = 'video/x-matroska';
/**
* @description Microsoft Excel 2007 files
*/
public static ApplicationVndOpenxmlformatsOfficedocumentSpreadsheetmlSheet =
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
/**
* @description Microsoft Excel files
*/
public static ApplicationVndMsExcel = 'application/vnd.ms-excel';
/**
* @description Microsoft Powerpoint 2007 files
*/
public static ApplicationVndOpenxmlformatsOfficedocumentPresentationmlPresentation =
'application/vnd.openxmlformats-officedocument.presentationml.presentation';
/**
* @description Microsoft Powerpoint files
*/
public static ApplicationVndMsPowerpoint = 'application/vnd.ms-powerpoint';
/**
* @description Microsoft Word 2007 files
*/
public static ApplicationVndOpenxmlformatsOfficedocumentWordprocessingmlDocument =
'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
/**
* @description Microsoft Word files[15]
*/
public static ApplicationMsword = 'application/msword';
/**
* @description MIME Email; Defined in RFC 2045 and RFC 2046
*/
public static MultipartAlternative = 'multipart/alternative';
/**
* @description MIME Email; Defined in RFC 2045 and RFC 2046
*/
public static MultipartMixed = 'multipart/mixed';
/**
* @description MIME Email; Defined in RFC 2387 and used by MHTML (HTML mail)
*/
public static MultipartRelated = 'multipart/related';
/**
* @description MIME Webform; Defined in RFC 2388
*/
public static MultipartFormData = 'multipart/form-data';
/**
* @description Mozilla XUL files
*/
public static ApplicationVndMozillaXulXml = 'application/vnd.mozilla.xul+xml';
/**
* @description MP3 or other MPEG audio; Defined in RFC 3003
*/
public static AudioMpeg = 'audio/mpeg';
/**
* @description MP4 audio
*/
public static AudioMp4 = 'audio/mp4';
/**
* @description MP4 video; Defined in RFC 4337
*/
public static VideoMp4 = 'video/mp4';
/**
* @description MPEG-1 video with multiplexed audio; Defined in RFC 2045 and RFC 2046
*/
public static VideoMpeg = 'video/mpeg';
/**
* @description MSH files, MESH files; Defined in RFC 2077, SILO files
*/
public static ModelMesh = 'model/mesh';
/**
* @description mulaw audio at 8 kHz, 1 channel; Defined in RFC 2046
*/
public static AudioBasic = 'audio/basic';
/**
* @description Ogg Theora or other video (with audio); Defined in RFC 5334
*/
public static VideoOgg = 'video/ogg';
/**
* @description Ogg Vorbis, Speex, Flac and other audio; Defined in RFC 5334
*/
public static AudioOgg = 'audio/ogg';
/**
* @description Ogg, a multimedia bitstream container format; Defined in RFC 5334
*/
public static ApplicationOgg = 'application/ogg';
/**
* @description OP
*/
public static ApplicationXopXml = 'application/xop+xml';
/**
* @description OpenDocument Graphics; Registered[14]
*/
public static ApplicationVndOasisOpendocumentGraphics =
'application/vnd.oasis.opendocument.graphics';
/**
* @description OpenDocument Presentation; Registered[13]
*/
public static ApplicationVndOasisOpendocumentPresentation =
'application/vnd.oasis.opendocument.presentation';
/**
* @description OpenDocument Spreadsheet; Registered[12]
*/
public static ApplicationVndOasisOpendocumentSpreadsheet =
'application/vnd.oasis.opendocument.spreadsheet';
/**
* @description OpenDocument Text; Registered[11]
*/
public static ApplicationVndOasisOpendocumentText =
'application/vnd.oasis.opendocument.text';
/**
* @description p12 files
*/
public static ApplicationXPkcs12 = 'application/x-pkcs12';
/**
* @description p7b and spc files
*/
public static ApplicationXPkcs7Certificates =
'application/x-pkcs7-certificates';
/**
* @description p7c files
*/
public static ApplicationXPkcs7Mime = 'application/x-pkcs7-mime';
/**
* @description p7r files
*/
public static ApplicationXPkcs7Certreqresp =
'application/x-pkcs7-certreqresp';
/**
* @description p7s files
*/
public static ApplicationXPkcs7Signature = 'application/x-pkcs7-signature';
/**
* @description Portable Document Format, PDF has been in use for document exchange on the Internet since 1993; Defined in RFC 3778
*/
public static ApplicationPdf = 'application/pdf';
/**
* @description Portable Network Graphics; Registered,[8] Defined in RFC 2083
*/
public static ImagePng = 'image/png';
/**
* @description PostScript; Defined in RFC 2046
*/
public static ApplicationPostscript = 'application/postscript';
/**
* @description QuickTime video; Registered[10]
*/
public static VideoQuicktime = 'video/quicktime';
/**
* @description RAR archive files
*/
public static ApplicationXRarCompressed = 'application/x-rar-compressed';
/**
* @description RealAudio; Documented in RealPlayer Customer Support Answer 2559
*/
public static AudioVndRnRealaudio = 'audio/vnd.rn-realaudio';
/**
* @description Resource Description Framework; Defined by RFC 3870
*/
public static ApplicationRdfXml = 'application/rdf+xml';
/**
* @description RSS feeds
*/
public static ApplicationRssXml = 'application/rss+xml';
/**
* @description SOAP; Defined by RFC 3902
*/
public static ApplicationSoapXml = 'application/soap+xml';
/**
* @description StuffIt archive files
*/
public static ApplicationXStuffit = 'application/x-stuffit';
/**
* @description SVG vector image; Defined in SVG Tiny 1.2 Specification Appendix M
*/
public static ImageSvgXml = 'image/svg+xml';
/**
* @description Tag Image File Format (only for Baseline TIFF); Defined in RFC 3302
*/
public static ImageTiff = 'image/tiff';
/**
* @description Tarball files
*/
public static ApplicationXTar = 'application/x-tar';
/**
* @description Textual data; Defined in RFC 2046 and RFC 3676
*/
public static TextPlain = 'text/plain';
/**
* @description TrueType Font No registered MIME type, but this is the most commonly used
*/
public static ApplicationXFontTtf = 'application/x-font-ttf';
/**
* @description Card (contact information); Defined in RFC 6350
*/
public static TextVcard = 'text/vcard';
/**
* @description Vorbis encoded audio; Defined in RFC 5215
*/
public static AudioVorbis = 'audio/vorbis';
/**
* @description WAV audio; Defined in RFC 2361
*/
public static AudioVndWave = 'audio/vnd.wave';
/**
* @description Web Open Font Format; (candidate recommendation; use application/x-font-woff until standard is official)
*/
public static ApplicationFontWoff = 'application/font-woff';
/**
* @description WebM Matroska-based open media format
*/
public static VideoWebm = 'video/webm';
/**
* @description WebM open media format
*/
public static AudioWebm = 'audio/webm';
/**
* @description Windows Media Audio Redirector; Documented in Microsoft help page
*/
public static AudioXMsWax = 'audio/x-ms-wax';
/**
* @description Windows Media Audio; Documented in Microsoft KB 288102
*/
public static AudioXMsWma = 'audio/x-ms-wma';
/**
* @description Windows Media Video; Documented in Microsoft KB 288102
*/
public static VideoXMsWmv = 'video/x-ms-wmv';
/**
* @description WRL files, VRML files; Defined in RFC 2077
*/
public static ModelVrml = 'model/vrml';
/**
* @description X3D ISO standard for representing 3D computer graphics, X3D XML files
*/
public static ModelX3DXml = 'model/x3d+xml';
/**
* @description X3D ISO standard for representing 3D computer graphics, X3DB binary files
*/
public static ModelX3DBinary = 'model/x3d+binary';
/**
* @description X3D ISO standard for representing 3D computer graphics, X3DV VRML files
*/
public static ModelX3DVrml = 'model/x3d+vrml';
/**
* @description XHTML; Defined by RFC 3236
*/
public static ApplicationXhtmlXml = 'application/xhtml+xml';
/**
* @description ZIP archive files; Registered[7]
*/
public static ApplicationZip = 'application/zip';
} | the_stack |
import React from "react";
import type { RenderResult } from "@testing-library/react";
import { fireEvent } from "@testing-library/react";
import directoryForLensLocalStorageInjectable from "../../common/directory-for-lens-local-storage/directory-for-lens-local-storage.injectable";
import routesInjectable from "../../renderer/routes/routes.injectable";
import { matches } from "lodash/fp";
import type { ApplicationBuilder } from "../../renderer/components/test-utils/get-application-builder";
import { getApplicationBuilder } from "../../renderer/components/test-utils/get-application-builder";
import writeJsonFileInjectable from "../../common/fs/write-json-file.injectable";
import pathExistsInjectable from "../../common/fs/path-exists.injectable";
import readJsonFileInjectable from "../../common/fs/read-json-file.injectable";
import type { DiContainer } from "@ogre-tools/injectable";
import { navigateToRouteInjectionToken } from "../../common/front-end-routing/navigate-to-route-injection-token";
import assert from "assert";
import { getSidebarItem } from "../utils";
import type { FakeExtensionData } from "../../renderer/components/test-utils/get-renderer-extension-fake";
import { getRendererExtensionFakeFor } from "../../renderer/components/test-utils/get-renderer-extension-fake";
describe("cluster - sidebar and tab navigation for extensions", () => {
let applicationBuilder: ApplicationBuilder;
let rendererDi: DiContainer;
let rendered: RenderResult;
beforeEach(() => {
jest.useFakeTimers();
applicationBuilder = getApplicationBuilder();
rendererDi = applicationBuilder.dis.rendererDi;
applicationBuilder.setEnvironmentToClusterFrame();
applicationBuilder.beforeApplicationStart(({ rendererDi }) => {
rendererDi.override(
directoryForLensLocalStorageInjectable,
() => "/some-directory-for-lens-local-storage",
);
});
});
describe("given extension with cluster pages and cluster page menus", () => {
beforeEach(async () => {
const getRendererExtensionFake = getRendererExtensionFakeFor(applicationBuilder);
const testExtension = getRendererExtensionFake(extensionStubWithSidebarItems);
await applicationBuilder.addExtensions(testExtension);
});
describe("given no state for expanded sidebar items exists, and navigated to child sidebar item, when rendered", () => {
beforeEach(async () => {
applicationBuilder.beforeRender(({ rendererDi }) => {
const navigateToRoute = rendererDi.inject(navigateToRouteInjectionToken);
const route = rendererDi
.inject(routesInjectable)
.get()
.find(
matches({
path: "/extension/some-extension-name/some-child-page-id",
}),
);
assert(route);
navigateToRoute(route);
});
rendered = await applicationBuilder.render();
});
it("renders", () => {
expect(rendered.container).toMatchSnapshot();
});
it("parent is highlighted", () => {
const parent = getSidebarItem(
rendered,
"some-extension-name-some-parent-id",
);
expect(parent?.dataset.isActiveTest).toBe("true");
});
it("parent sidebar item is not expanded", () => {
const child = getSidebarItem(
rendered,
"some-extension-name-some-child-id",
);
expect(child).toBeUndefined();
});
it("child page is shown", () => {
expect(rendered.getByTestId("some-child-page")).not.toBeNull();
});
});
describe("given state for expanded sidebar items already exists, when rendered", () => {
beforeEach(async () => {
applicationBuilder.beforeRender(async ({ rendererDi }) => {
const writeJsonFileFake = rendererDi.inject(writeJsonFileInjectable);
await writeJsonFileFake(
"/some-directory-for-lens-local-storage/app.json",
{
sidebar: {
expanded: { "some-extension-name-some-parent-id": true },
width: 200,
},
},
);
});
rendered = await applicationBuilder.render();
});
it("renders", () => {
expect(rendered.container).toMatchSnapshot();
});
it("parent sidebar item is not highlighted", () => {
const parent = getSidebarItem(
rendered,
"some-extension-name-some-parent-id",
);
expect(parent?.dataset.isActiveTest).toBe("false");
});
it("parent sidebar item is expanded", () => {
const child = getSidebarItem(
rendered,
"some-extension-name-some-child-id",
);
expect(child).not.toBeUndefined();
});
});
describe("given state for expanded unknown sidebar items already exists, when rendered", () => {
beforeEach(async () => {
applicationBuilder.beforeRender(async ({ rendererDi }) => {
const writeJsonFileFake = rendererDi.inject(writeJsonFileInjectable);
await writeJsonFileFake(
"/some-directory-for-lens-local-storage/app.json",
{
sidebar: {
expanded: { "some-extension-name-some-unknown-parent-id": true },
width: 200,
},
},
);
});
rendered = await applicationBuilder.render();
});
it("renders without errors", () => {
expect(rendered.container).toMatchSnapshot();
});
it("parent sidebar item is not expanded", () => {
const child = getSidebarItem(
rendered,
"some-extension-name-some-child-id",
);
expect(child).toBeUndefined();
});
});
describe("given empty state for expanded sidebar items already exists, when rendered", () => {
beforeEach(async () => {
applicationBuilder.beforeRender(async ({ rendererDi }) => {
const writeJsonFileFake = rendererDi.inject(writeJsonFileInjectable);
await writeJsonFileFake(
"/some-directory-for-lens-local-storage/app.json",
{
someThingButSidebar: {},
},
);
});
rendered = await applicationBuilder.render();
});
it("renders without errors", () => {
expect(rendered.container).toMatchSnapshot();
});
it("parent sidebar item is not expanded", () => {
const child = getSidebarItem(
rendered,
"some-extension-name-some-child-id",
);
expect(child).toBeUndefined();
});
});
describe("given no initially persisted state for sidebar items, when rendered", () => {
beforeEach(async () => {
rendered = await applicationBuilder.render();
});
it("renders", () => {
expect(rendered.container).toMatchSnapshot();
});
it("parent sidebar item is not highlighted", () => {
const parent = getSidebarItem(
rendered,
"some-extension-name-some-parent-id",
);
expect(parent?.dataset.isActiveTest).toBe("false");
});
it("parent sidebar item is not expanded", () => {
const child = getSidebarItem(
rendered,
"some-extension-name-some-child-id",
);
expect(child).toBeUndefined();
});
describe("when a parent sidebar item is expanded", () => {
beforeEach(() => {
const parentLink = rendered.getByTestId(
"sidebar-item-link-for-some-extension-name-some-parent-id",
);
fireEvent.click(parentLink);
});
it("renders", () => {
expect(rendered.container).toMatchSnapshot();
});
it("parent sidebar item is not highlighted", () => {
const parent = getSidebarItem(
rendered,
"some-extension-name-some-parent-id",
);
expect(parent?.dataset.isActiveTest).toBe("false");
});
it("parent sidebar item is expanded", () => {
const child = getSidebarItem(
rendered,
"some-extension-name-some-child-id",
);
expect(child).not.toBeUndefined();
});
describe("when a child of the parent is selected", () => {
beforeEach(() => {
const childLink = rendered.getByTestId(
"sidebar-item-link-for-some-extension-name-some-child-id",
);
fireEvent.click(childLink);
});
it("renders", () => {
expect(rendered.container).toMatchSnapshot();
});
it("parent is highlighted", () => {
const parent = getSidebarItem(
rendered,
"some-extension-name-some-parent-id",
);
expect(parent?.dataset.isActiveTest).toBe("true");
});
it("child is highlighted", () => {
const child = getSidebarItem(
rendered,
"some-extension-name-some-child-id",
);
expect(child?.dataset.isActiveTest).toBe("true");
});
it("child page is shown", () => {
expect(rendered.getByTestId("some-child-page")).not.toBeNull();
});
it("renders tabs", () => {
expect(rendered.getByTestId("tab-layout")).not.toBeNull();
});
it("tab for child page is active", () => {
const tabLink = rendered.getByTestId(
"tab-link-for-some-extension-name-some-child-id",
);
expect(tabLink.dataset.isActiveTest).toBe("true");
});
it("tab for sibling page is not active", () => {
const tabLink = rendered.getByTestId(
"tab-link-for-some-extension-name-some-other-child-id",
);
expect(tabLink.dataset.isActiveTest).toBe("false");
});
it("when not enough time passes, does not store state for expanded sidebar items to file system yet", async () => {
jest.advanceTimersByTime(250 - 1);
const pathExistsFake = rendererDi.inject(pathExistsInjectable);
const actual = await pathExistsFake(
"/some-directory-for-lens-local-storage/app.json",
);
expect(actual).toBe(false);
});
it("when enough time passes, stores state for expanded sidebar items to file system", async () => {
jest.advanceTimersByTime(250);
const readJsonFileFake = rendererDi.inject(readJsonFileInjectable);
const actual = await readJsonFileFake(
"/some-directory-for-lens-local-storage/app.json",
);
expect(actual).toEqual({
sidebar: {
expanded: { "some-extension-name-some-parent-id": true },
width: 200,
},
});
});
describe("when selecting sibling tab", () => {
beforeEach(() => {
const childTabLink = rendered.getByTestId(
"tab-link-for-some-extension-name-some-other-child-id",
);
fireEvent.click(childTabLink);
});
it("renders", () => {
expect(rendered.container).toMatchSnapshot();
});
it("sibling child page is shown", () => {
expect(
rendered.getByTestId("some-other-child-page"),
).not.toBeNull();
});
it("tab for sibling page is active", () => {
const tabLink = rendered.getByTestId(
"tab-link-for-some-extension-name-some-other-child-id",
);
expect(tabLink.dataset.isActiveTest).toBe("true");
});
it("tab for previous page is not active", () => {
const tabLink = rendered.getByTestId(
"tab-link-for-some-extension-name-some-child-id",
);
expect(tabLink.dataset.isActiveTest).toBe("false");
});
});
});
});
});
});
});
const extensionStubWithSidebarItems: FakeExtensionData = {
id: "some-extension-id",
name: "some-extension-name",
clusterPages: [
{
components: {
Page: () => {
throw new Error("should never come here");
},
},
},
{
id: "some-child-page-id",
components: {
Page: () => <div data-testid="some-child-page">Some child page</div>,
},
},
{
id: "some-other-child-page-id",
components: {
Page: () => (
<div data-testid="some-other-child-page">Some other child page</div>
),
},
},
],
clusterPageMenus: [
{
id: "some-parent-id",
title: "Parent",
components: {
Icon: () => <div>Some icon</div>,
},
},
{
id: "some-child-id",
target: { pageId: "some-child-page-id" },
parentId: "some-parent-id",
title: "Child 1",
components: {
Icon: null as never,
},
},
{
id: "some-other-child-id",
target: { pageId: "some-other-child-page-id" },
parentId: "some-parent-id",
title: "Child 2",
components: {
Icon: null as never,
},
},
],
}; | the_stack |
type MaybeArray<T> = T|T[];
/**
* The chrome.tabs.QueryInfo interface
*/
interface QueryInfo {
/**
* Whether the tabs have completed loading.
* One of: "loading", or "complete"
*/
status?: string;
/**
* Whether the tabs are in the last focused window.
* @since Chrome 19.
*/
lastFocusedWindow?: boolean;
/**
* The ID of the parent window, or windows.WINDOW_ID_CURRENT for the current window.
*/
windowId?: number;
/**
* The type of window the tabs are in.
* One of: "normal", "popup", "panel", "app", or "devtools"
*/
windowType?: 'normal'|'popup'|'panel'|'app'|'devtools';
/** Whether the tabs are active in their windows. */
active?: boolean;
/**
* The position of the tabs within their windows.
* @since Chrome 18.
*/
index?: number;
/**
* Match page titles against a pattern.
*/
title?: string;
/**
* Match tabs against one or more URL patterns. Note that fragment identifiers are not matched.
*/
url?: string | string[];
/**
* Whether the tabs are in the current window.
* @since Chrome 19.
*/
currentWindow?: boolean;
/**
* Whether the tabs are highlighted.
*/
highlighted?: boolean;
/**
* Whether the tabs are pinned.
*/
pinned?: boolean;
/**
* Whether the tabs are audible.
* @since Chrome 45.
*/
audible?: boolean;
/**
* Whether the tabs are muted.
* @since Chrome 45.
*/
muted?: boolean;
}
/**
* The ID of a tab
*/
type TabId = number;
/**
* The ID of a node's instances on a tab
*/
type TabIndex = number;
/**
* Definitions for the CRM extension
*/
declare namespace CRM {
namespace ScriptOptionsSchema {
/**
* An option type
*/
type OptionsValue = OptionCheckbox|OptionString|OptionChoice|
OptionArray|OptionNumber|OptionColorPicker;
/**
* The options object of a script or stylesheet
*/
type Options = {
/**
* The name of the option as a key and its descriptor
* as a value
*/
[key: string]: OptionsValue;
}
/**
* An option allowing the input of a number
*/
interface OptionNumber {
/**
* The type of the option
*/
type: 'number';
/**
* The minimum value of the number
*/
minimum?: number;
/**
* The maximum value of the number
*/
maximum?: number;
/**
* The description of this option
*/
descr?: string;
/**
* The value of this option
*/
value: null|number;
/**
* The default value for this option
*/
defaultValue?: number;
}
/**
* An option allowing the input of a string
*/
interface OptionString {
/**
* The type of the option
*/
type: 'string';
/**
* The maximum length of the string
*/
maxLength?: number;
/**
* A regex string the value has to match
*/
format?: string;
/**
* The description of this option
*/
descr?: string;
/**
* The value of this option
*/
value: null|string;
/**
* The default value for this option
*/
defaultValue?: number;
}
/**
* An option allowing the choice between a number of values
*/
interface OptionChoice {
/**
* The type of the option
*/
type: 'choice';
/**
* The description of this option
*/
descr?: string;
/**
* The index of the currently selected value
*/
selected: number;
/**
* The values of which to choose
*/
values: (string|number)[];
}
/**
* An option allowing you to pick a color
*/
interface OptionColorPicker {
/**
* THe type of the option
*/
type: 'color';
/**
* The description of this option
*/
descr?: string;
/**
* The value of this option
*/
value: null|string;
/**
* The default value for this option
*/
defaultValue?: string;
}
/**
* An option allowing you to choose between true and false
*/
interface OptionCheckbox {
/**
* The type of the option
*/
type: 'boolean';
/**
* The description of this option
*/
descr?: string;
/**
* The value of this option
*/
value: null|boolean;
/**
* The default value for this option
*/
defaultValue?: boolean;
}
/**
* The base of an option for inputting arrays
*/
interface OptionArrayBase {
/**
* The type of the option
*/
type: 'array';
/**
* The maximum number of values
*/
maxItems?: number;
/**
* The description of this option
*/
descr?: string;
}
/**
* An option for inputting arrays of strings
*/
interface OptionArrayString extends OptionArrayBase {
/**
* The type of items the array is made of
*/
items: 'string';
/**
* The array's value
*/
value: null|string[];
/**
* The default value for this option
*/
defaultValue?: string[];
}
/**
* An option for inputting arrays of numbers
*/
interface OptionArrayNumber extends OptionArrayBase {
/**
* The type of items the array is made of
*/
items: 'number';
/**
* The array's value
*/
value: null|number[];
/**
* The default value for this option
*/
defaultValue?: number[];
}
/**
* An option for inputting arrays of numbers or strings
*/
type OptionArray = OptionArrayString|OptionArrayNumber;
}
namespace CRMAPI {
/**
* Data about the click on the page
*/
interface ContextData {
/**
* The X-position of the click relative to the viewport
*/
clientX: number;
/**
* The Y-position of the click relative to the viewport
*/
clientY: number;
/**
* The Y-position of the click relative to the viewport
*/
offsetX: number;
/**
* The Y-position of the click relative to the viewport
*/
offsetY: number;
/**
* The X-position of the click relative to the (embedded) page top left point
* with scrolling added
*/
pageX: number;
/**
* The Y-position of the click relative to the (embedded) page
* with scrolling added
*/
pageY: number;
/**
* The X-position of the click relative to the screen(s) of the user
*/
screenX: number;
/**
* The Y-position of the click relative to the screen(s) of the user
*/
screenY: number;
/**
* The mouse-button used to trigger the menu
*/
which: number;
/**
* The X-position of the click
*/
x: number;
/**
* The Y-position of the click
*/
y: number;
/**
* The element that was clicked
*/
srcElement: HTMLElement|void;
/**
* The element that was clicked
*/
target: HTMLElement|void;
/**
* The element that was clicked
*/
toElement: HTMLElement|void;
}
/**
* Tab muted state and the reason for the last state change.
*/
interface MutedInfo {
/**
* Whether the tab is prevented from playing sound
* (but hasn't necessarily recently produced sound).
* Equivalent to whether the muted audio indicator is showing.
*/
muted: boolean;
/**
* The reason the tab was muted or unmuted.
* Not set if the tab's mute state has never been changed.
*/
reason?: string;
/**
* The ID of the extension that changed the muted state.
* Not set if an extension was not the reason the muted state last changed.
*/
extensionId?: string;
}
/**
* Data about the tab itself
*/
interface TabData { // https://developer.chrome.com/extensions/tabs#type-Tab
/**
* The ID of the tab
*/
id?: TabId;
/**
* The index of this tab within its window
*/
index: number;
/**
* The ID of the window the tab is contained within
*/
windowId: number;
/**
* The ID of the tab that opened this tab, if any.
* This property is only present if the opener tab still exists.
*/
openerTabId?: TabId;
/**
* Whether the tab is selected (deprecated since chrome 33)
*/
selected?: boolean;
/**
* Whether the tab is highlighted
*/
highlighted: boolean;
/**
* Whether the tab is active in its window
*/
active: boolean;
/**
* Whether the tab is pinned
*/
pinned: boolean;
/**
* Whether the tab has produced sound in the last few seconds (since chrome 45)
*/
audible?: boolean;
/**
* Whether the tab is discarded. A discarded tab is one whose content has been
* unloaded from memory, but is still visible in the tab strip. Its content
* gets reloaded the next time it's activated. (since chrome 54)
*/
discarded?: boolean;
/**
* Whether the tab can be discarded automatically by the browser when resources
* are low. (since chrome 54)
*/
autoDiscardable?: boolean;
/**
* Tab muted state and the reason for the last state change. (since chrome 46)
*/
mutedInfo?: MutedInfo;
/**
* The URL the tab
*/
url?: string;
/**
* The title of the tab
*/
title?: string;
/**
* The URL fo the tab's favicon
*/
faviconUrl?: string;
/**
* The status of the tab (loading or complete)
*/
status: 'loading'|'complete';
/**
* Whether the tab is an incognito window
*/
incognito: boolean;
/**
* The width of the tab in pixels (since chrome 31)
*/
width?: number;
/**
* The height of the tab in pixels (since chrome 31)
*/
height?: number;
/**
* The session ID used to uniquely identify a Tab obtained from the sessions API.
* (since chrome 31)
*/
sessionId?: number;
}
/**
* Data about the click inside the context-menu
*/
interface ClickData { // https://developer.chrome.com/extensions/contextMenus#event-onClicked
/**
* The ID of the menu item that was clicked. (since chrome 35)
*/
menuItemId: string|number;
/**
* The parent ID, if any, for the item clicked.
* (since chrome 35)
*/
parentMenuItemId?: string|number;
/**
* The media type the right-click menu was summoned on.
* (since chrome 35)
*/
mediaType?: 'image'|'video'|'audio';
/**
* If the element is a link, the URL it points to.
* (since chrome 35)
*/
linkUrl?: string;
/**
* The src attribute, if the clicked-on element has one.
* (since chrome 35)
*/
srcUrl?: string;
/**
* The URL fo the page where the item was clicked.
* (since chrome 35)
*/
pageUrl?: string;
/**
* The URL of the frame where the context menu was clicked.
* (since chrome 35)
*/
frameUrl?: string;
/**
* The selected text (if any). (since chrome 35)
*/
selectionText?: string;
/**
* Whether the element is editable (text input, textarea etc).
* (since chrome 35)
*/
editable: boolean;
/**
* Whether a radio button or checkbox was checked,
* before it was clicked on. (since chrome 35)
*/
wasChecked?: boolean;
/**
* Whether a radio button or checkbox was checked,
* after it was clicked on. (since chrome 35)
*/
checked?: boolean;
}
/**
* The storage for this node, an object
*/
type NodeStorage = Object;
/**
* A resource for a script
*/
interface Resource {
/**
* A dataURI representing the data
*/
dataURI: string;
/**
* A string of the data itself
*/
dataString: string;
/**
* The URL the data was downloaded from
*/
url: string;
/**
* The URL used to load the data
*/
crmUrl: string;
}
/**
* Resources for scripts
*/
type Resources = { [name: string]: Resource }
/**
* Data about greasemonkey's options
*/
interface GreaseMonkeyOptions {
awareOfChrome: boolean;
compat_arrayleft: boolean;
compat_foreach: boolean;
compat_forvarin: boolean;
compat_metadata: boolean;
compat_prototypes: boolean;
compat_uW_gmonkey: boolean;
noframes?: string;
override: {
excludes: boolean;
includes: boolean;
orig_excludes?: string[];
orig_includes?: string[];
use_excludes: string[];
use_includes: string[];
}
}
/**
* Data about a script in greasemonkey's script data
*/
interface GreaseMonkeyScriptData {
/**
* The author of the script
*/
author?: string;
/**
* The copyright of the script
*/
copyright?: string;
/**
* A description of the script
*/
description?: string;
/**
* URLs not to run this script on
*/
excludes?: string[];
/**
* A homepage for this script
*/
homepage?: string;
/**
* An icon used for this script
*/
icon?: string;
/**
* A 64x64 icon used for this script
*/
icon64?: string;
/**
* URLs on which to run this script (can use globs)
*/
includes?: string[];
/**
* The last time this script was updated
*/
lastUpdated: number; //Never updated
/**
* URLs on which this script is ran
*/
matches?: string[];
/**
* Whether the user is incognito
*/
isIncognito: boolean;
/**
* The downloadMode (???)
*/
downloadMode: string;
/**
* The name of the script
*/
name: string;
/**
* The namespace the script is running in (url)
*/
namespace?: string;
/**
* Options for greasemonkey
*/
options: GreaseMonkeyOptions;
/**
* The position of this script (???)
*/
position: number;
/**
* The resources loaded for this script
*/
resources: Resource[];
/**
* When to run this script in the page-load cycle
*/
"run-at": string;
system: boolean;
unwrap: boolean;
/**
* The version number of this script
*/
version?: number;
}
/**
* GreaseMonkey data
*/
interface GreaseMonkeyDataInfo {
/**
* Data about the script
*/
script: GreaseMonkeyScriptData;
/**
* The metastring for this script
*/
scriptMetaStr: string;
/**
* The source of this script
*/
scriptSource: string;
/**
* The URL from which this script can be updated
*/
scriptUpdateURL?: string;
/**
* Whether this script gets updated
*/
scriptWillUpdate: boolean;
scriptHandler: string;
/**
* The version number of this script
*/
version: string;
}
/**
* Data about greasemonkey
*/
interface GreaseMonkeyData {
/**
* The info about the script
*/
info: GreaseMonkeyDataInfo;
/**
* The resources used by this script
*/
resources: Resources;
}
/**
* An instance of a script running on a tab
*/
interface CommInstance {
/**
* The ID of the tab
*/
id: TabId;
/**
* The index of this script in the array of
* scripts with this ID running on a tab
*/
tabIndex: TabIndex;
/**
* A function used to send a message to this instance
*/
sendMessage: (message: any, callback?: () => void) => void
}
type NodeIdAssignable = CRM.GenericNodeId|CRM.GenericSafeNodeId|number;
/**
* A relation between a node to any other node
*/
interface Relation {
/**
* The ID of the node that it's relative to (defaults to tree root)
*/
node?: NodeIdAssignable;
/**
* The relation between them
*/
relation?: 'firstChild'|'firstSibling'|'lastChild'|'lastSibling'|'before'|'after';
}
/**
* Data about a chrome request
*/
interface BrowserRequest {
/**
* The API it's using
*/
api: string,
/**
* Arguments passed to the request
*/
chromeAPIArguments: {
/**
* The type of argument
*/
type: 'fn'|'arg'|'return';
/**
* The value of the argument
*/
val: any;
}[],
/**
* The type of this chrome request (if a special one
* that can not be made by the user themselves)
*/
type?: 'GM_download'|'GM_notification';
}
/**
* A partial chrome request
*/
interface ChromeRequestReturn extends Function {
/**
* A regular call with given arguments (functions can only be called once
* unless you use .persistent)
*/
(...params: any[]): ChromeRequestReturn;
/**
* A regular call with given arguments (functions can only be called once
* unless you use .persistent)
*/
args: (...params: any[]) => ChromeRequestReturn;
/**
* A regular call with given arguments (functions can only be called once
* unless you use .persistent)
*/
a: (...params: any[]) => ChromeRequestReturn;
/**
* A function to call when a value is returned by the call
*/
return: (handler: (value: any) => void) => ChromeRequestReturn;
/**
* A function to call when a value is returned by the call
*/
r: (handler: (value: any) => void) => ChromeRequestReturn;
/**
* A persistent callback (that can be called multiple times)
*/
persistent: (...functions: Function[]) => ChromeRequestReturn;
/**
* A persistent callback (that can be called multiple times)
*/
p: (...functions: Function[]) => ChromeRequestReturn;
/**
* Sends the function and runs it
*/
send: () => ChromeRequestReturn;
/**
* Sends the function and runs it
*/
s: () => ChromeRequestReturn;
/**
* Info about the request itself
*/
request: BrowserRequest;
/**
* A function to run when an error occurs on running given chrome request
*/
onError?: Function
}
interface BrowserRequestReturn extends Function {
/**
* A regular call with given arguments (functions can only be called once
* unless you use .persistent)
*/
(...params: any[]): BrowserRequestReturn;
/**
* A regular call with given arguments (functions can only be called once
* unless you use .persistent)
*/
args: (...params: any[]) => BrowserRequestReturn;
/**
* A regular call with given arguments (functions can only be called once
* unless you use .persistent)
*/
a: (...params: any[]) => BrowserRequestReturn;
/**
* A persistent callback (that can be called multiple times)
*/
persistent: (...functions: Function[]) => BrowserRequestReturn;
/**
* A persistent callback (that can be called multiple times)
*/
p: (...functions: Function[]) => BrowserRequestReturn;
/**
* Sends the function and returns a promise that resolves with its result
*/
send: () => Promise<any>;
/**
* Sends the function and returns a promise that resolves with its result
*/
s: () => Promise<any>;
/**
* Info about the request itself
*/
request: BrowserRequest;
}
interface BrowserRequestEvent {
addListener: BrowserRequestReturn;
removeListener: BrowserRequestReturn;
}
interface BrowserRequestObj {
any(api: string): BrowserRequestReturn;
alarms: {
create: BrowserRequestReturn,
get: BrowserRequestReturn,
getAll: BrowserRequestReturn,
clear: BrowserRequestReturn,
clearAll: BrowserRequestReturn,
onAlarm: BrowserRequestEvent
},
bookmarks: {
create: BrowserRequestReturn,
get: BrowserRequestReturn,
getChildren: BrowserRequestReturn,
getRecent: BrowserRequestReturn,
getSubTree: BrowserRequestReturn,
getTree: BrowserRequestReturn,
move: BrowserRequestReturn,
remove: BrowserRequestReturn,
removeTree: BrowserRequestReturn,
search: BrowserRequestReturn,
update: BrowserRequestReturn,
onCreated: BrowserRequestEvent,
onRemoved: BrowserRequestEvent,
onChanged: BrowserRequestEvent,
onMoved: BrowserRequestEvent
},
browserAction: {
setTitle: BrowserRequestReturn,
getTitle: BrowserRequestReturn,
setIcon: BrowserRequestReturn,
setPopup: BrowserRequestReturn,
getPopup: BrowserRequestReturn,
openPopup: BrowserRequestReturn,
setBadgeText: BrowserRequestReturn,
getBadgeText: BrowserRequestReturn,
setBadgeBackgroundColor: BrowserRequestReturn,
getBadgeBackgroundColor: BrowserRequestReturn,
enable: BrowserRequestReturn,
disable: BrowserRequestReturn,
onClicked: BrowserRequestEvent
},
browsingData: {
remove: BrowserRequestReturn,
removeCache: BrowserRequestReturn,
removeCookies: BrowserRequestReturn,
removeDownloads: BrowserRequestReturn,
removeFormData: BrowserRequestReturn,
removeHistory: BrowserRequestReturn,
removePasswords: BrowserRequestReturn,
removePluginData: BrowserRequestReturn,
settings: BrowserRequestReturn
},
commands: {
getAll: BrowserRequestReturn,
onCommand: BrowserRequestEvent
},
contextMenus: {
create: BrowserRequestReturn,
update: BrowserRequestReturn,
remove: BrowserRequestReturn,
removeAll: BrowserRequestReturn,
onClicked: BrowserRequestEvent
},
contextualIdentities: {
create: BrowserRequestReturn,
get: BrowserRequestReturn,
query: BrowserRequestReturn,
update: BrowserRequestReturn,
remove: BrowserRequestReturn
},
cookies: {
get: BrowserRequestReturn,
getAll: BrowserRequestReturn,
set: BrowserRequestReturn,
remove: BrowserRequestReturn,
getAllCookieStores: BrowserRequestReturn,
onChanged: BrowserRequestEvent
},
devtools: {
inspectedWindow: {
eval: BrowserRequestReturn,
reload: BrowserRequestReturn
},
network: {
onNavigated: BrowserRequestEvent
},
panels: {
create: BrowserRequestReturn,
}
},
downloads: {
download: BrowserRequestReturn,
search: BrowserRequestReturn,
pause: BrowserRequestReturn,
resume: BrowserRequestReturn,
cancel: BrowserRequestReturn,
open: BrowserRequestReturn,
show: BrowserRequestReturn,
showDefaultFolder: BrowserRequestReturn,
erase: BrowserRequestReturn,
removeFile: BrowserRequestReturn,
onCreated: BrowserRequestEvent,
onErased: BrowserRequestEvent,
onChanged: BrowserRequestEvent
},
extension: {
getURL: BrowserRequestReturn,
getViews: BrowserRequestReturn,
getBackgroundPage: BrowserRequestReturn,
isAllowedIncognitoAccess: BrowserRequestReturn,
isAllowedFileSchemeAccess: BrowserRequestReturn,
},
history: {
search: BrowserRequestReturn,
getVisits: BrowserRequestReturn,
addUrl: BrowserRequestReturn,
deleteUrl: BrowserRequestReturn,
deleteRange: BrowserRequestReturn,
deleteAll: BrowserRequestReturn,
onVisited: BrowserRequestEvent,
onVisitRemoved: BrowserRequestEvent
},
i18n: {
getAcceptLanguage: BrowserRequestReturn,
getMessage: BrowserRequestReturn,
getUILanguage: BrowserRequestReturn,
detectLanguage: BrowserRequestReturn,
},
identity: {
getRedirectURL: BrowserRequestReturn,
launchWebAuthFlow: BrowserRequestReturn
},
idle: {
queryState: BrowserRequestReturn,
setDetectionInterval: BrowserRequestReturn,
onStateChanged: BrowserRequestEvent
},
management: {
getSelf: BrowserRequestReturn,
uninstallSelf: BrowserRequestReturn,
},
notifications: {
create: BrowserRequestReturn,
clear: BrowserRequestReturn,
getAll: BrowserRequestReturn,
onClicked: BrowserRequestEvent,
onClosed: BrowserRequestEvent
},
omnibox: {
setDefaultSuggestion: BrowserRequestReturn,
onInputStarted: BrowserRequestEvent,
onInputChanged: BrowserRequestEvent,
onInputEntered: BrowserRequestEvent,
onInputCancelled: BrowserRequestEvent
},
pageAction: {
show: BrowserRequestReturn,
hide: BrowserRequestReturn,
setTitle: BrowserRequestReturn,
getTitle: BrowserRequestReturn,
setIcon: BrowserRequestReturn,
setPopup: BrowserRequestReturn,
getPopup: BrowserRequestReturn,
onClicked: BrowserRequestEvent
},
permissions: {
contains: BrowserRequestReturn,
getAll: BrowserRequestReturn,
request: BrowserRequestReturn,
remove: BrowserRequestReturn
},
runtime: {
setUninstallURL: BrowserRequestReturn,
connectNative: BrowserRequestReturn,
sendNativeMessage: BrowserRequestReturn,
getBrowserInfo: BrowserRequestReturn,
connect: BrowserRequestReturn,
getBackgroundPage: BrowserRequestReturn,
getManifest: BrowserRequestReturn,
getURL: BrowserRequestReturn,
getPlatformInfo: BrowserRequestReturn,
openOptionsPage: BrowserRequestReturn,
reload: BrowserRequestReturn,
sendMessage: BrowserRequestReturn,
onStartup: BrowserRequestEvent,
onUpdateAvailable: BrowserRequestEvent,
onInstalled: BrowserRequestEvent,
onConnectExternal: BrowserRequestEvent,
onConnect: BrowserRequestEvent,
onMessage: BrowserRequestEvent,
onMessageExternal: BrowserRequestEvent,
lastError: null,
id: null
},
sessions: {
getRecentlyClosed: BrowserRequestReturn,
restore: BrowserRequestReturn,
setTabValue: BrowserRequestReturn,
getTabValue: BrowserRequestReturn,
removeTabValue: BrowserRequestReturn,
setWindowValue: BrowserRequestReturn,
getWindowValue: BrowserRequestReturn,
removeWindowValue: BrowserRequestReturn,
onChanged: BrowserRequestEvent
},
sidebarAction: {
setPanel: BrowserRequestReturn,
getPanel: BrowserRequestReturn,
setTitle: BrowserRequestReturn,
getTitle: BrowserRequestReturn,
setIcon: BrowserRequestReturn,
open: BrowserRequestReturn,
close: BrowserRequestReturn
},
storage: {
local: {
get: BrowserRequestReturn,
set: BrowserRequestReturn,
remove: BrowserRequestReturn,
clear: BrowserRequestReturn
},
sync: {
get: BrowserRequestReturn,
set: BrowserRequestReturn,
remove: BrowserRequestReturn,
clear: BrowserRequestReturn
},
onChanged: BrowserRequestEvent
},
tabs: {
connect: BrowserRequestReturn,
detectLanguage: BrowserRequestReturn,
duplicate: BrowserRequestReturn,
getZoom: BrowserRequestReturn,
getZoomSettings: BrowserRequestReturn,
insertCSS: BrowserRequestReturn,
removeCSS: BrowserRequestReturn,
move: BrowserRequestReturn,
print: BrowserRequestReturn,
printPreview: BrowserRequestReturn,
reload: BrowserRequestReturn,
remove: BrowserRequestReturn,
saveAsPDF: BrowserRequestReturn,
setZoom: BrowserRequestReturn,
setZoomSettings: BrowserRequestReturn,
create: BrowserRequestReturn,
get: BrowserRequestReturn,
getCurrent: BrowserRequestReturn,
captureVisibleTab: BrowserRequestReturn,
update: BrowserRequestReturn,
query: BrowserRequestReturn,
executeScript: BrowserRequestReturn,
sendMessage: BrowserRequestReturn,
onActivated: BrowserRequestEvent,
onAttached: BrowserRequestEvent,
onCreated: BrowserRequestEvent,
onDetached: BrowserRequestEvent,
onMoved: BrowserRequestEvent,
onReplaced: BrowserRequestEvent,
onZoomChanged: BrowserRequestEvent,
onUpdated: BrowserRequestEvent,
onRemoved: BrowserRequestEvent,
onHighlighted: BrowserRequestEvent
},
topSites: {
get: BrowserRequestReturn,
},
webNavigation: {
getFrame: BrowserRequestReturn,
getAllFrames: BrowserRequestReturn,
onBeforeNavigate: BrowserRequestEvent,
onCommitted: BrowserRequestEvent,
onCreateNavigationTarget: BrowserRequestEvent,
onDOMContentLoaded: BrowserRequestEvent,
onCompleted: BrowserRequestEvent,
onErrorOccurred: BrowserRequestEvent,
onReferenceFragmentUpdated: BrowserRequestEvent,
onHistoryStateUpdated: BrowserRequestEvent
},
webRequest: {
onBeforeRequest: BrowserRequestEvent,
onBeforeSendHeaders: BrowserRequestEvent,
onSendHeaders: BrowserRequestEvent,
onHeadersReceived: BrowserRequestEvent,
onAuthRequired: BrowserRequestEvent,
onResponseStarted: BrowserRequestEvent,
onBeforeRedirect: BrowserRequestEvent,
onCompleted: BrowserRequestEvent,
onErrorOccurred: BrowserRequestEvent,
filterResponseData: BrowserRequestReturn,
},
windows: {
get: BrowserRequestReturn,
getCurrent: BrowserRequestReturn,
getLastFocused: BrowserRequestReturn,
getAll: BrowserRequestReturn,
create: BrowserRequestReturn,
update: BrowserRequestReturn,
remove: BrowserRequestReturn,
onCreated: BrowserRequestEvent,
onRemoved: BrowserRequestEvent,
onFocusChanged: BrowserRequestEvent
},
theme: {
getCurrent: BrowserRequestReturn,
update: BrowserRequestReturn,
reset: BrowserRequestReturn
}
}
/**
* Headers for a GM_download call
*/
interface GMHeaders {
[headerKey: string]: string
}
/**
* Settings for a GM_download call
*/
interface DownloadSettings {
/**
* The URL to download
*/
url?: string;
/**
* The name of the downloaded files
*/
name?: string;
/**
* Headers for the XHR
*/
headers?: GMHeaders;
/**
* A function to call when downloaded
*/
onload?: () => void;
/**
* A function to call on error
*/
onerror?: (e: any) => void;
}
/**
* Settings for a GM_notification call
*/
interface NotificationOptions {
/**
* The text on the notification
*/
text?: string;
/**
* The URL of the image to use
*/
imageUrl?: string;
/**
* The title of the notification
*/
title?: string;
/**
* A function to run when the notification is clicked
*/
onclick?: (e: Event) => void;
/**
* Whether the notification should be clickable
*/
isClickable?: boolean;
/**
* A function to run when the notification disappears
*/
ondone?: () => void;
}
/**
* A callback that gets called immediately (as a polyfill)
*/
type InstantCB = (callback: () => void) => void;
/**
* A function with no args or return value (as a polyfill)
*/
type EmptyFn = () => void;
/**
* The handler of a message that is sent to the crm-api
*/
type MessageHandler = (message: any) => void;
/**
* A successful response to an instance call
*/
type UnsuccessfulInstanceCallback = {
error: true;
success: false;
message: any;
}
/**
* An unsuccessful response to an instance call
*/
type SuccessfulInstanceCallback = {
error: false;
success: true;
}
/**
* The callback function for an instance call
*/
type InstanceCallback = (data: UnsuccessfulInstanceCallback|SuccessfulInstanceCallback) => void;
/**
* A listener for an instance
*/
type InstanceListener = (message: any) => void;
/**
* A listener for an instance that can be responded to
*/
type RespondableInstanceListener = (message: any, respond: (response: any) => void) => void;
/**
* A keypath to a storage location
*/
interface KeyPath {
[key: string]: any;
[key: number]: any;
}
/**
* A query for a CRM item
*/
interface CRMQuery {
/**
* The name of the item
*/
name?: string;
/**
* The type of the item
*/
type?: CRM.NodeType;
/**
* The ID of the node whose subtree to search in (none for root)
*/
inSubTree?: NodeIdAssignable
}
/**
* The GM API that fills in any APIs that GreaseMonkey uses and points them to their
* CRM counterparts
* Documentation can be found here http://wiki.greasespot.net/Greasemonkey_Manual:API
* and here http://tampermonkey.net/documentation.php
*/
interface GM_Fns {
/**
* Returns any info about the script
*
* @see {@link https://tampermonkey.net/documentation.php#GM_info}
* @returns {Object} - Data about the script
*/
GM_info(): GreaseMonkeyDataInfo,
/**
* This method retrieves a value that was set with GM_setValue. See GM_setValue
* for details on the storage of these values.
*
* @see {@link https://tampermonkey.net/documentation.php#GM_getValue}
* @param {String} name - The property name to get
* @param {any} [defaultValue] - Any value to be returned, when no value has previously been set
* @returns {any} - Returns the value if the value is defined, if it's undefined, returns defaultValue
* when defaultValue is also undefined, returns undefined
*/
GM_getValue<T>(name: string, defaultValue?: T): T,
/**
* This method retrieves a value that was set with GM_setValue. See GM_setValue
* for details on the storage of these values.
*
* @see {@link https://tampermonkey.net/documentation.php#GM_getValue}
* @param {String} name - The property name to get
* @param {any} [defaultValue] - Any value to be returned, when no value has previously been set
* @returns {void} - Returns the value if the value is defined, if it's undefined, returns defaultValue
* when defaultValue is also undefined, returns undefined
*/
GM_getValue<T>(name: string, defaultValue?: T): void,
/**
* This method retrieves a value that was set with GM_setValue. See GM_setValue
* for details on the storage of these values.
*
* @see {@link https://tampermonkey.net/documentation.php#GM_getValue}
* @param {String} name - The property name to get
* @param {any} [defaultValue] - Any value to be returned, when no value has previously been set
* @returns {any} - Returns the value if the value is defined, if it's undefined, returns defaultValue
* when defaultValue is also undefined, returns undefined
*/
GM_getValue<T>(name: string, defaultValue?: T): any,
/**
* This method allows user script authors to persist simple values across page-loads.
*
* @see {@link https://tampermonkey.net/documentation.php#GM_setValue}
* @param {String} name - The unique (within this script) name for this value. Should be restricted to valid Javascript identifier characters.
* @param {any} value - The value to store
*/
GM_setValue(name: string, value: any): void,
/**
* This method deletes an existing name / value pair from storage.
*
* @see {@link https://tampermonkey.net/documentation.php#GM_deleteValue}
* @param {String} name - Property name to delete.
*/
GM_deleteValue(name: string): void,
/**
* This method retrieves an array of storage keys that this script has stored.
*
* @see {@link https://tampermonkey.net/documentation.php#GM_listValues}
* @returns {String[]} All keys of the storage
*/
GM_listValues(): string[],
/**
* Gets the resource URL for given resource name
*
* @see {@link https://tampermonkey.net/documentation.php#GM_getResourceURL}
* @param {String} name - The name of the resource
* @returns {String} - A URL that can be used to get the resource value
*/
GM_getResourceURL(name: string): string,
/**
* Gets the resource string for given resource name
*
* @see {@link https://tampermonkey.net/documentation.php#GM_getResourceString}
* @param {String} name - The name of the resource
* @returns {String} - The resource value
*/
GM_getResourceString(name: string): string,
/**
* This method adds a string of CSS to the document. It creates a new `style` element,
* adds the given CSS to it, and inserts it into the `head`.
*
* @see {@link https://tampermonkey.net/documentation.php#GM_addStyle}
* @param {String} css - The CSS to put on the page
*/
GM_addStyle(css: string): void,
/**
* Logs to the console
*
* @see {@link https://tampermonkey.net/documentation.php#GM_log}
* @param {any} any - The data to log
*/
GM_log(...params: any[]): void,
/**
* Open specified URL in a new tab, open_in_background is not available here since that
* not possible in chrome
*
* @see {@link https://tampermonkey.net/documentation.php#GM_openInTab}
* @param {String} url - The url to open
*/
GM_openInTab(url: string): void,
/**
* This is only here to prevent errors from occurring when calling any of these functions,
* this function does nothing
*
* @see {@link https://tampermonkey.net/documentation.php#GM_registerMenuCommand}
* @param {any} ignoredArguments - An argument that is ignored
*/
GM_registerMenuCommand: EmptyFn,
/**
* This is only here to prevent errors from occurring when calling any of these functions,
* this function does nothing
*
* @see {@link https://tampermonkey.net/documentation.php#GM_unregisterMenuCommand}
* @param {any} ignoredArguments - An argument that is ignored
*/
GM_unregisterMenuCommand: EmptyFn;
/**
* This is only here to prevent errors from occurring when calling any of these functions,
* this function does nothing
*
* @see {@link https://tampermonkey.net/documentation.php#GM_setClipboard}
* @param {any} ignoredArguments - An argument that is ignored
*/
GM_setClipboard: EmptyFn;
/**
* Sends an xmlhttpRequest with given parameters
*
* @see {@link https://tampermonkey.net/documentation.php#GM_xmlhttpRequest}
* @param {Object} options - The options
* @param {string} [options.method] - The method to use (GET, HEAD or POST)
* @param {string} [options.url] - The url to request
* @param {Object} [options.headers] - The headers for the request
* @param {Object} [options.data] - The data to send along
* @param {boolean} [options.binary] - Whether the data should be sent in binary mode
* @param {number} [options.timeout] - The time to wait in ms
* @param {Object} [options.context] - A property which will be applied to the response object
* @param {string} [options.responseType] - The type of response, arraybuffer, blob or json
* @param {string} [options.overrideMimeType] - The MIME type to use
* @param {boolean} [options.anonymous] - If true, sends no cookies along with the request
* @param {boolean} [options.fetch] - Use a fetch instead of an xhr
* @param {string} [options.username] - A username for authentication
* @param {string} [options.password] - A password for authentication
* @param {function} [options.onload] - A callback on that event
* @param {function} [options.onerror] - A callback on that event
* @param {function} [options.onreadystatechange] - A callback on that event
* @param {function} [options.onprogress] - A callback on that event
* @param {function} [options.onloadstart] - A callback on that event
* @param {function} [options.ontimeout] - A callback on that event
* @returns {XMLHttpRequest} The XHR
*/
GM_xmlhttpRequest(options: {
/**
* The method to use (GET, HEAD or POST)
*/
method?: string,
/**
* The url to request
*/
url?: string,
/**
* The headers for the request
*/
headers?: { [headerKey: string]: string },
/**
* The data to send along
*/
data?: any,
/**
* Whether the data should be sent in binary mode
*/
binary?: boolean,
/**
* The time to wait in ms
*/
timeout?: number,
/**
* A property which will be applied to the response object
*/
context?: any,
/**
* The type of response, arraybuffer, blob or json
*/
responseType?: string,
/**
* The MIME type to use
*/
overrideMimeType?: string,
/**
* If true, sends no cookies along with the request
*/
anonymous?: boolean,
/**
* Use a fetch instead of an xhr
*/
fetch?: boolean,
/**
* A username for authentication
*/
username?: string,
/**
* A password for authentication
*/
password?: string,
/**
* A callback on that event
*/
onload?: (e: Event) => void,
/**
* A callback on that event
*/
onerror?: (e: Event) => void,
/**
* A callback on that event
*/
onreadystatechange?: (e: Event) => void,
/**
* A callback on that event
*/
onprogress?: (e: Event) => void,
/**
* A callback on that event
*/
onloadstart?: (e: Event) => void,
/**
* A callback on that event
*/
ontimeout?: (e: Event) => void
}): XMLHttpRequest
/**
* Adds a change listener to the storage and returns the listener ID.
* 'name' is the name of the observed variable. The 'remote' argument
* of the callback function shows whether this value was modified
* from the instance of another tab (true) or within this script
* instance (false). Therefore this functionality can be used by
* scripts of different browser tabs to communicate with each other.
*
* @see {@link https://tampermonkey.net/documentation.php#GM_addValueChangeListener}
* @param {string} name - The name of the observed variable
* @param {function} callback - A callback in which the first argument is
* the name of the observed, variable, the second one is the old value,
* the third one is the new value and the fourth one is a boolean that
* indicates whether the change was from a remote tab
* @returns {number} - The id of the listener, used for removing it
*/
GM_addValueChangeListener(name: string,
callback: (key: string, oldValue: any, newValue: any, remote: boolean) => void): number,
/**
* Removes a change listener by its ID.
*
* @see {@link https://tampermonkey.net/documentation.php#GM_removeValueChangeListener}
* @param {number} listenerId - The id of the listener
*/
GM_removeValueChangeListener(listenerId: number): void,
/**
* Downloads the file at given URL
*
* @see {@link https://tampermonkey.net/documentation.php#GM_GM_download}
* @param {string|Object} details - A details object containing any data
* @param {string} [details.url] - The url of the download
* @param {string} [details.name] - The name of the file after download
* @param {Object} [details.headers] - The headers for the request
* @param {function} [details.onload] - Called when the request loads
* @param {function} [details.onerror] - Called on error, gets called with an object
* containing an error attribute that specifies the reason for the error
* and a details attribute that gives a more detailed description of the error
* @param {string} name - The name of the file after download
*/
GM_download(details: DownloadSettings): void,
/**
* Downloads the file at given URL
*
* @see {@link https://tampermonkey.net/documentation.php#GM_GM_download}
* @param {string} url - The URL
* @param {string} name - The name of the file after download
*/
GM_download(url: string, name: string): void,
/**
* Please use the comms API instead of this one
*
* @see {@link https://tampermonkey.net/documentation.php#GM_getTab}
* @param {function} callback - A callback that is immediately called
*/
GM_getTab: InstantCB,
/**
* Please use the comms API instead of this one
*
* @see {@link https://tampermonkey.net/documentation.php#GM_getTabs}
* @param {function} callback - A callback that is immediately called
*/
GM_getTabs: InstantCB,
/**
* Please use the comms API instead of this one, this one does nothing
*
* @see {@link https://tampermonkey.net/documentation.php#GM_saveTab}
* @param {function} callback - A callback that is immediately called
*/
GM_saveTab: InstantCB;
/**
* The unsafeWindow object provides full access to the pages javascript functions and variables.
*
* @see {@link https://tampermonkey.net/documentation.php#unsafeWindow}
* @type Window
*/
unsafeWindow: Window,
/**
* Shows a HTML5 Desktop notification and/or highlight the current tab.
*
* @see {@link https://tampermonkey.net/documentation.php#GM_notification}
* @param {string|Object} options - The message of the notification
* @param {string} [options.text] - The message of the notification
* @param {string} [options.imageUrl] - The URL of the image to use
* @param {string} [options.title] - The title of the notification
* @param {function} [options.onclick] - A function to call on clicking
* @param {boolean} [options.isClickable] - Whether the notification is clickable
* @param {function} [options.ondone] - A function to call when the notification
* disappears or is closed by the user.
* @param {string} [title] - The title of the notification
* @param {string} [image] - A url to the image to use for the notification
* @param {function} [onclick] - A function to run on clicking the notification
*/
GM_notification(options: NotificationOptions): void,
/**
* Shows a HTML5 Desktop notification and/or highlight the current tab.
*
* @see {@link https://tampermonkey.net/documentation.php#GM_notification}
* @param {string|Object} text - The message of the notification
* @param {string} [title] - The title of the notification
* @param {string} [image] - A url to the image to use for the notification
* @param {function} [onclick] - A function to run on clicking the notification
*/
GM_notification(text: string, title?: string, image?: string, onclick?: Function): void,
//This seems to be deprecated from the tampermonkey documentation page, removed somewhere between january 1st 2016
// and january 24th 2016 waiting for any update
/**
* THIS FUNCTION DOES NOT WORK AND IS DEPRECATED
*
* @see {@link https://tampermonkey.net/documentation.php#GM_installScript}
* @param {any} ignoredArguments - An argument that is ignored
*/
GM_installScript: EmptyFn
}
/**
* A class for constructing the CRM API
*
* @class
*/
export class Instance {
constructor(node: CRM.SafeNode, id: NodeIdAssignable, tabData: TabData,
clickData: ClickData, secretKey: number[],
nodeStorage: NodeStorage, contextData: ContextData,
greasemonkeyData: GreaseMonkeyData, isBackground: boolean,
options: CRM.Options, enableBackwardsCompatibility: boolean,
tabIndex: TabIndex, extensionId: string, supportedAPIs: string,
nodeStorageSync: CRM.NodeStorage);
/**
* When true, shows stacktraces on error in the console of the page
* the script runs on, true by default.
*/
stackTraces: boolean;
/**
* If true, throws an error when one of your crmAPI calls is incorrect
* (such as a type mismatch or any other fail). True by default.
*/
errors: boolean;
/**
* If true, when an error occurs anywhere in the script, opens the
* chrome debugger by calling the debugger command. This does
* not preserve the stack or values. If you want that, use the
* `catchErrors` option on the options page.
*/
debugOnerror: boolean;
/**
* Is set if a chrome call triggered an error, otherwise unset
*/
lastError: Error;
/**
* When true, warns you after 5 seconds of not sending a chrome function
* that you probably forgot to send it
*/
warnOnChromeFunctionNotSent: boolean;
/**
* Returns the options for this script/stylesheet. Any missing values are
* filled in with the corresponding field in the 'defaults' param
*/
options<T extends Object, O extends Object>(defaults?: T): T & O;
/**
* The ID of the the tab this script is running on
*/
tabId: TabId;
/**
* The ID of this node
*/
id: NodeIdAssignable;
/**
* The tabIndex of this instance
*/
currentTabIndex: TabIndex;
/**
* The ID of this instance of this script. Can be used to filter it
* from all instances or to send to another instance.
*/
instanceId: number;
/**
* Data about the click on the page
*/
contextData: ContextData;
/**
* All permissions that are allowed on this script
*/
permissions: CRM.Permission[];
/**
* If set, calls this function when an error occurs
*/
onError: Function;
/**
* Whether this script is running on the backgroundpage
*/
isBackground: boolean;
/**
* The communications API used to communicate with other scripts and other instances
*
* @type Object
*/
comm: {
/**
* Returns all instances running in other tabs, these instances can be passed
* to the .comm.sendMessage function to send a message to them, you can also
* call instance.sendMessage on them
*
* @param {function} [callback] - A function to call with the instances
* @returns {Promise<CommInstance[]>} A promise that resolves with the instances
*/
getInstances(callback?: (instances: CommInstance[]) => void): Promise<CommInstance[]>,
/**
* Sends a message to given instance
*
* @param {number} instance - The ID of the instance to send it to
* @param {Object} message - The message to send
* @param {function} [callback] - A callback that tells you the result,
* gets passed one argument (object) that contains the two boolean
* values `error` and `success` indicating whether the message
* succeeded. If it did not succeed and an error occurred,
* the message key of that object will be filled with the reason
* it failed ("instance no longer exists" or "no listener exists")
* @returns {InstanceCallback} A promise that resolves with the result,
* an object that contains the two boolean
* values `error` and `success` indicating whether the message
* succeeded. If it did not succeed and an error occurred,
* the message key of that object will be filled with the reason
* it failed ("instance no longer exists" or "no listener exists")
*/
sendMessage(instance: number, message: any, callback?: InstanceCallback): Promise<InstanceCallback>,
/**
* Sends a message to given instance
*
* @param {Instance} instance - The instance to send the message to
* @param {Object} message - The message to send
* @param {function} [callback] - A callback that tells you the result,
* gets passed one argument (object) that contains the two boolean
* values `error` and `success` indicating whether the message
* succeeded. If it did not succeed and an error occurred,
* the message key of that object will be filled with the reason
* it failed ("instance no longer exists" or "no listener exists")
* @returns {InstanceCallback} A promise that resolves with the result,
* an object that contains the two boolean
* values `error` and `success` indicating whether the message
* succeeded. If it did not succeed and an error occurred,
* the message key of that object will be filled with the reason
* it failed ("instance no longer exists" or "no listener exists")
*/
sendMessage(instance: CommInstance, message: any, callback?: InstanceCallback): Promise<InstanceCallback>,
/**
* Adds a listener for any comm-messages sent from other instances of
* this script
*
* @param {function} listener - The listener that gets called with the message
* @returns {number} An id that can be used to remove the listener
*/
addListener(listener: InstanceListener): number,
/**
* Removes a listener currently added by using comm.addListener
*
* @param {number} listener - The index of the listener (given by addListener)
*/
removeListener(listener: number): void,
/**
* Removes a listener currently added by using comm.addListener
*
* @param {InstanceListener} listener - The listener to remove
*/
removeListener(listener: InstanceListener): void,
/**
* Sends a message to the background page for this script
*
* @param {any} message - The message to send
* @param {Function} callback - A function to be called with a response
* @returns {Promise<any>} A promise that resolves with the response
*/
messageBackgroundPage(message: any, response?: MessageHandler): Promise<any>,
/**
* Listen for any messages to the background page
*
* @param {Function} callback - The function to call on message.
* Contains the message and the respond params respectively.
* Calling the respond param with data sends a message back.
*/
listenAsBackgroundPage(callback: RespondableInstanceListener): void
};
/**
* The storage API used to store and retrieve data for this script
*/
storage: {
/**
* Gets the value at given key, if no key is given returns the entire storage object
*
* @param {string} [keyPath] - The path at which to look, a string separated with dots
*/
get(keyPath?: string): any,
/**
* Gets the value at given key, if no key is given returns the entire storage object
*
* @param {array} [keyPath] - The path at which to look, an array of strings and numbers representing keys
*/
get(keyPath?: (string|number)[]): any,
/**
* Sets the data at given key given value
*
* @param {string} keyPath - The path at which to look, a string separated with dots
* @param {any} [value] - The value to set it to, optional if keyPath is an object
*/
set(keyPath: string, value?: any): void,
/**
* Sets the data at given key given value
*
* @param {array} keyPath - The path at which to look, an array of strings and numbers representing keys
* @param {any} [value] - The value to set it to, optional if keyPath is an object
*/
set(keyPath: (string|number)[], value?: any): void,
/**
* Deletes the data at given key given value
*
* @param {string} keyPath - The path at which to look, a string separated with dots
*/
remove(keyPath: string): void,
/**
* Deletes the data at given key given value
*
* @param {array} keyPath - The path at which to look, an array of strings and numbers representing keys
*/
remove(keyPath: (string|number)[]): void,
/**
* Functions related to the onChange event of the storage API
*/
onChange: {
/**
* Adds an onchange listener for the storage, listens for a key if given
*
* @param {function} listener - The function to run, gets called
* gets called with the first argument being the key, the second being
* the old value, the third being the new value and the fourth
* a boolean indicating if the change was on a remote tab
* @param {string} [key] - The key to listen for, if it's nested separate it by dots
* like a.b.c
* @returns {number} A number that can be used to remove the listener
*/
addListener(listener: (key: string, oldValue: any, newValue: any, remote: boolean) => void,
key?: string): number,
/**
* Removes ALL listeners with given listener (function) as the listener,
* if key is given also checks that they have that key
*
* @param {number} listener - The number of the listener to remove (given by addListener)
* @param {string} [key] - The key to check
*/
removeListener(listener: number, key?: string): void,
/**
* Removes ALL listeners with given listener (function) as the listener,
* if key is given also checks that they have that key
*
* @param {function} listener - The listener to remove
* @param {string} [key] - The key to check
*/
removeListener(listener: (key: string, oldValue: any, newValue: any, remote: boolean) => void,
key?: string): void,
}
}
/**
* The storage API used to store and retrieve data for this script
*/
storageSync: {
/**
* Gets the value at given key, if no key is given returns the entire storage object
*
* @param {string} [keyPath] - The path at which to look, a string separated with dots
*/
get(keyPath?: string): any,
/**
* Gets the value at given key, if no key is given returns the entire storage object
*
* @param {array} [keyPath] - The path at which to look, an array of strings and numbers representing keys
*/
get(keyPath?: (string|number)[]): any,
/**
* Sets the data at given key given value
*
* @param {string} keyPath - The path at which to look, a string separated with dots
* @param {any} [value] - The value to set it to, optional if keyPath is an object
*/
set(keyPath: string, value?: any): void,
/**
* Sets the data at given key given value
*
* @param {array} keyPath - The path at which to look, an array of strings and numbers representing keys
* @param {any} [value] - The value to set it to, optional if keyPath is an object
*/
set(keyPath: (string|number)[], value?: any): void,
/**
* Deletes the data at given key given value
*
* @param {string} keyPath - The path at which to look, a string separated with dots
*/
remove(keyPath: string): void,
/**
* Deletes the data at given key given value
*
* @param {array} keyPath - The path at which to look, an array of strings and numbers representing keys
*/
remove(keyPath: (string|number)[]): void,
/**
* Functions related to the onChange event of the storage API
*/
onChange: {
/**
* Adds an onchange listener for the storage, listens for a key if given
*
* @param {function} listener - The function to run, gets called
* gets called with the first argument being the key, the second being
* the old value, the third being the new value and the fourth
* a boolean indicating if the change was on a remote tab
* @param {string} [key] - The key to listen for, if it's nested separate it by dots
* like a.b.c
* @returns {number} A number that can be used to remove the listener
*/
addListener(listener: (key: string, oldValue: any, newValue: any, remote: boolean) => void,
key?: string): number,
/**
* Removes ALL listeners with given listener (function) as the listener,
* if key is given also checks that they have that key
*
* @param {number} listener - The number of the listener to remove (given by addListener)
* @param {string} [key] - The key to check
*/
removeListener(listener: number, key?: string): void,
/**
* Removes ALL listeners with given listener (function) as the listener,
* if key is given also checks that they have that key
*
* @param {function} listener - The listener to remove
* @param {string} [key] - The key to check
*/
removeListener(listener: (key: string, oldValue: any, newValue: any, remote: boolean) => void,
key?: string): void,
}
}
/**
* The contextMenuItem API which controls the look of this contextmenu item
* None of these changes are persisted to the source node and only affect
* the properties of the contextmenu item this session.
*/
contextMenuItem: {
/**
* Set the type of this contextmenu item. Options are "normal" for a regular one,
* "checkbox" for one that can be checked, "radio" for one of many that can be
* checked and "separator" for a divider line. Is not saved across sessions.
*
* @param {CRM.ContextMenuItemType} itemType - The type to set it to
* @param {boolean} [allTabs] - Whether to apply this change to all tabs, defaults to false
* @returns {Promise<void>} A promise that resolves with nothing and throws if something
* went wrong
*/
setType(itemType: CRM.ContextMenuItemType, allTabs?: boolean): Promise<void>;
/**
* Sets whether this item should be checked or not. If the contextmenu item type is either
* "normal" or "separator", the type is first changed to "checkbox".
* Is not saved across sessions.
*
* @param {boolean} checked - Whether it should be checked
* @param {boolean} [allTabs] - Whether to apply this change to all tabs, defaults to false
* @returns {Promise<void>} A promise that resolves with nothing and throws if something
* went wrong
*/
setChecked(checked: boolean, allTabs?: boolean): Promise<void>;
/**
* Sets the content types on which this item should appear. This is an array
* containing the types it should appear on. It will not appear on types that
* are not in the array. Possible values are "page", "link", "selection",
* "image", "video" and "audio". Is not saved across sessions.
*
* @param {CRM.ContentTypeString[]} contentTypes - The content types it should appear on
* @param {boolean} [allTabs] - Whether to apply this change to all tabs, defaults to false
* @returns {Promise<void>} A promise that resolves with nothing and throws if something
* went wrong
*/
setContentTypes(contentTypes: CRM.ContentTypeString[], allTabs?: boolean): Promise<void>;
/**
* Sets whether this item should be visible or not. This is only available in
* chrome 62 and above (no other browsers), won't throw an error if
* executed on a different browser/version. If this node is invisible by default
* (for example run on specified), this won't do anything and throw an error.
* Is not saved across sessions.
*
* @param {boolean} isVisible - Whether it should be visible
* @param {boolean} [allTabs] - Whether to apply this change to all tabs, defaults to false
* @returns {Promise<void>} A promise that resolves with nothing and throws if something
* went wrong
*/
setVisibility(isVisible: boolean, allTabs?: boolean): Promise<void>;
/**
* Sets whether this item should be disabled or not. A disabled node
* is simply greyed out and can not be clicked. Is not saved across sessions.
*
* @param {boolean} isDisabled - Whether it should be disabled
* @param {boolean} [allTabs] - Whether to apply this change to all tabs, defaults to false
* @returns {Promise<void>} A promise that resolves with nothing and throws if something
* went wrong
*/
setDisabled(isDisabled: boolean, allTabs?: boolean): Promise<void>;
/**
* Changes the display name of this item (can't be empty).
* Requires the "crmContextmenu" permission in order to prevent nodes from
* pretending to be other nodes. Can be reset to the default name by calling
* crmAPI.contextMenuItem.resetName. Is not saved across sessions.
*
* @permission crmContextmenu
* @param {string} name - The new name
* @param {boolean} [allTabs] - Whether to apply this change to all tabs, defaults to false
* @returns {Promise<void>} A promise that resolves with nothing and throws if something
* went wrong
*/
setName(name: string, allTabs?: boolean): Promise<void>;
/**
* Resets the name to the original node name.
*
* @param {boolean} [allTabs] - Whether to apply this change to all tabs, defaults to false
* @returns {Promise<void>} A promise that resolves with nothing and throws if something
* went wrong
*/
resetName(allTabs?: boolean): Promise<void>;
};
/**
* General CRM API functions
*/
/**
* Gets the current text selection
*
* @returns {string} - The current selection
*/
getSelection(): string;
/**
* All of the remaining functions in this region below this message will only work if your
* script runs on clicking, not if your script runs automatically, in that case you will always
* get undefined (except for the function above). For more info check out this page's onclick
* section (https://developer.chrome.com/extensions/contextMenus#method-create)
*/
/**
* Returns any data about the click on the page, check (https://developer.chrome.com/extensions/contextMenus#method-create)
* for more info of what can be returned.
*
* @returns {Object} - An object containing any info about the page, some data may be undefined if it doesn't apply
*/
getClickInfo(): ClickData;
/**
* Gets any info about the current tab/window
*
* @returns {Object} - An object of type tab (https://developer.chrome.com/extensions/tabs#type-Tab)
*/
getTabInfo(): TabData;
/**
* Gets the current node
*
* @returns {Object} - The node that is being executed right now
*/
getNode(): Node;
/**
* The crm API, used to make changes to the crm, some API calls may require permissions crmGet and crmWrite
*
* @type Object
*/
crm: {
/**
* Gets the root contextmenu ID (used by browser.contextMenus).
* Keep in mind that this is not a node id. See:
* https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/menus
*
* @param {function} [callback] - A function that is called with
* the contextmenu ID as an argument
* @returns {Promise<string|number>} A promise that resolves with the ID
*/
getRootContextMenuId(callback?: (contextMenuId: string|number) => void): Promise<string|number>;
/**
* Gets the CRM tree from the tree's root
*
* @permission crmGet
* @param {function} [callback] - A function that is called when done with the data as an argument
* @returns {Promise<SafeNode[]>} A promise that resolves with the tree
*/
getTree(callback?: (data: CRM.SafeNode[]) => void): Promise<CRM.SafeNode[]>,
/**
* Gets the CRM's tree from either the root or from the node with ID nodeId
*
* @permission crmGet
* @param {NodeIdAssignable} nodeId - The ID of the subtree's root node
* @param {function} callback - A function that is called when done with the data as an argument
* @returns {Promise<CRM.SafeNode[]>} A promise that resolves with the subtree
*/
getSubTree(nodeId: NodeIdAssignable, callback?: (data: CRM.SafeNode[]) => void): Promise<CRM.SafeNode[]>,
/**
* Gets the node with ID nodeId
*
* @permission crmGet
* @param {Instance~crmCallback} [callback] - A function that is called when done
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the node
*/
getNode<T extends CRM.SafeNode>(nodeId: CRM.NodeId<T>, callback?: (node: T) => void): Promise<T>,
getNode(nodeId: NodeIdAssignable, callback?: (node: CRM.SafeNode) => void): Promise<CRM.SafeNode>,
/**
* Gets a node's ID from a path to the node
*
* @permission crmGet
* @param {number[]} path - An array of numbers representing the path, each number
* represents the n-th child of the current node, so [1,2] represents the 2nd item(0,>1<,2)'s third child (0,1,>2<,3)
* @param {function} [callback] - The function that is called with the ID as an argument
* @returns {Promise<NodeIdAssignable>} A promise that resolves with the ID
*/
getNodeIdFromPath(path: number[], callback?: (id: NodeIdAssignable) => void): Promise<NodeIdAssignable>,
/**
* Queries the CRM for any items matching your query
*
* @permission crmGet
* @param {crmCallback} callback - The function to call when done, returns one array of results
* @param {Object} query - The query to look for
* @param {string} [query.name] - The name of the item
* @param {string} [query.type] - The type of the item (link, script, stylesheet, divider or menu)
* @param {NodeIdAssignable} [query.inSubTree] - The subtree in which this item is located (the number given is the id of the root item)
* @param {Instance~crmCallback} [callback] - A callback that is called with the resulting nodes in an array
* @returns {Promise<CRM.SafeNode[]>} A promise that resolves with the resulting nodes
*/
queryCrm(query: CRMQuery, callback?: (results: CRM.SafeNode[]) => void): Promise<CRM.SafeNode[]>,
/**
* Gets the parent of the node with ID nodeId
*
* @permission crmGet
* @param {NodeIdAssignable} nodeId - The node of which to get the parent
* @param {(node: CRM.SafeNode|CRM.SafeNode[]) => void} callback - A callback with the parent of the given node as an argument
* @returns {Promise<CRM.SafeNode|CRM.SafeNode[]>} A promise that resolves with the parent of given node
*/
getParentNode(nodeId: NodeIdAssignable, callback?: (node: CRM.SafeNode|CRM.SafeNode[]) => void): Promise<CRM.SafeNode|CRM.SafeNode[]>,
/**
* Gets the type of node with ID nodeId
*
* @permission crmGet
* @param {NodeIdAssignable} nodeId - The id of the node whose type to get
* @param {function} [callback] - A callback that is called with the type of the node as the parameter (link, script, menu or divider)
* @returns {Promise<CRM.NodeType>} A promise that resolves with the type of the node
*/
getNodeType<T extends CRM.SafeNode>(nodeId: CRM.NodeId<T>, callback?: (type: T['type']) => void): Promise<T['type']>,
getNodeType(nodeId: NodeIdAssignable, callback?: (type: CRM.NodeType) => void): Promise<CRM.NodeType>,
/**
* Gets the value of node with ID nodeId
*
* @permission crmGet
* @param {NodeIdAssignable} nodeId - The id of the node whose value to get
* @param {function} [callback] - A callback that is called with parameter linkVal, scriptVal, stylesheetVal or an empty object depending on type
* @returns {Promise<CRM.LinkVal|CRM.ScriptVal|CRM.StylesheetVal|null>} A promise that resolves with the value of the node
*/
getNodeValue<T extends CRM.SafeNode>(nodeId: CRM.NodeId<T>, callback?: (value: T['value']) => void): Promise<T['value']>,
getNodeValue(nodeId: NodeIdAssignable,
callback?: (value: CRM.LinkVal|CRM.ScriptVal|CRM.StylesheetVal|null) => void): Promise<CRM.LinkVal|CRM.ScriptVal|CRM.StylesheetVal|null>,
/**
* Creates a node with the given options
*
* @permission crmGet
* @permission crmWrite
* @param {Object} options - An object containing all the options for the node
* @param {Object} [options.position] - An object containing info about where to place the item, defaults to last if not given
* @param {NodeIdAssignable} [options.position.node] - The other node's id, if not given, "relates" to the root
* @param {string} [options.position.relation] - The position relative to the other node, possibilities are:
* firstChild: becomes the first child of given node, throws an error if given node is not of type menu
* firstSibling: first of the subtree that given node is in
* lastChild: becomes the last child of given node, throws an error if given node is not of type menu
* lastSibling: last of the subtree that given node is in
* before: before given node
* after: after the given node
* @param {string} [options.name] - The name of the object, not required, defaults to "name"
* @param {string} [options.type] - The type of the node (link, script, divider or menu), not required, defaults to link
* @param {boolean} [options.usesTriggers] - Whether the node uses triggers to launch or if it just always launches (only applies to
* link, menu and divider)
* @param {Object[]} [options.triggers] - An array of objects telling the node to show on given triggers. (only applies to link,
* menu and divider)
* @param {string} [options.triggers.url ] - The URL of the site on which to run,
* if launchMode is 2 aka run on specified pages can be any of these
* https://wiki.greasespot.net/Include_and_exclude_rules
* otherwise the url should match this pattern, even when launchMode does not exist on the node (links etc)
* https://developer.chrome.com/extensions/match_patterns
* @param {Object[]} [options.linkData] - The links to which the node of type "link" should... link (defaults to example.com in a new tab),
* consists of an array of objects each containing a URL property and a newTab property, the url being the link they open and the
* newTab boolean being whether or not it opens in a new tab.
* @param {string} [options.linkData.url] - The url to open when clicking the link, this value is required.
* @param {boolean} [options.linkData.newTab] - Whether or not to open the link in a new tab, not required, defaults to true
* @param {Object} [options.scriptData] - The data of the script, required if type is script
* @param {string} [options.scriptData.script] - The actual script, will be empty string if none given, required
* @param {number} [options.scriptData.launchMode] - The time at which this script launches, not required, defaults to 0,
* 0 = run on clicking
* 1 = always run
* 2 = run on specified pages
* 3 = only show on specified pages
* 4 = disabled
* @param {Object[]} [options.scriptData.libraries] - The libraries for the script to include, if the library is not yet
* registered throws an error, so do that first, value not required
* @param {string} [options.scriptData.libraries.name] - The name of the library
* @param {Object[]} [options.scriptData.backgroundLibraries] - The libraries for the backgroundpage to include, if the library is not yet
* registered throws an error, so do that first, value not required
* @param {string} [options.scriptData.backgroundLibraries.name] - The name of the library
* @param {Object} [options.stylesheetData] - The data of the stylesheet, required if type is stylesheet
* @param {number} [options.stylesheetData.launchMode] - The time at which this stylesheet launches, not required, defaults to 0,
* 0 = run on clicking
* 1 = always run
* 2 = run on specified pages
* 3 = only show on specified pages
* 4 = disabled
* @param {string} [options.stylesheetData.stylesheet] - The stylesheet that is ran itself
* @param {boolean} [options.stylesheetData.toggle] - Whether the stylesheet is always on or toggle-able by clicking (true = toggle-able), not required, defaults to true
* @param {boolean} [options.stylesheetData.defaultOn] - Whether the stylesheet is on by default or off, only used if toggle is true, not required, defaults to true
* @param {Instance~crmCallback} [callback] - A callback given the new node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the created node
*/
createNode(options: Partial<CRM.SafeNode> & {
position?: Relation;
}, callback?: (node: CRM.SafeNode) => void): Promise<CRM.SafeNode>,
/**
* Copies given node including children,
* WARNING: following properties are not copied:
* file, storage, id, permissions, nodeInfo
* Full permissions rights only if both the to be cloned and the script executing this have full rights
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The id of the node to copy
* @param {Object} options - An object containing all the options for the node
* @param {string} [options.name] - The new name of the object (same as the old one if none given)
* @param {Object} [options.position] - An object containing info about where to place the item, defaults to last if not given
* @param {NodeIdAssignable} [options.position.node] - The other node's id, if not given, "relates" to the root
* @param {string} [options.position.relation] - The position relative to the other node, possibilities are:
* firstChild: becomes the first child of given node, throws an error if given node is not of type menu
* firstSibling: first of the subtree that given node is in
* lastChild: becomes the last child of given node, throws an error if given node is not of type menu
* lastSibling: last of the subtree that given node is in
* before: before given node
* after: after the given node
* @param {Instance~crmCallback} [callback] - A callback given the new node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the copied node
*/
copyNode<T extends CRM.SafeNode, U extends string = 'name'>(nodeId: CRM.NodeId<T>, options: {
/**
* The name of the new node (defaults to "name")
*/
name?: U;
/**
* The position to copy it to
*/
position?: Relation
}, callback?: (node: T & { name: U }) => void): Promise<T & { name: U }>,
/**
* Copies given node including children,
* WARNING: following properties are not copied:
* file, storage, id, permissions, nodeInfo
* Full permissions rights only if both the to be cloned and the script executing this have full rights
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The id of the node to copy
* @param {Object} options - An object containing all the options for the node
* @param {string} [options.name] - The new name of the object (same as the old one if none given)
* @param {Object} [options.position] - An object containing info about where to place the item, defaults to last if not given
* @param {NodeIdAssignable} [options.position.node] - The other node's id, if not given, "relates" to the root
* @param {string} [options.position.relation] - The position relative to the other node, possibilities are:
* firstChild: becomes the first child of given node, throws an error if given node is not of type menu
* firstSibling: first of the subtree that given node is in
* lastChild: becomes the last child of given node, throws an error if given node is not of type menu
* lastSibling: last of the subtree that given node is in
* before: before given node
* after: after the given node
* @param {Instance~crmCallback} [callback] - A callback given the new node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the copied node
*/
copyNode(nodeId: NodeIdAssignable, options: {
/**
* The name of the new node (defaults to "name")
*/
name?: string;
/**
* The position to copy it to
*/
position?: Relation
}, callback?: (node: CRM.SafeNode) => void): Promise<CRM.SafeNode>,
/**
* Moves given node to position specified in `position`
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The id of the node to move
* @param {Object} [position] - An object containing info about where to place the item, defaults to last child of root if not given
* @param {NodeIdAssignable} [position.node] - The other node, if not given, "relates" to the root
* @param {string} [position.relation] - The position relative to the other node, possibilities are:
* firstChild: becomes the first child of given node, throws an error if given node is not of type menu
* firstSibling: first of the subtree that given node is in
* lastChild: becomes the last child of given node, throws an error if given node is not of type menu
* lastSibling: last of the subtree that given node is in
* before: before given node
* after: after the given node
* @param {Instance~crmCallback} [callback] - A function that gets called with the new node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the moved node
*/
moveNode<T extends CRM.SafeNode>(nodeId: CRM.NodeId<T>, position: Relation, callback?: (node: T) => void): Promise<T>,
moveNode(nodeId: NodeIdAssignable, position: Relation, callback?: (node: CRM.SafeNode) => void): Promise<CRM.SafeNode>,
/**
* Deletes given node
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The id of the node to delete
* @param {function} [callback] - A function to run when done
* @returns {((errorMessage: string) => void)((successStatus: boolean) => void)} A promise
* that resolves with an error message or the success status
*/
deleteNode(nodeId: NodeIdAssignable, callback?: (errorMessage: string) => void): Promise<string>,
deleteNode(nodeId: NodeIdAssignable, callback?: (successStatus: boolean) => void): Promise<boolean>,
/**
* Edits given settings of the node
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The id of the node to edit
* @param {Object} options - An object containing the settings for what to edit
* @param {string} [options.name] - Changes the name to given string
* @param {string} [options.type] - The type to switch to (link, script, stylesheet, divider or menu)
* @param {Instance~crmCallback} [callback] - A function to run when done, contains the new node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the edited node
*/
editNode<T extends CRM.SafeNode, U extends string = T['name'], NT extends CRM.NodeType = T['type']>(nodeId: CRM.NodeId<T>, options: {
/**
* The new name of the node
*/
name?: U,
/**
* The new type of the node
*/
type?: NT;
}, callback?: (node: T & { name: U, type: NT }) => void): Promise<T & { name: U, type: NT }>,
/**
* Edits given settings of the node
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The id of the node to edit
* @param {Object} options - An object containing the settings for what to edit
* @param {string} [options.name] - Changes the name to given string
* @param {string} [options.type] - The type to switch to (link, script, stylesheet, divider or menu)
* @param {Instance~crmCallback} [callback] - A function to run when done, contains the new node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the edited node
*/
editNode(nodeId: NodeIdAssignable, options: {
/**
* The new name of the node
*/
name?: string,
/**
* The new type of the node
*/
type?: CRM.NodeType
}, callback?: (node: CRM.SafeNode) => void): Promise<CRM.SafeNode>,
/**
* Gets the triggers for given node
*
* @permission crmGet
* @param {NodeIdAssignable} nodeId - The node of which to get the triggers
* @param {Instance~crmCallback} [callback] - A function to run when done, with the triggers as an argument
* @returns {Promise<CRM.Trigger[]>} A promise that resolves with the triggers
*/
getTriggers(nodeId: NodeIdAssignable, callback?: (triggers: CRM.Trigger[]) => void): Promise<CRM.Trigger[]>,
/**
* Sets the triggers for given node
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The node of which to get the triggers
* @param {Object[]} triggers - The triggers that launch this node, automatically turns triggers on
* @param {string} triggers.url - The URL of the site on which to run,
* if launchMode is 2 aka run on specified pages can be any of these
* https://wiki.greasespot.net/Include_and_exclude_rules
* otherwise the url should match this pattern, even when launchMode does not exist on the node (links etc)
* https://developer.chrome.com/extensions/match_patterns
* @param {boolean} triggers.not - If true does NOT show the node on that URL
* @param {Instance~crmCallback} [callback] - A function to run when done, with the node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the node
*/
setTriggers<T extends CRM.SafeNode>(nodeId: CRM.NodeId<T>, triggers: CRM.Trigger[], callback?: (node: T) => void): Promise<T>,
setTriggers(nodeId: NodeIdAssignable, triggers: CRM.Trigger[], callback?: (node: CRM.SafeNode) => void): Promise<CRM.SafeNode>,
/**
* Gets the trigger' usage for given node (true - it's being used, or false), only works on
* link, menu and divider
*
* @permission crmGet
* @param {NodeIdAssignable} nodeId - The node of which to get the triggers
* @param {Instance~crmCallback} [callback] - A function to run when done, with the triggers' usage as an argument
* @returns {Promise<boolean>} A promise that resolves with a boolean indicating whether triggers are used
*/
getTriggerUsage(nodeId: NodeIdAssignable, callback?: (usage: boolean) => void): Promise<boolean>,
/**
* Sets the usage of triggers for given node, only works on link, menu and divider
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The node of which to get the triggers
* @param {boolean} useTriggers - Whether the triggers should be used or not
* @param {Instance~crmCallback} [callback] - A function to run when done, with the node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the node
*/
setTriggerUsage<T extends CRM.SafeNode>(nodeId: CRM.NodeId<T>, useTriggers: boolean, callback?: (node: T) => void): Promise<T>
setTriggerUsage(nodeId: NodeIdAssignable, useTriggers: boolean, callback?: (node: CRM.SafeNode) => void): Promise<CRM.SafeNode>
/**
* Gets the content types for given node
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The node of which to get the content types
* @param {Instance~crmCallback} [callback] - A function to run when done, with the content types array as an argument
* @returns {Promise<CRM.ContentTypes>} A promise that resolves with the content types
*/
getContentTypes(nodeId: NodeIdAssignable, callback?: (contentTypes: CRM.ContentTypes) => void): Promise<CRM.ContentTypes>,
/**
* Sets the content type at index `index` to given value `value`
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The node whose content types to set
* @param {number|CRM.ContentTypeString} indexOrName - The index of the array to set, 0-5, ordered this way:
* page, link, selection, image, video, audio. Can also be the name of the index (one of those words)
* @param {boolean} value - The new value at index `index`
* @param {Instance~crmCallback} [callback] - A function to run when done, with the new array as an argument
* @returns {Promise<CRM.ContentTypes>} A promise that resolves with the new content types
*/
setContentType(nodeId: NodeIdAssignable, indexOrName: number, value: boolean, callback?: (contentTypes: CRM.ContentTypes) => void): Promise<CRM.ContentTypes>,
setContentType(nodeId: NodeIdAssignable, indexOrName: CRM.ContentTypeString, value: boolean, callback?: (contentTypes: CRM.ContentTypes) => void): Promise<CRM.ContentTypes>,
/**
* Sets the content types to given contentTypes array
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The node whose content types to set
* @param {number[]} contentTypes - An array of number, if an index is true, it's displayed at that index's value
* @param {Instance~crmCallback} [callback] - A function to run when done, with the node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the node
*/
setContentTypes<T extends CRM.SafeNode>(nodeId: CRM.NodeId<T>, contentTypes: CRM.ContentTypes, callback?: (node: T) => void): Promise<T>,
setContentTypes(nodeId: NodeIdAssignable, contentTypes: CRM.ContentTypes, callback?: (node: CRM.SafeNode) => void): Promise<CRM.SafeNode>,
setContentTypes(nodeId: NodeIdAssignable, contentTypes: boolean[], callback?: (node: CRM.SafeNode) => void): Promise<CRM.SafeNode>,
/**
* Sets the launch mode of node with ID nodeId to `launchMode`
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The node to edit
* @param {number} launchMode - The new launchMode, which is the time at which this script/stylesheet runs
* 0 = run on clicking
* 1 = always run
* 2 = run on specified pages
* 3 = only show on specified pages
* 4 = disabled
* @param {Instance~crmCallback} [callback] - A function that is ran when done with the new node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the node
*/
setLaunchMode<T extends CRM.SafeNode>(nodeId: CRM.NodeId<T>, launchMode: CRMLaunchModes, callback?: (node: T) => void): Promise<T>,
setLaunchMode(nodeId: NodeIdAssignable, launchMode: CRMLaunchModes, callback?: (node: CRM.SafeNode) => void): Promise<CRM.SafeNode>,
/**
* Gets the launchMode of the node with ID nodeId
*
* @permission crmGet
* @param {NodeIdAssignable} nodeId - The id of the node to get the launchMode of
* @param {function} [callback] - A callback that is called with the launchMode as an argument
* @returns {Promise<CRM.CRMLaunchModes>} A promise that resolves with the launchMode
*/
getLaunchMode(nodeId: NodeIdAssignable, callback?: (launchMode: CRMLaunchModes) => void): Promise<CRMLaunchModes>,
/**
* All functions related specifically to the stylesheet type
*/
stylesheet: {
/**
* Sets the stylesheet of node with ID nodeId to value `stylesheet`
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The node of which to change the stylesheet
* @param {string} stylesheet - The code to change to
* @param {Instance~crmCallback} [callback] - A function with the node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the node
*/
setStylesheet<T extends CRM.SafeNode>(nodeId: CRM.NodeId<T>, stylesheet: string, callback?: (node: T) => void): Promise<T>
setStylesheet(nodeId: NodeIdAssignable, stylesheet: string, callback?: (node: CRM.SafeNode) => void): Promise<CRM.SafeNode>
/**
* Gets the value of the stylesheet
*
* @permission crmGet
* @param {NodeIdAssignable} nodeId - The id of the node of which to get the stylesheet
* @param {function} [callback] - A callback that is called with the stylesheet's value as an argument
* @returns {Promise<string>} A promise that resolves with the stylesheet
*/
getStylesheet(nodeId: NodeIdAssignable, callback?: (stylesheet: string) => void): Promise<string>
},
/**
* All functions related specifically to the link type
*/
link: {
/**
* Gets the links of the node with ID nodeId
*
* @permission crmGet
* @param {NodeIdAssignable} nodeId - The id of the node to get the links from
* @param {function} [callback] - A callback that is called with an array of objects as parameters, all containing two keys:
* newTab: Whether the link should open in a new tab or the current tab
* url: The URL of the link
* @returns {Promise<CRM.LinkNodeLink[]>} A promise that resolves with the links
*/
getLinks(nodeId: NodeIdAssignable, callback?: (result: CRM.LinkNodeLink[]) => void): Promise<CRM.LinkNodeLink[]>,
/**
* Gets the links of the node with ID nodeId
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The id of the node to get the links from
* @param {Object} item - The item to push
* @param {boolean} [items.newTab] - Whether the link should open in a new tab, defaults to true
* @param {string} [items.url] - The URL to open on clicking the link
* @param {function} [callback] - A function that gets called when done with the new array as an argument
* @returns {Promise<CRM.LinkNodeLink[]>} A promise that resolves with the links
*/
setLinks(nodeId: NodeIdAssignable, item: CRM.LinkNodeLink,
callback?: (arr: CRM.LinkNodeLink[]) => void): Promise<CRM.LinkNodeLink[]>;
/**
* Gets the links of the node with ID nodeId
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The id of the node to get the links from
* @param {Object[]} items - The items to push
* @param {boolean} [items.newTab] - Whether the link should open in a new tab, defaults to true
* @param {string} [items.url] - The URL to open on clicking the link
* @param {function} [callback] - A function that gets called when done with the new array as an argument
* @returns {Promise<CRM.LinkNodeLink[]>} A promise that resolves with the links
*/
setLinks(nodeId: NodeIdAssignable, items: CRM.LinkNodeLink[],
callback?: (arr: CRM.LinkNodeLink[]) => void): Promise<CRM.LinkNodeLink[]>;
/**
* Pushes given items into the array of URLs of node with ID nodeId
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The node to push the items to
* @param {Object} items - One item to push
* @param {boolean} [items.newTab] - Whether the link should open in a new tab, defaults to true
* @param {string} [items.url] - The URL to open on clicking the link
* @param {function} [callback] - A function that gets called when done with the new array as an argument
* @returns {Promise<CRM.LinkNodeLink[]>} A promise that resolves with the new links array
*/
push(nodeId: NodeIdAssignable, items: CRM.LinkNodeLink,
callback?: (arr: CRM.LinkNodeLink[]) => void): Promise<CRM.LinkNodeLink[]>,
/**
* Pushes given items into the array of URLs of node with ID nodeId
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The node to push the items to
* @param {Object[]} items - An array of items to push
* @param {boolean} [items.newTab] - Whether the link should open in a new tab, defaults to true
* @param {string} [items.url] - The URL to open on clicking the link
* @param {function} [callback] - A function that gets called when done with the new array as an argument
* @returns {Promise<CRM.LinkNodeLink[]>} A promise that resolves with the new links array
*/
push(nodeId: NodeIdAssignable, items: CRM.LinkNodeLink[],
callback?: (arr: CRM.LinkNodeLink[]) => void): Promise<CRM.LinkNodeLink[]>
/**
* Splices the array of URLs of node with ID nodeId. Start at `start` and splices `amount` items (just like array.splice)
* and returns them as an array in the callback function
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The node to splice
* @param {number} start - The index of the array at which to start splicing
* @param {number} amount - The amount of items to splice
* @param {function} [callback] - A function that gets called with the spliced items as the first parameter and the new array as the second parameter
* @returns {Promise<{spliced: CRM.LinkNodeLink[], newArr: CRM.LinkNodeLink[]}>} A promise that resolves with an object
* containing a `spliced` property, which holds the spliced items, and a `newArr` property, holding the new array
*/
splice(nodeId: NodeIdAssignable, start: number, amount: number,
callback?: (spliced: CRM.LinkNodeLink[], newArr: CRM.LinkNodeLink[]) => void): Promise<{
spliced: CRM.LinkNodeLink[];
newArr: CRM.LinkNodeLink[];
}>;
},
script: {
/**
* Sets the script of node with ID nodeId to value `script`
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The node of which to change the script
* @param {string} script - The code to change to
* @param {Instance~crmCallback} [callback] - A function with the node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the new node
*/
setScript<T extends CRM.SafeNode>(nodeId: CRM.NodeId<T>, script: string, callback?: (node: T) => void): Promise<T>,
setScript(nodeId: NodeIdAssignable, script: string, callback?: (node: CRM.SafeNode) => void): Promise<CRM.SafeNode>,
/**
* Gets the value of the script
*
* @permission crmGet
* @param {NodeIdAssignable} nodeId - The id of the node of which to get the script
* @param {function} [callback] - A callback that is called with the script's value as an argument
* @returns {Promise<string>} A promise that resolves with the script
*/
getScript(nodeId: NodeIdAssignable, callback?: (script: string) => void): Promise<string>,
/**
* Sets the backgroundScript of node with ID nodeId to value `script`
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The node of which to change the script
* @param {string} script - The code to change to
* @param {Instance~crmCallback} [callback] - A function with the node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the node
*/
setBackgroundScript<T extends CRM.SafeNode>(nodeId: CRM.NodeId<T>, script: string, callback?: (node: T) => void): Promise<T>,
setBackgroundScript(nodeId: NodeIdAssignable, script: string, callback?: (node: CRM.SafeNode) => void): Promise<CRM.SafeNode>,
/**
* Gets the value of the backgroundScript
*
* @permission crmGet
* @param {NodeIdAssignable} nodeId - The id of the node of which to get the backgroundScript
* @param {function} [callback] - A callback that is called with the backgroundScript's value as an argument
* @returns {Promise<string>} A promise that resolves with the backgroundScript
*/
getBackgroundScript(nodeId: NodeIdAssignable, callback?: (backgroundScript: string) => void): Promise<string>,
libraries: {
/**
* Pushes given libraries to the node with ID nodeId's libraries array,
* make sure to register them first or an error is thrown, only works on script nodes
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The node to edit
* @param {Object} libraries - One library to push
* @param {string} libraries.name - The name of the library
* @param {function} [callback] - A callback that is called with the new array as an argument
* @returns {Promise<CRM.Library[]>} A promise that resolves with the new libraries
*/
push(nodeId: NodeIdAssignable, libraries: {
name: string;
}, callback?: (libs: CRM.Library[]) => void): Promise<CRM.Library[]>,
/**
* Pushes given libraries to the node with ID nodeId's libraries array,
* make sure to register them first or an error is thrown, only works on script nodes
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The node to edit
* @param {Object[]} libraries - An array of libraries to push
* @param {string} libraries.name - The name of the library
* @param {function} [callback] - A callback that is called with the new array as an argument
* @returns {Promise<CRM.Library[]>} A promise that resolves with the new libraries
*/
push(nodeId: NodeIdAssignable, libraries: {
name: string;
}[], callback?: (libs: CRM.Library[]) => void): Promise<CRM.Library[]>,
/**
* Splices the array of libraries of node with ID nodeId. Start at `start` and splices `amount` items (just like array.splice)
* and returns them as an array in the callback function, only works on script nodes
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The node to splice
* @param {number} start - The index of the array at which to start splicing
* @param {number} amount - The amount of items to splice
* @param {function} [callback] - A function that gets called with the spliced items as the first parameter and the new array as the second parameter
* @returns {Promise<{spliced: CRM.Library[], newArr: CRM.Library[]}>} A promise that resolves with an object
* that contains a `spliced` property, which contains the spliced items and a `newArr` property containing the new array
*/
splice(nodeId: NodeIdAssignable, start: number, amount: number,
callback?: (spliced: CRM.Library[], newArr: CRM.Library[]) => void): Promise<{
spliced: CRM.Library[];
newArr: CRM.Library[];
}>;
},
/**
* All functions related specifically to the background script's libraries
*/
backgroundLibraries: {
/**
* Pushes given libraries to the node with ID nodeId's libraries array,
* make sure to register them first or an error is thrown, only works on script nodes
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The node to edit
* @param {Object} libraries - One library to push
* @param {string} libraries.name - The name of the library
* @param {function} [callback] - A callback that is called with the new array as an argument
* @returns {Promise<CRM.Library[]>} A promise that resolves with the new libraries
*/
push(nodeId: NodeIdAssignable, libraries: {
name: string;
}, callback?: (libs: CRM.Library[]) => void): Promise<CRM.Library[]>,
/**
* Pushes given libraries to the node with ID nodeId's libraries array,
* make sure to register them first or an error is thrown, only works on script nodes
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The node to edit
* @param {Object[]} libraries - An array of libraries to push
* @param {string} libraries.name - The name of the library
* @param {function} [callback] - A callback that is called with the new array as an argument
* @returns {Promise<CRM.Library[]>} A promise that resolves with the new libraries
*/
push(nodeId: NodeIdAssignable, libraries: {
name: string;
}[], callback?: (libs: CRM.Library[]) => void): Promise<CRM.Library[]>,
/**
* Splices the array of libraries of node with ID nodeId. Start at `start` and splices `amount` items (just like array.splice)
* and returns them as an array in the callback function, only works on script nodes
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The node to splice
* @param {number} start - The index of the array at which to start splicing
* @param {number} amount - The amount of items to splice
* @param {function} [callback] - A function that gets called with the spliced items as the first parameter and the new array as the second parameter
* @returns {Promise<{spliced: CRM.Library[], newArr: CRM.Library[]}>} A promise that resolves with an object
* that contains a `spliced` property, which contains the spliced items and a `newArr` property containing the new array
*/
splice(nodeId: NodeIdAssignable, start: number, amount: number,
callback?: (spliced: CRM.Library[], newArr: CRM.Library[]) => void): Promise<{
spliced: CRM.Library[];
newArr: CRM.Library[];
}>;
}
},
/**
* All functions related specifically to the menu type
*/
menu: {
/**
* Gets the children of the node with ID nodeId, only works for menu type nodes
*
* @permission crmGet
* @param {NodeIdAssignable} nodeId - The id of the node of which to get the children
* @param {Instance~crmCallback} [callback] - A callback that is called with the node as an argument
* @returns {Promise<CRM.SafeNode[]>} A promise that resolves with the children
*/
getChildren(nodeId: NodeIdAssignable, callback?: (nodes: CRM.SafeNode[]) => void): Promise<CRM.SafeNode[]>,
/**
* Sets the children of node with ID nodeId to the nodes with IDs childrenIds
* only works for menu type nodes
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The id of the node of which to set the children
* @param {NodeIdAssignable[]} childrenIds - Each number in the array represents a node that will be a new child
* @param {Instance~crmCallback} [callback] - A callback that is called with the node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the menu node
*/
setChildren<T extends CRM.SafeNode>(nodeId: CRM.NodeId<T>, childrenIds: NodeIdAssignable[], callback?: (node: T) => void): Promise<T>,
setChildren(nodeId: NodeIdAssignable, childrenIds: NodeIdAssignable[], callback?: (node: CRM.SafeNode) => void): Promise<CRM.SafeNode>,
/**
* Pushes the nodes with IDs childrenIds to the node with ID nodeId
* only works for menu type nodes
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The id of the node of which to push the children
* @param {NodeIdAssignable[]} childrenIds - Each number in the array represents a node that will be a new child
* @param {Instance~crmCallback} [callback] - A callback that is called with the node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the menu
*/
push<T extends CRM.SafeNode>(nodeId: CRM.NodeId<T>, childrenIds: NodeIdAssignable[], callback?: (node: T) => void): Promise<T>,
push(nodeId: NodeIdAssignable, childrenIds: NodeIdAssignable[], callback?: (node: CRM.SafeNode) => void): Promise<CRM.SafeNode>,
/**
* Splices the children of the node with ID nodeId, starting at `start` and splicing `amount` items,
* the removed items will be put in the root of the tree instead
* only works for menu type nodes
*
* @permission crmGet
* @permission crmWrite
* @param {NodeIdAssignable} nodeId - The id of the node of which to splice the children
* @param {number} start - The index at which to start
* @param {number} amount - The amount to splice
* @param {function} [callback] - A function that gets called with the spliced items as the first parameter and the new array as the second parameter
* @returns {Promise<{spliced: CRM.SafeNode[], newArr: CRM.SafeNode[]}>} A promise that resolves with an object
* that contains a `spliced` property, which contains the spliced children and a `newArr` property containing the new children array
*/
splice(nodeId: NodeIdAssignable, start: number, amount: number,
callback?: (spliced: CRM.SafeNode[], newArr: CRM.SafeNode[]) => void): Promise<{
spliced: CRM.SafeNode[];
newArr: CRM.SafeNode[];
}>;
}
}
/**
* Background-page specific APIs
*
* @type Object
*/
background: {
/**
* Runs given script on given tab(s)
*
* @permission crmRun
* @param {NodeIdAssignable} id - The id of the script to run
* @param {Object} options - The options for the tab to run it on
* @param {boolean} [options.all] - Whether to execute on all tabs
* @param {string} [options.status] - Whether the tabs have completed loading.
* One of: "loading", or "complete"
* @param {boolean} [options.lastFocusedWindow] - Whether the tabs are in the last focused window.
* @param {number} [options.windowId] - The ID of the parent window, or windows.WINDOW_ID_CURRENT for the current window
* @param {string} [options.windowType] - The type of window the tabs are in (normal, popup, panel, app or devtools)
* @param {boolean} [options.active] - Whether the tabs are active in their windows
* @param {number} [options.index] - The position of the tabs within their windows
* @param {string} [options.title] - The title of the page
* @param {string|string[]} [options.url] - The URL of the page, can use chrome match patterns
* @param {boolean} [options.currentWindow] - Whether the tabs are in the current window
* @param {boolean} [options.highlighted] - Whether the tabs are highlighted
* @param {boolean} [options.pinned] - Whether the tabs are pinned
* @param {boolean} [options.audible] - Whether the tabs are audible
* @param {boolean} [options.muted] - Whether the tabs are muted
* @param {TabId|TabId[]} [options.tabId] - The IDs of the tabs
*/
runScript(id: NodeIdAssignable, options: QueryInfo & {
tabId?: MaybeArray<TabId>;
all?: boolean;
}): void;
/**
* Runs this script on given tab(s)
*
* @permission crmRun
* @param {Object} options - The options for the tab to run it on
* @param {boolean} [options.all] - Whether to execute on all tabs
* @param {string} [options.status] - Whether the tabs have completed loading.
* One of: "loading", or "complete"
* @param {boolean} [options.lastFocusedWindow] - Whether the tabs are in the last focused window.
* @param {number} [options.windowId] - The ID of the parent window, or windows.WINDOW_ID_CURRENT for the current window
* @param {string} [options.windowType] - The type of window the tabs are in (normal, popup, panel, app or devtools)
* @param {boolean} [options.active] - Whether the tabs are active in their windows
* @param {number} [options.index] - The position of the tabs within their windows
* @param {string} [options.title] - The title of the page
* @param {string|string[]} [options.url] - The URL of the page, can use chrome match patterns
* @param {boolean} [options.currentWindow] - Whether the tabs are in the current window
* @param {boolean} [options.highlighted] - Whether the tabs are highlighted
* @param {boolean} [options.pinned] - Whether the tabs are pinned
* @param {boolean} [options.audible] - Whether the tabs are audible
* @param {boolean} [options.muted] - Whether the tabs are muted
* @param {TabId|TabId[]} [options.tabId] - The IDs of the tabs
*/
runSelf(options: QueryInfo & {
tabId?: MaybeArray<TabId>;
all?: boolean;
}): void;
/**
* Adds a listener for a keyboard event
* Not supported in Edge (as of Edge 41)
*
* @param {string} key - The keyboard shortcut to listen for
* @param {function} callback - The function to call when a keyboard event occurs
*/
addKeyboardListener(key: string, callback: () => void): void;
}
/**
* The libraries API used to register libraries
*/
libraries: {
/**
* Registers a library with name `name`
*
* @permission crmWrite
* @param {string} name - The name to give the library
* @param {Object} options - The options related to the library (fill at least one)
* @param {string} [options.url] - The url to fetch the code from, must end in .js
* @param {string} [options.code] - The code to use
* @param {boolean} [options.ts] - Whether the library uses the typescript language
* @param {function} [callback] - A callback that is called with the library object as an argument
* @returns {Promise<CRM.InstalledLibrary>} A promise that resolves with the new library
*/
register(name: string, options: {
/**
* The code to use
*/
code?: string;
/**
* The URL to fetch the code from
*/
url?: string
/**
* Whether the library uses the typescript language
*/
ts?: boolean;
}, callback?: (lib: CRM.InstalledLibrary) => void): Promise<CRM.InstalledLibrary>,
}
/**
* Calls the chrome API given in the `API` parameter. Due to some issues with the chrome message passing
* API it is not possible to pass messages and preserve scope. This could be fixed in other ways but
* unfortunately chrome.tabs.executeScript (what is used to execute scripts on the page) runs in a
* sandbox and does not allow you to access a lot. As a solution to this there are a few types of
* functions you can chain-call on the crmAPI.chrome(API) object:
*
*
* a or args or (): uses given arguments as arguments for the API in order specified. When passing a function,
* it will be converted to a placeholder function that will be called on return with the
* arguments chrome passed to it. This means the function is never executed on the background
* page and is always executed here to preserve scope. The arguments are however passed on as they should.
* You can call this function by calling .args or by just using the parentheses as below.
* Keep in mind that this function will not work after it has been called once, meaning that
* if your API calls callbacks multiple times (like chrome.tabs.onCreated) you should use
* persistent callbacks (see below).
*
*
* r or return: a function that is called with the value that the chrome API returned. This can
* be used for APIs that don't use callbacks and instead just return values such as
* chrome.runtime.getURL().
*
*
* p or persistent: a function that is a persistent callback that will not be removed when called.
* This can be used on APIs like chrome.tabs.onCreated where multiple calls can occurring
* contrary to chrome.tabs.get where only one callback will occur.
*
*
* s or send: executes the request
* Examples:
*
*
* // For a function that uses a callback:
* crmAPI.chrome('alarms.get')('name', function(alarm) {
* //Do something with the result here
* }).send();
*
* // For a function that returns a value:
* crmAPI.chrome('runtime.getUrl')(path).return(function(result) {
* //Do something with the result
* }).send();
*
* // For a function that uses neither:
* crmAPI.chrome('alarms.create')('name', {}).send();
*
* // For a function that uses a persistent callback
* crmAPI.chrome('tabs.onCreated.addListener').persistent(function(tab) {
* //Do something with the tab
* }).send();
*
* // A compacter version:
* crmAPI.chrome('runtime.getUrl')(path).r(function(result) {
* //Do something with the result
* }).s();
*
* Requires permission `chrome` and the permission of the the API, so chrome.bookmarks requires
* permission `bookmarks`, chrome.alarms requires `alarms`
*
* @permission chrome
* @param {string} api - The API to use
* @returns {Object} - An object on which you can call `.args`, `.fn`, `.return` and
* `.send` and their first-letter-only versions (`.a`, `.f`, `.r` and `.s`)
*/
chrome(api: string): ChromeRequestReturn;
/**
* An object closely resembling the browser API object.
* Access the function you want to run through the object and then
* call it like the chrome API by calling a set of functions on it.
* You can either call functions by finding them through their respective
* objects (like crmAPI.browser.alarms.create) or by calling
* crmAPI.browser.any(api) where api is a string where the apis
* are separated by dots (for example: crmAPI.browser.any('alarms.create'))
* There are a few types of functions you can chain-call on the
* crmAPI.browser.{api} object:
* a or args or (): uses given arguments as arguments for the API in order specified. When passing a function,
* it will be converted to a placeholder function that will be called on return with the
* arguments chrome passed to it. This means the function is never executed on the background
* page and is always executed here to preserve scope. The arguments are however passed on as they should.
* You can call this function by calling .args or by just using the parentheses as below.
* Keep in mind that this function will not work after it has been called once, meaning that
* if your API calls callbacks multiple times (like chrome.tabs.onCreated) you should use
* persistent callbacks (see below).
* p or persistent: a function that is a persistent callback that will not be removed when called.
* This can be used on APIs like chrome.tabs.onCreated where multiple calls can occurring
* contrary to chrome.tabs.get where only one callback will occur.
* s or send: executes the request
* Examples:
* - For a function that returns a promise:
* crmAPI.browser.alarms.get('name').send().then((alarm) => {
* //Do something with the result here
* });
* -
* - Or the async version
* const alarm = await crmAPI.browser.alarms.get('name').send();
* -
* - For a function that returns a value it works the same:
* crmAPI.browser.runtime.getURL(path).send().then((result) => {
* //Do something with the result
* });
* -
* - For a function that uses neither:
* crmAPI.browser.alarms.create('name', {}).send();
* -
* - Or you can still await it to know when it's done executing
* crmAPI.browser.alarms.create('name', {}).send();
* -
* - For a function that uses a persistent callback
* crmAPI.browser.tabs.onCreated.addListener.persistent(function(tab) {
* //Do something with the tab
* }).send();
* -
* - A compacter version:
* const { url } = await crmAPI.browser.tabs.create('name').s();
* -
* Requires permission "chrome" (or "browser", they're the same) and the permission
* of the the API, so browser.bookmarks requires permission "bookmarks",
* browser.alarms requires "alarms"
*
* @permission chrome
* @permission browser
* @returns {Object} - An object on which you can call .args, .fn and .send
* (and their first-letter-only versions)
*/
browser: typeof crmbrowser & {
any(api: string): BrowserRequestReturn;
}
/**
* The GM API that fills in any APIs that GreaseMonkey uses and points them to their
* CRM counterparts
* Documentation can be found here http://wiki.greasespot.net/Greasemonkey_Manual:API
* and here http://tampermonkey.net/documentation.php
*/
GM: GM_Fns;
/**
* Fetches resource at given url. If this keeps failing with
* a CORB error, try crmAPI.fetchBackground
*
* @param {string} url - The url to fetch the data from
* @returns {Promise<string>} A promise that resolves to the content
*/
fetch(url: string): Promise<string>;
/**
* Fetches resource at given url through the background-page, bypassing
* any CORS or CORB-like blocking
*
* @param {string} url - The url to fetch the data from
* @returns {Promise<string>} A promise that resolves to the content
*/
fetchBackground(url: string): Promise<string>
/**
* Logs given arguments to the background page and logger page
*
* @param {any[]} argument - An argument to pass (can be as many as you want)
* in the form of crmAPI.log(a,b,c,d);
*/
log(...args: any[]): void;
/**
* Gets the current text selection
*
* @returns {string} - The current selection
*/
getSelection(): string;
/**
* Returns the elements matching given selector within given context
*
* @param {string} selector - A css selector string to find elements with
* @param {Object} [context] - The context of the search (the node from which to start, default is document)
* @returns {Element[]} An array of the matching HTML elements
*/
$crmAPI(selector: string): HTMLElement[];
$crmAPI(selector: string): void[];
$crmAPI(selector: string, context: HTMLElement): HTMLElement[];
$crmAPI(selector: string, context: HTMLElement): void[];
$crmAPI(selector: string, context: Document): HTMLElement[];
$crmAPI(selector: string, context: Document): void[];
/**
* Returns the elements matching given selector within given context
*
* @param {string} selector - A css selector string to find elements with
* @param {Object} [context] - The context of the search (the node from which to start, default is document)
* @returns {Element[]} An array of the matching HTML elements
*/
$(selector: string): HTMLElement[];
$(selector: string): void[];
$(selector: string, context: HTMLElement): HTMLElement[];
$(selector: string, context: HTMLElement): void[];
$(selector: string, context: Document): HTMLElement[];
$(selector: string, context: Document): void[];
}
}
}
/**
* If you want to use the window.$ property of the CRM API, put this line in your code:
* declare var $: crmAPIQuerySelector
* you can also use jQuery if you have that included as a library
*/
type ElementMaps = HTMLElementTagNameMap & ElementTagNameMap;
type crmAPIQuerySelector = <T extends keyof ElementMaps>(selector: T, context?: HTMLElement|Element|Document) => ElementMaps[T][];
type CRMAPI = CRM.CRMAPI.Instance;
declare var crmAPI: CRMAPI;
interface Window extends CRM.CRMAPI.GM_Fns {
crmAPI: CRMAPI
$?: crmAPIQuerySelector
} | the_stack |
import { ResolveConfigOptions, format, resolveConfig } from 'prettier';
type ArrayType = { type: 'array'; of: Array<{ type: string }> };
type BlockType = { type: 'block' };
type BooleanType = { type: 'boolean' };
type DateType = { type: 'date' };
type DatetimeType = { type: 'datetime' };
type DocumentType = {
type: 'document';
fields: Field[];
name: string;
title?: string;
description?: string;
};
type FileType = { type: 'file'; name?: string; fields?: any[] };
type GeopointType = { type: 'geopoint' };
type ImageType = { type: 'image'; name?: string; fields?: any[] };
type NumberType = { type: 'number' };
type ObjectType = {
type: 'object';
fields: Field[];
name?: string;
title?: string;
description?: string;
};
type ReferenceType = {
type: 'reference';
// even though the sanity docs say this is only ever an array, their default
// blog example doesn't follow this.
to: { type: string } | Array<{ type: string }>;
weak?: boolean;
};
type SlugType = { name?: string; type: 'slug' };
type StringType = {
type: 'string';
options?: { list?: Array<string | { title: string; value: string }> };
};
type SpanType = { type: 'span' };
type TextType = { type: 'text'; rows?: number };
type UrlType = { type: 'url' };
type IntrinsicType =
| ArrayType
| BlockType
| BooleanType
| DateType
| DatetimeType
| DocumentType
| FileType
| GeopointType
| ImageType
| NumberType
| ObjectType
| ReferenceType
| SlugType
| StringType
| SpanType
| TextType
| UrlType;
type GetNameTypes<T> = T extends { name?: string } ? T : never;
type NamedType = GetNameTypes<IntrinsicType>;
type Field = {
name: string;
title?: string;
type: string;
description?: string;
codegen?: { required?: boolean };
validation?: any;
};
type Node = IntrinsicType | { type: string };
type Parent = { node: Node; path: string | number };
function validatePropertyName(
sanityTypeName: string,
parents: Parent[],
params: { allowHyphen: boolean; allowPeriod: boolean }
) {
const regex = new RegExp(
`^[A-Z][A-Z0-9_${params.allowPeriod ? '\\.' : ''}${
params.allowHyphen ? '-' : ''
}]*$`,
'i'
);
if (!regex.test(sanityTypeName)) {
throw new Error(
`Name "${sanityTypeName}" ${
parents.length > 0
? `in type "${parents.map((i) => i.path).join('.')}" `
: ''
}is not valid. Ensure camel case, alphanumeric, and underscore characters only`
);
}
}
function defaultGenerateTypeName(sanityTypeName: string) {
const typeName = `${sanityTypeName
.substring(0, 1)
.toUpperCase()}${sanityTypeName
// If using snake_case, remove underscores and convert to uppercase the letter following them.
.replace(/(_[A-Z])/gi, (replace) => replace.substring(1).toUpperCase())
.replace(/(-[A-Z])/gi, (replace) => replace.substring(1).toUpperCase())
.replace(/(\.[A-Z])/gi, (replace) => replace.substring(1).toUpperCase())
.substring(1)}`;
return typeName;
}
export interface GenerateTypesOptions {
/**
* Provide an array of uncompiled sanity types prior to running them through
* sanity's `createSchema`
*/
types: IntrinsicType[];
/**
* Optionally provide a function that generates the typescript type identifer
* from the sanity type name. Use this function to override the default and
* prevent naming collisions.
*/
generateTypeName?: (sanityTypeName: string) => string;
/**
* This option is fed directly to prettier `resolveConfig`
*
* https://prettier.io/docs/en/api.html#prettierresolveconfigfilepath--options
*/
prettierResolveConfigPath?: string;
/**
* This options is also fed directly to prettier `resolveConfig`
*
* https://prettier.io/docs/en/api.html#prettierresolveconfigfilepath--options
*/
prettierResolveConfigOptions?: ResolveConfigOptions;
}
async function generateTypes({
types,
generateTypeName = defaultGenerateTypeName,
prettierResolveConfigPath,
prettierResolveConfigOptions,
}: GenerateTypesOptions) {
const documentTypes = types.filter(
(t): t is DocumentType => t.type === 'document'
);
const otherTypes = types.filter(
(t): t is Exclude<IntrinsicType, DocumentType> => t.type !== 'document'
);
const createdTypeNames: { [name: string]: boolean } = {};
const referencedTypeNames: { [name: string]: boolean } = {};
function createTypeName(
sanityTypeName: string,
params: { allowHyphen: boolean; allowPeriod: boolean }
) {
validatePropertyName(sanityTypeName, [], params);
const typeName = generateTypeName(sanityTypeName);
createdTypeNames[typeName] = true;
return typeName;
}
/**
* Given a sanity type name, it returns a normalized name that will be used for
* typescript interfaces throwing if invalid
*/
function getTypeName(
sanityTypeName: string,
params: { allowHyphen: boolean; allowPeriod: boolean }
) {
validatePropertyName(sanityTypeName, [], params);
const typeName = generateTypeName(sanityTypeName);
referencedTypeNames[typeName] = true;
return typeName;
}
/**
* Converts a sanity type to a typescript type recursively
*/
function convertType(obj: Node, parents: Parent[]): string {
const intrinsic = obj as IntrinsicType;
if (intrinsic.type === 'array') {
const union = intrinsic.of
.map((i, index) =>
convertType(i, [
...parents,
{
node: intrinsic,
path: index,
},
])
)
.map((i) => {
// if the wrapping type is a reference, we need to replace that type
// with `SanityKeyedReference<T>` in order to preserve `T` (which
// is purely for meta programming purposes)
const referenceMatch = /^\s*SanityReference<([^>]+)>\s*$/.exec(i);
if (referenceMatch) {
const innerType = referenceMatch[1];
return `SanityKeyedReference<${innerType}>`;
}
return `SanityKeyed<${i}>`;
})
.join(' | ');
return `Array<${union}>`;
}
if (intrinsic.type === 'block') {
return 'SanityBlock';
}
if (intrinsic.type === 'document') {
throw new Error('Found nested document type');
}
if (intrinsic.type === 'span') {
throw new Error('Found span outside of a block type.');
}
if (intrinsic.type === 'geopoint') {
return 'SanityGeoPoint';
}
if (intrinsic.type === 'image' || intrinsic.type === 'file') {
const lastParent = parents[parents.length - 1] as Parent | undefined;
// if the last parent has fields, then the resulting type won't use it's
// name as the `_type`
const lastParentHasFields =
lastParent?.node.type &&
['object', 'image', 'file'].includes(lastParent.node.type);
const typeName = lastParentHasFields
? intrinsic.type
: intrinsic.name || intrinsic.type;
const typeClause = `_type: '${typeName}'; `;
const assetClause = `asset: SanityReference<${
intrinsic.type === 'image'
? 'SanityImageAsset'
: // TODO: add types for non-image assets
'any'
}>;`;
const imageSpecificClause =
intrinsic.type === 'image'
? `
crop?: SanityImageCrop;
hotspot?: SanityImageHotspot;
`
: '';
const fields = intrinsic?.fields || [];
return `{ ${typeClause} ${assetClause} ${imageSpecificClause} ${fields
.map((field) =>
convertField(field, [
...parents,
{
node: intrinsic,
path: intrinsic.name || `(anonymous ${intrinsic.type})`,
},
])
)
.filter(Boolean)
.join('\n')} }`;
}
if (intrinsic.type === 'object') {
const typeClause = intrinsic.name ? `_type: '${intrinsic.name}';` : '';
return `{ ${typeClause} ${intrinsic.fields
.map((field) =>
convertField(field, [
...parents,
{
node: intrinsic,
path: intrinsic.name || '(anonymous object)',
},
])
)
.filter(Boolean)
.join('\n')} }`;
}
if (intrinsic.type === 'reference') {
// TODO for weak references, the expand should return \`T | undefined\`
const to = Array.isArray(intrinsic.to) ? intrinsic.to : [intrinsic.to];
const union = to
.map((refType) =>
convertType(refType, [
...parents,
{
node: intrinsic,
path: '_ref',
},
])
)
.join(' | ');
// Note: we want the union to be wrapped by one Reference<T> so when
// unwrapped the union can be further discriminated using the `_type`
// of each individual reference type
return `SanityReference<${union}>`;
}
if (intrinsic.type === 'boolean') {
return 'boolean';
}
if (intrinsic.type === 'date') {
return 'string';
}
if (intrinsic.type === 'datetime') {
return 'string';
}
if (intrinsic.type === 'number') {
return 'number';
}
if (intrinsic.type === 'slug') {
return `{ _type: '${
intrinsic.name || intrinsic.type
}'; current: string; }`;
}
if (intrinsic.type === 'string') {
// Sanity lets you specify a set of list allowed strings in the editor
// for the type of string. This checks for that and returns unioned
// literals instead of just `string`
if (intrinsic.options?.list && Array.isArray(intrinsic.options?.list)) {
return intrinsic.options?.list
.map((item) => (typeof item === 'object' ? item.value : item))
.map((item) => `'${item}'`)
.join(' | ');
}
// else just return a string
return 'string';
}
if (intrinsic.type === 'text') {
return 'string';
}
if (intrinsic.type === 'url') {
return 'string';
}
return getTypeName(obj.type, { allowHyphen: true, allowPeriod: true });
}
function convertField(field: Field, parents: Parent[]) {
const required = !!field.codegen?.required;
const optional = !required ? '?' : '';
if (required && typeof field.validation !== 'function') {
throw new Error(
`Field "${[...parents.map((i) => i.path), field.name].join(
'.'
)}" was marked as required but did not have a validation function.`
);
}
validatePropertyName(field.name, parents, {
allowHyphen: false,
allowPeriod: false,
});
return `
/**
* ${field.title || field.name} — \`${field.type}\`
*
* ${field.description || ''}
*/
${field.name}${optional}: ${convertType(field, [
...parents,
{ node: field, path: field.name },
])};
`;
}
function generateTypeForDocument(schemaType: DocumentType) {
const { name, title, description, fields } = schemaType;
if (!name) {
throw new Error(`Found a document type with no name field.`);
}
return `
/**
* ${title || name}
*
* ${description || ''}
*/
export interface ${createTypeName(name, {
allowHyphen: true,
allowPeriod: false,
})} extends SanityDocument {
_type: '${name}';
${fields
.map((field) =>
convertField(field, [{ node: schemaType, path: name }])
)
.filter(Boolean)
.join('\n')}
}
`;
}
const typeStrings = [
`
import type {
SanityReference,
SanityKeyedReference,
SanityAsset,
SanityImage,
SanityFile,
SanityGeoPoint,
SanityBlock,
SanityDocument,
SanityImageCrop,
SanityImageHotspot,
SanityKeyed,
SanityImageAsset,
SanityImageMetadata,
SanityImageDimensions,
SanityImagePalette,
SanityImagePaletteSwatch,
} from 'sanity-codegen';
export type {
SanityReference,
SanityKeyedReference,
SanityAsset,
SanityImage,
SanityFile,
SanityGeoPoint,
SanityBlock,
SanityDocument,
SanityImageCrop,
SanityImageHotspot,
SanityKeyed,
SanityImageAsset,
SanityImageMetadata,
SanityImageDimensions,
SanityImagePalette,
SanityImagePaletteSwatch,
};
`,
...types
.filter((t): t is DocumentType => t.type === 'document')
.map(generateTypeForDocument),
...otherTypes
.filter(
(t): t is Exclude<NamedType, DocumentType> & { name: string } =>
!!(t as any).name
)
.map((type) => {
return `
export type ${createTypeName(type.name, {
allowHyphen: false,
allowPeriod: false,
})} = ${convertType(type, [])};
`;
}),
];
if (documentTypes.length) {
typeStrings.push(`
export type Documents = ${documentTypes
.map(({ name }) =>
getTypeName(name, { allowHyphen: true, allowPeriod: false })
)
.join(' | ')}
`);
}
const missingTypes = Object.keys(referencedTypeNames).filter(
(typeName) => !createdTypeNames[typeName]
);
if (missingTypes.length) {
console.warn(
`Could not find types for: ${missingTypes
.map((t) => `"${t}"`)
.join(', ')}. Ensure they are present in your schema. ` +
`Future versions of sanity-codegen will allow you to type them separately.`
);
}
for (const missingType of missingTypes) {
typeStrings.push(`
/**
* This interface is a stub. It was referenced in your sanity schema but
* the definition was not actually found. Future versions of
* sanity-codegen will let you type this explicity.
*/
type ${missingType} = any;
`);
}
const resolvedConfig = prettierResolveConfigPath
? await resolveConfig(
prettierResolveConfigPath,
prettierResolveConfigOptions
)
: null;
return format(typeStrings.join('\n'), {
...resolvedConfig,
parser: 'typescript',
});
}
export default generateTypes; | the_stack |
import { makeSingleDeviceUILogicTestFactory } from 'src/tests/ui-logic-tests'
import { setupTest } from './logic.test.util'
import { STORAGE_KEYS as CLOUD_STORAGE_KEYS } from 'src/personal-cloud/constants'
import { TEST_USER } from '@worldbrain/memex-common/lib/authentication/dev'
describe('Dashboard Refactor misc logic', () => {
const it = makeSingleDeviceUILogicTestFactory()
it('should be able to load local lists during init logic', async ({
device,
}) => {
device.backgroundModules.backupModule.isAutomaticBackupEnabled = async () =>
false
device.backgroundModules.backupModule.getBackupTimes = async () => ({
lastBackup: null,
nextBackup: null,
})
const { searchResults } = await setupTest(device)
const listNames = ['testA', 'testB']
const listIds = await device.backgroundModules.customLists.createCustomLists(
{ names: listNames },
)
const expectedListData = {
[listIds[0]]: expect.objectContaining({
id: listIds[0],
name: listNames[0],
}),
[listIds[1]]: expect.objectContaining({
id: listIds[1],
name: listNames[1],
}),
}
expect(
searchResults.state.listsSidebar.localLists.loadingState,
).toEqual('pristine')
expect(searchResults.state.listsSidebar.listData).toEqual({})
expect(
searchResults.state.listsSidebar.localLists.filteredListIds,
).toEqual([])
expect(searchResults.state.listsSidebar.localLists.allListIds).toEqual(
[],
)
await searchResults.processEvent('init', null)
expect(
searchResults.state.listsSidebar.localLists.loadingState,
).toEqual('success')
expect(searchResults.state.listsSidebar.listData).toEqual(
expectedListData,
)
expect(
searchResults.state.listsSidebar.localLists.filteredListIds,
).toEqual(listIds)
expect(searchResults.state.listsSidebar.localLists.allListIds).toEqual(
listIds,
)
})
it('should trigger search during init logic', async ({ device }) => {
const { searchResults } = await setupTest(device, {
overrideSearchTrigger: true,
})
expect(searchResults.logic['searchTriggeredCount']).toBe(0)
await searchResults.processEvent('init', null)
expect(searchResults.logic['searchTriggeredCount']).toBe(1)
})
it('should hydrate state from local storage during init logic', async ({
device,
}) => {
const {
searchResults: searchResultsA,
logic: logicA,
} = await setupTest(device, { withAuth: true })
const now = Date.now()
await logicA.syncSettings.dashboard.set('listSidebarLocked', false)
await logicA.syncSettings.dashboard.set(
'subscribeBannerShownAfter',
now,
)
await logicA['options'].localStorage.set({
[CLOUD_STORAGE_KEYS.isSetUp]: false,
})
expect(searchResultsA.state.listsSidebar.isSidebarLocked).toBe(false)
expect(
searchResultsA.state.searchResults.isSubscriptionBannerShown,
).toBe(false)
expect(
searchResultsA.state.searchResults.isCloudUpgradeBannerShown,
).toBe(false)
expect(searchResultsA.state.isCloudEnabled).toBe(true)
await searchResultsA.processEvent('init', null)
expect(searchResultsA.state.listsSidebar.isSidebarLocked).toBe(false)
expect(
searchResultsA.state.searchResults.isSubscriptionBannerShown,
).toBe(true)
expect(
searchResultsA.state.searchResults.isCloudUpgradeBannerShown,
).toBe(true)
expect(searchResultsA.state.isCloudEnabled).toBe(false)
const {
searchResults: searchResultsB,
logic: logicB,
} = await setupTest(device, { withAuth: true })
await logicA.syncSettings.dashboard.set('listSidebarLocked', true)
await logicA.syncSettings.dashboard.set(
'subscribeBannerShownAfter',
null,
)
await logicB['options'].localStorage.set({
[CLOUD_STORAGE_KEYS.isSetUp]: true,
})
expect(searchResultsB.state.listsSidebar.isSidebarLocked).toBe(false)
expect(
searchResultsB.state.searchResults.isSubscriptionBannerShown,
).toBe(false)
expect(
searchResultsB.state.searchResults.isCloudUpgradeBannerShown,
).toBe(false)
expect(searchResultsB.state.isCloudEnabled).toBe(true)
await searchResultsB.processEvent('init', null)
expect(searchResultsB.state.listsSidebar.isSidebarLocked).toBe(true)
expect(
searchResultsB.state.searchResults.isSubscriptionBannerShown,
).toBe(false)
expect(
searchResultsB.state.searchResults.isCloudUpgradeBannerShown,
).toBe(false)
expect(searchResultsB.state.isCloudEnabled).toBe(true)
})
// it('should get sharing access state during init logic', async ({
// device,
// }) => {
// const { searchResults: searchResultsA } = await setupTest(device)
// device.backgroundModules.auth.remoteFunctions.isAuthorizedForFeature = async () =>
// true
// expect(searchResultsA.state.searchResults.sharingAccess).toEqual(
// 'feature-disabled',
// )
// await searchResultsA.processEvent('init', null)
// expect(searchResultsA.state.searchResults.sharingAccess).toEqual(
// 'sharing-allowed',
// )
// const { searchResults: searchResultsB } = await setupTest(device)
// device.backgroundModules.auth.remoteFunctions.isAuthorizedForFeature = async () =>
// false
// expect(searchResultsB.state.searchResults.sharingAccess).toEqual(
// 'feature-disabled',
// )
// await searchResultsB.processEvent('init', null)
// expect(searchResultsB.state.searchResults.sharingAccess).toEqual(
// 'feature-disabled',
// )
// })
it('should get current user state during init logic', async ({
device,
}) => {
const { searchResults: searchResultsA } = await setupTest(device, {
withAuth: true,
})
expect(searchResultsA.state.currentUser).toBeNull()
await searchResultsA.processEvent('init', null)
expect(searchResultsA.state.currentUser).toEqual(TEST_USER)
const { searchResults: searchResultsB } = await setupTest(device, {
withAuth: false,
})
expect(searchResultsB.state.currentUser).toBeNull()
await searchResultsB.processEvent('init', null)
expect(searchResultsB.state.currentUser).toEqual(TEST_USER)
})
it('should get feed activity status during init logic', async ({
device,
}) => {
device.backgroundModules.backupModule.isAutomaticBackupEnabled = async () =>
false
device.backgroundModules.backupModule.getBackupTimes = async () => ({
lastBackup: null,
nextBackup: null,
})
device.backgroundModules.activityIndicator.remoteFunctions.checkActivityStatus = async () =>
'has-unseen'
const { searchResults: logicA } = await setupTest(device)
expect(logicA.state.listsSidebar.hasFeedActivity).toBe(false)
await logicA.init()
expect(logicA.state.listsSidebar.hasFeedActivity).toBe(true)
device.backgroundModules.activityIndicator.remoteFunctions.checkActivityStatus = async () =>
'all-seen'
const { searchResults: logicB } = await setupTest(device)
expect(logicB.state.listsSidebar.hasFeedActivity).toBe(false)
await logicB.init()
expect(logicB.state.listsSidebar.hasFeedActivity).toBe(false)
device.backgroundModules.activityIndicator.remoteFunctions.checkActivityStatus = async () =>
'error'
const { searchResults: logicC } = await setupTest(device)
expect(logicC.state.listsSidebar.hasFeedActivity).toBe(false)
await logicC.init()
expect(logicC.state.listsSidebar.hasFeedActivity).toBe(false)
device.backgroundModules.activityIndicator.remoteFunctions.checkActivityStatus = async () =>
'not-logged-in'
const { searchResults: logicD } = await setupTest(device)
expect(logicD.state.listsSidebar.hasFeedActivity).toBe(false)
await logicD.init()
expect(logicD.state.listsSidebar.hasFeedActivity).toBe(false)
await logicA.cleanup()
await logicB.cleanup()
await logicC.cleanup()
await logicD.cleanup()
})
it('should get feed activity status during init logic', async ({
device,
}) => {
let activitiesMarkedAsSeen = false
let feedUrlOpened = false
device.backgroundModules.activityIndicator.remoteFunctions.markActivitiesAsSeen = async () => {
activitiesMarkedAsSeen = true
}
const { searchResults } = await setupTest(device, {
withAuth: true,
openFeedUrl: () => {
feedUrlOpened = true
},
})
searchResults.processMutation({
listsSidebar: { hasFeedActivity: { $set: true } },
})
expect(searchResults.state.listsSidebar.hasFeedActivity).toBe(true)
expect(feedUrlOpened).toBe(false)
expect(activitiesMarkedAsSeen).toBe(false)
await searchResults.processEvent('clickFeedActivityIndicator', null)
expect(searchResults.state.listsSidebar.hasFeedActivity).toBe(false)
expect(feedUrlOpened).toBe(true)
expect(activitiesMarkedAsSeen).toBe(true)
})
it('should hide banner and set cloud enabled flag on migration finish', async ({
device,
}) => {
const { searchResults } = await setupTest(device)
const initState = () =>
searchResults.processMutation({
modals: { showCloudOnboarding: { $set: true } },
searchResults: { isCloudUpgradeBannerShown: { $set: true } },
isCloudEnabled: { $set: false },
})
initState()
expect(searchResults.state.isCloudEnabled).toBe(false)
expect(
searchResults.state.searchResults.isCloudUpgradeBannerShown,
).toBe(true)
expect(searchResults.state.modals.showCloudOnboarding).toBe(true)
await searchResults.processEvent('closeCloudOnboardingModal', {
didFinish: false,
})
expect(searchResults.state.isCloudEnabled).toBe(false)
expect(
searchResults.state.searchResults.isCloudUpgradeBannerShown,
).toBe(true)
expect(searchResults.state.modals.showCloudOnboarding).toBe(false)
initState()
await searchResults.processEvent('closeCloudOnboardingModal', {
didFinish: true,
})
expect(searchResults.state.isCloudEnabled).toBe(true)
expect(
searchResults.state.searchResults.isCloudUpgradeBannerShown,
).toBe(false)
expect(searchResults.state.modals.showCloudOnboarding).toBe(false)
})
}) | the_stack |
import { Plane } from '../math/Plane'
// import {Shader} from '../renderers/shaders/ShaderLib'
import { EventDispatcher } from '../core/EventDispatcher'
import { Event } from '../core/Event'
// import {WebGLRenderer} from '../renderers/WebGLRenderer'
import {
BlendingDstFactor,
BlendingEquation,
Blending,
BlendingSrcFactor,
DepthModes,
Side,
Colors,
NormalBlending,
NoColors,
AddEquation,
LessEqualDepth,
ShadowSide,
Precision,
} from '../constants'
import { generateUUID } from '../math/MathUtils'
// Materials //////////////////////////////////////////////////////////////////////////////////
let materialId: i32 = 0
// TODO ?
// export interface MaterialParameters {
// alphaTest?: f32
// blendDst?: BlendingDstFactor
// blendDstAlpha?: f32
// blendEquation?: BlendingEquation
// blendEquationAlpha?: f32
// blending?: Blending
// blendSrc?: BlendingSrcFactor | BlendingDstFactor
// blendSrcAlpha?: f32
// clipIntersection?: boolean
// clippingPlanes?: Plane[]
// clipShadows?: boolean
// colorWrite?: boolean
// depthFunc?: DepthModes
// depthTest?: boolean
// depthWrite?: boolean
// fog?: boolean
// lights?: boolean
// name?: string
// opacity?: f32
// overdraw?: f32
// polygonOffset?: boolean
// polygonOffsetFactor?: f32
// polygonOffsetUnits?: f32
// precision?: 'highp' | 'mediump' | 'lowp' | null
// premultipliedAlpha?: boolean
// dithering?: boolean
// flatShading?: boolean
// side?: Side
// shadowSide?: Side
// transparent?: boolean
// vertexColors?: Colors
// vertexTangents?: boolean
// visible?: boolean
// }
/**
* Materials describe the appearance of objects. They are defined in a (mostly) renderer-independent way, so you don't have to rewrite materials if you decide to use a different renderer.
*/
export class Material extends EventDispatcher {
/**
* Unique number of this material instance.
*/
id: i32 = materialId++
/**
* UUID of this material instance. This gets automatically assigned, so
* this shouldn't be edited.
*/
uuid: string = generateUUID()
/**
* Material name. Default is an empty string.
*/
name: string = ''
/**
* Value is the string 'Material'. This shouldn't be changed, and can be
* used to find all objects of this type in a scene.
*/
type: string = 'Material'
/**
* Used to check whether this or derived classes are materials. Default is true.
* You should not change this, as it used internally for optimisation.
*/
isMaterial: true = true
/**
* Whether the material is affected by fog. Default is true.
*/
fog: boolean = true
/**
* Whether the material is affected by lights. Default is true.
*/
lights: boolean = true
/**
* Which blending to use when displaying objects with this material.
* Default is {@link NormalBlending}.
*/
blending: Blending = NormalBlending
/**
* Defines which of the face sides will be rendered - front, back or both.
* Default is THREE.FrontSide. Other options are THREE.BackSide and
* THREE.DoubleSide.
*/
side: Side = Side.FrontSide
/**
* Define whether the material is rendered with flat shading. Default is false.
*/
flatShading: boolean = false
/**
* Defines whether precomputed vertex tangents are used. Default is false.
*/
vertexTangents: boolean = false
/**
* Defines whether vertex coloring is used. Default is THREE.NoColors.
* Other options are VertexColors and FaceColors.
*/
vertexColors: Colors = NoColors
/**
* Opacity. Default is 1.
*/
opacity: f32 = 1
/**
* Defines whether this material is transparent. This has an effect on rendering as transparent objects need special treatment and are rendered after non-transparent objects.
* When set to true, the extent to which the material is transparent is controlled by setting it's .opacity property.
* Default is false.
*/
transparent: boolean = false
/**
* Blending source. It's one of the blending mode constants defined in
* Three.js. Default is {@link SrcAlphaFactor}.
*/
blendSrc: BlendingSrcFactor = BlendingSrcFactor.SrcAlphaFactor
/**
* Blending destination. It's one of the blending mode constants defined in
* Three.js. Default is {@link OneMinusSrcAlphaFactor}.
*/
blendDst: BlendingDstFactor = BlendingDstFactor.OneMinusSrcAlphaFactor
/**
* Blending equation to use when applying blending. It's one of the
* constants defined in Three.js. Default is {@link AddEquation}.
*/
blendEquation: BlendingEquation = AddEquation
/**
* The tranparency of the .blendSrc, between 0 to 1, or equal to -1 if
* disabled. Default is -1, which means it will use the value from
* .blendSrc.
*/
// TODO make sure to update parts of the code that check blendSrcAlpha for null to instead check for -1.
blendSrcAlpha: f32 = -1
/**
* The tranparency of the .blendDst. Default is null.
*/
// TODO update null checking to check for -1 instead
blendDstAlpha: f32 = -1
/**
* The tranparency of the .blendEquation. Default is null.
*/
blendEquationAlpha: f32 = -1
/**
* Which depth function to use. Default is {@link LessEqualDepth}. See the
* depth mode constants for all possible values.
*/
depthFunc: DepthModes = LessEqualDepth
/**
* Whether to have depth test enabled when rendering this material. Default is true.
*/
depthTest: boolean = true
/**
* Whether rendering this material has any effect on the depth buffer. Default is true.
* When drawing 2D overlays it can be useful to disable the depth writing in order to layer several things together without creating z-index artifacts.
*/
depthWrite: boolean = true
/**
* User-defined clipping planes specified as THREE.Plane objects in world
* space. These planes apply to the objects this material is attached to.
* Points in space whose signed distance to the plane is negative are
* clipped (not rendered). See the WebGL / clipping / intersection example.
* Default is null.
*/
clippingPlanes: Plane[] | null = null
/**
* Changes the behavior of clipping planes so that only their intersection
* is clipped, rather than their union. Default is false.
*/
clipIntersection: boolean = false
/**
* Defines whether to clip shadows according to the clipping planes
* specified on this material. Default is false.
*/
clipShadows: boolean = false
/** TODO: describe shadowSide. */
// TODO code should test for AutoSide instead of null
shadowSide: ShadowSide = ShadowSide.AutoSide
/**
* Whether to render the material's color. This can be used in conjunction
* with a mesh's .renderOrder property to create invisible objects that
* occlude other objects. Default is true.
*/
colorWrite: boolean = true
/**
* Override the renderer's default precision for this material. Can be
* "highp", "mediump" or "lowp". Defaults is null.
*/
// TODO code should check for Precision.default instead of null
precision: Precision = Precision.Default
/**
* Whether to use polygon offset. Default is false. This corresponds to the
* POLYGON_OFFSET_FILL WebGL feature.
*/
polygonOffset: boolean = false
/**
* Sets the polygon offset factor. Default is 0.
*/
polygonOffsetFactor: f32 = 0
/**
* Sets the polygon offset units. Default is 0.
*/
polygonOffsetUnits: f32 = 0
/**
* Whether to apply dithering to the color to remove the appearance of
* banding. Default is false.
*/
dithering: boolean = false
/**
* Sets the alpha value to be used when running an alpha test. Default is 0.
*/
alphaTest: f32 = 0
/**
* Whether to premultiply the alpha (transparency) value. See WebGL /
* Materials / Transparency for an example of the difference. Default is
* false.
*/
premultipliedAlpha: boolean = false
/**
* Defines whether this material is visible. Default is true.
*/
visible: boolean = true
/**
* An object that can be used to store custom data about the Material. It
* should not hold references to functions as these will not be cloned.
*/
// userData: any // No dynamic objects with random type in AS.
/**
* Specifies that the material needs to be updated, WebGL wise. Set it to true if you made changes that need to be reflected in WebGL.
* This property is automatically set to true when instancing a new material.
*/
needsUpdate: boolean = true
// /**
// * An optional callback that is executed immediately before the shader program is compiled. This function is called with the shader source code as a parameter. Useful for the modification of built-in materials.
// * @param shader Source code of the shader
// * @param renderer WebGLRenderer Context that is initializing the material
// */
// TODO
// onBeforeCompile: (shader: Shader, renderer: WebGLRenderer) => void = () => {}
// /**
// * Sets the properties based on the values.
// * @param values A container with parameters.
// */
// TODO This method is very dynamic JS. Possible to do in AS, perhaps with Maps? For now, just set properties directly.
// setValues(values: MaterialParameters): this {
// if (values === undefined) return this
// for (var key in values) {
// var newValue = values[key]
// if (newValue === undefined) {
// console.warn("THREE.Material: '" + key + "' parameter is undefined.")
// continue
// }
// // for backward compatability if shading is set in the constructor
// if (key === 'shading') {
// console.warn(
// 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.'
// )
// this.flatShading = newValue === FlatShading ? true : false
// continue
// }
// var currentValue = this[key]
// if (currentValue === undefined) {
// console.warn('THREE.' + this.type + ": '" + key + "' is not a property of this material.")
// continue
// }
// if (currentValue && currentValue.isColor) {
// currentValue.set(newValue)
// } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
// currentValue.copy(newValue)
// } else {
// this[key] = newValue
// }
// }
// return this
// }
// /**
// * Convert the material to three.js JSON format.
// * @param meta Object containing metadata such as textures or images for the material.
// */
// TODO too dynamic. How to handle to/fromJSON in AS?
// toJSON(meta?: any): any {
// var isRoot = meta === undefined || typeof meta === 'string'
// if (isRoot) {
// meta = {
// textures: {},
// images: {},
// }
// }
// var data = {
// metadata: {
// version: 4.5,
// type: 'Material',
// generator: 'Material.toJSON',
// },
// }
// // standard Material serialization
// data.uuid = this.uuid
// data.type = this.type
// if (this.name !== '') data.name = this.name
// if (this.color && this.color.isColor) data.color = this.color.getHex()
// if (this.roughness !== undefined) data.roughness = this.roughness
// if (this.metalness !== undefined) data.metalness = this.metalness
// if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex()
// if (this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity
// if (this.specular && this.specular.isColor) data.specular = this.specular.getHex()
// if (this.shininess !== undefined) data.shininess = this.shininess
// if (this.clearCoat !== undefined) data.clearCoat = this.clearCoat
// if (this.clearCoatRoughness !== undefined) data.clearCoatRoughness = this.clearCoatRoughness
// if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid
// if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid
// if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid
// if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid
// if (this.aoMap && this.aoMap.isTexture) {
// data.aoMap = this.aoMap.toJSON(meta).uuid
// data.aoMapIntensity = this.aoMapIntensity
// }
// if (this.bumpMap && this.bumpMap.isTexture) {
// data.bumpMap = this.bumpMap.toJSON(meta).uuid
// data.bumpScale = this.bumpScale
// }
// if (this.normalMap && this.normalMap.isTexture) {
// data.normalMap = this.normalMap.toJSON(meta).uuid
// data.normalMapType = this.normalMapType
// data.normalScale = this.normalScale.toArray()
// }
// if (this.displacementMap && this.displacementMap.isTexture) {
// data.displacementMap = this.displacementMap.toJSON(meta).uuid
// data.displacementScale = this.displacementScale
// data.displacementBias = this.displacementBias
// }
// if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid
// if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid
// if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid
// if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid
// if (this.envMap && this.envMap.isTexture) {
// data.envMap = this.envMap.toJSON(meta).uuid
// data.reflectivity = this.reflectivity // Scale behind envMap
// if (this.combine !== undefined) data.combine = this.combine
// if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity
// }
// if (this.gradientMap && this.gradientMap.isTexture) {
// data.gradientMap = this.gradientMap.toJSON(meta).uuid
// }
// if (this.size !== undefined) data.size = this.size
// if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation
// if (this.blending !== NormalBlending) data.blending = this.blending
// if (this.flatShading === true) data.flatShading = this.flatShading
// if (this.side !== FrontSide) data.side = this.side
// if (this.vertexColors !== NoColors) data.vertexColors = this.vertexColors
// if (this.opacity < 1) data.opacity = this.opacity
// if (this.transparent === true) data.transparent = this.transparent
// data.depthFunc = this.depthFunc
// data.depthTest = this.depthTest
// data.depthWrite = this.depthWrite
// // rotation (SpriteMaterial)
// if (this.rotation !== 0) data.rotation = this.rotation
// if (this.polygonOffset === true) data.polygonOffset = true
// if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor
// if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits
// if (this.linewidth !== 1) data.linewidth = this.linewidth
// if (this.dashSize !== undefined) data.dashSize = this.dashSize
// if (this.gapSize !== undefined) data.gapSize = this.gapSize
// if (this.scale !== undefined) data.scale = this.scale
// if (this.dithering === true) data.dithering = true
// if (this.alphaTest > 0) data.alphaTest = this.alphaTest
// if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha
// if (this.wireframe === true) data.wireframe = this.wireframe
// if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth
// if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap
// if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin
// if (this.morphTargets === true) data.morphTargets = true
// if (this.skinning === true) data.skinning = true
// if (this.visible === false) data.visible = false
// if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData
// // TODO: Copied from Object3D.toJSON
// function extractFromCache(cache) {
// var values = []
// for (var key in cache) {
// var data = cache[key]
// delete data.metadata
// values.push(data)
// }
// return values
// }
// if (isRoot) {
// var textures = extractFromCache(meta.textures)
// var images = extractFromCache(meta.images)
// if (textures.length > 0) data.textures = textures
// if (images.length > 0) data.images = images
// }
// return data
// },
/**
* Return a new material with the same properties as this material.
*/
clone(): Material {
return new Material().copy(this)
}
/**
* Copy the properties from the passed material into this material.
*/
copy(source: Material): this {
this.name = source.name
this.fog = source.fog
this.lights = source.lights
this.blending = source.blending
this.side = source.side
this.flatShading = source.flatShading
this.vertexColors = source.vertexColors
this.opacity = source.opacity
this.transparent = source.transparent
this.blendSrc = source.blendSrc
this.blendDst = source.blendDst
this.blendEquation = source.blendEquation
this.blendSrcAlpha = source.blendSrcAlpha
this.blendDstAlpha = source.blendDstAlpha
this.blendEquationAlpha = source.blendEquationAlpha
this.depthFunc = source.depthFunc
this.depthTest = source.depthTest
this.depthWrite = source.depthWrite
this.colorWrite = source.colorWrite
this.precision = source.precision
this.polygonOffset = source.polygonOffset
this.polygonOffsetFactor = source.polygonOffsetFactor
this.polygonOffsetUnits = source.polygonOffsetUnits
this.dithering = source.dithering
this.alphaTest = source.alphaTest
this.premultipliedAlpha = source.premultipliedAlpha
this.visible = source.visible
// No random dynamic objects in AS.
// this.userData = JSON.parse(JSON.stringify(source.userData))
this.clipShadows = source.clipShadows
this.clipIntersection = source.clipIntersection
const srcPlanes = source.clippingPlanes
let dstPlanes: Plane[] | null = null
if (srcPlanes !== null) {
const n = srcPlanes.length
dstPlanes = new Array(n)
for (let i = 0; i !== n; ++i) dstPlanes[i] = srcPlanes[i].clone()
}
if (dstPlanes !== null) this.clippingPlanes = dstPlanes
this.shadowSide = source.shadowSide
return this
}
private disposeEvent: Event = new Event('dispose')
/**
* This disposes the material. Textures of a material don't get disposed.
* These needs to be disposed by {@link Texture}.
*/
dispose(): void {
this.dispatchEvent(this.disposeEvent)
}
} | the_stack |
import { assert } from 'chai';
import { render } from 'lit-html';
import { renderMarkdown } from '../libs/markdown_utils';
import { BuildStatus } from '../services/buildbucket';
import { StepExt } from './step_ext';
describe('StepExt', () => {
function createStep(index: number, name: string, status = BuildStatus.Success, summaryMarkdown = '') {
const nameSegs = name.split('|');
return new StepExt({
step: {
name,
startTime: '2020-11-01T21:43:03.351951Z',
status,
summaryMarkdown,
},
selfName: nameSegs.pop()!,
depth: nameSegs.length,
index,
});
}
describe('succeededRecursively', () => {
it('succeeded step with no children should return true', async () => {
const step = createStep(0, 'child', BuildStatus.Success);
assert.isTrue(step.succeededRecursively);
});
it('succeeded step with only succeeded children should return true', async () => {
const step = createStep(0, 'child', BuildStatus.Success);
step.children.push(createStep(0, 'parent|child1', BuildStatus.Success));
step.children.push(createStep(1, 'parent|child2', BuildStatus.Success));
assert.isTrue(step.succeededRecursively);
});
it('succeeded step with failed child should return false', async () => {
const step = createStep(0, 'parent', BuildStatus.Success);
step.children.push(createStep(0, 'parent|child1', BuildStatus.Success));
step.children.push(createStep(1, 'parent|child2', BuildStatus.Failure));
assert.isFalse(step.succeededRecursively);
});
it('succeeded step with failed child should return false', async () => {
const step = createStep(0, 'parent', BuildStatus.Success);
step.children.push(createStep(0, 'parent|child1', BuildStatus.Success));
step.children.push(createStep(1, 'parent|child2', BuildStatus.Failure));
assert.isFalse(step.succeededRecursively);
});
it('succeeded step with started child should return false', async () => {
const step = createStep(0, 'parent', BuildStatus.Success);
step.children.push(createStep(0, 'parent|child1', BuildStatus.Success));
step.children.push(createStep(1, 'parent|child2', BuildStatus.Started));
assert.isFalse(step.succeededRecursively);
});
it('succeeded step with scheduled child should return false', async () => {
const step = createStep(0, 'parent', BuildStatus.Success);
step.children.push(createStep(0, 'parent|child1', BuildStatus.Success));
step.children.push(createStep(1, 'parent|child2', BuildStatus.Scheduled));
assert.isFalse(step.succeededRecursively);
});
it('succeeded step with canceled child should return false', async () => {
const step = createStep(0, 'parent', BuildStatus.Success);
step.children.push(createStep(0, 'parent|child1', BuildStatus.Success));
step.children.push(createStep(1, 'parent|child2', BuildStatus.Canceled));
assert.isFalse(step.succeededRecursively);
});
it('failed step with no children should return false', async () => {
const step = createStep(0, 'child', BuildStatus.Failure);
assert.isFalse(step.succeededRecursively);
});
it('failed step with succeeded children should return false', async () => {
const step = createStep(0, 'parent', BuildStatus.Failure);
step.children.push(createStep(0, 'parent|child1', BuildStatus.Success));
step.children.push(createStep(1, 'parent|child2', BuildStatus.Success));
assert.isFalse(step.succeededRecursively);
});
it('failed step with failed children should return false', async () => {
const step = createStep(0, 'parent', BuildStatus.Failure);
step.children.push(createStep(0, 'parent|child1', BuildStatus.Success));
step.children.push(createStep(1, 'parent|child2', BuildStatus.Failure));
assert.isFalse(step.succeededRecursively);
});
});
describe('failed', () => {
it('succeeded step with no children should return false', async () => {
const step = createStep(0, 'child', BuildStatus.Success);
assert.isFalse(step.failed);
});
it('succeeded step with only succeeded children should return false', async () => {
const step = createStep(0, 'child', BuildStatus.Success);
step.children.push(createStep(0, 'parent|child1', BuildStatus.Success));
step.children.push(createStep(1, 'parent|child2', BuildStatus.Success));
assert.isFalse(step.failed);
});
it('succeeded step with failed child should return true', async () => {
const step = createStep(0, 'parent', BuildStatus.Success);
step.children.push(createStep(0, 'parent|child1', BuildStatus.Success));
step.children.push(createStep(1, 'parent|child2', BuildStatus.Failure));
assert.isTrue(step.failed);
});
it('failed step with no children should return true', async () => {
const step = createStep(0, 'child', BuildStatus.Failure);
assert.isTrue(step.failed);
});
it('infra-failed step with no children should return true', async () => {
const step = createStep(0, 'child', BuildStatus.InfraFailure);
assert.isTrue(step.failed);
});
it('canceled step with no children should return false', async () => {
const step = createStep(0, 'child', BuildStatus.Canceled);
assert.isFalse(step.failed);
});
it('scheduled step with no children should return false', async () => {
const step = createStep(0, 'child', BuildStatus.Scheduled);
assert.isFalse(step.failed);
});
it('started step with no children should return false', async () => {
const step = createStep(0, 'child', BuildStatus.Started);
assert.isFalse(step.failed);
});
it('failed step with succeeded children should return true', async () => {
const step = createStep(0, 'parent', BuildStatus.Failure);
step.children.push(createStep(0, 'parent|child1', BuildStatus.Success));
step.children.push(createStep(1, 'parent|child2', BuildStatus.Success));
assert.isTrue(step.failed);
});
it('failed step with failed children should return true', async () => {
const step = createStep(0, 'parent', BuildStatus.Failure);
step.children.push(createStep(0, 'parent|child1', BuildStatus.Success));
step.children.push(createStep(1, 'parent|child2', BuildStatus.Failure));
assert.isTrue(step.failed);
});
});
describe('summary header and content should be split properly', () => {
function getExpectedHeaderHTML(markdownBody: string): string {
const container = document.createElement('div');
// Wrap in a <p> and remove it later so <!----> are not injected.
render(renderMarkdown(`<p>${markdownBody}</p>`), container);
return container.firstElementChild!.innerHTML;
}
function getExpectedBodyHTML(markdownBody: string): string {
const container = document.createElement('div');
render(renderMarkdown(markdownBody), container);
return container.innerHTML;
}
it('for no summary', async () => {
const step = createStep(0, 'step', BuildStatus.Success, undefined);
assert.strictEqual(step.header, null);
assert.strictEqual(step.summary, null);
});
it('for empty summary', async () => {
const step = createStep(0, 'step', BuildStatus.Success, '');
assert.strictEqual(step.header, null);
assert.strictEqual(step.summary, null);
});
it('for text summary', async () => {
const step = createStep(0, 'step', BuildStatus.Success, 'this is some text');
assert.strictEqual(step.header?.innerHTML, 'this is some text');
assert.strictEqual(step.summary, null);
});
it('for header and content separated by <br/>', async () => {
const step = createStep(0, 'step', BuildStatus.Success, 'header<br/>content');
assert.strictEqual(step.header?.innerHTML, getExpectedHeaderHTML('header'));
assert.strictEqual(step.summary?.innerHTML, getExpectedBodyHTML('content'));
});
it('for header and content separated by <br/>, header is empty', async () => {
const step = createStep(0, 'step', BuildStatus.Success, '<br/>body');
assert.strictEqual(step.header, null);
assert.strictEqual(step.summary?.innerHTML, getExpectedBodyHTML('body'));
});
it('for header and content separated by <br/>, body is empty', async () => {
const step = createStep(0, 'step', BuildStatus.Success, 'header<br/>');
assert.strictEqual(step.header?.innerHTML, getExpectedHeaderHTML('header'));
assert.strictEqual(step.summary, null);
});
it('for header and content separated by <br/>, header is a link', async () => {
const step = createStep(0, 'step', BuildStatus.Success, '<a href="http://google.com">Link</a><br/>content');
assert.strictEqual(step.header?.innerHTML, getExpectedHeaderHTML('<a href="http://google.com">Link</a>'));
assert.strictEqual(step.summary?.innerHTML, getExpectedBodyHTML('content'));
});
it('for header and content separated by <br/>, header has some inline elements', async () => {
const step = createStep(
0,
'step',
BuildStatus.Success,
'<span>span</span><i>i</i><b>b</b><strong>strong</strong><br/>content'
);
assert.strictEqual(
step.header?.innerHTML,
getExpectedHeaderHTML('<span>span</span><i>i</i><b>b</b><strong>strong</strong>')
);
assert.strictEqual(step.summary?.innerHTML, getExpectedBodyHTML('content'));
});
it('for header and content separated by <br/>, header is a list', async () => {
const step = createStep(0, 'step', BuildStatus.Success, '<ul><li>item</li></ul><br/>content');
assert.strictEqual(step.header, null);
assert.strictEqual(step.summary?.innerHTML, getExpectedBodyHTML('<ul><li>item</li></ul><br/>content'));
});
it('for header is a list', async () => {
const step = createStep(0, 'step', BuildStatus.Success, '<ul><li>item1</li><li>item2</li></ul>');
assert.strictEqual(step.header, null);
assert.strictEqual(step.summary?.innerHTML, getExpectedBodyHTML('<ul><li>item1</li><li>item2</li></ul>'));
});
it('for <br/> is contained in <div>', async () => {
const step = createStep(0, 'step', BuildStatus.Success, '<div>header<br/>other</div>content');
assert.strictEqual(step.header?.innerHTML, getExpectedHeaderHTML('header'));
assert.strictEqual(step.summary?.innerHTML, getExpectedBodyHTML('<div>other</div>content'));
});
it('for <br/> is contained in some nested tags', async () => {
const step = createStep(0, 'step', BuildStatus.Success, '<div><div>header<br/>other</div></div>content');
assert.strictEqual(step.header, null);
assert.strictEqual(step.summary?.innerHTML, getExpectedBodyHTML('<div><div>header<br/>other</div></div>content'));
});
});
}); | the_stack |
import {
CallExpression,
FunctionDeclaration,
Node,
NodePath,
Printable,
StringLiteral,
TypeName,
} from 'ast-types';
import { JsCodeShift } from 'jscodeshift';
import astService, { AstRoot, LanguageId, Selection } from './astService';
interface UnordedSelection {
start: number;
end: number;
}
function fromSelection(selection: Selection) {
let start;
let end;
if (selection.anchor > selection.active) {
start = selection.active;
end = selection.anchor;
} else {
start = selection.anchor;
end = selection.active;
}
return {
start,
end,
};
}
function toSelection(result: { start: number; end: number }, previousSelection: Selection) {
if (previousSelection.anchor > previousSelection.active) {
return {
anchor: result.end,
active: result.start,
};
} else {
return {
anchor: result.start,
active: result.end,
};
}
}
function wrapBrackets(
source: string,
start: number,
end: number,
brackets: string
): UnordedSelection {
while (start > 0 && source[start] !== brackets[0]) {
start--;
}
while (end < source.length && source[end - 1] !== brackets[1]) {
end++;
}
return {
start,
end,
};
}
function equalSelections(selA: Selection, selB: Selection) {
return selA.active === selB.active && selA.anchor === selB.anchor;
}
class SmartSelectionService {
private _selectionCache: Map<
string,
{
source: string;
selectionStack: Selection[][];
}
> = new Map();
public extendSelection({
languageId,
source,
fileName,
ast,
selections,
}: {
languageId: LanguageId;
source: string;
fileName: string;
ast: AstRoot;
selections: Selection[];
}): Selection[] {
const j = astService.getCodeShift(languageId);
let changed = false;
const newSelections = selections.map((sel) => {
const result = this._extendOneSelection(j, source, ast, sel);
if (!result) {
return sel;
} else {
changed = true;
return toSelection(result, sel);
}
});
if (!changed) {
return selections;
}
return this._pushSelections(fileName, source, newSelections, selections);
}
public shrinkSelection({
languageId,
fileName,
source,
ast,
selections,
}: {
languageId: LanguageId;
fileName: string;
source: string;
ast: AstRoot;
selections: Selection[];
}): Selection[] {
const jscodeshift = astService.getCodeShift(languageId);
return this._popSelections(fileName, source, selections);
}
private _extendOneSelection(
j: JsCodeShift,
source: string,
ast: AstRoot,
selection: Selection
): UnordedSelection | null {
const target = ast.findNodeInRange(selection.anchor, selection.active);
if (target.length === 0) {
return null;
}
const { start, end } = fromSelection(selection);
let result = {
start,
end,
};
let targetNode = target.firstNode<Node>()!;
let targetPath = target.firstPath<Node>()!;
// If a node is covered completely, switch to its parent as the target node
while (start === targetNode.start && end === targetNode.end) {
if (!targetPath.parentPath) {
// root object achieved -> no change
return null;
}
if (
Array.isArray(targetPath.parentPath.value) &&
targetPath.parentPath.value.length > 1
) {
// extend to siblings -> return result
const siblings = targetPath.parentPath.value as Node[];
result.start = siblings[0].start;
result.end = siblings[siblings.length - 1].end;
return result;
}
// switch node to parent -> proceed as planned
targetPath = targetPath.parent as NodePath<Node>;
targetNode = targetPath.node;
}
if (!j.Node.check(targetNode)) {
return null;
}
switch (targetNode.type as TypeName) {
case 'StringLiteral':
result = this._extendStringLiteral(targetNode as StringLiteral, start, end);
break;
case 'BlockStatement':
case 'ArrayExpression':
case 'ObjectExpression':
case 'ClassBody':
case 'TSTypeLiteral':
case 'TSInterfaceBody':
result = this._extendBracketNode(targetNode, start, end);
break;
case 'FunctionDeclaration':
result = this._extendFunctionDeclaration(
targetNode as FunctionDeclaration,
start,
end,
source
);
break;
case 'CallExpression':
result = this._extendCallExpression(
targetNode as CallExpression,
start,
end,
source
);
break;
default:
result.start = targetNode.start;
result.end = targetNode.end;
break;
}
return result;
}
private _extendCallExpression(
targetNode: CallExpression,
start: number,
end: number,
source: string
): UnordedSelection {
if (
targetNode.arguments.length > 0 &&
targetNode.arguments[0].start === start &&
targetNode.arguments[targetNode.arguments.length - 1].end === end
) {
// bar( |var1, var2| ) => bar|( var1, var2 )|
return wrapBrackets(source, start, end, '()');
} else {
// ba|r|(var1, var2) => |bar(var1, var2)|
start = targetNode.start;
end = targetNode.end;
}
return { start, end };
}
private _extendFunctionDeclaration(
targetNode: FunctionDeclaration,
start: number,
end: number,
source: string
): UnordedSelection {
if (
targetNode.params.length > 0 &&
targetNode.params[0].start === start &&
targetNode.params[targetNode.params.length - 1].end === end
) {
// function bar( |var1, var2| ) {} => bar|( var1, var2 )| {}
return wrapBrackets(source, start, end, '()');
} else {
// function ba|r|(var1, var2) {} => |function bar(var1, var2) {}|
start = targetNode.start;
end = targetNode.end;
}
return { start, end };
}
private _extendBracketNode(targetNode: Node, start: number, end: number): UnordedSelection {
if (targetNode.start === start || targetNode.end === end) {
// { expres|sions }| => |{ expressions }|
start = targetNode.start;
end = targetNode.end;
} else if (targetNode.start + 1 === start && targetNode.end - 1 === end) {
// {| expressions |} => |{ expressions }|
start = targetNode.start;
end = targetNode.end;
} else {
// { ex|press|ions } => {| expressions |}
start = targetNode.start + 1;
end = targetNode.end - 1;
}
return { start, end };
}
private _extendStringLiteral(
targetNode: StringLiteral,
start: number,
end: number
): UnordedSelection {
if (targetNode.start === start || targetNode.end === end) {
// 'cont|ent'| => |'content'|
start = targetNode.start;
end = targetNode.end;
} else if (targetNode.start + 1 === start && targetNode.end - 1 === end) {
// '|content|' => |'content'|
start = targetNode.start;
end = targetNode.end;
} else {
const value = targetNode.value;
let startIndex = start - targetNode.start - 1;
let endIndex = end - targetNode.start - 1;
let expanded = false;
while (startIndex > 0 && /[a-zA-Z0-9$_]/.test(value[startIndex - 1])) {
startIndex--;
expanded = true;
}
while (endIndex < value.length && /[a-zA-Z0-9$_]/.test(value[endIndex])) {
endIndex++;
expanded = true;
}
if (expanded) {
// 'content is a se|nt|ence' => 'content is a |sentence|'
start = startIndex + targetNode.start + 1;
end = endIndex + targetNode.start + 1;
} else {
// 'content is a |sentence|' => '|content is a sentence|'
start = targetNode.start + 1;
end = targetNode.end - 1;
}
}
return { start, end };
}
private _pushSelections(
fileName: string,
source: string,
newSelections: Selection[],
activeSelections: Selection[]
): Selection[] {
let cache = this._selectionCache.get(fileName);
let invalidCache = !cache;
if (cache) {
// 1. Active selection found in stack => great.
// 2. New active selection? Start from scratch.
// 3. Cache has active selections which are now gone? Remove them.
const storedActiveSelections = cache.selectionStack[cache.selectionStack.length - 1];
const allSelectionsPresentInCache = activeSelections.every((sel) => {
return storedActiveSelections.some((val) => equalSelections(sel, val));
});
const cacheHasRemovedSelections = storedActiveSelections.some((sel) => {
return !activeSelections.some((val) => equalSelections(sel, val));
});
invalidCache = !allSelectionsPresentInCache || cacheHasRemovedSelections;
}
if (invalidCache) {
// Invalid cache, start from scratch
cache = {
source,
selectionStack: [activeSelections],
};
this._selectionCache.set(fileName, cache);
}
cache!.selectionStack.push(newSelections);
return newSelections;
}
private _popSelections(
fileName: string,
source: string,
activeSelections: Selection[]
): Selection[] {
function collapseSelection(sel: Selection) {
return {
active: sel.active,
anchor: sel.active,
};
}
const cache = this._selectionCache.get(fileName);
if (!cache || cache.selectionStack.length < 2) {
// We must have at least two history items: active selections and one before
this._selectionCache.delete(fileName);
return activeSelections.map(collapseSelection);
}
// 1. Selection exists in cache => return its previous state
// 2. Can't find selection => collapse active selection
const storedActiveSelections = cache.selectionStack.pop()!;
const storedPrevSelections = cache.selectionStack[cache.selectionStack.length - 1];
const newSelections = activeSelections.map((sel) => {
const index = storedActiveSelections.findIndex((val) => equalSelections(sel, val));
if (index !== -1) {
return storedPrevSelections[index];
} else {
return collapseSelection(sel);
}
});
return newSelections;
}
}
export default new SmartSelectionService(); | the_stack |
import {ProtractorBrowser} from './browser';
import {Config} from './config';
import {ConfigParser} from './configParser';
import {Logger} from './logger';
let logger = new Logger('plugins');
export interface PluginConfig {
path?: string;
package?: string;
inline?: ProtractorPlugin;
name?: string;
[key: string]: any;
}
export interface ProtractorPlugin {
/**
* Sets up plugins before tests are run. This is called after the WebDriver
* session has been started, but before the test framework has been set up.
*
* @this {Object} bound to module.exports.
*
* @throws {*} If this function throws an error, a failed assertion is added to
* the test results.
*
* @return {Promise=} Can return a promise, in which case protractor will wait
* for the promise to resolve before continuing. If the promise is
* rejected, a failed assertion is added to the test results.
*/
setup?(): void|Promise<void>;
/**
* This is called before the test have been run but after the test framework has
* been set up. Analogous to a config file's `onPrepare`.
*
* Very similar to using `setup`, but allows you to access framework-specific
* variables/functions (e.g. `jasmine.getEnv().addReporter()`).
*
* @this {Object} bound to module.exports.
*
* @throws {*} If this function throws an error, a failed assertion is added to
* the test results.
*
* @return {Promise=} Can return a promise, in which case protractor will wait
* for the promise to resolve before continuing. If the promise is
* rejected, a failed assertion is added to the test results.
*/
onPrepare?(): void|Promise<void>;
/**
* This is called after the tests have been run, but before the WebDriver
* session has been terminated.
*
* @this {Object} bound to module.exports.
*
* @throws {*} If this function throws an error, a failed assertion is added to
* the test results.
*
* @return {Promise=} Can return a promise, in which case protractor will wait
* for the promise to resolve before continuing. If the promise is
* rejected, a failed assertion is added to the test results.
*/
teardown?(): void|Promise<void>;
/**
* Called after the test results have been finalized and any jobs have been
* updated (if applicable).
*
* @this {Object} bound to module.exports.
*
* @throws {*} If this function throws an error, it is outputted to the console.
* It is too late to add a failed assertion to the test results.
*
* @return {Promise=} Can return a promise, in which case protractor will wait
* for the promise to resolve before continuing. If the promise is
* rejected, an error is logged to the console.
*/
postResults?(): void|Promise<void>;
/**
* Called after each test block (in Jasmine, this means an `it` block)
* completes.
*
* @param {boolean} passed True if the test passed.
* @param {Object} testInfo information about the test which just ran.
*
* @this {Object} bound to module.exports.
*
* @throws {*} If this function throws an error, a failed assertion is added to
* the test results.
*
* @return {Promise=} Can return a promise, in which case protractor will wait
* for the promise to resolve before outputting test results. Protractor
* will *not* wait before executing the next test; however, if the promise
* is rejected, a failed assertion is added to the test results.
*/
postTest?(passed: boolean, testInfo: any): void|Promise<void>;
/**
* This is called inside browser.get() directly after the page loads, and before
* angular bootstraps.
*
* @param {ProtractorBrowser} browser The browser instance which is loading a page.
*
* @this {Object} bound to module.exports.
*
* @throws {*} If this function throws an error, a failed assertion is added to
* the test results.
*
* @return {Promise=} Can return a promise, in which case
* protractor will wait for the promise to resolve before continuing. If
* the promise is rejected, a failed assertion is added to the test results.
*/
onPageLoad?(browser: ProtractorBrowser): void|Promise<void>;
/**
* This is called inside browser.get() directly after angular is done
* bootstrapping/synchronizing. If `await browser.waitForAngularEnabled()`
* is `false`, this will not be called.
*
* @param {ProtractorBrowser} browser The browser instance which is loading a page.
*
* @this {Object} bound to module.exports.
*
* @throws {*} If this function throws an error, a failed assertion is added to
* the test results.
*
* @return {Promise=} Can return a promise, in which case
* protractor will wait for the promise to resolve before continuing. If
* the promise is rejected, a failed assertion is added to the test results.
*/
onPageStable?(browser: ProtractorBrowser): void|Promise<void>;
/**
* Between every webdriver action, Protractor calls browser.waitForAngular() to
* make sure that Angular has no outstanding $http or $timeout calls.
* You can use waitForPromise() to have Protractor additionally wait for your
* custom promise to be resolved inside of browser.waitForAngular().
*
* @param {ProtractorBrowser} browser The browser instance which needs invoked `waitForAngular`.
*
* @this {Object} bound to module.exports.
*
* @throws {*} If this function throws an error, a failed assertion is added to
* the test results.
*
* @return {Promise=} Can return a promise, in which case
* protractor will wait for the promise to resolve before continuing. If the
* promise is rejected, a failed assertion is added to the test results, and
* protractor will continue onto the next command. If nothing is returned or
* something other than a promise is returned, protractor will continue
* onto the next command.
*/
waitForPromise?(browser: ProtractorBrowser): Promise<void>;
/**
* Between every webdriver action, Protractor calls browser.waitForAngular() to
* make sure that Angular has no outstanding $http or $timeout calls.
* You can use waitForCondition() to have Protractor additionally wait for your
* custom condition to be truthy. If specified, this function will be called
* repeatedly until truthy.
*
* @param {ProtractorBrowser} browser The browser instance which needs invoked `waitForAngular`.
*
* @this {Object} bound to module.exports.
*
* @throws {*} If this function throws an error, a failed assertion is added to
* the test results.
*
* @return {Promise<boolean>|boolean} If truthy, Protractor
* will continue onto the next command. If falsy, webdriver will
* continuously re-run this function until it is truthy. If a rejected promise
* is returned, a failed assertion is added to the test results, and Protractor
* will continue onto the next command.
*/
waitForCondition?(browser: ProtractorBrowser): Promise<boolean>|boolean;
/**
* Used to turn off default checks for angular stability
*
* Normally Protractor waits for all $timeout and $http calls to be processed
* before executing the next command. This can be disabled using
* browser.ignoreSynchronization, but that will also disable any
* <Plugin>.waitForPromise or <Plugin>.waitForCondition checks. If you want
* to disable synchronization with angular, but leave intact any custom plugin
* synchronization, this is the option for you.
*
* This is used by plugin authors who want to replace Protractor's
* synchronization code with their own.
*
* @type {boolean}
*/
skipAngularStability?: boolean;
/**
* The name of the plugin. Used when reporting results.
*
* If you do not specify this property, it will be filled in with something
* reasonable (e.g. the plugin's path) by Protractor at runtime.
*
* @type {string}
*/
name?: string;
/**
* The plugin's configuration object.
*
* Note: this property is added by Protractor at runtime. Any pre-existing
* value will be overwritten.
*
* Note: that this is not the entire Protractor config object, just the entry
* in the `plugins` array for this plugin.
*
* @type {Object}
*/
config?: PluginConfig;
/**
* Adds a failed assertion to the test's results.
*
* Note: this property is added by Protractor at runtime. Any pre-existing
* value will be overwritten.
*
* @param {string} message The error message for the failed assertion
* @param {specName: string, stackTrace: string} options Some optional extra
* information about the assertion:
* - specName The name of the spec which this assertion belongs to.
* Defaults to `PLUGIN_NAME + ' Plugin Tests'`.
* - stackTrace The stack trace for the failure. Defaults to undefined.
* Defaults to `{}`.
*
* @throws {Error} Throws an error if called after results have been reported
*/
addFailure?(message?: string, info?: {specName?: string, stackTrace?: string}): void;
/**
* Adds a passed assertion to the test's results.
*
* Note: this property is added by Protractor at runtime. Any pre-existing
* value will be overwritten.
*
* @param {specName: string} options Extra information about the assertion:
* - specName The name of the spec which this assertion belongs to.
* Defaults to `PLUGIN_NAME + ' Plugin Tests'`.
* Defaults to `{}`.
*
* @throws {Error} Throws an error if called after results have been reported
*/
addSuccess?(info?: {specName?: string}): void;
/**
* Warns the user that something is problematic.
*
* Note: this property is added by Protractor at runtime. Any pre-existing
* value will be overwritten.
*
* @param {string} message The message to warn the user about
* @param {specName: string} options Extra information about the assertion:
* - specName The name of the spec which this assertion belongs to.
* Defaults to `PLUGIN_NAME + ' Plugin Tests'`.
* Defaults to `{}`.
*/
addWarning?(message?: string, info?: {specName?: string}): void;
}
/**
* The plugin API for Protractor. Note that this API is unstable. See
* plugins/README.md for more information.
*
* @constructor
* @param {Object} config parsed from the config file
*/
export class Plugins {
pluginObjs: ProtractorPlugin[];
assertions: {[key: string]: AssertionResult[]};
resultsReported: boolean;
constructor(config: Config) {
this.pluginObjs = [];
this.assertions = {};
this.resultsReported = false;
if (config.plugins) {
config.plugins.forEach((pluginConf, i) => {
let path: string;
if (pluginConf.path) {
path = ConfigParser.resolveFilePatterns(pluginConf.path, true, config.configDir)[0];
if (!path) {
throw new Error('Invalid path to plugin: ' + pluginConf.path);
}
} else {
path = pluginConf.package;
}
let pluginObj: ProtractorPlugin;
if (path) {
pluginObj = require(path) as ProtractorPlugin;
} else if (pluginConf.inline) {
pluginObj = pluginConf.inline;
} else {
throw new Error(
'Plugin configuration did not contain a valid path or ' +
'inline definition.');
}
this.annotatePluginObj(pluginObj, pluginConf, i);
logger.debug('Plugin "' + pluginObj.name + '" loaded.');
this.pluginObjs.push(pluginObj);
});
}
}
/**
* Adds properties to a plugin's object
*
* @see docs/plugins.md#provided-properties-and-functions
*/
private annotatePluginObj(obj: ProtractorPlugin, conf: PluginConfig, i: number): void {
let addAssertion =
(info: {specName?: string, stackTrace?: string}, passed: boolean, message?: string) => {
if (this.resultsReported) {
throw new Error(
'Cannot add new tests results, since they were already ' +
'reported.');
}
info = info || {};
const specName = info.specName || (obj.name + ' Plugin Tests');
const assertion: AssertionResult = {passed: passed};
if (!passed) {
assertion.errorMsg = message;
if (info.stackTrace) {
assertion.stackTrace = info.stackTrace;
}
}
this.assertions[specName] = this.assertions[specName] || [];
this.assertions[specName].push(assertion);
};
obj.name = obj.name || conf.name || conf.path || conf.package || ('Plugin #' + i);
obj.config = conf;
obj.addFailure = (message?, info?) => {
addAssertion(info, false, message);
};
obj.addSuccess = (options?) => {
addAssertion(options, true);
};
obj.addWarning = (message?, options?) => {
options = options || {};
logger.warn(
'Warning ' +
(options.specName ? 'in ' + options.specName : 'from "' + obj.name + '" plugin') + ': ' +
message);
};
}
private printPluginResults(specResults: SpecResult[]) {
const green = '\x1b[32m';
const red = '\x1b[31m';
const normalColor = '\x1b[39m';
const printResult = (message: string, pass: boolean) => {
logger.info(pass ? green : red, '\t', pass ? 'Pass: ' : 'Fail: ', message, normalColor);
};
for (const specResult of specResults) {
const passed = specResult.assertions.map(x => x.passed).reduce((x, y) => (x && y), true);
printResult(specResult.description, passed);
if (!passed) {
for (const assertion of specResult.assertions) {
if (!assertion.passed) {
logger.error('\t\t' + assertion.errorMsg);
if (assertion.stackTrace) {
logger.error('\t\t' + assertion.stackTrace.replace(/\n/g, '\n\t\t'));
}
}
}
}
}
}
/**
* Gets the tests results generated by any plugins
*
* @see lib/frameworks/README.md#requirements for a complete description of what
* the results object must look like
*
* @return {Object} The results object
*/
getResults() {
const results = {failedCount: 0, specResults: [] as SpecResult[]};
for (const specName in this.assertions) {
results.specResults.push({description: specName, assertions: this.assertions[specName]});
results.failedCount +=
this.assertions[specName].filter(assertion => !assertion.passed).length;
}
this.printPluginResults(results.specResults);
this.resultsReported = true;
return results;
}
/**
* Returns true if any loaded plugin has skipAngularStability enabled.
*
* @return {boolean}
*/
skipAngularStability() {
const result = this.pluginObjs.some(pluginObj => pluginObj.skipAngularStability);
return result;
}
/**
* @see docs/plugins.md#writing-plugins for information on these functions
*/
setup = this.pluginFunFactory('setup');
onPrepare = this.pluginFunFactory('onPrepare');
teardown = this.pluginFunFactory('teardown');
postResults = this.pluginFunFactory('postResults');
postTest = this.pluginFunFactory('postTest');
onPageLoad = this.pluginFunFactory('onPageLoad');
onPageStable = this.pluginFunFactory('onPageStable');
waitForPromise = this.pluginFunFactory('waitForPromise');
waitForCondition = this.pluginFunFactory('waitForCondition', true);
/**
* Calls a function from a plugin safely. If the plugin's function throws an
* exception or returns a rejected promise, that failure will be logged as a
* failed test result instead of crashing protractor. If the tests results have
* already been reported, the failure will be logged to the console.
*
* @param {Object} pluginObj The plugin object containing the function to be run
* @param {string} funName The name of the function we want to run
* @param {*[]} args The arguments we want to invoke the function with
* @param {boolean} resultsReported If the results have already been reported
* @param {*} failReturnVal The value to return if the function fails
*
* @return {Promise} A promise which resolves to the
* function's return value
*/
private safeCallPluginFun(
pluginObj: ProtractorPlugin, funName: string, args: any[], failReturnVal: any): Promise<any> {
const resolver = async (done: (result: any) => void) => {
const logError = (e: any) => {
if (this.resultsReported) {
this.printPluginResults([{
description: pluginObj.name + ' Runtime',
assertions: [{
passed: false,
errorMsg: 'Failure during ' + funName + ': ' + (e.message || e),
stackTrace: e.stack
}]
}]);
} else {
pluginObj.addFailure(
'Failure during ' + funName + ': ' + e.message || e, {stackTrace: e.stack});
}
done(failReturnVal);
};
try {
const result = await(pluginObj as any)[funName].apply(pluginObj, args);
done(result);
} catch (e) {
logError(e);
}
};
return new Promise(resolver);
}
/**
* Generates the handler for a plugin function (e.g. the setup() function)
*
* @param {string} funName The name of the function to make a handler for
* @param {boolean=} failReturnVal The value that the function should return if the plugin crashes
*
* @return The handler
*/
private pluginFunFactory(funName: string, failReturnVal?: boolean):
(...args: any[]) => Promise<any[]>;
private pluginFunFactory(funName: string, failReturnVal?: boolean):
(...args: any[]) => Promise<any[]>;
private pluginFunFactory(funName: string, failReturnVal?: boolean) {
return (...args: any[]) => {
const promises =
this.pluginObjs.filter(pluginObj => typeof(pluginObj as any)[funName] === 'function')
.map(pluginObj => this.safeCallPluginFun(pluginObj, funName, args, failReturnVal));
return Promise.all(promises);
};
}
}
export interface SpecResult {
description: string;
assertions: AssertionResult[];
}
export interface AssertionResult {
passed: boolean;
errorMsg?: string;
stackTrace?: string;
} | the_stack |
import { Plugin } from '../../../core/plugin'
import { Analytics } from '../../../analytics'
import { Context } from '../../../core/context'
import { schemaFilter } from '..'
import { LegacySettings } from '../../../browser'
import { segmentio, SegmentioSettings } from '../../segmentio'
const settings: LegacySettings = {
integrations: {
'Braze Web Mode (Actions)': {},
// note that Fullstory's name here doesn't contain 'Actions'
Fullstory: {},
'Segment.io': {},
},
remotePlugins: [
{
name: 'Braze Web Mode (Actions)',
libraryName: 'brazeDestination',
url:
'https://cdn.segment.com/next-integrations/actions/braze/9850d2cc8308a89db62a.js',
settings: {
subscriptions: [
{
partnerAction: 'trackEvent',
},
{
partnerAction: 'updateUserProfile',
},
{
partnerAction: 'trackPurchase',
},
],
},
},
{
// note that Fullstory name contains 'Actions'
name: 'Fullstory (Actions)',
libraryName: 'fullstoryDestination',
url:
'https://cdn.segment.com/next-integrations/actions/fullstory/35ea1d304f85f3306f48.js',
settings: {
subscriptions: [
{
partnerAction: 'trackEvent',
},
{
partnerAction: 'identifyUser',
},
],
},
},
],
}
const trackEvent: Plugin = {
name: 'Braze Web Mode (Actions) trackEvent',
type: 'destination',
version: '1.0',
load(_ctx: Context): Promise<void> {
return Promise.resolve()
},
isLoaded(): boolean {
return true
},
track: async (ctx) => ctx,
identify: async (ctx) => ctx,
page: async (ctx) => ctx,
group: async (ctx) => ctx,
alias: async (ctx) => ctx,
}
const trackPurchase: Plugin = {
...trackEvent,
name: 'Braze Web Mode (Actions) trackPurchase',
}
const updateUserProfile: Plugin = {
...trackEvent,
name: 'Braze Web Mode (Actions) updateUserProfile',
}
const amplitude: Plugin = {
...trackEvent,
name: 'amplitude',
}
const fullstory: Plugin = {
...trackEvent,
name: 'Fullstory (Actions) trackEvent',
}
describe('schema filter', () => {
let options: SegmentioSettings
let filterXt: Plugin
let segment: Plugin
let ajs: Analytics
beforeEach(async () => {
jest.resetAllMocks()
jest.restoreAllMocks()
options = { apiKey: 'foo' }
ajs = new Analytics({ writeKey: options.apiKey })
segment = segmentio(ajs, options, {})
filterXt = schemaFilter({}, settings)
jest.spyOn(segment, 'track')
jest.spyOn(trackEvent, 'track')
jest.spyOn(trackPurchase, 'track')
jest.spyOn(updateUserProfile, 'track')
jest.spyOn(amplitude, 'track')
jest.spyOn(fullstory, 'track')
})
describe('plugins and destinations', () => {
it('loads plugin', async () => {
await ajs.register(filterXt)
expect(filterXt.isLoaded()).toBe(true)
})
it('does not drop events when no plan is defined', async () => {
await ajs.register(
segment,
trackEvent,
trackPurchase,
updateUserProfile,
schemaFilter({}, settings)
)
await ajs.track('A Track Event')
expect(segment.track).toHaveBeenCalled()
expect(trackEvent.track).toHaveBeenCalled()
expect(trackPurchase.track).toHaveBeenCalled()
expect(updateUserProfile.track).toHaveBeenCalled()
})
it('drops an event when the event is disabled', async () => {
await ajs.register(
segment,
trackEvent,
trackPurchase,
updateUserProfile,
amplitude,
schemaFilter(
{
hi: {
enabled: true,
integrations: {
'Braze Web Mode (Actions)': false,
},
},
},
settings
)
)
await ajs.track('hi')
expect(segment.track).toHaveBeenCalled()
expect(amplitude.track).toHaveBeenCalled()
expect(trackEvent.track).not.toHaveBeenCalled()
expect(trackPurchase.track).not.toHaveBeenCalled()
expect(updateUserProfile.track).not.toHaveBeenCalled()
})
it('does not drop events with different names', async () => {
await ajs.register(
segment,
trackEvent,
trackPurchase,
updateUserProfile,
amplitude,
schemaFilter(
{
'Fake Track Event': {
enabled: true,
integrations: { amplitude: false },
},
},
settings
)
)
await ajs.track('Track Event')
expect(segment.track).toHaveBeenCalled()
expect(amplitude.track).toHaveBeenCalled()
expect(trackEvent.track).toHaveBeenCalled()
expect(trackPurchase.track).toHaveBeenCalled()
expect(updateUserProfile.track).toHaveBeenCalled()
})
it('drops enabled event for matching destination', async () => {
await ajs.register(
segment,
trackEvent,
trackPurchase,
updateUserProfile,
amplitude,
schemaFilter(
{
'Track Event': {
enabled: true,
integrations: { amplitude: false },
},
},
settings
)
)
await ajs.track('Track Event')
expect(segment.track).toHaveBeenCalled()
expect(trackEvent.track).toHaveBeenCalled()
expect(trackPurchase.track).toHaveBeenCalled()
expect(updateUserProfile.track).toHaveBeenCalled()
expect(amplitude.track).not.toHaveBeenCalled()
})
it('does not drop event for non-matching destination', async () => {
const filterXt = schemaFilter(
{
'Track Event': {
enabled: true,
integrations: { 'not amplitude': false },
},
},
settings
)
await ajs.register(
segment,
trackEvent,
trackPurchase,
updateUserProfile,
amplitude,
filterXt
)
await ajs.track('Track Event')
expect(segment.track).toHaveBeenCalled()
expect(trackEvent.track).toHaveBeenCalled()
expect(trackPurchase.track).toHaveBeenCalled()
expect(updateUserProfile.track).toHaveBeenCalled()
expect(amplitude.track).toHaveBeenCalled()
})
it('does not drop enabled event with enabled destination', async () => {
const filterXt = schemaFilter(
{
'Track Event': {
enabled: true,
integrations: { amplitude: true },
},
},
settings
)
await ajs.register(
segment,
trackEvent,
trackPurchase,
updateUserProfile,
amplitude,
filterXt
)
await ajs.track('Track Event')
expect(segment.track).toHaveBeenCalled()
expect(trackEvent.track).toHaveBeenCalled()
expect(trackPurchase.track).toHaveBeenCalled()
expect(updateUserProfile.track).toHaveBeenCalled()
expect(amplitude.track).toHaveBeenCalled()
})
it('properly sets event integrations object with enabled plan', async () => {
const filterXt = schemaFilter(
{
'Track Event': {
enabled: true,
integrations: { amplitude: true },
},
},
settings
)
await ajs.register(
segment,
trackEvent,
trackPurchase,
updateUserProfile,
amplitude,
filterXt
)
const ctx = await ajs.track('Track Event')
expect(ctx.event.integrations).toEqual({ amplitude: true })
expect(segment.track).toHaveBeenCalled()
})
it('sets event integrations object when integration is disabled', async () => {
const filterXt = schemaFilter(
{
'Track Event': {
enabled: true,
integrations: { amplitude: false },
},
},
settings
)
await ajs.register(
segment,
trackEvent,
trackPurchase,
updateUserProfile,
amplitude,
filterXt
)
const ctx = await ajs.track('Track Event')
expect(segment.track).toHaveBeenCalled()
expect(trackEvent.track).toHaveBeenCalled()
expect(trackPurchase.track).toHaveBeenCalled()
expect(updateUserProfile.track).toHaveBeenCalled()
expect(amplitude.track).not.toHaveBeenCalled()
expect(ctx.event.integrations).toEqual({ amplitude: false })
})
it('doesnt set event integrations object with different event', async () => {
const filterXt = schemaFilter(
{
'Track Event': {
enabled: true,
integrations: { amplitude: true },
},
},
settings
)
await ajs.register(
segment,
trackEvent,
trackPurchase,
updateUserProfile,
amplitude,
filterXt
)
const ctx = await ajs.track('Not Track Event')
expect(ctx.event.integrations).toEqual({})
})
})
describe('action destinations', () => {
it('disables action destinations', async () => {
const filterXt = schemaFilter(
{
'Track Event': {
enabled: true,
integrations: {
'Braze Web Mode (Actions)': false,
},
},
__default: {
enabled: true,
integrations: {},
},
hi: {
enabled: true,
integrations: {
'Braze Web Mode (Actions)': false,
},
},
},
settings
)
await ajs.register(
segment,
trackEvent,
trackPurchase,
updateUserProfile,
amplitude,
filterXt
)
await ajs.track('Track Event')
expect(segment.track).toHaveBeenCalled()
expect(amplitude.track).toHaveBeenCalled()
expect(trackEvent.track).not.toHaveBeenCalled()
expect(trackPurchase.track).not.toHaveBeenCalled()
expect(updateUserProfile.track).not.toHaveBeenCalled()
await ajs.track('a non blocked event')
expect(segment.track).toHaveBeenCalled()
expect(amplitude.track).toHaveBeenCalled()
expect(trackEvent.track).toHaveBeenCalled()
expect(trackPurchase.track).toHaveBeenCalled()
expect(updateUserProfile.track).toHaveBeenCalled()
})
it('covers different names between remote plugins and integrations', async () => {
const filterXt = schemaFilter(
{
hi: {
enabled: true,
integrations: {
// note that Fullstory's name here does not contain 'Actions'
Fullstory: false,
},
},
},
settings
)
await ajs.register(
segment,
trackEvent,
trackPurchase,
updateUserProfile,
amplitude,
fullstory,
filterXt
)
await ajs.track('hi')
expect(segment.track).toHaveBeenCalled()
expect(amplitude.track).toHaveBeenCalled()
expect(trackEvent.track).toHaveBeenCalled()
expect(trackPurchase.track).toHaveBeenCalled()
expect(updateUserProfile.track).toHaveBeenCalled()
expect(fullstory.track).not.toHaveBeenCalled()
await ajs.track('a non blocked event')
expect(segment.track).toHaveBeenCalled()
expect(amplitude.track).toHaveBeenCalled()
expect(trackEvent.track).toHaveBeenCalled()
expect(trackPurchase.track).toHaveBeenCalled()
expect(updateUserProfile.track).toHaveBeenCalled()
expect(fullstory.track).toHaveBeenCalled()
})
})
}) | the_stack |
import * as React from 'react';
import { mount } from 'enzyme';
import { PluginHost } from '@devexpress/dx-react-core';
import {
pluginDepsToComponents, getComputedState,
executeComputedAction, testStatePluginField, setupConsole,
} from '@devexpress/dx-testing';
import {
tableColumnsWithWidths,
tableColumnsWithDraftWidths,
changeTableColumnWidth,
draftTableColumnWidth,
cancelTableColumnWidthDraft,
TABLE_DATA_TYPE,
} from '@devexpress/dx-grid-core';
import { TableColumnResizing } from './table-column-resizing';
jest.mock('@devexpress/dx-grid-core', () => ({
tableColumnsWithWidths: jest.fn(),
tableColumnsWithDraftWidths: jest.fn(),
changeTableColumnWidth: jest.fn(),
draftTableColumnWidth: jest.fn(),
cancelTableColumnWidthDraft: jest.fn(),
}));
const defaultDeps = {
getter: {
tableColumns: [
{ key: 'a', type: TABLE_DATA_TYPE, column: { name: 'a' } },
],
},
plugins: ['Table'],
};
const defaultProps = {
minColumnWidth: 40,
maxColumnWidth: Infinity,
columnExtensions: undefined,
resizingMode: 'widget',
cachedWidths: {}, // NOTE: need to correct (?)
};
describe('TableColumnResizing', () => {
let resetConsole;
beforeAll(() => {
resetConsole = setupConsole({ ignore: ['validateDOMNesting'] });
});
afterAll(() => {
resetConsole();
});
beforeEach(() => {
tableColumnsWithWidths.mockImplementation(() => 'tableColumnsWithWidths');
tableColumnsWithDraftWidths.mockImplementation(() => 'tableColumnsWithDraftWidths');
changeTableColumnWidth.mockImplementation(() => ([]));
draftTableColumnWidth.mockImplementation(() => ([]));
cancelTableColumnWidthDraft.mockImplementation(() => ([]));
});
afterEach(() => {
jest.resetAllMocks();
});
testStatePluginField({
defaultDeps,
defaultProps,
Plugin: TableColumnResizing,
propertyName: 'columnWidths',
getGetterValue: () => tableColumnsWithWidths
.mock
.calls[tableColumnsWithWidths.mock.calls.length - 1][1],
customPayload: defaultProps,
values: [
[{ columnName: 'a', width: 1 }],
[{ columnName: 'a', width: 2 }],
[{ columnName: 'a', width: 3 }],
],
actions: [{
actionName: 'changeTableColumnWidth',
reducer: changeTableColumnWidth,
fieldReducer: false,
}],
});
describe('table layout getters', () => {
// tslint:disable-next-line: max-line-length
it('should apply the column widths specified in the "defaultColumnWidths" property in uncontrolled mode', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<TableColumnResizing
{...defaultProps}
defaultColumnWidths={[{ columnName: 'a', width: 100 }]}
/>
</PluginHost>
));
expect(getComputedState(tree).tableColumns)
.toBe('tableColumnsWithDraftWidths');
expect(tableColumnsWithWidths)
.toBeCalledWith(
defaultDeps.getter.tableColumns,
[{ columnName: 'a', width: 100 }],
defaultProps.resizingMode,
);
expect(tableColumnsWithDraftWidths)
.toBeCalledWith('tableColumnsWithWidths', [], defaultProps.resizingMode);
});
});
describe('undefined columnExtensions', () => {
const tableColumn = { column: { name: 'a' } };
const payload = {
cachedWidths: {
a: 100,
},
changes: { a: 50 },
columnName: 'a',
minColumnWidth: defaultProps.minColumnWidth,
maxColumnWidth: defaultProps.maxColumnWidth,
columnExtensions: undefined,
resizingMode: defaultProps.resizingMode,
};
// tslint:disable-next-line: max-line-length
it('should correctly update column widths after the "changeTableColumnWidth" action is fired', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<TableColumnResizing
{...defaultProps}
defaultColumnWidths={[{ columnName: 'a', width: 100 }]}
/>
</PluginHost>
));
changeTableColumnWidth.mockReturnValue({ columnWidths: [{ columnName: 'a', width: 150 }] });
executeComputedAction(tree, actions => actions.storeWidthGetters({
tableColumn,
getter: () => 100,
tableColumns: [tableColumn],
}));
executeComputedAction(tree, actions => actions.draftTableColumnWidth(payload));
executeComputedAction(tree, actions => actions.changeTableColumnWidth(payload));
expect(changeTableColumnWidth)
.toBeCalledWith(expect.objectContaining(
{ columnWidths: [{ columnName: 'a', width: 100 }] }), payload,
);
expect(tableColumnsWithDraftWidths)
.toBeCalledWith('tableColumnsWithWidths', [], payload.resizingMode);
});
// tslint:disable-next-line: max-line-length
it('should correctly update column widths after the "draftTableColumnWidth" action is fired', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<TableColumnResizing
{...defaultProps}
defaultColumnWidths={[{ columnName: 'a', width: 100 }]}
/>
</PluginHost>
));
draftTableColumnWidth.mockReturnValue({
draftColumnWidths: [{ columnName: 'a', width: 150 }],
});
executeComputedAction(tree, actions => actions.storeWidthGetters({
tableColumn,
getter: () => 100,
tableColumns: [tableColumn],
}));
executeComputedAction(tree, actions => actions.draftTableColumnWidth(payload));
expect(draftTableColumnWidth)
.toBeCalledWith(expect.objectContaining({ draftColumnWidths: [] }), payload);
expect(tableColumnsWithDraftWidths)
.toBeCalledWith(
'tableColumnsWithWidths',
[{ columnName: 'a', width: 150 }],
payload.resizingMode,
);
});
});
describe('defined columnExtensions', () => {
const tableColumn = { column: { name: 'a' } };
const columnExtensions = [{ columnName: 'a', minWidth: 50, maxWidth: 150 }];
const payload = {
cachedWidths: {
a: 100,
},
changes: { a: 50 },
columnName: 'a',
minColumnWidth: defaultProps.minColumnWidth,
maxColumnWidth: defaultProps.maxColumnWidth,
columnExtensions,
resizingMode: 'widget',
};
it('should correctly provide columnExtensions into the "changeTableColumnWidth" action', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<TableColumnResizing
{...defaultProps}
defaultColumnWidths={[{ columnName: 'a', width: 100 }]}
columnExtensions={columnExtensions}
/>
</PluginHost>
));
changeTableColumnWidth.mockReturnValue({ columnWidths: [{ columnName: 'a', width: 150 }] });
executeComputedAction(tree, actions => actions.storeWidthGetters({
tableColumn,
getter: () => 100,
tableColumns: [tableColumn],
}));
executeComputedAction(tree, actions => actions.draftTableColumnWidth(payload));
executeComputedAction(tree, actions => actions.changeTableColumnWidth(payload));
expect(changeTableColumnWidth)
.toBeCalledWith(
expect.objectContaining({ columnWidths: [{ columnName: 'a', width: 100 }] }),
payload,
);
expect(tableColumnsWithDraftWidths)
.toBeCalledWith('tableColumnsWithWidths', [], payload.resizingMode);
});
// tslint:disable-next-line: max-line-length
it('should correctly provide columnExtensions into the "draftTableColumnWidth" action', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<TableColumnResizing
{...defaultProps}
defaultColumnWidths={[{ columnName: 'a', width: 100 }]}
columnExtensions={columnExtensions}
/>
</PluginHost>
));
draftTableColumnWidth.mockReturnValue({
draftColumnWidths: [{ columnName: 'a', width: 150 }],
});
executeComputedAction(tree, actions => actions.storeWidthGetters({
tableColumn,
getter: () => 100,
tableColumns: [tableColumn],
}));
executeComputedAction(tree, actions => actions.draftTableColumnWidth(payload));
expect(draftTableColumnWidth)
.toBeCalledWith(expect.objectContaining({ draftColumnWidths: [] }), payload);
expect(tableColumnsWithDraftWidths)
.toBeCalledWith('tableColumnsWithWidths',
[{ columnName: 'a', width: 150 }], payload.resizingMode,
);
});
});
// tslint:disable-next-line: max-line-length
it('should correctly update column widths after the "cancelTableColumnWidthDraft" action is fired', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<TableColumnResizing
{...defaultProps}
defaultColumnWidths={[{ columnName: 'a', width: 100 }]}
/>
</PluginHost>
));
const payload = { changes: { a: 50 } };
cancelTableColumnWidthDraft.mockReturnValue({
draftColumnWidths: [{ columnName: 'a', width: 150 }],
});
executeComputedAction(tree, actions => actions.cancelTableColumnWidthDraft(payload));
expect(cancelTableColumnWidthDraft)
.toBeCalledWith(expect.objectContaining({ draftColumnWidths: [] }), payload);
expect(tableColumnsWithDraftWidths)
.toBeCalledWith('tableColumnsWithWidths',
[{ columnName: 'a', width: 150 }], defaultProps.resizingMode,
);
});
describe('nextColumn resizing mode', () => {
const resizingMode = 'nextColumn';
const tableColumnA = { column: { name: 'a' } };
const tableColumnB = { column: { name: 'b' } };
const payload = {
cachedWidths: {
a: 100,
b: 100,
},
changes: { a: 50 },
columnName: 'a',
nextColumnName: 'b',
minColumnWidth: defaultProps.minColumnWidth,
maxColumnWidth: defaultProps.maxColumnWidth,
columnExtensions: undefined,
resizingMode,
};
it('should correctly provide nextResizing into the "changeTableColumnWidth" action', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<TableColumnResizing
{...defaultProps}
defaultColumnWidths={[{ columnName: 'a', width: 100 }, { columnName: 'b', width: 100 }]}
resizingMode={resizingMode}
/>
</PluginHost>
));
changeTableColumnWidth.mockReturnValue({
columnWidths: [{ columnName: 'a', width: 150 }, { columnName: 'b', width: 50 }],
});
executeComputedAction(tree, actions => actions.storeWidthGetters({
tableColumn: tableColumnA,
getter: () => 100,
tableColumns: [tableColumnA, tableColumnB],
}));
executeComputedAction(tree, actions => actions.storeWidthGetters({
tableColumn: tableColumnB,
getter: () => 100,
tableColumns: [tableColumnA, tableColumnB],
}));
executeComputedAction(tree, actions => actions.draftTableColumnWidth(payload));
executeComputedAction(tree, actions => actions.changeTableColumnWidth(payload));
expect(changeTableColumnWidth)
.toBeCalledWith(
expect.objectContaining({
columnWidths: [{ columnName: 'a', width: 100 }, { columnName: 'b', width: 100 }],
}),
payload,
);
expect(tableColumnsWithDraftWidths)
.toBeCalledWith('tableColumnsWithWidths', [], resizingMode);
});
it('should correctly provide nextResizing into the "draftTableColumnWidth" action', () => {
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<TableColumnResizing
{...defaultProps}
defaultColumnWidths={[{ columnName: 'a', width: 100 }, { columnName: 'b', width: 100 }]}
resizingMode={resizingMode}
/>
</PluginHost>
));
draftTableColumnWidth.mockReturnValue({
draftColumnWidths: [{ columnName: 'a', width: 150 }, { columnName: 'b', width: 50 }],
});
executeComputedAction(tree, actions => actions.storeWidthGetters({
tableColumn: tableColumnA,
getter: () => 100,
tableColumns: [tableColumnA, tableColumnB],
}));
executeComputedAction(tree, actions => actions.storeWidthGetters({
tableColumn: tableColumnB,
getter: () => 100,
tableColumns: [tableColumnA, tableColumnB],
}));
executeComputedAction(tree, actions => actions.draftTableColumnWidth(payload));
expect(draftTableColumnWidth)
.toBeCalledWith(expect.objectContaining({ draftColumnWidths: [] }), payload);
expect(tableColumnsWithDraftWidths)
.toBeCalledWith('tableColumnsWithWidths',
[{ columnName: 'a', width: 150 }, { columnName: 'b', width: 50 }],
payload.resizingMode,
);
});
});
}); | the_stack |
import { ethers, upgrades, waffle } from "hardhat";
import { Signer, BigNumber } from "ethers";
import chai from "chai";
import { solidity } from "ethereum-waffle";
import "@openzeppelin/test-helpers";
import {
MockERC20,
MockERC20__factory,
PancakeFactory,
PancakeFactory__factory,
PancakeRouterV2__factory,
PancakeRouterV2,
WETH,
WETH__factory,
CakeToken,
CakeToken__factory,
SimplePriceOracle,
SimplePriceOracle__factory,
MockPancakeswapV2Worker,
WorkerConfig__factory,
WorkerConfig,
MockPancakeswapV2Worker__factory,
PancakePair__factory,
IERC20__factory,
} from "../../../../typechain";
import * as TimeHelpers from "../../../helpers/time";
chai.use(solidity);
const { expect } = chai;
describe("WokerConfig", () => {
const FOREVER = "2000000000";
/// PancakeswapV2-related instance(s)
let factoryV2: PancakeFactory;
let routerV2: PancakeRouterV2;
/// Token-related instance(s)
let wbnb: WETH;
let baseToken: MockERC20;
let cake: CakeToken;
// Accounts
let deployer: Signer;
let alice: Signer;
let bob: Signer;
let eve: Signer;
// WorkerConfig instance
let workerConfig: WorkerConfig;
// Workers
let mockWorker1: MockPancakeswapV2Worker;
let mockWorker2: MockPancakeswapV2Worker;
// Contract Signer
let baseTokenAsAlice: MockERC20;
let cakeAsAlice: MockERC20;
let wbnbTokenAsAlice: WETH;
let wbnbTokenAsBob: WETH;
let routerV2AsAlice: PancakeRouterV2;
let simplePriceOracleAsAlice: SimplePriceOracle;
let workerConfigAsAlice: WorkerConfig;
/// SimpleOracle-related instance(s)
let simplePriceOracle: SimplePriceOracle;
let lpPriceFarmBNB: BigNumber;
let lpPriceBNBFarm: BigNumber;
async function fixture() {
[deployer, alice, bob, eve] = await ethers.getSigners();
/// Deploy SimpleOracle
const SimplePriceOracle = (await ethers.getContractFactory(
"SimplePriceOracle",
deployer
)) as SimplePriceOracle__factory;
simplePriceOracle = (await upgrades.deployProxy(SimplePriceOracle, [
await alice.getAddress(),
])) as SimplePriceOracle;
await simplePriceOracle.deployed();
// Setup Pancakeswap
const PancakeFactory = (await ethers.getContractFactory("PancakeFactory", deployer)) as PancakeFactory__factory;
factoryV2 = await PancakeFactory.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 PancakeRouterV2__factory;
routerV2 = await PancakeRouterV2.deploy(factoryV2.address, wbnb.address);
await routerV2.deployed();
/// Deploy WorkerConfig
const WorkerConfig = (await ethers.getContractFactory("WorkerConfig", deployer)) as WorkerConfig__factory;
workerConfig = (await upgrades.deployProxy(WorkerConfig, [simplePriceOracle.address])) as WorkerConfig;
await workerConfig.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 alice.getAddress(), ethers.utils.parseEther("100"));
await baseToken.mint(await bob.getAddress(), ethers.utils.parseEther("100"));
const CakeToken = (await ethers.getContractFactory("CakeToken", deployer)) as CakeToken__factory;
cake = await CakeToken.deploy();
await cake.deployed();
await cake["mint(address,uint256)"](await deployer.getAddress(), ethers.utils.parseEther("100"));
await cake["mint(address,uint256)"](await alice.getAddress(), ethers.utils.parseEther("10"));
await cake["mint(address,uint256)"](await bob.getAddress(), ethers.utils.parseEther("10"));
await factoryV2.createPair(baseToken.address, wbnb.address);
await factoryV2.createPair(cake.address, wbnb.address);
/// Setup MockWorker
const MockWorker = (await ethers.getContractFactory(
"MockPancakeswapV2Worker",
deployer
)) as MockPancakeswapV2Worker__factory;
mockWorker1 = (await MockWorker.deploy(
await factoryV2.getPair(wbnb.address, cake.address),
wbnb.address,
cake.address
)) as MockPancakeswapV2Worker;
await mockWorker1.deployed();
mockWorker2 = (await MockWorker.deploy(
await factoryV2.getPair(wbnb.address, baseToken.address),
wbnb.address,
baseToken.address
)) as MockPancakeswapV2Worker;
await mockWorker2.deployed();
// Assign contract signer
baseTokenAsAlice = MockERC20__factory.connect(baseToken.address, alice);
cakeAsAlice = MockERC20__factory.connect(cake.address, alice);
wbnbTokenAsAlice = WETH__factory.connect(wbnb.address, alice);
wbnbTokenAsBob = WETH__factory.connect(wbnb.address, bob);
routerV2AsAlice = PancakeRouterV2__factory.connect(routerV2.address, alice);
workerConfigAsAlice = WorkerConfig__factory.connect(workerConfig.address, alice);
simplePriceOracleAsAlice = SimplePriceOracle__factory.connect(simplePriceOracle.address, alice);
await simplePriceOracle.setFeeder(await alice.getAddress());
// Adding liquidity to the pool
// Alice adds 0.1 FTOKEN + 1 WBTC + 1 WBNB
await wbnbTokenAsAlice.deposit({
value: ethers.utils.parseEther("52"),
});
await wbnbTokenAsBob.deposit({
value: ethers.utils.parseEther("50"),
});
await cakeAsAlice.approve(routerV2.address, ethers.utils.parseEther("0.1"));
await baseTokenAsAlice.approve(routerV2.address, ethers.utils.parseEther("1"));
await wbnbTokenAsAlice.approve(routerV2.address, ethers.utils.parseEther("11"));
// Add liquidity to the WBTC-WBNB pool on Pancakeswap
await routerV2AsAlice.addLiquidity(
baseToken.address,
wbnb.address,
ethers.utils.parseEther("1"),
ethers.utils.parseEther("10"),
"0",
"0",
await alice.getAddress(),
FOREVER
);
// Add liquidity to the WBNB-FTOKEN pool on Pancakeswap
await routerV2AsAlice.addLiquidity(
cake.address,
wbnb.address,
ethers.utils.parseEther("0.1"),
ethers.utils.parseEther("1"),
"0",
"0",
await alice.getAddress(),
FOREVER
);
lpPriceFarmBNB = ethers.utils.parseEther("1").mul(ethers.utils.parseEther("1")).div(ethers.utils.parseEther("0.1"));
lpPriceBNBFarm = ethers.utils.parseEther("0.1").mul(ethers.utils.parseEther("1")).div(ethers.utils.parseEther("1"));
await workerConfig.setConfigs(
[mockWorker1.address, mockWorker2.address],
[
{ acceptDebt: true, workFactor: 1, killFactor: 1, maxPriceDiff: 11000 },
{ acceptDebt: true, workFactor: 1, killFactor: 1, maxPriceDiff: 11000 },
]
);
}
beforeEach(async () => {
await waffle.loadFixture(fixture);
});
describe("#emergencySetAcceptDebt", async () => {
context("when non owner try to set governor", async () => {
it("should be reverted", async () => {
await expect(workerConfigAsAlice.setGovernor(await deployer.getAddress())).to.be.revertedWith(
"Ownable: caller is not the owner"
);
});
});
context("when an owner set governor", async () => {
it("should work", async () => {
await workerConfig.setGovernor(await deployer.getAddress());
expect(await workerConfig.governor()).to.be.eq(await deployer.getAddress());
});
});
context("when non governor try to use emergencySetAcceptDebt", async () => {
it("should revert", async () => {
await expect(workerConfigAsAlice.emergencySetAcceptDebt([mockWorker1.address], false)).to.be.revertedWith(
"WorkerConfig::onlyGovernor:: msg.sender not governor"
);
});
});
context("when governor uses emergencySetAcceptDebt", async () => {
it("should work", async () => {
await workerConfig.setGovernor(await deployer.getAddress());
await workerConfig.emergencySetAcceptDebt([mockWorker1.address, mockWorker2.address], false);
expect((await workerConfig.workers(mockWorker1.address)).acceptDebt).to.be.eq(false);
expect((await workerConfig.workers(mockWorker1.address)).workFactor).to.be.eq(1);
expect((await workerConfig.workers(mockWorker1.address)).killFactor).to.be.eq(1);
expect((await workerConfig.workers(mockWorker1.address)).maxPriceDiff).to.be.eq(11000);
expect((await workerConfig.workers(mockWorker2.address)).acceptDebt).to.be.eq(false);
expect((await workerConfig.workers(mockWorker2.address)).workFactor).to.be.eq(1);
expect((await workerConfig.workers(mockWorker2.address)).killFactor).to.be.eq(1);
expect((await workerConfig.workers(mockWorker2.address)).maxPriceDiff).to.be.eq(11000);
});
});
});
describe("#isStable", async () => {
context("when the baseToken is a wrap native", async () => {
context("when the oracle hasn't updated any prices", async () => {
it("should be reverted", async () => {
await simplePriceOracleAsAlice.setPrices([wbnb.address, cake.address], [cake.address, wbnb.address], [1, 1]);
await TimeHelpers.increase(BigNumber.from("86401")); // 1 day and 1 second have passed
await expect(workerConfigAsAlice.isStable(mockWorker1.address)).to.revertedWith(
"WorkerConfig::isStable:: price too stale"
);
});
});
context("when price is too high", async () => {
it("should be reverted", async () => {
// feed the price with price too low on the first hop
await simplePriceOracleAsAlice.setPrices(
[wbnb.address, cake.address],
[cake.address, wbnb.address],
[lpPriceBNBFarm.mul(10000).div(11001), lpPriceFarmBNB.mul(10000).div(11001)]
);
await expect(workerConfigAsAlice.isStable(mockWorker1.address)).to.revertedWith(
"WorkerConfig::isStable:: price too high"
);
});
});
context("when price is too low", async () => {
it("should be reverted", async () => {
// feed the price with price too low on the first hop
await simplePriceOracleAsAlice.setPrices(
[wbnb.address, cake.address],
[cake.address, wbnb.address],
[lpPriceBNBFarm.mul(11001).div(10000), lpPriceFarmBNB.mul(11001).div(10000)]
);
await expect(workerConfigAsAlice.isStable(mockWorker1.address)).to.revertedWith(
"WorkerConfig::isStable:: price too low"
);
});
});
context("when price is stable", async () => {
it("should return true", async () => {
// feed the price with price too low on the first hop
await simplePriceOracleAsAlice.setPrices(
[wbnb.address, cake.address],
[cake.address, wbnb.address],
[lpPriceBNBFarm, lpPriceFarmBNB]
);
const isStable = await workerConfigAsAlice.isStable(mockWorker1.address);
expect(isStable).to.true;
});
});
});
});
describe("#isReserveConsistent", async () => {
context("when reserve is consistent", async () => {
it("should return true", async () => {
expect(await workerConfig.isReserveConsistent(mockWorker1.address)).to.be.eq(true);
});
});
context("when reserve is inconsistent", async () => {
it("should revert", async () => {
const lp = PancakePair__factory.connect(await factoryV2.getPair(cake.address, wbnb.address), deployer);
const [t0Address, t1Address] = await Promise.all([lp.token0(), lp.token1()]);
const [token0, token1] = [
IERC20__factory.connect(t0Address, deployer),
IERC20__factory.connect(t1Address, deployer),
];
if (token0.address === wbnb.address) await wbnb.deposit({ value: ethers.utils.parseEther("10") });
await token0.transfer(lp.address, ethers.utils.parseEther("10"));
await expect(workerConfig.isReserveConsistent(mockWorker1.address)).to.be.revertedWith(
"WorkerConfig::isReserveConsistent:: bad t0 balance"
);
await lp.skim(await deployer.getAddress());
if (token1.address === wbnb.address) await wbnb.deposit({ value: ethers.utils.parseEther("10") });
await token1.transfer(lp.address, ethers.utils.parseEther("10"));
await expect(workerConfig.isReserveConsistent(mockWorker1.address)).to.be.revertedWith(
"WorkerConfig::isReserveConsistent:: bad t1 balance"
);
await lp.skim(await deployer.getAddress());
});
});
});
}); | the_stack |
import { TransformBit } from '../../core/scene-graph/node-enum';
import { Node } from '../../core';
import { BulletWorld } from './bullet-world';
import { BulletRigidBody } from './bullet-rigid-body';
import { BulletShape } from './shapes/bullet-shape';
import { bullet2CocosVec3, cocos2BulletQuat, cocos2BulletVec3, bullet2CocosQuat } from './bullet-utils';
import { btCollisionFlags, btCollisionObjectStates, EBtSharedBodyDirty } from './bullet-enum';
import { IBulletBodyStruct, IBulletGhostStruct } from './bullet-interface';
import { CC_V3_0, CC_QUAT_0, BulletCache } from './bullet-cache';
import { PhysicsSystem } from '../framework';
import { ERigidBodyType, PhysicsGroup } from '../framework/physics-enum';
import { fastRemoveAt } from '../../core/utils/array';
import { bt } from './instantiated';
import { BulletConstraint } from './constraints/bullet-constraint';
/**
* @packageDocumentation
* @hidden
*/
const v3_0 = CC_V3_0;
const quat_0 = CC_QUAT_0;
let IDCounter = 0;
/**
* shared object, node : shared = 1 : 1
* body for static \ dynamic \ kinematic (collider)
* ghost for trigger
*/
export class BulletSharedBody {
private static idCounter = 0;
private static readonly sharedBodesMap = new Map<string, BulletSharedBody>();
static getSharedBody (node: Node, wrappedWorld: BulletWorld, wrappedBody?: BulletRigidBody) {
const key = node.uuid;
let newSB!: BulletSharedBody;
if (BulletSharedBody.sharedBodesMap.has(key)) {
newSB = BulletSharedBody.sharedBodesMap.get(key)!;
} else {
newSB = new BulletSharedBody(node, wrappedWorld);
const g = PhysicsGroup.DEFAULT;
const m = PhysicsSystem.instance.collisionMatrix[g];
newSB._collisionFilterGroup = g;
newSB._collisionFilterMask = m;
BulletSharedBody.sharedBodesMap.set(node.uuid, newSB);
}
if (wrappedBody) {
newSB._wrappedBody = wrappedBody;
const g = wrappedBody.rigidBody.group;
const m = PhysicsSystem.instance.collisionMatrix[g];
newSB._collisionFilterGroup = g;
newSB._collisionFilterMask = m;
}
return newSB;
}
get wrappedBody () {
return this._wrappedBody;
}
get bodyCompoundShape () {
return this.bodyStruct.compound;
}
get ghostCompoundShape () {
return this.ghostStruct.compound;
}
get body () {
return this.bodyStruct.body;
}
get ghost () {
return this.ghostStruct.ghost;
}
get collisionFilterGroup () { return this._collisionFilterGroup; }
set collisionFilterGroup (v: number) {
if (v !== this._collisionFilterGroup) {
this._collisionFilterGroup = v;
this.dirty |= EBtSharedBodyDirty.BODY_RE_ADD;
this.dirty |= EBtSharedBodyDirty.GHOST_RE_ADD;
}
}
get collisionFilterMask () { return this._collisionFilterMask; }
set collisionFilterMask (v: number) {
if (v !== this._collisionFilterMask) {
this._collisionFilterMask = v;
this.dirty |= EBtSharedBodyDirty.BODY_RE_ADD;
this.dirty |= EBtSharedBodyDirty.GHOST_RE_ADD;
}
}
get bodyStruct () {
this._instantiateBodyStruct();
return this._bodyStruct;
}
get ghostStruct () {
this._instantiateGhostStruct();
return this._ghostStruct;
}
readonly id: number;
readonly node: Node;
readonly wrappedWorld: BulletWorld;
readonly wrappedJoints0: BulletConstraint[] = [];
readonly wrappedJoints1: BulletConstraint[] = [];
dirty: EBtSharedBodyDirty = 0;
private _collisionFilterGroup: number = PhysicsSystem.PhysicsGroup.DEFAULT;
private _collisionFilterMask = -1;
private ref = 0;
private bodyIndex = -1;
private ghostIndex = -1;
private _bodyStruct!: IBulletBodyStruct;
private _ghostStruct!: IBulletGhostStruct;
private _wrappedBody: BulletRigidBody | null = null;
/**
* add or remove from world \
* add, if enable \
* remove, if disable & shapes.length == 0 & wrappedBody disable
*/
set bodyEnabled (v: boolean) {
if (v) {
if (this.bodyIndex < 0) {
// add to world only if it is a dynamic body or having shapes.
if (this.bodyStruct.wrappedShapes.length === 0) {
if (!this.wrappedBody) return;
if (!this.wrappedBody.rigidBody.isDynamic) return;
}
this.bodyIndex = this.wrappedWorld.bodies.length;
this.wrappedWorld.addSharedBody(this);
this.syncInitialBody();
}
} else if (this.bodyIndex >= 0) {
const isRemoveBody = (this.bodyStruct.wrappedShapes.length === 0 && this.wrappedBody == null)
|| (this.bodyStruct.wrappedShapes.length === 0 && this.wrappedBody != null && !this.wrappedBody.isEnabled)
|| (this.bodyStruct.wrappedShapes.length === 0 && this.wrappedBody != null && !this.wrappedBody.rigidBody.enabledInHierarchy);
if (isRemoveBody) {
bt.RigidBody_clearState(this.body); // clear velocity etc.
this.bodyIndex = -1;
this.wrappedWorld.removeSharedBody(this);
}
}
}
set ghostEnabled (v: boolean) {
if (v) {
if (this.ghostIndex < 0 && this.ghostStruct.wrappedShapes.length > 0) {
this.ghostIndex = 1;
this.wrappedWorld.addGhostObject(this);
this.syncInitialGhost();
}
} else if (this.ghostIndex >= 0) {
/** remove trigger */
const isRemoveGhost = (this.ghostStruct.wrappedShapes.length === 0 && this.ghost);
if (isRemoveGhost) {
this.ghostIndex = -1;
this.wrappedWorld.removeGhostObject(this);
}
}
}
set reference (v: boolean) {
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
v ? this.ref++ : this.ref--;
if (this.ref === 0) { this.destroy(); }
}
private constructor (node: Node, wrappedWorld: BulletWorld) {
this.id = BulletSharedBody.idCounter++;
this.wrappedWorld = wrappedWorld;
this.node = node;
}
private _instantiateBodyStruct () {
if (this._bodyStruct) return;
let mass = 0;
if (this._wrappedBody && this._wrappedBody.rigidBody.enabled && this._wrappedBody.rigidBody.isDynamic) {
mass = this._wrappedBody.rigidBody.mass;
}
const trans = BulletCache.instance.BT_TRANSFORM_0;
const quat = BulletCache.instance.BT_QUAT_0;
cocos2BulletVec3(bt.Transform_getOrigin(trans), this.node.worldPosition);
cocos2BulletQuat(quat, this.node.worldRotation);
bt.Transform_setRotation(trans, quat);
const motionState = bt.ccMotionState_new(this.id, trans);
const body = bt.RigidBody_new(mass, motionState);
const sleepTd = PhysicsSystem.instance.sleepThreshold;
bt.RigidBody_setSleepingThresholds(body, sleepTd, sleepTd);
this._bodyStruct = {
id: IDCounter++, body, motionState, compound: bt.ccCompoundShape_new(), wrappedShapes: [], useCompound: false,
};
BulletCache.setWrapper(this.id, bt.BODY_CACHE_NAME, this);
if (this._ghostStruct) bt.CollisionObject_setIgnoreCollisionCheck(this.ghost, this.body, true);
if (this._wrappedBody) this.setBodyType(this._wrappedBody.rigidBody.type);
}
private _instantiateGhostStruct () {
if (this._ghostStruct) return;
const ghost = bt.CollisionObject_new();
const ghostShape = bt.ccCompoundShape_new();
bt.CollisionObject_setCollisionShape(ghost, ghostShape);
bt.CollisionObject_setCollisionFlags(ghost, btCollisionFlags.CF_STATIC_OBJECT | btCollisionFlags.CF_NO_CONTACT_RESPONSE);
this._ghostStruct = { id: IDCounter++, ghost, compound: ghostShape, wrappedShapes: [] };
if (this._bodyStruct) bt.CollisionObject_setIgnoreCollisionCheck(this.body, this.ghost, true);
if (this._wrappedBody) this.setGhostType(this._wrappedBody.rigidBody.type);
}
setType (v: ERigidBodyType) {
this.setBodyType(v);
this.setGhostType(v);
}
setBodyType (v: ERigidBodyType) {
if (this._bodyStruct && this._wrappedBody) {
const body = this._bodyStruct.body;
const wrap = this._wrappedBody;
const com = wrap.rigidBody;
let m_bcf = bt.CollisionObject_getCollisionFlags(body);
const localInertia = BulletCache.instance.BT_V3_0;
switch (v) {
case ERigidBodyType.DYNAMIC:
m_bcf &= (~btCollisionFlags.CF_KINEMATIC_OBJECT);
m_bcf &= (~btCollisionFlags.CF_STATIC_OBJECT);
bt.CollisionObject_setCollisionFlags(body, m_bcf);
wrap.setMass(com.mass);
wrap.useGravity(com.useGravity);
wrap.setAllowSleep(com.allowSleep);
break;
case ERigidBodyType.KINEMATIC:
bt.Vec3_set(localInertia, 0, 0, 0);
bt.RigidBody_setMassProps(body, 0, localInertia);
m_bcf |= btCollisionFlags.CF_KINEMATIC_OBJECT;
m_bcf &= (~btCollisionFlags.CF_STATIC_OBJECT);
bt.CollisionObject_setCollisionFlags(body, m_bcf);
bt.CollisionObject_forceActivationState(body, btCollisionObjectStates.DISABLE_DEACTIVATION);
break;
case ERigidBodyType.STATIC:
default:
bt.Vec3_set(localInertia, 0, 0, 0);
bt.RigidBody_setMassProps(body, 0, localInertia);
m_bcf |= btCollisionFlags.CF_STATIC_OBJECT;
m_bcf &= (~btCollisionFlags.CF_KINEMATIC_OBJECT);
bt.CollisionObject_setCollisionFlags(body, m_bcf);
bt.CollisionObject_forceActivationState(body, btCollisionObjectStates.ISLAND_SLEEPING);
break;
}
this.dirty |= EBtSharedBodyDirty.BODY_RE_ADD;
}
}
setGhostType (v: ERigidBodyType) {
if (this._ghostStruct) {
const ghost = this._ghostStruct.ghost;
let m_gcf = bt.CollisionObject_getCollisionFlags(ghost);
switch (v) {
case ERigidBodyType.DYNAMIC:
case ERigidBodyType.KINEMATIC:
m_gcf &= (~btCollisionFlags.CF_STATIC_OBJECT);
m_gcf |= btCollisionFlags.CF_KINEMATIC_OBJECT;
bt.CollisionObject_setCollisionFlags(ghost, m_gcf);
bt.CollisionObject_forceActivationState(ghost, btCollisionObjectStates.DISABLE_DEACTIVATION);
break;
case ERigidBodyType.STATIC:
default:
m_gcf &= (~btCollisionFlags.CF_KINEMATIC_OBJECT);
m_gcf |= btCollisionFlags.CF_STATIC_OBJECT;
bt.CollisionObject_setCollisionFlags(ghost, m_gcf);
bt.CollisionObject_forceActivationState(ghost, btCollisionObjectStates.ISLAND_SLEEPING);
break;
}
this.dirty |= EBtSharedBodyDirty.GHOST_RE_ADD;
}
}
addShape (v: BulletShape, isTrigger: boolean) {
function switchShape (that: BulletSharedBody, shape: Bullet.ptr) {
bt.CollisionObject_setCollisionShape(that.body, shape);
that.dirty |= EBtSharedBodyDirty.BODY_RE_ADD;
if (that._wrappedBody && that._wrappedBody.isEnabled) {
that._wrappedBody.setMass(that._wrappedBody.rigidBody.mass);
}
}
if (isTrigger) {
const index = this.ghostStruct.wrappedShapes.indexOf(v);
if (index < 0) {
this.ghostStruct.wrappedShapes.push(v);
v.setCompound(this.ghostCompoundShape);
this.ghostEnabled = true;
}
} else {
const index = this.bodyStruct.wrappedShapes.indexOf(v);
if (index < 0) {
this.bodyStruct.wrappedShapes.push(v);
if (this.bodyStruct.useCompound) {
v.setCompound(this.bodyCompoundShape);
} else {
const l = this.bodyStruct.wrappedShapes.length;
if (l === 1 && !v.needCompound()) {
switchShape(this, v.impl);
} else {
this.bodyStruct.useCompound = true;
for (let i = 0; i < l; i++) {
const childShape = this.bodyStruct.wrappedShapes[i];
childShape.setCompound(this.bodyCompoundShape);
}
switchShape(this, this.bodyStruct.compound);
}
}
this.bodyEnabled = true;
}
}
}
removeShape (v: BulletShape, isTrigger: boolean) {
if (isTrigger) {
const index = this.ghostStruct.wrappedShapes.indexOf(v);
if (index >= 0) {
fastRemoveAt(this.ghostStruct.wrappedShapes, index);
v.setCompound(0);
this.ghostEnabled = false;
}
} else {
const index = this.bodyStruct.wrappedShapes.indexOf(v);
if (index >= 0) {
if (this.bodyStruct.useCompound) {
v.setCompound(0);
} else {
bt.CollisionObject_setCollisionShape(this.body, bt.EmptyShape_static());
}
bt.CollisionObject_activate(this.body, true);
this.dirty |= EBtSharedBodyDirty.BODY_RE_ADD;
fastRemoveAt(this.bodyStruct.wrappedShapes, index);
this.bodyEnabled = false;
}
}
}
addJoint (v: BulletConstraint, type: 0 | 1) {
if (type) {
const i = this.wrappedJoints1.indexOf(v);
if (i < 0) this.wrappedJoints1.push(v);
} else {
const i = this.wrappedJoints0.indexOf(v);
if (i < 0) this.wrappedJoints0.push(v);
}
}
removeJoint (v: BulletConstraint, type: 0 | 1) {
if (type) {
const i = this.wrappedJoints1.indexOf(v);
if (i >= 0) fastRemoveAt(this.wrappedJoints1, i);
} else {
const i = this.wrappedJoints0.indexOf(v);
if (i >= 0) fastRemoveAt(this.wrappedJoints0, i);
}
}
updateDirty () {
if (this.dirty) {
if (this.bodyIndex >= 0 && this.dirty & EBtSharedBodyDirty.BODY_RE_ADD) this.updateBodyByReAdd();
if (this.ghostIndex >= 0 && this.dirty & EBtSharedBodyDirty.GHOST_RE_ADD) this.updateGhostByReAdd();
this.dirty = 0;
}
}
syncSceneToPhysics () {
if (this.node.hasChangedFlags) {
const bt_quat = BulletCache.instance.BT_QUAT_0;
const bt_transform = bt.CollisionObject_getWorldTransform(this.body);
cocos2BulletQuat(bt_quat, this.node.worldRotation);
cocos2BulletVec3(bt.Transform_getOrigin(bt_transform), this.node.worldPosition);
bt.Transform_setRotation(bt_transform, bt_quat);
if (this.node.hasChangedFlags & TransformBit.SCALE) {
this.syncBodyScale();
}
if (bt.CollisionObject_isKinematicObject(this.body)) {
// Kinematic objects must be updated using motion state
const ms = bt.RigidBody_getMotionState(this.body);
if (ms) bt.MotionState_setWorldTransform(ms, bt_transform);
} else if (this.isBodySleeping()) bt.CollisionObject_activate(this.body);
}
}
syncPhysicsToScene () {
if (bt.CollisionObject_isStaticOrKinematicObject(this.body)) return;
this.syncPhysicsToGraphics();
}
syncPhysicsToGraphics () {
if (this.isBodySleeping()) return;
const bt_quat = BulletCache.instance.BT_QUAT_0;
const bt_transform = BulletCache.instance.BT_TRANSFORM_0;
bt.MotionState_getWorldTransform(bt.RigidBody_getMotionState(this.body), bt_transform);
bt.Transform_getRotation(bt_transform, bt_quat);
this.node.worldRotation = bullet2CocosQuat(quat_0, bt_quat);
this.node.worldPosition = bullet2CocosVec3(v3_0, bt.Transform_getOrigin(bt_transform));
// sync node to ghost
if (this._ghostStruct) {
const bt_transform1 = bt.CollisionObject_getWorldTransform(this.ghost);
cocos2BulletVec3(bt.Transform_getOrigin(bt_transform1), this.node.worldPosition);
cocos2BulletQuat(bt_quat, this.node.worldRotation);
bt.Transform_setRotation(bt_transform1, bt_quat);
}
}
syncSceneToGhost () {
if (this.node.hasChangedFlags) {
const bt_quat = BulletCache.instance.BT_QUAT_0;
const bt_transform = bt.CollisionObject_getWorldTransform(this.ghost);
cocos2BulletVec3(bt.Transform_getOrigin(bt_transform), this.node.worldPosition);
cocos2BulletQuat(bt_quat, this.node.worldRotation);
bt.Transform_setRotation(bt_transform, bt_quat);
if (this.node.hasChangedFlags & TransformBit.SCALE) this.syncGhostScale();
bt.CollisionObject_activate(this.ghost);
}
}
syncInitialBody () {
const bt_quat = BulletCache.instance.BT_QUAT_0;
const bt_transform = bt.CollisionObject_getWorldTransform(this.body);
cocos2BulletVec3(bt.Transform_getOrigin(bt_transform), this.node.worldPosition);
cocos2BulletQuat(bt_quat, this.node.worldRotation);
bt.Transform_setRotation(bt_transform, bt_quat);
this.syncBodyScale();
bt.CollisionObject_activate(this.body);
}
syncInitialGhost () {
const bt_quat = BulletCache.instance.BT_QUAT_0;
const bt_transform = bt.CollisionObject_getWorldTransform(this.ghost);
cocos2BulletVec3(bt.Transform_getOrigin(bt_transform), this.node.worldPosition);
cocos2BulletQuat(bt_quat, this.node.worldRotation);
bt.Transform_setRotation(bt_transform, bt_quat);
this.syncGhostScale();
bt.CollisionObject_activate(this.body);
}
syncBodyScale () {
for (let i = 0; i < this.bodyStruct.wrappedShapes.length; i++) {
this.bodyStruct.wrappedShapes[i].updateScale();
}
for (let i = 0; i < this.wrappedJoints0.length; i++) {
this.wrappedJoints0[i].updateScale0();
}
for (let i = 0; i < this.wrappedJoints1.length; i++) {
this.wrappedJoints1[i].updateScale1();
}
}
syncGhostScale () {
for (let i = 0; i < this.ghostStruct.wrappedShapes.length; i++) {
this.ghostStruct.wrappedShapes[i].updateScale();
}
}
/**
* see: https://pybullet.org/Bullet/phpBB3/viewtopic.php?f=9&t=5312&p=19094&hilit=how+to+change+group+mask#p19097
*/
updateBodyByReAdd () {
if (this.bodyIndex >= 0) {
this.wrappedWorld.removeSharedBody(this);
this.bodyIndex = this.wrappedWorld.bodies.length;
this.wrappedWorld.addSharedBody(this);
}
}
updateGhostByReAdd () {
if (this.ghostIndex >= 0) {
this.wrappedWorld.removeGhostObject(this);
this.ghostIndex = this.wrappedWorld.ghosts.length;
this.wrappedWorld.addGhostObject(this);
}
}
private destroy () {
BulletSharedBody.sharedBodesMap.delete(this.node.uuid);
(this.node as any) = null;
(this.wrappedWorld as any) = null;
if (this._bodyStruct) {
const bodyStruct = this._bodyStruct;
BulletCache.delWrapper(bodyStruct.body, bt.BODY_CACHE_NAME);
bt.MotionState_del(bodyStruct.motionState);
bt.CollisionShape_del(bodyStruct.compound);
bt.CollisionObject_del(bodyStruct.body);
(this._bodyStruct as any) = null;
}
if (this._ghostStruct) {
const ghostStruct = this._ghostStruct;
bt.CollisionShape_del(ghostStruct.compound);
bt.CollisionObject_del(ghostStruct.ghost);
(this._ghostStruct as any) = null;
}
}
private isBodySleeping () {
return bt.CollisionObject_getActivationState(this.body) === btCollisionObjectStates.ISLAND_SLEEPING;
}
} | the_stack |
import { Readable, Writable } from "stream";
// ------------------------------------------------------------------------
type StateMachine = {
nodes: Node[];
};
type RunState = {
candidateUsage: string | null;
errorMessage: string | null;
ignoreOptions: boolean;
options: {
name: string;
value: any;
}[];
path: string[];
positionals: {
value: string;
extra: boolean | typeof NoLimits;
}[];
remainder: string | null;
selectedIndex: number | null;
};
// ------------------------------------------------------------------------
type Transition = {
to: number;
reducer?: Callback<keyof typeof reducers, typeof reducers>;
};
type Node = {
dynamics: [Callback<keyof typeof tests, typeof tests>, Transition][];
shortcuts: Transition[];
statics: {
[segment: string]: Transition[];
};
};
type CallbackFn<P extends any[], R> = (state: RunState, segment: string, ...args: P) => R;
type CallbackStore<T extends string, R> = Record<T, CallbackFn<any, R>>;
type Callback<T extends string, S extends CallbackStore<T, any>> = [
] extends [
] ? (T | [
]) : [
];
declare const tests: {
always: () => boolean;
isOptionLike: (state: RunState, segment: string) => boolean;
isNotOptionLike: (state: RunState, segment: string) => boolean;
isOption: (state: RunState, segment: string, name: string, hidden?: boolean | undefined) => boolean;
isBatchOption: (state: RunState, segment: string, names: string[]) => boolean;
isBoundOption: (state: RunState, segment: string, names: string[], options: OptDefinition[]) => boolean;
isNegatedOption: (state: RunState, segment: string, name: string) => boolean;
isHelp: (state: RunState, segment: string) => boolean;
isUnsupportedOption: (state: RunState, segment: string, names: string[]) => boolean;
isInvalidOption: (state: RunState, segment: string) => boolean;
}; // @ts-ignore
// @ts-ignore
// @ts-ignore
// @ts-ignore
declare const reducers: {
setCandidateUsage: (state: RunState, segment: string, usage: string) => {
candidateUsage: string;
errorMessage: string | null;
ignoreOptions: boolean;
options: {
name: string;
value: any;
}[];
path: string[];
positionals: {
value: string;
extra: boolean | typeof NoLimits;
}[];
remainder: string | null;
selectedIndex: number | null;
};
setSelectedIndex: (state: RunState, segment: string, index: number) => {
selectedIndex: number;
candidateUsage: string | null;
errorMessage: string | null;
ignoreOptions: boolean;
options: {
name: string;
value: any;
}[];
path: string[];
positionals: {
value: string;
extra: boolean | typeof NoLimits;
}[];
remainder: string | null;
};
pushBatch: (state: RunState, segment: string) => {
options: {
name: string;
value: any;
}[];
candidateUsage: string | null;
errorMessage: string | null;
ignoreOptions: boolean;
path: string[];
positionals: {
value: string;
extra: boolean | typeof NoLimits;
}[];
remainder: string | null;
selectedIndex: number | null;
};
pushBound: (state: RunState, segment: string) => {
options: {
name: string;
value: any;
}[];
candidateUsage: string | null;
errorMessage: string | null;
ignoreOptions: boolean;
path: string[];
positionals: {
value: string;
extra: boolean | typeof NoLimits;
}[];
remainder: string | null;
selectedIndex: number | null;
};
pushPath: (state: RunState, segment: string) => {
path: string[];
candidateUsage: string | null;
errorMessage: string | null;
ignoreOptions: boolean;
options: {
name: string;
value: any;
}[];
positionals: {
value: string;
extra: boolean | typeof NoLimits;
}[];
remainder: string | null;
selectedIndex: number | null;
};
pushPositional: (state: RunState, segment: string) => {
positionals: {
value: string;
extra: boolean | typeof NoLimits;
}[];
candidateUsage: string | null;
errorMessage: string | null;
ignoreOptions: boolean;
options: {
name: string;
value: any;
}[];
path: string[];
remainder: string | null;
selectedIndex: number | null;
};
pushExtra: (state: RunState, segment: string) => {
positionals: {
value: string;
extra: boolean | typeof NoLimits;
}[];
candidateUsage: string | null;
errorMessage: string | null;
ignoreOptions: boolean;
options: {
name: string;
value: any;
}[];
path: string[];
remainder: string | null;
selectedIndex: number | null;
};
pushExtraNoLimits: (state: RunState, segment: string) => {
positionals: {
value: string;
extra: boolean | typeof NoLimits;
}[];
candidateUsage: string | null;
errorMessage: string | null;
ignoreOptions: boolean;
options: {
name: string;
value: any;
}[];
path: string[];
remainder: string | null;
selectedIndex: number | null;
};
pushTrue: (state: RunState, segment: string, name?: string) => {
options: {
name: string;
value: any;
}[];
candidateUsage: string | null;
errorMessage: string | null;
ignoreOptions: boolean;
path: string[];
positionals: {
value: string;
extra: boolean | typeof NoLimits;
}[];
remainder: string | null;
selectedIndex: number | null;
};
pushFalse: (state: RunState, segment: string, name?: string) => {
options: {
name: string;
value: any;
}[];
candidateUsage: string | null;
errorMessage: string | null;
ignoreOptions: boolean;
path: string[];
positionals: {
value: string;
extra: boolean | typeof NoLimits;
}[];
remainder: string | null;
selectedIndex: number | null;
};
pushUndefined: (state: RunState, segment: string) => {
options: {
name: string;
value: any;
}[];
candidateUsage: string | null;
errorMessage: string | null;
ignoreOptions: boolean;
path: string[];
positionals: {
value: string;
extra: boolean | typeof NoLimits;
}[];
remainder: string | null;
selectedIndex: number | null;
};
pushStringValue: (state: RunState, segment: string) => {
options: {
name: string;
value: any;
}[];
candidateUsage: string | null;
errorMessage: string | null;
ignoreOptions: boolean;
path: string[];
positionals: {
value: string;
extra: boolean | typeof NoLimits;
}[];
remainder: string | null;
selectedIndex: number | null;
};
setStringValue: (state: RunState, segment: string) => {
options: {
name: string;
value: any;
}[];
candidateUsage: string | null;
errorMessage: string | null;
ignoreOptions: boolean;
path: string[];
positionals: {
value: string;
extra: boolean | typeof NoLimits;
}[];
remainder: string | null;
selectedIndex: number | null;
};
inhibateOptions: (state: RunState) => {
ignoreOptions: boolean;
candidateUsage: string | null;
errorMessage: string | null;
options: {
name: string;
value: any;
}[];
path: string[];
positionals: {
value: string;
extra: boolean | typeof NoLimits;
}[];
remainder: string | null;
selectedIndex: number | null;
};
useHelp: (state: RunState, segment: string, command: number) => {
options: {
name: string;
value: string;
}[];
candidateUsage: string | null;
errorMessage: string | null;
ignoreOptions: boolean;
path: string[];
positionals: {
value: string;
extra: boolean | typeof NoLimits;
}[];
remainder: string | null;
selectedIndex: number | null;
};
setError: (state: RunState, segment: string, errorMessage: string) => {
errorMessage: string;
candidateUsage: string | null;
ignoreOptions: boolean;
options: {
name: string;
value: any;
}[];
path: string[];
positionals: {
value: string;
extra: boolean | typeof NoLimits;
}[];
remainder: string | null;
selectedIndex: number | null;
};
setOptionArityError: (state: RunState, segment: string) => {
errorMessage: string;
candidateUsage: string | null;
ignoreOptions: boolean;
options: {
name: string;
value: any;
}[];
path: string[];
positionals: {
value: string;
extra: boolean | typeof NoLimits;
}[];
remainder: string | null;
selectedIndex: number | null;
};
}; // ------------------------------------------------------------------------
// ------------------------------------------------------------------------
declare const NoLimits: unique symbol;
type ArityDefinition = {
leading: string[];
extra: string[] | typeof NoLimits;
trailing: string[];
proxy: boolean;
};
type OptDefinition = {
names: string[];
description?: string;
arity: number;
hidden: boolean;
allowBinding: boolean;
};
declare class CommandBuilder<Context> {
readonly cliIndex: number;
readonly cliOpts: Readonly<CliOptions>;
readonly allOptionNames: string[];
readonly arity: ArityDefinition;
readonly options: OptDefinition[];
readonly paths: string[][];
private context?;
constructor(cliIndex: number, cliOpts: CliOptions);
addPath(path: string[]): void;
setArity({ leading, trailing, extra, proxy }: Partial<ArityDefinition>): void;
addPositional({ name, required }?: {
name?: string;
required?: boolean;
}): void;
addRest({ name, required }?: {
name?: string;
required?: number;
}): void;
addProxy({ required }?: {
name?: string;
required?: number;
}): void;
addOption({ names, description, arity, hidden, allowBinding }: Partial<OptDefinition> & {
names: string[];
}): void;
setContext(context: Context): void;
usage({ detailed, inlineOptions }?: {
detailed?: boolean;
inlineOptions?: boolean;
}): {
usage: string;
options: {
definition: string;
description: string;
}[];
};
compile(): {
machine: StateMachine;
context: Context;
};
private registerOptions;
}
type CliOptions = {
binaryName: string;
};
/**
* The base context of the CLI.
*
* All Contexts have to extend it.
*/
type BaseContext = {
/**
* The input stream of the CLI.
*
* @default
* process.stdin
*/
stdin: Readable;
/**
* The output stream of the CLI.
*
* @default
* process.stdout
*/
stdout: Writable;
/**
* The error stream of the CLI.
*
* @default
* process.stderr
*/
stderr: Writable;
};
type CliContext<Context extends BaseContext> = {
commandClass: CommandClass<Context>;
};
type CliOptions$0 = Readonly<{
/**
* The label of the binary.
*
* Shown at the top of the usage information.
*/
binaryLabel?: string;
/**
* The name of the binary.
*
* Included in the path and the examples of the definitions.
*/
binaryName: string;
/**
* The version of the binary.
*
* Shown at the top of the usage information.
*/
binaryVersion?: string;
/**
* If `true`, the Cli will use colors in the output.
*
* @default
* process.env.FORCE_COLOR ?? process.stdout.isTTY
*/
enableColors: boolean;
}>;
type MiniCli<Context extends BaseContext> = CliOptions$0 & {
/**
* Returns an Array representing the definitions of all registered commands.
*/
definitions(): Definition[];
/**
* Formats errors using colors.
*
* @param error The error to format. If `error.name` is `'Error'`, it is replaced with `'Internal Error'`.
* @param opts.command The command whose usage will be included in the formatted error.
*/
error(error: Error, opts?: {
command?: Command<Context> | null;
}): string;
/**
* Compiles a command and its arguments using the `CommandBuilder`.
*
* @param input An array containing the name of the command and its arguments
*
* @returns The compiled `Command`, with its properties populated with the arguments.
*/
process(input: string[]): Command<Context>;
/**
* Runs a command.
*
* @param input An array containing the name of the command and its arguments
* @param context Overrides the Context of the main `Cli` instance
*
* @returns The exit code of the command
*/
run(input: string[], context?: Partial<Context>): Promise<number>;
/**
* Returns the usage of a command.
*
* @param command The `Command` whose usage will be returned or `null` to return the usage of all commands.
* @param opts.detailed If `true`, the usage of a command will also include its description, details, and examples. Doesn't have any effect if `command` is `null` or doesn't have a `usage` property.
* @param opts.prefix The prefix displayed before each command. Defaults to `$`.
*/
usage(command?: CommandClass<Context> | Command<Context> | null, opts?: {
detailed?: boolean;
prefix?: string;
}): string;
};
/**
* @template Context The context shared by all commands. Contexts are a set of values, defined when calling the `run`/`runExit` functions from the CLI instance, that will be made available to the commands via `this.context`.
*/
declare class Cli<Context extends BaseContext = BaseContext> implements MiniCli<Context> {
/**
* The default context of the CLI.
*
* Contains the stdio of the current `process`.
*/
static defaultContext: {
stdin: NodeJS.ReadStream;
stdout: NodeJS.WriteStream;
stderr: NodeJS.WriteStream;
};
private readonly builder;
private readonly registrations;
readonly binaryLabel?: string;
readonly binaryName: string;
readonly binaryVersion?: string;
readonly enableColors: boolean;
/**
* Creates a new Cli and registers all commands passed as parameters.
*
* @param commandClasses The Commands to register
* @returns The created `Cli` instance
*/
static from<Context extends BaseContext = BaseContext>(commandClasses: CommandClass<Context>[], options?: Partial<CliOptions$0>): Cli<Context>;
constructor({ binaryLabel, binaryName: binaryNameOpt, binaryVersion, enableColors }?: Partial<CliOptions$0>);
/**
* Registers a command inside the CLI.
*/
register(commandClass: CommandClass<Context>): void;
process(input: string[]): Command<Context>;
run(input: Command<Context> | string[], context: Context): Promise<number>;
/**
* Runs a command and exits the current `process` with the exit code returned by the command.
*
* @param input An array containing the name of the command and its arguments.
*
* @example
* cli.runExit(process.argv.slice(2), Cli.defaultContext)
*/
runExit(input: Command<Context> | string[], context: Context): Promise<void>;
suggest(input: string[], partial: boolean): string[][];
definitions({ colored }?: {
colored?: boolean;
}): Definition[];
usage(command?: CommandClass<Context> | Command<Context> | null, { colored, detailed, prefix }?: {
colored?: boolean;
detailed?: boolean;
prefix?: string;
}): string;
error(error: Error | any, { colored, command }?: {
colored?: boolean;
command?: Command<Context> | null;
}): string;
private getUsageByRegistration;
private getUsageByIndex;
private format;
}
declare class HelpCommand extends Command {
execute(): Promise<void>;
}
declare class VersionCommand extends Command {
execute(): Promise<void>;
}
type Meta<Context extends BaseContext> = {
definitions: ((command: CommandBuilder<CliContext<Context>>) => void)[];
transformers: ((state: RunState, command: Command<Context>, builder: CommandBuilder<CliContext<Context>>) => void)[];
}; /**
* The usage of a Command.
*/
/**
* The usage of a Command.
*/
type Usage = {
/**
* The category of the command.
*
* Included in the detailed usage.
*/
category?: string;
/**
* The short description of the command, formatted as Markdown.
*
* Included in the detailed usage.
*/
description?: string;
/**
* The extended details of the command, formatted as Markdown.
*
* Included in the detailed usage.
*/
details?: string;
/**
* Examples of the command represented as an Array of tuples.
*
* The first element of the tuple represents the description of the example.
*
* The second element of the tuple represents the command of the example.
* If present, the leading `$0` is replaced with `cli.binaryName`.
*/
examples?: [string, string][];
}; /**
* The definition of a Command.
*/
/**
* The definition of a Command.
*/
type Definition = Usage & {
/**
* The path of the command, starting with `cli.binaryName`.
*/
path: string;
/**
* The detailed usage of the command.
*/
usage: string;
/**
* The various options registered on the command.
*/
options: {
definition: string;
description?: string;
}[];
}; /**
* The schema used to validate the Command instance.
*
* The easiest way to validate it is by using the [Yup](https://github.com/jquense/yup) library.
*
* @example
* yup.object().shape({
* a: yup.number().integer(),
* b: yup.number().integer(),
* })
*/
/**
* The schema used to validate the Command instance.
*
* The easiest way to validate it is by using the [Yup](https://github.com/jquense/yup) library.
*
* @example
* yup.object().shape({
* a: yup.number().integer(),
* b: yup.number().integer(),
* })
*/
type Schema<C extends Command<any>> = {
/**
* A function that takes the `Command` instance as a parameter and validates it, throwing an Error if the validation fails.
*/
validate: (object: C) => void;
};
type CommandClass<Context extends BaseContext = BaseContext> = {
new (): Command<Context>;
resolveMeta(prototype: Command<Context>): Meta<Context>;
schema?: Schema<any>;
usage?: Usage;
};
declare abstract class Command<Context extends BaseContext = BaseContext> {
private static meta?;
static getMeta<Context extends BaseContext>(prototype: Command<Context>): Meta<Context>;
static resolveMeta<Context extends BaseContext>(prototype: Command<Context>): Meta<Context>;
private static registerDefinition;
private static registerTransformer;
static addPath(...path: string[]): void;
static addOption<Context extends BaseContext>(name: string, builder: (prototype: Command<Context>, propertyName: string) => void): void;
/**
* Wrap the specified command to be attached to the given path on the command line.
* The first path thus attached will be considered the "main" one, and all others will be aliases.
* @param path The command path.
*/
static Path(...path: string[]): <Context extends BaseContext>(prototype: Command<Context>, propertyName: string) => void;
/**
* Register a boolean listener for the given option names. When Clipanion detects that this argument is present, the value will be set to false. The value won't be set unless the option is found, so you must remember to set it to an appropriate default value.
* @param descriptor the option names.
*/
static Boolean(descriptor: string, { hidden, description }?: {
hidden?: boolean;
description?: string;
}): <Context extends BaseContext>(prototype: Command<Context>, propertyName: string) => void;
/**
* Register a boolean listener for the given option names. Each time Clipanion detects that this argument is present, the counter will be incremented. Each time the argument is negated, the counter will be reset to `0`. The counter won't be set unless the option is found, so you must remember to set it to an appropriate default value.
* @param descriptor A comma-separated list of option names.
*/
static Counter(descriptor: string, { hidden, description }?: {
hidden?: boolean;
description?: string;
}): <Context extends BaseContext>(prototype: Command<Context>, propertyName: string) => void;
/**
* Register a listener that looks for an option and its followup argument. When Clipanion detects that this argument is present, the value will be set to whatever follows the option in the input. The value won't be set unless the option is found, so you must remember to set it to an appropriate default value.
* Note that all methods affecting positional arguments are evaluated in the definition order; don't mess with it (for example sorting your properties in ascendent order might have adverse results).
* @param descriptor The option names.
*/
static String(descriptor: string, opts?: {
arity?: number;
tolerateBoolean?: boolean;
hidden?: boolean;
description?: string;
}): PropertyDecorator;
/**
* Register a listener that looks for positional arguments. When Clipanion detects that an argument isn't an option, it will put it in this property and continue processing the rest of the command line.
* Note that all methods affecting positional arguments are evaluated in the definition order; don't mess with it (for example sorting your properties in ascendent order might have adverse results).
* @param descriptor Whether or not filling the positional argument is required for the command to be a valid selection.
*/
static String(descriptor?: {
required?: boolean;
name?: string;
}): PropertyDecorator;
/**
* Register a listener that looks for an option and its followup argument. When Clipanion detects that this argument is present, the value will be pushed into the array represented in the property.
*/
static Array(descriptor: string, { arity, hidden, description }?: {
arity?: number;
hidden?: boolean;
description?: string;
}): <Context extends BaseContext>(prototype: Command<Context>, propertyName: string) => void;
/**
* Register a listener that takes all the positional arguments remaining and store them into the selected property.
* Note that all methods affecting positional arguments are evaluated in the definition order; don't mess with it (for example sorting your properties in ascendent order might have adverse results).
*/
static Rest(): PropertyDecorator;
/**
* Register a listener that takes all the positional arguments remaining and store them into the selected property.
* Note that all methods affecting positional arguments are evaluated in the definition order; don't mess with it (for example sorting your properties in ascendent order might have adverse results).
* @param opts.required The minimal number of arguments required for the command to be successful.
*/
static Rest(opts: {
required: number;
}): PropertyDecorator;
/**
* Register a listener that takes all the arguments remaining (including options and such) and store them into the selected property.
* Note that all methods affecting positional arguments are evaluated in the definition order; don't mess with it (for example sorting your properties in ascendent order might have adverse results).
*/
static Proxy({ required }?: {
required?: number;
}): <Context extends BaseContext>(prototype: Command<Context>, propertyName: string) => void;
/**
* Defines the usage information for the given command.
* @param usage
*/
static Usage(usage: Usage): Usage;
/**
* Contains the usage information for the command. If undefined, the command will be hidden from the general listing.
*/
static usage?: Usage;
/**
* Defines the schema for the given command.
* @param schema
*/
static Schema<C extends Command<any> = Command<BaseContext>>(schema: Schema<C>): Schema<C>;
/**
* The schema used to validate the Command instance.
*/
static schema?: Schema<any>;
/**
* Standard command that'll get executed by `Cli#run` and `Cli#runExit`. Expected to return an exit code or nothing (which Clipanion will treat as if 0 had been returned).
*/
abstract execute(): Promise<number | void>;
/**
* Standard error handler which will simply rethrow the error. Can be used to add custom logic to handle errors
* from the command or simply return the parent class error handling.
* @param error
*/
catch(error: any): Promise<void>;
validateAndExecute(): Promise<number>;
/**
* Predefined that will be set to true if `-h,--help` has been used, in which case `Command#execute` shouldn't be called.
*/
help: boolean;
/**
* Predefined variable that will be populated with a miniature API that can be used to query Clipanion and forward commands.
*/
cli: MiniCli<Context>;
/**
* Predefined variable that will be populated with the context of the application.
*/
context: Context;
/**
* The path that got used to access the command being executed.
*/
path: string[];
/**
* A list of useful semi-opinionated command entries that have to be registered manually.
*
* They cover the basic needs of most CLIs (e.g. help command, version command).
*
* @example
* cli.register(Command.Entries.Help);
* cli.register(Command.Entries.Version);
*/
static Entries: {
/**
* A command that prints the usage of all commands.
*
* Paths: `-h`, `--help`
*/
Help: typeof HelpCommand;
/**
* A command that prints the version of the binary (`cli.binaryVersion`).
*
* Paths: `-v`, `--version`
*/
Version: typeof VersionCommand;
};
}
type ErrorMeta = {
type: `none`;
} | {
type: `usage`;
}; /**
* A generic usage error with the name `UsageError`.
*
* It should be used over `Error` only when it's the user's fault.
*/
/**
* A generic usage error with the name `UsageError`.
*
* It should be used over `Error` only when it's the user's fault.
*/
declare class UsageError extends Error {
clipanion: ErrorMeta;
constructor(message: string);
}
export { Command, BaseContext, Cli, CliOptions$0 as CliOptions, CommandClass, Usage, Definition, Schema, UsageError }; | the_stack |
import {SchematicContext, SchematicsException, Tree} from '@angular-devkit/schematics';
import {ProjectType, WorkspaceProject, WorkspaceSchema} from '../../schematics-core/utility/workspace-models';
import {OptionsAfterSetup} from './options-after-setup';
import {xliffmergeBuilderName, xliffmergeBuilderSpec} from './constants';
import {buildConfigurationForLanguage, serveConfigurationForLanguage} from './common-functions';
import {IXliffMergeOptions} from '@ngx-i18nsupport/ngx-i18nsupport';
/**
* Read and edit functionality on angular.json
* It allows multiple changes on angular.json file.
* At the end we call commit() to write angular.json.
*/
export class WorkspaceSnaphot {
private readonly workspace: WorkspaceSchema;
/**
* Create it.
* Read the file angular.json
* @param host host tree
* @param context context (used for logging)
* @throws SchematicsException when angular.json does not exists.
*/
constructor(private host: Tree, private context?: SchematicContext) {
this.workspace = this.readAngularJson();
}
/**
* Commit all changes done on workspace.
* (writes angular.json)
*/
public commit() {
const newAngularJsonContent = JSON.stringify(this.workspace, null, 2);
this.host.overwrite('/angular.json', newAngularJsonContent);
}
/**
* Get project from angular.json.
* @param projectName Name of project
* @throws an exception if angular.json or project does not exist.
*/
public getProjectByName(
projectName: string,
): WorkspaceProject<ProjectType> {
const projects = this.workspace.projects;
if (!projects) {
throw new SchematicsException('angular.json does not contain projects');
}
const project = projects[projectName];
if (!project) {
throw new SchematicsException('angular.json does not contain project ' + projectName);
}
return project;
}
/**
* Return all projects.
*/
public getAllProjects(): {name: string, project: WorkspaceProject<ProjectType>}[] {
return Object.keys(this.workspace.projects).map(projectName => {
return {
name: projectName,
project: this.workspace.projects[projectName]
};
});
}
/**
* Return name of default project.
*/
public getDefaultProjectName(): string|undefined {
return this.workspace.defaultProject;
}
/**
* Add a build configuration to angular.json.
* Configuration is stored under architect.build.configurations
* @param projectName Name of project
* @param configurationName Name of configuration to add
* @param configuration configuration object
*/
public addArchitectBuildConfigurationToProject(
projectName: string,
configurationName: string,
configuration: any) {
return this.addObjectToProjectPath(projectName,
'build configuration',
['architect', 'build', 'configurations'],
configurationName, configuration);
}
/**
* Add a serve configuration to angular.json.
* Configuration is stored under architect.serve.configurations
* @param projectName Name of project
* @param configurationName Name of configuration to add
* @param configuration configuration object
*/
public addArchitectServeConfigurationToProject(
projectName: string,
configurationName: string,
configuration: any) {
return this.addObjectToProjectPath(projectName,
'serve configuration',
['architect', 'serve', 'configurations'],
configurationName, configuration);
}
/**
* Add a builder to angular.json.
* Builder is stored under architect
* @param projectName Name of project
* @param builderName Name of builder to add
* @param builder builder in syntax <class|package>:name
* @param options options
* @param configuration optional configuration object
*/
public addArchitectBuilderToProject(
projectName: string,
builderName: string,
builder: string,
options: any,
configuration?: any) {
const builderSpec: any = {
builder: builder,
options: options
};
if (configuration) {
builderSpec.configuration = configuration;
}
return this.addObjectToProjectPath(projectName,
'architect builder',
['architect'],
builderName, builderSpec);
}
/**
* Add the build and serve configuration for a given language to angular.json.
* @param options options containing project etc.
* @param language the language to be added.
*/
public addLanguageConfigurationToProject(options: OptionsAfterSetup,
language: string) {
this.addArchitectBuildConfigurationToProject(
options.project,
language,
buildConfigurationForLanguage(options, language)
);
if (this.context) {
this.context.logger.info(`added build configuration for language "${language}" to project "${options.project}"`);
}
this.addArchitectServeConfigurationToProject(
options.project,
language,
serveConfigurationForLanguage(options, language)
);
if (this.context) {
this.context.logger.info(`added serve configuration for language "${language}" to project "${options.project}"`);
}
}
/**
* Add the builder configuration for xliffmerge builder to angular.json.
* @param options options containing project etc.
*/
public addBuilderConfigurationToProject(options: OptionsAfterSetup) {
const baseDir = (options.isDefaultProject) ? '' : `projects/${options.project}/`;
const builderOptions = {
xliffmergeOptions: {
i18nFormat: options.i18nFormat,
srcDir: `${baseDir}${options.srcDir}`,
genDir: `${baseDir}${options.genDir}`,
defaultLanguage: options.parsedLanguages[0],
languages: options.parsedLanguages
}
};
this.addArchitectBuilderToProject(
options.project,
xliffmergeBuilderName,
xliffmergeBuilderSpec,
builderOptions
);
if (this.context) {
this.context.logger.info(`added builder xliffmerge to project "${options.project}"`);
}
}
/**
* Read the xliffmerge configuration form the builder options.
* @param projectName name of project
*/
public getActualXliffmergeConfigFromWorkspace(projectName: string)
: {xliffmergeOptions: IXliffMergeOptions, profile?: string} | null {
if (!projectName) {
return null;
}
const project: WorkspaceProject<ProjectType>|null = this.getProjectByName(projectName);
if (!project || !project.architect) {
return null;
}
const xliffmergeBuilder = project.architect['xliffmerge'];
if (!xliffmergeBuilder || !xliffmergeBuilder.options) {
return null;
}
if (xliffmergeBuilder.options && xliffmergeBuilder.options.xliffmergeOptions) {
return xliffmergeBuilder.options;
} else if (xliffmergeBuilder.options.profile) {
// read profile
const content = this.host.read(xliffmergeBuilder.options.profile);
if (!content) {
return null;
}
const contentString = content.toString('UTF-8');
const profileContent = JSON.parse(contentString) as {xliffmergeOptions: IXliffMergeOptions};
return {
xliffmergeOptions: profileContent.xliffmergeOptions,
profile: xliffmergeBuilder.options.profile
};
} else {
return null;
}
}
/**
* (private) Add an object to angular.json.
* Object is stored under path given as parameter.
* @param objectType Type of object, will be shown in log (either a build or serve configuration or a builder)
* @param projectName Name of project
* @param path path in project, like ['architect', 'build', 'configurations']
* @param objectName Name of object to add
* @param objectToAdd object to be added (either a configuration or a builder)
*/
private addObjectToProjectPath(
projectName: string,
objectType: string,
path: string[],
objectName: string,
objectToAdd: any) {
const projects = this.workspace.projects;
if (!projects) {
throw new SchematicsException('angular.json does not contain projects');
}
const project = projects[projectName];
if (!project) {
throw new SchematicsException('angular.json does not contain project ' + projectName);
}
const container = this.getObjectFromProjectUsingPath(projectName, project, path);
const addedOrChanged = (container[objectName]) ? 'changed' : 'added';
container[objectName] = objectToAdd;
if (this.context) {
this.context.logger.info(`${addedOrChanged} ${objectType} ${objectName} to project ${projectName}`);
}
}
/**
* (private) get a special object from project by navigating a path
* Throws an exception if path does not exist.
* @param projectName Name of project.
* @param project the project read from angular.json
* @param path path like ['architect', 'build', 'configurations']
* @return the object at the path position
* @throws SchematicsException if path does not exist.
*/
private getObjectFromProjectUsingPath(projectName: string, project: WorkspaceProject<ProjectType>, path: string[]): any {
let object: any = project;
let currentPath = '';
for (let i = 0; i < path.length; i++) {
currentPath = currentPath + '.' + path[i];
object = object[path[i]];
if (!object) {
throw new SchematicsException('angular.json does not contain ' + currentPath + ' in project ' + projectName);
}
}
return object;
}
/*
private helper function to read angular.json
*/
private readAngularJson(): WorkspaceSchema {
const noAngularJsonMsg = 'file angular.json not found';
if (this.host.exists('/angular.json')) {
const content = this.host.read('/angular.json');
if (!content) {
throw new SchematicsException(noAngularJsonMsg);
}
const sourceText = content.toString('utf-8');
return JSON.parse(sourceText);
} else {
throw new SchematicsException(noAngularJsonMsg);
}
}
} | the_stack |
import * as vs from "vscode";
import { CancellationToken, CompletionContext, CompletionItem, CompletionItemProvider, CompletionList, Position, Range, SnippetString, TextDocument, commands, Hover } from "vscode";
import { getXPath, isAttributeValue, isAttribute, isTagName, isClosingTagName } from "../xmlUtils";
import { PropertyHandlerProvider } from "../../providers/property-handler-provider";
import { PropertyResolver } from "../../resolvers/property-resolver";
import { getDartDocument, getDartCodeIndex } from "../utils";
export class DartCompletionItemProvider implements CompletionItemProvider {
constructor(
private propertyHandlerProvider: PropertyHandlerProvider,
private propertyResolver: PropertyResolver) {
}
public async provideCompletionItems(
document: TextDocument, position: Position,
token: CancellationToken, context: CompletionContext): Promise<CompletionList | undefined> {
let allResults: any[] = [];
if (isTagName(document, position) || isClosingTagName(document, position)) {
allResults = (await this.getTagNameCompletions(document, position, token)).concat(this.getClosingTagNameCompletions(document, position));
}
else if (isAttribute(document, position)) {
allResults = await this.getAttributeCompletions(document, position, token);
}
else if (isAttributeValue(document, position)) {
allResults = await this.getValueCompletions(document, position, token);
}
return new CompletionList(allResults);
}
private async getTagNameCompletions(xmlDocument: TextDocument, xmlPosition: Position, token: CancellationToken): Promise<CompletionItem[]> {
const completions: vs.CompletionItem[] = [];
const line = xmlDocument.lineAt(xmlPosition.line).text.slice(0, xmlPosition.character);
const segments = line.split(/[ <>"']/g);
let tag = segments[segments.length - 1];
const xPath = getXPath(xmlDocument, xmlPosition);
const parentTag = xPath[xPath.length - 1];
const isTopLevelElement = xPath.length === 0;
const isSecondLevelElement = xPath.length === 1;
const isAttributeOrCustomTag = tag.length && /[a-z].*/g.test(tag[0]);
if (isTopLevelElement) {
return [];
}
if (isAttributeOrCustomTag) {
if (isSecondLevelElement) {
return this.getSecondLevelElementCompletions(xmlDocument, xmlPosition);
}
else {
return await this.getAttributeCompletionsForElement(parentTag, true, xmlDocument, xmlPosition, token);
}
}
else if (!tag.length) {
if (isSecondLevelElement) {
completions.push(...await this.getSecondLevelElementCompletions(xmlDocument, xmlPosition));
}
completions.push(...await this.getAttributeCompletionsForElement(parentTag, true, xmlDocument, xmlPosition, token));
}
const dartDocument = await getDartDocument(xmlDocument);
const dartCode = dartDocument.getText();
const buildMethod = 'Widget build(BuildContext context) {';
const dartOffset = dartCode.indexOf(buildMethod) + buildMethod.length;
const nextCharacter = xmlDocument.getText(new Range(xmlPosition, xmlPosition.translate({ characterDelta: 1 })));
const completionList: vs.CompletionList = await this.getCompletionItems(dartDocument, dartOffset);
completionList.items = completionList.items
.filter(a => a.kind == vs.CompletionItemKind.Constructor)
.map(item => {
item.range = null;
item.kind = vs.CompletionItemKind.Property;
item.label = item.label.replace('(…)', '').replace('()', '');
this.createSnippetString(true, item, nextCharacter);
return item;
});
const result = [...completions, ...completionList.items];
return result;
}
private getClosingTagNameCompletions(document: TextDocument, position: Position): CompletionItem[] {
const xPath = getXPath(document, position);
const parentTag = xPath[xPath.length - 1];
const suggestion = new CompletionItem('/' + parentTag);
suggestion.detail = 'Closing tag';
return [suggestion];
}
private async getAttributeCompletions(document: TextDocument, position: Position, token: CancellationToken): Promise<CompletionItem[]> {
const xPath = getXPath(document, position);
const tag = xPath[xPath.length - 1];
const isTopLevelElement = xPath.length === 1;
const isSecondLevelElement = xPath.length === 2;
const isCustomTag = tag.length && /[a-z].*/g.test(tag[0]);
if (isTopLevelElement) {
return await this.getTopLevelElementAttributesCompletions(document, position);
}
if (isCustomTag) {
if (isSecondLevelElement) {
return await this.getSecondLevelElementAttributesCompletions(tag, document, position);
}
return this.getAttributeCompletionsForAttribute(tag, document, position);
}
return await this.getAttributeCompletionsForElement(tag, false, document, position, token);
}
private getUnnamedArgsRange(tag: string, dartDocument: TextDocument, offset: number): number {
const dart = dartDocument.getText();
offset = dart.indexOf(' ' + tag + '(', offset - tag.length - 4);
const pos = dartDocument.positionAt(offset).translate({ lineDelta: 1, characterDelta: 200 });
offset = dartDocument.offsetAt(pos);
return offset;
}
private async getAttributeCompletionsForElement(elementTag: string, isTag: boolean, xmlDocument: TextDocument, xmlPosition: Position, token: CancellationToken): Promise<CompletionItem[]> {
const dartDocument = await getDartDocument(xmlDocument);
const hasUnnamedArgs = !!this.propertyResolver.getUnNamedParameter(elementTag);
const wordRange = xmlDocument.getWordRangeAtPosition(xmlPosition);
let dartOffset = getDartCodeIndex(xmlDocument, xmlPosition, dartDocument, wordRange, false, !!elementTag, hasUnnamedArgs);
if (hasUnnamedArgs) {
dartOffset = this.getUnnamedArgsRange(elementTag, dartDocument, dartOffset);
}
// const line = xmlDocument.lineAt(xmlPosition.line).text.slice(0, xmlPosition.character);
const nextCharacter = xmlDocument.getText(new Range(xmlPosition, xmlPosition.translate({ characterDelta: 200 }))).trim().substr(0, 1);
const completionList: vs.CompletionList = await this.getCompletionItems(dartDocument, dartOffset);
const result = completionList.items
.filter(a => a.kind === vs.CompletionItemKind.Property ||
a.kind === vs.CompletionItemKind.Field ||
a.kind === vs.CompletionItemKind.Variable)
.map(item => {
item.range = null;
item.label = item.label.replace(':', '');
this.createSnippetString(isTag, item, nextCharacter);
return item;
});
return [...result.filter(a => a.kind == vs.CompletionItemKind.Variable), ...(isTag ? this.getWrapperPropertiesElementsCompletionItems(xmlDocument, xmlPosition) : this.getWrapperPropertiesCompletionItems(xmlDocument, xmlPosition))];
}
private getAttributeCompletionsForAttribute(elementTag: string, document: TextDocument, position: Position): vs.CompletionItem[] {
const handlers = this.propertyHandlerProvider.getAll();
const items: vs.CompletionItem[] = [];
Object.keys(handlers)
.filter((k) => handlers[k].isElement && elementTag === k)
.forEach((k) => {
(handlers[k].elementAttributes as any[]).forEach((a) => {
items.push(this.createCustomCompletionItem(document, position, a.name, vs.CompletionItemKind.Variable, false, '="' + a.snippet + '"'));
});
});
return items;
}
private getWrapperPropertiesCompletionItems(document: TextDocument, position: Position): vs.CompletionItem[] {
const handlers = this.propertyHandlerProvider.getAll();
const items = Object.keys(handlers)
.filter((k) => !handlers[k].isElement)
.map((k) => {
return this.createCustomCompletionItem(document, position, k, vs.CompletionItemKind.Variable, false, handlers[k].valueSnippet);
});
return items;
}
private getWrapperPropertiesElementsCompletionItems(document: TextDocument, position: Position): vs.CompletionItem[] {
const handlers = this.propertyHandlerProvider.getAll();
const items = Object.keys(handlers)
.filter((k) => handlers[k].isElement)
.map((k) => {
return this.createCustomCompletionItem(document, position, k, vs.CompletionItemKind.Variable, true, handlers[k].valueSnippet);
});
return items;
}
private getTopLevelElementAttributesCompletions(document: TextDocument, position: Position): vs.CompletionItem[] {
return [
this.createCustomCompletionItem(document, position, 'xmlns', vs.CompletionItemKind.Variable),
this.createCustomCompletionItem(document, position, 'controller', vs.CompletionItemKind.Variable),
this.createCustomCompletionItem(document, position, 'routeAware', vs.CompletionItemKind.Variable),
];
}
private getSecondLevelElementCompletions(document: TextDocument, position: Position): vs.CompletionItem[] {
return [
this.createCustomCompletionItem(document, position, 'provider', vs.CompletionItemKind.Property, true, ' type="$0" name="$1">$2'),
this.createCustomCompletionItem(document, position, 'with', vs.CompletionItemKind.Property, true, ' mixin="$0">$1'),
this.createCustomCompletionItem(document, position, 'var', vs.CompletionItemKind.Property, true, ' name="$0" value="$1">$2'),
this.createCustomCompletionItem(document, position, 'param', vs.CompletionItemKind.Property, true, ' type="$0" name="$1">$2'),
];
}
private getSecondLevelElementAttributesCompletions(elementTag: string, document: TextDocument, position: Position): vs.CompletionItem[] {
const elements: { [name: string]: vs.CompletionItem[] } = {
'provider': [
this.createCustomCompletionItem(document, position, 'type', vs.CompletionItemKind.Variable),
this.createCustomCompletionItem(document, position, 'name', vs.CompletionItemKind.Variable),
],
'with': [
this.createCustomCompletionItem(document, position, 'mixin', vs.CompletionItemKind.Variable),
],
'var': [
this.createCustomCompletionItem(document, position, 'type', vs.CompletionItemKind.Variable),
this.createCustomCompletionItem(document, position, 'name', vs.CompletionItemKind.Variable),
this.createCustomCompletionItem(document, position, 'value', vs.CompletionItemKind.Variable),
],
'param': [
this.createCustomCompletionItem(document, position, 'type', vs.CompletionItemKind.Variable),
this.createCustomCompletionItem(document, position, 'name', vs.CompletionItemKind.Variable),
this.createCustomCompletionItem(document, position, 'required', vs.CompletionItemKind.Variable),
this.createCustomCompletionItem(document, position, 'value', vs.CompletionItemKind.Variable),
this.createCustomCompletionItem(document, position, 'superParamName', vs.CompletionItemKind.Variable),
],
};
return elements[elementTag];
}
private createCustomCompletionItem(document: TextDocument, position: Position, label: string, kind: vs.CompletionItemKind, isTag = false, snippet?: string): vs.CompletionItem {
const nextCharacter = document.getText(new Range(position, position.translate({ characterDelta: 1 })));
const line = document.lineAt(position).text.substring(0, position.character);
const isAttribute = kind === vs.CompletionItemKind.Variable && !isTag;
const bothHasStartingColon = line.substr(line.lastIndexOf(' ', line.length) + 1).startsWith(':') && label.startsWith(':');
label = bothHasStartingColon ? label.substr(1) : label;
const item = new vs.CompletionItem(label, kind);
this.createSnippetString(!isAttribute, item, nextCharacter, snippet);
return item;
}
private createSnippetString(isTag: boolean, item: vs.CompletionItem, nextCharacter: string, snippet: string = null) {
let insertText = '';
let name = item.label;
if (isTag) {
if (name.indexOf('.') !== -1) {
const parts = name.split('.');
name = parts[0];
insertText = name + ' :use="' + parts[1] + '"' + (snippet ? ' ' + snippet : '') + (nextCharacter === '>' ? '' : '>') + (snippet ? '' : '$0');
}
else {
insertText = name + (snippet ? ' ' + snippet : '') + (nextCharacter === '>' ? '' : '>') + (snippet ? '' : '$0');
}
if (nextCharacter !== '>') {
insertText += '</' + name + '>';
}
}
else {
insertText = name + '=' + (snippet ? snippet : '"$0"');
}
item.insertText = new SnippetString(insertText);
}
private async getValueCompletions(xmlDocument: TextDocument, xmlPosition: Position, token: CancellationToken): Promise<CompletionItem[]> {
// Get the attribute name
const wordRange = xmlDocument.getWordRangeAtPosition(xmlPosition);
const wordStart = wordRange ? wordRange.start : xmlPosition;
const wordEnd = wordRange ? wordRange.end : xmlPosition;
const lineRange = new Range(wordStart.line, 0, wordStart.line, wordEnd.character);
const line = xmlDocument.getText(lineRange);
const lineContent = xmlDocument.lineAt(xmlPosition).text;
let after = lineContent.substring(xmlPosition.character, lineContent.indexOf('"', xmlPosition.character));
if (!after) {
after = '"';
}
const before = lineContent.substring(lineContent.lastIndexOf('="', xmlPosition.character), xmlPosition.character);
const assignIndex = lineContent.lastIndexOf('="', xmlPosition.character);
const attrName = lineContent.substring(assignIndex, lineContent.lastIndexOf(' ', assignIndex) + 1).replace(':', '');
// const attrValue = before.replace('="', '') + after;
const attrValue = before.replace('="', '');
// Get the XPath
const xPath = getXPath(xmlDocument, xmlPosition);
const isTopLevelElement = xPath.length === 1;
const isSecondLevelElement = xPath.length === 2;
if (isTopLevelElement) {
return this.getTopLevelAttributeValueCompletions(attrName);
}
if (isSecondLevelElement) {
const tag = xPath[xPath.length - 1];
const isCustomTag = tag.length && /[a-z].*/g.test(tag[0]);
if (isCustomTag) {
return this.getSecondLevelAttributeValueCompletions(tag, attrName);
}
}
const dartDocument = await getDartDocument(xmlDocument);
const cursorPos = line.substr(line.lastIndexOf(attrName + '="') + 2).length - attrName.length - Math.abs(wordEnd.character - xmlPosition.character);
let dartOffset = dartDocument.getText().indexOf(attrName + ': ' + attrValue) + attrName.length + 2 + cursorPos;
if (attrValue.endsWith('ctrl.')) {
dartOffset = dartDocument.getText().indexOf(' ctrl.') + 6;
}
const completionList: vs.CompletionList = await this.getCompletionItems(dartDocument, dartOffset);
return completionList.items.map(item => {
item.range = null;
return item;
});
}
private getTopLevelAttributeValueCompletions(attrName: string): vs.CompletionItem[] {
if (attrName.startsWith('xmlns')) {
// todo get import statments
}
return [];
}
private getSecondLevelAttributeValueCompletions(tag: string, attrName: string): vs.CompletionItem[] {
if (attrName === 'type') {
// todo
}
return [];
}
private async getCompletionItems(dartDocument: vs.TextDocument, dartOffset: number): Promise<CompletionList> {
const triggerCharachter: string = undefined;
const itemResolveCount: number = undefined;
const completionList: CompletionList = await commands.executeCommand('vscode.executeCompletionItemProvider', dartDocument.uri, dartDocument.positionAt(dartOffset), triggerCharachter, itemResolveCount);
return completionList;
}
public async resolveCompletionItem(item: CompletionItem, token: CancellationToken): Promise<CompletionItem | undefined> {
// const itemAny: any = item;
// if (itemAny.dartDocument) {
// let result: Hover[] = await commands.executeCommand('vscode.executeHoverProvider', itemAny.dartDocument.uri, itemAny.dartDocument.positionAt(itemAny.dartOffset));
// result.forEach(a => a.range = null);
// // item. = result[0].contents[0] as any;
// if (result[0] && result[0].contents.length) {
// item.documentation = result[0].contents[1] as any;
// }
// }
// return item;
return new Promise(() => item);
}
} | the_stack |
import * as _ from "lodash";
import * as MongoDB from "mongodb";
import {Changes} from "../Changes";
export class Omnom {
constructor(public options: {
atomicNumbers?: boolean;
} = {}) {
this._changes = {};
}
private _changes: Changes;
get changes(): Changes {
return this._changes;
}
diff(original: number, modified: number): Omnom;
diff(original: [any], modified: any[]): Omnom;
diff(original: MongoDB.ObjectID, modified: MongoDB.ObjectID): Omnom;
diff(original: Object, modified: Object): Omnom;
diff(original: any, modified: any): Omnom {
this.onSomething(original, modified);
return this;
}
static diff(original: number, modified: number, options?: {
atomicNumbers?: boolean;
}): Changes;
static diff(original: [any], modified: any[], options?: {
atomicNumbers?: boolean;
}): Changes;
static diff(original: MongoDB.ObjectID, modified: MongoDB.ObjectID, options?: {
atomicNumbers?: boolean;
}): Changes;
static diff(original: Object, modified: Object, options?: {
atomicNumbers?: boolean;
}): Changes;
static diff(original: any, modified: any, options?: {
atomicNumbers?: boolean;
}): Changes {
return new Omnom(options).diff(original, modified).changes;
}
private onSomething(original: number, modified: number, changePath?: string): void;
private onSomething(original: any[], modified: any[], changePath?: string): void;
private onSomething(original: MongoDB.ObjectID, modified: MongoDB.ObjectID, changePath?: string): void;
private onSomething(original: Object, modified: Object, changePath?: string): void;
private onSomething(original: any, modified: any, changePath?: string): void {
if (changePath) {
if (original === undefined || original === null)
return this.onUndefined(original, modified, changePath);
if (typeof original === "number" && typeof modified === "number")
return this.onNumber(original, modified, changePath);
if (Array.isArray(original) && Array.isArray(modified))
return this.onArray(original, modified, changePath);
if (original instanceof MongoDB.ObjectID && modified instanceof MongoDB.ObjectID)
return this.onObjectID(original, modified, changePath);
if (!_.isPlainObject(original) || !_.isPlainObject(modified))
return this.onScalar(original, modified, changePath);
}
if (!_.isPlainObject(original) || !_.isPlainObject(modified)) {
throw new Error("Unable to perform a diff of a top level object unless it is an object itself. Provide an object to diff or specify the changePath");
}
return this.onObject(original, modified, changePath);
}
private onUndefined(original: undefined|null, modified: any, changePath: string): void {
return <never>(original !== modified) && this.set(changePath, modified);
}
private onNumber(original: number, modified: number, changePath: string): void {
if (original == modified) return;
if (this.options.atomicNumbers) return this.inc(changePath, modified - original);
return this.set(changePath, modified);
}
private onObjectID(original: MongoDB.ObjectID, modified: MongoDB.ObjectID, changePath: string): void {
return <never>!original.equals(modified) && this.set(changePath, modified);
}
private onScalar(original: any, modified: any, changePath: string): void {
return <never>!_.isEqual(original, modified) && this.set(changePath, modified);
}
private onObject(original: { [prop: string]: any }, modified: { [prop: string]: any }, changePath?: string): void {
_.forOwn(modified, (value, key) => {
if (!key) return;
// Handle array diffs in their own special way
if (Array.isArray(value) && Array.isArray(original[key])) this.onArray(original[key], value, this.resolve(changePath, key));
// Otherwise, just keep going
else this.onSomething(original[key], value, this.resolve(changePath, key));
});
// Unset removed properties
_.forOwn(original, (value, key) => {
if (!key) return;
if (modified[key] === undefined) return this.unset(this.resolve(changePath, key));
});
}
private onArray(original: any[], modified: any[], changePath: string): void {
// Check if we can get from original => modified using just pulls
if (original.length > modified.length) {
return this.onSmallerArray(original, modified, changePath);
}
// Check if we can get from original => modified using just pushes
if (original.length < modified.length) {
return this.onLargerArray(original, modified, changePath);
}
// Otherwise, we need to use $set to generate the new array
return this.onSimilarArray(original, modified, changePath);
}
private onSmallerArray(original: any[], modified: any[], changePath: string): void {
let pulls: any[] = [];
let i = 0;
let j = 0;
for (; i < original.length && j < modified.length; i++) {
const equalityDistance = this.almostEqual(original[i], modified[j])
if (equalityDistance == 1) j++;
else if(equalityDistance > 0)
// If we would need to both pull and $set on this array, we have to
// just use the $set operator.
return this.set(changePath, modified);
else pulls.push(original[i]);
}
for (; i < original.length; i++)
pulls.push(original[i]);
if (j === modified.length) {
if (pulls.length === 1) return this.pull(changePath, pulls[0]);
// We can complete using just pulls
return pulls.forEach((pull) => this.pull(changePath, pull));
}
// If we have a smaller target array than our source, we will need to re-create it
// regardless (if we want to do so in a single operation anyway)
return this.set(changePath, modified);
}
private onLargerArray(original: any[], modified: any[], changePath: string): void {
let canPush = true;
for (let i = 0; i < original.length; i++)
if (this.almostEqual(original[i], modified[i]) < 1) {
canPush = false;
break;
}
if (canPush) {
for (let i = original.length; i < modified.length; i++)
this.push(changePath, modified[i]);
return;
}
return this.onSimilarArray(original, modified, changePath);
}
private onSimilarArray(original: any[], modified: any[], changePath: string): void {
// Check how many manipulations would need to be performed, if it's more than half the array size
// then rather re-create the array
let sets: number[] = [];
let partials: number[] = [];
for (let i = 0; i < modified.length; i++) {
let equality = this.almostEqual(original[i], modified[i]);
if (equality === 0) sets.push(i);
else if (equality < 1) partials.push(i);
}
if (sets.length > modified.length / 2)
return this.set(changePath, modified);
for (let i = 0; i < sets.length; i++)
this.set(this.resolve(changePath, sets[i].toString()), modified[sets[i]]);
for (let i = 0; i < partials.length; i++)
this.onSomething(original[partials[i]], modified[partials[i]], this.resolve(changePath, partials[i].toString()));
}
private set(path: string, value: any) {
if (!this.changes.$set)
this.changes.$set = {};
this.changes.$set[path] = value;
}
private unset(path: string) {
if (!this.changes.$unset)
this.changes.$unset = {};
this.changes.$unset[path] = true;
}
private inc(path: string, value: number) {
if (!this.changes.$inc)
this.changes.$inc = {};
this.changes.$inc[path] = value;
}
private push(path: string, value: any) {
if (!this.changes.$push)
this.changes.$push = {};
if (this.changes.$push[path]) {
const change = <{ $each: any[]; }>this.changes.$push[path];
if (change && change.$each)
change.$each.push(value);
else
this.changes.$push[path] = { $each: [change, value] };
} else this.changes.$push[path] = value;
}
private pull(path: string, value: any) {
if (!this.changes.$pull)
this.changes.$pull = {};
if (this.changes.$pullAll && this.changes.$pullAll[path]) {
this.changes.$pullAll[path].push(value);
if (_.keys(this.changes.$pull).length === 0)
delete this.changes.$pull;
return;
}
if (this.changes.$pull[path]) {
this.pullAll(path, [this.changes.$pull[path], value]);
delete this.changes.$pull[path];
if (_.keys(this.changes.$pull).length === 0)
delete this.changes.$pull;
return;
}
this.changes.$pull[path] = value;
}
private pullAll(path: string, values: any[]) {
if (!this.changes.$pullAll)
this.changes.$pullAll = {};
this.changes.$pullAll[path] = values;
}
private resolve(...args: (string|undefined)[]) {
let validArguments: string[] = [];
args.forEach(function (arg) {
if (arg) validArguments.push(arg);
});
return validArguments.join(".");
}
private almostEqual(o1: Object, o2: Object): number;
private almostEqual(o1: any, o2: any): number {
if (!_.isPlainObject(o1) || !_.isPlainObject(o2)) return o1 == o2 ? 1 : 0;
let object1Keys = Object.keys(o1);
let object2Keys = Object.keys(o2);
let commonKeys: string[] = [];
for (let object1KeyIndex = 0; object1KeyIndex < object1Keys.length; object1KeyIndex++)
if (~object2Keys.indexOf(object1Keys[object1KeyIndex])) commonKeys.push(object1Keys[object1KeyIndex]);
let totalKeys = object1Keys.length + object2Keys.length - commonKeys.length;
let keysDifference = totalKeys - commonKeys.length;
let requiredChanges = 0;
for (let i = 0; i < commonKeys.length; i++)
if (this.almostEqual(o1[commonKeys[i]], o2[commonKeys[i]]) < 1) requiredChanges++;
return 1 - (keysDifference / totalKeys) - (requiredChanges / commonKeys.length);
}
} | the_stack |
import { HighlightResult } from 'highlight.js';
/* Utility functions */
function escapeHTML(value: string): string {
return value.replace(/&/gm, '&').replace(/</gm, '<').replace(/>/gm, '>');
}
function tag(node: Node): string {
return node.nodeName.toLowerCase();
}
/* Stream merging */
type NodeEvent = {
event: 'start' | 'stop';
offset: number;
node: Node;
};
export function nodeStream(node: Node): NodeEvent[] {
const result: NodeEvent[] = [];
const nodeStream = (node: Node, offset: number): number => {
for (let child = node.firstChild; child; child = child.nextSibling) {
if (child.nodeType === 3 && child.nodeValue !== null) {
offset += child.nodeValue.length;
} else if (child.nodeType === 1) {
result.push({
event: 'start',
offset: offset,
node: child,
});
offset = nodeStream(child, offset);
// Prevent void elements from having an end tag that would actually
// double them in the output. There are more void elements in HTML
// but we list only those realistically expected in code display.
if (!tag(child).match(/br|hr|img|input/)) {
result.push({
event: 'stop',
offset: offset,
node: child,
});
}
}
}
return offset;
};
nodeStream(node, 0);
return result;
}
export function mergeStreams(original: NodeEvent[], highlighted: NodeEvent[], value: string): string {
let processed = 0;
let result = '';
const nodeStack = [];
function isElement(arg?: unknown): arg is Element {
return arg !== null && (arg as Element)?.attributes !== undefined;
}
function selectStream(): NodeEvent[] {
if (!original.length || !highlighted.length) {
return original.length ? original : highlighted;
}
if (original[0].offset !== highlighted[0].offset) {
return original[0].offset < highlighted[0].offset ? original : highlighted;
}
/*
To avoid starting the stream just before it should stop the order is
ensured that original always starts first and closes last:
if (event1 == 'start' && event2 == 'start')
return original;
if (event1 == 'start' && event2 == 'stop')
return highlighted;
if (event1 == 'stop' && event2 == 'start')
return original;
if (event1 == 'stop' && event2 == 'stop')
return highlighted;
... which is collapsed to:
*/
return highlighted[0].event === 'start' ? original : highlighted;
}
function open(node: Node): void {
if (!isElement(node)) {
throw new Error('Node is not an Element');
}
result += `<${tag(node)} ${Array<Attr>()
.map.call(node.attributes, attr => `${attr.nodeName}="${escapeHTML(attr.value).replace(/"/g, '"')}"`)
.join(' ')}>`;
}
function close(node: Node): void {
result += '</' + tag(node) + '>';
}
function render(event: NodeEvent): void {
(event.event === 'start' ? open : close)(event.node);
}
while (original.length || highlighted.length) {
let stream = selectStream();
result += escapeHTML(value.substring(processed, stream[0].offset));
processed = stream[0].offset;
if (stream === original) {
/*
On any opening or closing tag of the original markup we first close
the entire highlighted node stack, then render the original tag along
with all the following original tags at the same offset and then
reopen all the tags on the highlighted stack.
*/
nodeStack.reverse().forEach(close);
do {
render(stream.splice(0, 1)[0]);
stream = selectStream();
} while (stream === original && stream.length && stream[0].offset === processed);
nodeStack.reverse().forEach(open);
} else {
if (stream[0].event === 'start') {
nodeStack.push(stream[0].node);
} else {
nodeStack.pop();
}
render(stream.splice(0, 1)[0]);
}
}
return result + escapeHTML(value.substr(processed));
}
// https://github.com/hexojs/hexo-util/blob/979873b63a725377c2bd6ad834d790023496130d/lib/highlight.js#L123
export function closeTags(res: HighlightResult): HighlightResult {
const tokenStack = new Array<string>();
res.value = res.value
.split('\n')
.map(line => {
const prepend = tokenStack.map(token => `<span class="${token}">`).join('');
const matches = line.matchAll(/(<span class="(.*?)">|<\/span>)/g);
Array.from(matches).forEach(match => {
if (match[0] === '</span>') tokenStack.shift();
else tokenStack.unshift(match[2]);
});
const append = '</span>'.repeat(tokenStack.length);
return prepend + line + append;
})
.join('\n');
return res;
}
// Sourced from https://github.com/highlightjs/highlight.js/blob/main/SUPPORTED_LANGUAGES.md and
// https://github.com/exercism/v2-website/blob/main/config/initializers/prism.rb#L187-L315
const languagesToExt: { [_: string]: string } = {
'1c': '1c',
abnf: 'abnf',
accesslog: 'accesslog',
as: 'actionscript',
adb: 'ada',
ada: 'ada',
ads: 'ada',
angelscript: 'angelscript',
// asc: 'angelscript',
apache: 'apache',
applescript: 'applescript',
scpt: 'applescript',
arcade: 'arcade',
cpp: 'cpp',
hpp: 'cpp',
arduino: 'arduino',
ino: 'arduino',
armasm: 'armasm',
arm: 'armasm',
xml: 'xml',
html: 'xml',
xhtml: 'xml',
rss: 'xml',
atom: 'xml',
xjb: 'xml',
xsd: 'xml',
xsl: 'xml',
plist: 'xml',
svg: 'xml',
asciidoc: 'asciidoc',
adoc: 'asciidoc',
asc: 'asciidoc',
aspectj: 'aspectj',
ahk: 'autohotkey',
ahkl: 'autohotkey',
au3: 'autoit',
avrasm: 'avrasm',
awk: 'awk',
axapta: 'axapta',
'x++': 'axapta',
bash: 'bash',
sh: 'bash',
zsh: 'bash',
b: 'basic',
bnf: 'bnf',
bf: 'brainfuck',
c: 'c',
h: 'c',
cats: 'c',
idc: 'c',
cal: 'cal',
capnproto: 'capnproto',
capnp: 'capnproto',
ceylon: 'ceylon',
clean: 'clean',
clj: 'clojure',
boot: 'clojure',
cl2: 'clojure',
cljc: 'clojure',
cljs: 'clojure',
'cljs.hl': 'clojure',
cljscm: 'clojure',
cljx: 'clojure',
hic: 'clojure',
'clojure-repl': 'clojure-repl',
cmake: 'cmake',
'cmake.in': 'cmake',
coffee: 'coffeescript',
_coffee: 'coffeescript',
cake: 'coffeescript',
cjsx: 'coffeescript',
iced: 'coffeescript',
cson: 'coffeescript',
coq: 'coq',
cos: 'cos',
cls: 'cos',
crmsh: 'crmsh',
crm: 'crmsh',
pcmk: 'crmsh',
cr: 'crystal',
cs: 'csharp',
csx: 'csharp',
csp: 'csp',
css: 'css',
d: 'd',
di: 'd',
md: 'markdown',
markdown: 'markdown',
mdown: 'markdown',
mdwn: 'markdown',
mkd: 'markdown',
mkdn: 'markdown',
mkdown: 'markdown',
ronn: 'markdown',
workbook: 'markdown',
dart: 'dart',
dpr: 'delphi',
dfm: 'delphi',
pas: 'delphi',
pascal: 'delphi',
diff: 'diff',
patch: 'diff',
django: 'django',
jinja: 'django',
dns: 'dns',
zone: 'dns',
bind: 'dns',
dockerfile: 'dockerfile',
docker: 'dockerfile',
dos: 'dos',
bat: 'dos',
cmd: 'dos',
dsconfig: 'dsconfig',
dts: 'dts',
dust: 'dust',
dst: 'dust',
ebnf: 'ebnf',
ex: 'elixir',
exs: 'elixir',
elm: 'elm',
rb: 'ruby',
builder: 'ruby',
eye: 'ruby',
gemspec: 'ruby',
god: 'ruby',
jbuilder: 'ruby',
mspec: 'ruby',
pluginspec: 'ruby',
podspec: 'ruby',
rabl: 'ruby',
rake: 'ruby',
rbuild: 'ruby',
rbw: 'ruby',
rbx: 'ruby',
ru: 'ruby',
ruby: 'ruby',
spec: 'ruby',
thor: 'ruby',
watchr: 'ruby',
erb: 'erb',
'erlang-repl': 'erlang-repl',
erl: 'erlang',
'app.src': 'erlang',
escript: 'erlang',
hrl: 'erlang',
xrl: 'erlang',
yrl: 'erlang',
excel: 'excel',
xls: 'excel',
xlsx: 'excel',
fix: 'fix',
flix: 'flix',
f90: 'fortran',
f: 'fortran',
f03: 'fortran',
f08: 'fortran',
f77: 'fortran',
f95: 'fortran',
for: 'fortran',
fpp: 'fortran',
fs: 'fsharp',
fsx: 'fsharp',
gams: 'gams',
gms: 'gams',
gauss: 'gauss',
gss: 'gauss',
gcode: 'gcode',
nc: 'gcode',
gherkin: 'gherkin',
glsl: 'glsl',
fp: 'glsl',
frag: 'glsl',
frg: 'glsl',
fsh: 'glsl',
fshader: 'glsl',
geo: 'glsl',
geom: 'glsl',
glslv: 'glsl',
gshader: 'glsl',
shader: 'glsl',
tesc: 'glsl',
tese: 'glsl',
vert: 'glsl',
vrx: 'glsl',
vsh: 'glsl',
vshader: 'glsl',
gml: 'gml',
go: 'go',
bal: 'go',
golo: 'golo',
gololang: 'golo',
gradle: 'gradle',
groovy: 'groovy',
grt: 'groovy',
gtpl: 'groovy',
gvy: 'groovy',
haml: 'haml',
'haml.deface': 'haml',
handlebars: 'handlebars',
hbs: 'handlebars',
'html.hbs': 'handlebars',
'html.handlebars': 'handlebars',
hs: 'haskell',
hsc: 'haskell',
idr: 'haskell',
purs: 'haskell',
hx: 'haxe',
hxsl: 'haxe',
hsp: 'hsp',
htmlbars: 'htmlbars',
http: 'http',
https: 'http',
hy: 'hy',
inform7: 'inform7',
i7: 'inform7',
ini: 'ini',
toml: 'ini',
cfg: 'ini',
prefs: 'ini',
// properties: 'ini',
irpf90: 'irpf90',
isbl: 'isbl',
java: 'java',
jsp: 'java',
js: 'javascript',
jsx: 'javascript',
_js: 'javascript',
bones: 'javascript',
es: 'javascript',
es6: 'javascript',
gs: 'javascript',
jake: 'javascript',
jsb: 'javascript',
jscad: 'javascript',
jsfl: 'javascript',
jsm: 'javascript',
jss: 'javascript',
mjs: 'javascript',
njs: 'javascript',
pac: 'javascript',
sjs: 'javascript',
ssjs: 'javascript',
xsjs: 'javascript',
xsjslib: 'javascript',
cfc: 'javascript',
'jboss-cli': 'jboss-cli',
json: 'json',
avsc: 'json',
geojson: 'json',
gltf: 'json',
'JSON-tmLanguage': 'json',
jsonl: 'json',
tfstate: 'json',
'tfstate.backup': 'json',
topojson: 'json',
webapp: 'json',
webmanifest: 'json',
jl: 'julia',
'julia-repl': 'julia-repl',
kt: 'kotlin',
ktm: 'kotlin',
kts: 'kotlin',
lasso: 'lasso',
// ls: 'lasso',
lassoscript: 'lasso',
tex: 'latex',
ldif: 'ldif',
leaf: 'leaf',
less: 'less',
lisp: 'lisp',
factor: 'lisp',
livecodeserver: 'livecodeserver',
ls: 'livescript',
_ls: 'livescript',
llvm: 'llvm',
lsl: 'lsl',
lua: 'lua',
nse: 'lua',
p8: 'lua',
pd_lua: 'lua',
rbxs: 'lua',
wlua: 'lua',
mak: 'makefile',
make: 'makefile',
mk: 'makefile',
mkfile: 'makefile',
mathematica: 'mathematica',
mma: 'mathematica',
wl: 'mathematica',
matlab: 'matlab',
maxima: 'maxima',
mel: 'mel',
mercury: 'mercury',
mipsasm: 'mipsasm',
miz: 'mizar',
voc: 'mizar',
al: 'perl',
cgi: 'perl',
fcgi: 'perl',
perl: 'perl',
ph: 'perl',
plx: 'perl',
pl: 'perl',
pm: 'perl',
psgi: 'perl',
t: 'perl',
mojolicious: 'mojolicious',
monkey: 'monkey',
monkey2: 'monkey',
moonscript: 'moonscript',
moon: 'moonscript',
n1ql: 'n1ql',
nginxconf: 'nginx',
nim: 'nim',
nimrod: 'nim',
nix: 'nix',
nsi: 'nsis',
nsh: 'nsis',
m: 'objectivec',
objc: 'objectivec',
mm: 'objectivec',
'obj-c': 'objectivec',
'obj-c++': 'objectivec',
'objective-c++': 'objectivec',
fun: 'ocaml',
sig: 'ocaml',
// sml: 'ocaml',
ml: 'ocaml',
mli: 'ocaml',
eliom: 'ocaml',
eliomi: 'ocaml',
ml4: 'ocaml',
mll: 'ocaml',
mly: 'ocaml',
openscad: 'openscad',
oxygene: 'oxygene',
parser3: 'parser3',
pf: 'pf',
'pf.conf': 'pf',
pgsql: 'pgsql',
postgres: 'pgsql',
postgresql: 'pgsql',
php: 'php',
aw: 'php',
ctp: 'php',
inc: 'php',
php3: 'php',
php4: 'php',
php5: 'php',
phps: 'php',
phpt: 'php',
'php-template': 'php-template',
plaintext: 'plaintext',
txt: 'plaintext',
text: 'plaintext',
pony: 'pony',
ps: 'powershell',
ps1: 'powershell',
psd1: 'powershell',
psm1: 'powershell',
pde: 'processing',
profile: 'profile',
pro: 'prolog',
prolog: 'prolog',
yap: 'prolog',
properties: 'properties',
proto: 'protobuf',
puppet: 'puppet',
pp: 'puppet',
purebasic: 'purebasic',
py: 'python',
bzl: 'python',
gyp: 'python',
gypi: 'python',
lmi: 'python',
py3: 'python',
pyde: 'python',
pyi: 'python',
pyp: 'python',
pyt: 'python',
pyw: 'python',
rpy: 'python',
tac: 'python',
wsgi: 'python',
xpy: 'python',
'python-repl': 'python-repl',
pycon: 'python-repl',
q: 'q',
k: 'q',
kdb: 'q',
qml: 'qml',
r: 'r',
rd: 'r',
rsx: 'r',
reasonml: 'reasonml',
re: 'reasonml',
rib: 'rib',
roboconf: 'roboconf',
graph: 'roboconf',
instances: 'roboconf',
routeros: 'routeros',
rsl: 'rsl',
ruleslanguage: 'ruleslanguage',
rs: 'rust',
'rs.in': 'rust',
sas: 'sas',
// pony: 'scala',
scala: 'scala',
kojo: 'scala',
sbt: 'scala',
sc: 'scala',
scm: 'scheme',
sch: 'scheme',
sld: 'scheme',
sls: 'scheme',
sps: 'scheme',
ss: 'scheme',
rkt: 'scheme',
scilab: 'scilab',
scss: 'scss',
shell: 'shell',
smali: 'smali',
st: 'smalltalk',
sml: 'sml',
sqf: 'sqf',
sql: 'sql',
cql: 'sql',
ddl: 'sql',
mysql: 'sql',
prc: 'sql',
tab: 'sql',
udf: 'sql',
viw: 'sql',
stan: 'stan',
stanfuncs: 'stan',
stata: 'stata',
step21: 'step21',
step: 'step21',
stp: 'step21',
styl: 'stylus',
subunit: 'subunit',
swift: 'swift',
taggerscript: 'taggerscript',
yml: 'yaml',
mir: 'yaml',
reek: 'yaml',
rviz: 'yaml',
'sublime-syntax': 'yaml',
syntax: 'yaml',
yaml: 'yaml',
'yaml-tmlanguage': 'yaml',
'yml.mysql': 'yaml',
tap: 'tap',
tcl: 'tcl',
adp: 'tcl',
tm: 'tcl',
thrift: 'thrift',
tp: 'tp',
twig: 'twig',
craftcms: 'twig',
ts: 'typescript',
tsx: 'typescript',
vala: 'vala',
vbnet: 'vbnet',
vb: 'vbnet',
vbscript: 'vbscript',
vbs: 'vbscript',
'vbscript-html': 'vbscript-html',
v: 'verilog',
veo: 'verilog',
vhdl: 'vhdl',
vhd: 'vhdl',
vhf: 'vhdl',
vhi: 'vhdl',
vho: 'vhdl',
vhs: 'vhdl',
vht: 'vhdl',
vhw: 'vhdl',
vim: 'vim',
x86asm: 'x86asm',
xl: 'xl',
xquery: 'xquery',
xpath: 'xquery',
xq: 'xquery',
zephir: 'zephir',
zep: 'zephir',
};
export function getLanguage(fileExtension: string): string {
return languagesToExt[fileExtension] ?? 'plaintext';
} | the_stack |
import { LogTypes, StorageTypes } from '@requestnetwork/types';
import Utils from '@requestnetwork/utils';
import * as Bluebird from 'bluebird';
import { EventEmitter } from 'events';
import { getIpfsExpectedBootstrapNodes, getMaxConcurrency, getPinRequestConfig } from './config';
import ethereumEntriesToIpfsContent from './ethereum-entries-to-ipfs-content';
import EthereumMetadataCache from './ethereum-metadata-cache';
import IgnoredDataIds from './ignored-dataIds';
import IpfsManager from './ipfs-manager';
import SmartContractManager from './smart-contract-manager';
import * as Keyv from 'keyv';
// time to wait before considering the web3 provider is not reachable
const WEB3_PROVIDER_TIMEOUT = 10000;
/**
* EthereumStorage
* @notice Manages storage layer of the Request Network Protocol v2
*/
export default class EthereumStorage implements StorageTypes.IStorage {
/**
* Manager for the storage smart contract
* This attribute is left public for mocking purpose to facilitate tests on the module
*/
public smartContractManager: SmartContractManager;
/**
* Manager for IPFS
* This attribute is left public for mocking purpose to facilitate tests on the module
*/
public ipfsManager: IpfsManager;
/**
* Cache to store Ethereum metadata
*/
public ethereumMetadataCache: EthereumMetadataCache;
/** Data ids ignored by the node */
public ignoredDataIds: IgnoredDataIds;
/**
* Maximum number of concurrent calls
*/
public maxConcurrency: number;
/**
* Timestamp of the dataId not mined on ethereum yet
*/
private buffer: { [id: string]: number | undefined };
/**
* Url where can be reached the data buffered by this storage
*/
private externalBufferUrl: string;
/**
* Logger instance
*/
private logger: LogTypes.ILogger;
private isInitialized = false;
/**
* Constructor
* @param ipfsGatewayConnection Information structure to connect to the ipfs gateway
* @param web3Connection Information structure to connect to the Ethereum network
* @param [options.getLastBlockNumberDelay] the minimum delay to wait between fetches of lastBlockNumber
* @param metadataStore a Keyv store to persist the metadata in ethereumMetadataCache
*/
public constructor(
externalBufferUrl: string,
ipfsGatewayConnection?: StorageTypes.IIpfsGatewayConnection,
web3Connection?: StorageTypes.IWeb3Connection,
{
getLastBlockNumberDelay,
logger,
maxConcurrency,
maxRetries,
retryDelay,
}: {
getLastBlockNumberDelay?: number;
logger?: LogTypes.ILogger;
maxConcurrency?: number;
maxRetries?: number;
retryDelay?: number;
} = {},
metadataStore?: Keyv.Store<any>,
) {
this.maxConcurrency = maxConcurrency || getMaxConcurrency();
this.logger = logger || new Utils.SimpleLogger();
this.ipfsManager = new IpfsManager(ipfsGatewayConnection);
this.smartContractManager = new SmartContractManager(web3Connection, {
getLastBlockNumberDelay,
logger: this.logger,
maxConcurrency: this.maxConcurrency,
maxRetries,
retryDelay,
});
this.ethereumMetadataCache = new EthereumMetadataCache(
this.smartContractManager,
metadataStore,
);
this.ignoredDataIds = new IgnoredDataIds(metadataStore);
this.buffer = {};
this.externalBufferUrl = externalBufferUrl;
}
/**
* Function to initialize the storage
* Checks the connection with ipfs
* Checks the connection with Ethereum
* Adds the known IPFS node (ipfs swarm connect)
*/
public async initialize(): Promise<void> {
if (this.isInitialized) {
throw new Error('ethereum-storage is already initialized');
}
// check ethereum node connection - will throw if the ethereum node is not reachable
this.logger.info('Checking ethereum node connection', ['ethereum', 'sanity']);
try {
await this.smartContractManager.checkWeb3ProviderConnection(WEB3_PROVIDER_TIMEOUT);
} catch (error) {
throw Error(`Ethereum node is not accessible: ${error}`);
}
// check if contracts are deployed on ethereum
this.logger.info('Checking ethereum node contract deployment', ['ethereum', 'sanity']);
try {
await this.smartContractManager.checkContracts();
} catch (error) {
throw Error(error);
}
// Check IPFS node state - will throw in case of error
await this.checkIpfsNode();
this.isInitialized = true;
}
/**
* Update gateway connection information and connect to the new gateway
* Missing value are filled with default config value
* @param ipfsConnection Information structure to connect to the ipfs gateway
*/
public async updateIpfsGateway(
ipfsGatewayConnection: StorageTypes.IIpfsGatewayConnection,
): Promise<void> {
this.ipfsManager = new IpfsManager(ipfsGatewayConnection);
// Check IPFS node state - will throw in case of error
await this.checkIpfsNode();
}
/**
* Update Ethereum network connection information and reconnect
* Missing value are filled with default config value
* @param web3Connection Information structure to connect to the Ethereum network
*/
public async updateEthereumNetwork(web3Connection: StorageTypes.IWeb3Connection): Promise<void> {
this.smartContractManager = new SmartContractManager(web3Connection);
// check ethereum node connection - will throw if the ethereum node is not reachable
try {
await this.smartContractManager.checkWeb3ProviderConnection(WEB3_PROVIDER_TIMEOUT);
} catch (error) {
throw Error(`Ethereum node is not accessible: ${error}`);
}
}
/**
* Append content into the storage: add the content to ipfs and the hash on Ethereum
* @param content Content to add into the storage
* @returns Promise resolving id used to retrieve the content
*/
public async append(content: string): Promise<StorageTypes.IAppendResult> {
if (!this.isInitialized) {
throw new Error('Ethereum storage must be initialized');
}
if (!content) {
throw Error('No content provided');
}
// Add content to IPFS and get the hash back
let ipfsHash: string;
try {
ipfsHash = await this.ipfsManager.add(content);
} catch (error) {
throw Error(`Ipfs add request error: ${error}`);
}
// Get content length from ipfs
let contentSize: number;
try {
contentSize = await this.ipfsManager.getContentLength(ipfsHash);
} catch (error) {
throw Error(`Ipfs get length request error: ${error}`);
}
const timestamp = Utils.getCurrentTimestampInSecond();
const result: StorageTypes.IAppendResult = Object.assign(new EventEmitter(), {
content,
id: ipfsHash,
meta: {
ipfs: { size: contentSize },
local: { location: this.externalBufferUrl },
state: StorageTypes.ContentState.PENDING,
storageType: StorageTypes.StorageSystemType.LOCAL,
timestamp,
},
});
// store in the buffer the timestamp
this.buffer[ipfsHash] = timestamp;
const feesParameters: StorageTypes.IFeesParameters = { contentSize };
this.smartContractManager
.addHashAndSizeToEthereum(ipfsHash, feesParameters)
.then(async (ethereumMetadata: StorageTypes.IEthereumMetadata) => {
const resultAfterBroadcast: StorageTypes.IEntry = {
content,
id: ipfsHash,
meta: {
ethereum: ethereumMetadata,
ipfs: { size: contentSize },
state: StorageTypes.ContentState.CONFIRMED,
storageType: StorageTypes.StorageSystemType.ETHEREUM_IPFS,
timestamp: ethereumMetadata.blockTimestamp,
},
};
// Save the metadata of the new ipfsHash into the Ethereum metadata cache
await this.ethereumMetadataCache.saveDataIdMeta(ipfsHash, ethereumMetadata);
result.emit('confirmed', resultAfterBroadcast);
})
.catch((error) => {
result.emit('error', error);
});
return result;
}
/**
* Add the content to ipfs
* To be used only in case of persisting the hash on ethereum outside the storage
*
* @param content Content to add into the storage
* @returns Promise resolving id used to retrieve the content
*/
public async _ipfsAdd(data: string): Promise<StorageTypes.IIpfsMeta> {
if (!this.isInitialized) {
throw new Error('Ethereum storage must be initialized');
}
if (!data) {
throw Error('No data provided');
}
// Add a small check to at least having JSON data added
try {
JSON.parse(data);
} catch (error) {
throw Error(`data not JSON parsable: ${error}`);
}
// Add content to IPFS and get the hash back
let ipfsHash;
try {
ipfsHash = await this.ipfsManager.add(data);
} catch (error) {
throw Error(`Ipfs add request error: ${error}`);
}
// Get content length from ipfs
let ipfsSize;
try {
ipfsSize = await this.ipfsManager.getContentLength(ipfsHash);
} catch (error) {
throw new Error(`Ipfs get length request error: ${error}`);
}
return {
ipfsHash,
ipfsSize,
};
}
/**
* Read content from the storage
* @param Id Id used to retrieve content
* @returns Promise resolving content from id
*/
public async read(id: string): Promise<StorageTypes.IEntry> {
if (!this.isInitialized) {
throw new Error('Ethereum storage must be initialized');
}
if (!id) {
throw Error('No id provided');
}
// Get Ethereum metadata
let ethereumMetadata;
let bufferTimestamp: number | undefined;
let ipfsObject;
try {
// Check if the data as been added on ethereum
ethereumMetadata = await this.ethereumMetadataCache.getDataIdMeta(id);
// Clear buffer if needed
if (this.buffer[id]) {
this.buffer[id] = undefined;
}
} catch (error) {
// if not found, check the buffer
bufferTimestamp = this.buffer[id];
if (!bufferTimestamp) {
throw Error('No content found from this id');
}
}
// Send ipfs request
try {
ipfsObject = await this.ipfsManager.read(id);
} catch (error) {
throw Error(`Ipfs read request error: ${error}`);
}
const meta = ethereumMetadata
? {
ethereum: ethereumMetadata,
ipfs: { size: ipfsObject.ipfsSize },
state: StorageTypes.ContentState.CONFIRMED,
storageType: StorageTypes.StorageSystemType.ETHEREUM_IPFS,
timestamp: ethereumMetadata.blockTimestamp,
}
: {
ipfs: { size: ipfsObject.ipfsSize },
local: { location: this.externalBufferUrl },
state: StorageTypes.ContentState.PENDING,
storageType: StorageTypes.StorageSystemType.LOCAL,
timestamp: bufferTimestamp || 0,
};
return {
content: ipfsObject.content,
id,
meta,
};
}
/**
* Read a list of content from the storage
*
* @param dataIds A list of dataIds used to retrieve the content
* @returns Promise resolving the list of contents
*/
public async readMany(dataIds: string[]): Promise<StorageTypes.IEntry[]> {
const totalCount = dataIds.length;
// Concurrently get all the content from the id's in the parameters
return Bluebird.map(
dataIds,
async (dataId, currentIndex) => {
const startTime = Date.now();
const data = await this.read(dataId);
this.logger.debug(
`[${currentIndex + 1}/${totalCount}] read ${dataId}. Took ${Date.now() - startTime} ms`,
['read'],
);
return data;
},
{
concurrency: this.maxConcurrency,
},
);
}
/**
* Get all data stored on the storage
*
* @param options timestamp boundaries for the data retrieval
* @returns Promise resolving stored data
*/
public async getData(
options?: StorageTypes.ITimestampBoundaries,
): Promise<StorageTypes.IEntriesWithLastTimestamp> {
const contentDataIdAndMeta = await this.getContentAndDataId(options);
return contentDataIdAndMeta;
}
/**
* Try to get some previous ignored data
*
* @param options timestamp boundaries for the data retrieval
* @returns Promise resolving stored data
*/
public async getIgnoredData(): Promise<StorageTypes.IEntry[]> {
if (!this.isInitialized) {
throw new Error('Ethereum storage must be initialized');
}
this.logger.info('Getting some previous ignored dataIds', ['ethereum']);
const ethereumEntries: StorageTypes.IEthereumEntry[] = await this.ignoredDataIds.getDataIdsToRetry();
// If no hash was found on ethereum, we return an empty list
if (!ethereumEntries.length) {
this.logger.info('No new data found.', ['ethereum']);
return [];
}
this.logger.debug('Fetching data from IPFS and checking correctness', ['ipfs']);
const entries = await ethereumEntriesToIpfsContent(
ethereumEntries,
this.ipfsManager,
this.ignoredDataIds,
this.logger,
this.maxConcurrency,
);
const ids = entries.map((entry) => entry.id) || [];
// Pin data asynchronously
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.pinDataToIPFS(ids);
// Save existing ethereum metadata to the ethereum metadata cache
for (const entry of entries) {
const ethereumMetadata = entry.meta.ethereum;
if (ethereumMetadata) {
// PROT-504: The saving of dataId's metadata should be encapsulated when retrieving dataId inside smart contract (getPastEvents)
await this.ethereumMetadataCache.saveDataIdMeta(entry.id, ethereumMetadata);
}
}
return entries;
}
/**
* Pin an array of IPFS hashes
*
* @param hashes An array of IPFS hashes to pin
*/
public async pinDataToIPFS(
hashes: string[],
{
delayBetweenCalls,
maxSize,
timeout,
}: StorageTypes.IPinRequestConfiguration = getPinRequestConfig(),
): Promise<void> {
// How many slices we need from the total list of hashes to be under pinRequestMaxSize
const slices = Math.ceil(hashes.length / maxSize);
// Iterate over the hashes list, slicing it at pinRequestMaxSize sizes and pinning it
for (let i = 0; i < slices; i++) {
await new Promise<void>((res): NodeJS.Timeout => setTimeout(() => res(), delayBetweenCalls));
const slice = hashes.slice(i * maxSize, (i + 1) * maxSize);
try {
await this.ipfsManager.pin(slice, timeout);
this.logger.debug(`Pinned ${slice.length} hashes to IPFS node.`);
} catch (error) {
this.logger.warn(`Failed pinning some hashes the IPFS node: ${error}`, ['ipfs']);
}
}
}
/**
* Get Information on the dataIds retrieved and ignored by the ethereum storage
*
* @param detailed if true get the list of the files hash
* @returns Promise resolving object with dataIds retrieved and ignored
*/
public async _getStatus(detailed = false): Promise<any> {
const dataIds = await this.ethereumMetadataCache.getDataIds();
const dataIdsWithReason = await this.ignoredDataIds.getDataIdsWithReasons();
const ethereum = this.smartContractManager.getConfig();
const ipfs = await this.ipfsManager.getConfig();
return {
dataIds: {
count: dataIds.length,
values: detailed ? dataIds : undefined,
},
ethereum,
ignoredDataIds: {
count: Object.keys(dataIdsWithReason).length,
values: detailed ? dataIdsWithReason : undefined,
},
ipfs,
};
}
/**
* Get all dataId and the contents stored on the storage
*
* @param options timestamp boundaries for the data id retrieval
* @returns Promise resolving object with content and dataId of stored data
*/
private async getContentAndDataId(
options?: StorageTypes.ITimestampBoundaries,
): Promise<StorageTypes.IEntriesWithLastTimestamp> {
if (!this.isInitialized) {
throw new Error('Ethereum storage must be initialized');
}
this.logger.info('Fetching dataIds from Ethereum', ['ethereum']);
const {
ethereumEntries,
lastTimestamp,
} = await this.smartContractManager.getEntriesFromEthereum(options);
// If no hash was found on ethereum, we return an empty list
if (!ethereumEntries.length) {
this.logger.info('No new data found.', ['ethereum']);
return {
entries: [],
lastTimestamp,
};
}
this.logger.debug('Fetching data from IPFS and checking correctness', ['ipfs']);
const entries = await ethereumEntriesToIpfsContent(
ethereumEntries,
this.ipfsManager,
this.ignoredDataIds,
this.logger,
this.maxConcurrency,
);
const ids = entries.map((entry) => entry.id) || [];
// Pin data asynchronously
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.pinDataToIPFS(ids);
// Save existing ethereum metadata to the ethereum metadata cache
for (const entry of entries) {
const ethereumMetadata = entry.meta.ethereum;
if (ethereumMetadata) {
// PROT-504: The saving of dataId's metadata should be encapsulated when retrieving dataId inside smart contract (getPastEvents)
await this.ethereumMetadataCache.saveDataIdMeta(entry.id, ethereumMetadata);
}
}
return {
entries,
lastTimestamp,
};
}
/**
* Verify the ipfs node (connectivity and network)
* Check if the node is reachable and if the list of bootstrap nodes is correct
*
* @returns nothing but throw if the ipfs node is not reachable or in the wrong network
*/
private async checkIpfsNode(): Promise<void> {
// check ipfs connection - will throw in case of error
this.logger.info('Checking ipfs connection', ['ipfs', 'sanity']);
try {
await this.ipfsManager.getIpfsNodeId();
} catch (error) {
throw Error(`IPFS node is not accessible or corrupted: ${error}`);
}
// check if the ipfs node is in the request network private network - will throw in case of error
this.logger.info('Checking ipfs network', ['ipfs', 'sanity']);
try {
const bootstrapList = await this.ipfsManager.getBootstrapList();
const bootstrapNodeFoundCount: number = getIpfsExpectedBootstrapNodes().filter(
(nodeExpected) => bootstrapList.includes(nodeExpected),
).length;
if (bootstrapNodeFoundCount !== getIpfsExpectedBootstrapNodes().length) {
throw Error(
`The list of bootstrap node in the ipfs config don't match the expected bootstrap nodes`,
);
}
} catch (error) {
throw Error(`IPFS node bootstrap node check failed: ${error}`);
}
}
} | the_stack |
import * as promiseLimit from 'promise-limit';
import config from '../../../config';
import Resolver from '../resolver';
import { resolveImage } from './image';
import { isCollectionOrOrderedCollection, isCollection, IPerson } from '../type';
import { DriveFile } from '../../../models/entities/drive-file';
import { fromHtml } from '../../../mfm/fromHtml';
import { URL } from 'url';
import { resolveNote, extractEmojis } from './note';
import { registerOrFetchInstanceDoc } from '../../../services/register-or-fetch-instance-doc';
import { ITag, extractHashtags } from './tag';
import { IIdentifier } from './identifier';
import { apLogger } from '../logger';
import { Note } from '../../../models/entities/note';
import { updateHashtag } from '../../../services/update-hashtag';
import { Users, UserNotePinings, Instances, DriveFiles, Followings, UserProfiles, UserPublickeys } from '../../../models';
import { User, IRemoteUser } from '../../../models/entities/user';
import { Emoji } from '../../../models/entities/emoji';
import { UserNotePining } from '../../../models/entities/user-note-pinings';
import { genId } from '../../../misc/gen-id';
import { instanceChart, usersChart } from '../../../services/chart';
import { UserPublickey } from '../../../models/entities/user-publickey';
import { isDuplicateKeyValueError } from '../../../misc/is-duplicate-key-value-error';
import { toPuny } from '../../../misc/convert-host';
import { UserProfile } from '../../../models/entities/user-profile';
import { validActor } from '../../../remote/activitypub/type';
import { getConnection } from 'typeorm';
import { ensure } from '../../../prelude/ensure';
const logger = apLogger;
/**
* Validate Person object
* @param x Fetched person object
* @param uri Fetch target URI
*/
function validatePerson(x: any, uri: string) {
const expectHost = toPuny(new URL(uri).hostname);
if (x == null) {
return new Error('invalid person: object is null');
}
if (!validActor.includes(x.type)) {
return new Error(`invalid person: object is not a person or service '${x.type}'`);
}
if (typeof x.preferredUsername !== 'string') {
return new Error('invalid person: preferredUsername is not a string');
}
if (typeof x.inbox !== 'string') {
return new Error('invalid person: inbox is not a string');
}
if (!Users.validateUsername(x.preferredUsername, true)) {
return new Error('invalid person: invalid username');
}
if (!Users.isValidName(x.name == '' ? null : x.name)) {
return new Error('invalid person: invalid name');
}
if (typeof x.id !== 'string') {
return new Error('invalid person: id is not a string');
}
const idHost = toPuny(new URL(x.id).hostname);
if (idHost !== expectHost) {
return new Error('invalid person: id has different host');
}
if (typeof x.publicKey.id !== 'string') {
return new Error('invalid person: publicKey.id is not a string');
}
const publicKeyIdHost = toPuny(new URL(x.publicKey.id).hostname);
if (publicKeyIdHost !== expectHost) {
return new Error('invalid person: publicKey.id has different host');
}
return null;
}
/**
* Personをフェッチします。
*
*/
export async function fetchPerson(uri: string, resolver?: Resolver): Promise<User | null> {
if (typeof uri !== 'string') throw new Error('uri is not string');
// URIがこのサーバーを指しているならデータベースからフェッチ
if (uri.startsWith(config.url + '/')) {
const id = uri.split('/').pop();
return await Users.findOne(id).then(x => x || null);
}
//#region このサーバーに既に登録されていたらそれを返す
const exist = await Users.findOne({ uri });
if (exist) {
return exist;
}
//#endregion
return null;
}
/**
* Personを作成します。
*/
export async function createPerson(uri: string, resolver?: Resolver): Promise<User> {
if (typeof uri !== 'string') throw new Error('uri is not string');
if (resolver == null) resolver = new Resolver();
const object = await resolver.resolve(uri) as any;
const err = validatePerson(object, uri);
if (err) {
throw err;
}
const person: IPerson = object;
logger.info(`Creating the Person: ${person.id}`);
const host = toPuny(new URL(object.id).hostname);
const { fields } = analyzeAttachments(person.attachment || []);
const tags = extractHashtags(person.tag).map(tag => tag.toLowerCase());
const isBot = object.type == 'Service';
// Create user
let user: IRemoteUser;
try {
// Start transaction
await getConnection().transaction(async transactionalEntityManager => {
user = await transactionalEntityManager.save(new User({
id: genId(),
avatarId: null,
bannerId: null,
createdAt: new Date(),
lastFetchedAt: new Date(),
name: person.name,
isLocked: person.manuallyApprovesFollowers,
username: person.preferredUsername,
usernameLower: person.preferredUsername.toLowerCase(),
host,
inbox: person.inbox,
sharedInbox: person.sharedInbox || (person.endpoints ? person.endpoints.sharedInbox : undefined),
featured: person.featured,
uri: person.id,
tags,
isBot,
isCat: (person as any).isCat === true
})) as IRemoteUser;
await transactionalEntityManager.save(new UserProfile({
userId: user.id,
description: person.summary ? fromHtml(person.summary) : null,
url: person.url,
fields,
userHost: host
}));
await transactionalEntityManager.save(new UserPublickey({
userId: user.id,
keyId: person.publicKey.id,
keyPem: person.publicKey.publicKeyPem
}));
});
} catch (e) {
// duplicate key error
if (isDuplicateKeyValueError(e)) {
throw new Error('already registered');
}
logger.error(e);
throw e;
}
// Register host
registerOrFetchInstanceDoc(host).then(i => {
Instances.increment({ id: i.id }, 'usersCount', 1);
instanceChart.newUser(i.host);
});
usersChart.update(user!, true);
// ハッシュタグ更新
for (const tag of tags) updateHashtag(user!, tag, true, true);
for (const tag of (user!.tags || []).filter(x => !tags.includes(x))) updateHashtag(user!, tag, true, false);
//#region アイコンとヘッダー画像をフェッチ
const [avatar, banner] = (await Promise.all<DriveFile | null>([
person.icon,
person.image
].map(img =>
img == null
? Promise.resolve(null)
: resolveImage(user!, img).catch(() => null)
)));
const avatarId = avatar ? avatar.id : null;
const bannerId = banner ? banner.id : null;
const avatarUrl = avatar ? DriveFiles.getPublicUrl(avatar) : null;
const bannerUrl = banner ? DriveFiles.getPublicUrl(banner) : null;
const avatarColor = avatar && avatar.properties.avgColor ? avatar.properties.avgColor : null;
const bannerColor = banner && banner.properties.avgColor ? banner.properties.avgColor : null;
await Users.update(user!.id, {
avatarId,
bannerId,
avatarUrl,
bannerUrl,
avatarColor,
bannerColor
});
user!.avatarId = avatarId;
user!.bannerId = bannerId;
user!.avatarUrl = avatarUrl;
user!.bannerUrl = bannerUrl;
user!.avatarColor = avatarColor;
user!.bannerColor = bannerColor;
//#endregion
//#region カスタム絵文字取得
const emojis = await extractEmojis(person.tag || [], host).catch(e => {
logger.info(`extractEmojis: ${e}`);
return [] as Emoji[];
});
const emojiNames = emojis.map(emoji => emoji.name);
await Users.update(user!.id, {
emojis: emojiNames
});
//#endregion
await updateFeatured(user!.id).catch(err => logger.error(err));
return user!;
}
/**
* Personの情報を更新します。
* @param uri URI of Person
* @param resolver Resolver
* @param hint Hint of Person object (この値が正当なPersonの場合、Remote resolveをせずに更新に利用します)
*/
export async function updatePerson(uri: string, resolver?: Resolver | null, hint?: object): Promise<void> {
if (typeof uri !== 'string') throw new Error('uri is not string');
// URIがこのサーバーを指しているならスキップ
if (uri.startsWith(config.url + '/')) {
return;
}
//#region このサーバーに既に登録されているか
const exist = await Users.findOne({ uri }) as IRemoteUser;
if (exist == null) {
return;
}
//#endregion
if (resolver == null) resolver = new Resolver();
const object = hint || await resolver.resolve(uri) as any;
const err = validatePerson(object, uri);
if (err) {
throw err;
}
const person: IPerson = object;
logger.info(`Updating the Person: ${person.id}`);
// アイコンとヘッダー画像をフェッチ
const [avatar, banner] = (await Promise.all<DriveFile | null>([
person.icon,
person.image
].map(img =>
img == null
? Promise.resolve(null)
: resolveImage(exist, img).catch(() => null)
)));
// カスタム絵文字取得
const emojis = await extractEmojis(person.tag || [], exist.host).catch(e => {
logger.info(`extractEmojis: ${e}`);
return [] as Emoji[];
});
const emojiNames = emojis.map(emoji => emoji.name);
const { fields, services } = analyzeAttachments(person.attachment || []);
const tags = extractHashtags(person.tag).map(tag => tag.toLowerCase());
const updates = {
lastFetchedAt: new Date(),
inbox: person.inbox,
sharedInbox: person.sharedInbox || (person.endpoints ? person.endpoints.sharedInbox : undefined),
featured: person.featured,
emojis: emojiNames,
name: person.name,
tags,
isBot: object.type == 'Service',
isCat: (person as any).isCat === true,
isLocked: person.manuallyApprovesFollowers,
} as Partial<User>;
if (avatar) {
updates.avatarId = avatar.id;
updates.avatarUrl = DriveFiles.getPublicUrl(avatar);
updates.avatarColor = avatar.properties.avgColor ? avatar.properties.avgColor : null;
}
if (banner) {
updates.bannerId = banner.id;
updates.bannerUrl = DriveFiles.getPublicUrl(banner);
updates.bannerColor = banner.properties.avgColor ? banner.properties.avgColor : null;
}
// Update user
await Users.update(exist.id, updates);
await UserPublickeys.update({ userId: exist.id }, {
keyId: person.publicKey.id,
keyPem: person.publicKey.publicKeyPem
});
await UserProfiles.update({ userId: exist.id }, {
url: person.url,
fields,
description: person.summary ? fromHtml(person.summary) : null,
twitterUserId: services.twitter ? services.twitter.userId : null,
twitterScreenName: services.twitter ? services.twitter.screenName : null,
githubId: services.github ? services.github.id : null,
githubLogin: services.github ? services.github.login : null,
discordId: services.discord ? services.discord.id : null,
discordUsername: services.discord ? services.discord.username : null,
discordDiscriminator: services.discord ? services.discord.discriminator : null,
});
// ハッシュタグ更新
for (const tag of tags) updateHashtag(exist, tag, true, true);
for (const tag of (exist.tags || []).filter(x => !tags.includes(x))) updateHashtag(exist, tag, true, false);
// 該当ユーザーが既にフォロワーになっていた場合はFollowingもアップデートする
await Followings.update({
followerId: exist.id
}, {
followerSharedInbox: person.sharedInbox || (person.endpoints ? person.endpoints.sharedInbox : undefined)
});
await updateFeatured(exist.id).catch(err => logger.error(err));
}
/**
* Personを解決します。
*/
export async function resolvePerson(uri: string, resolver?: Resolver): Promise<User> {
if (typeof uri !== 'string') throw new Error('uri is not string');
//#region このサーバーに既に登録されていたらそれを返す
const exist = await fetchPerson(uri);
if (exist) {
return exist;
}
//#endregion
// リモートサーバーからフェッチしてきて登録
if (resolver == null) resolver = new Resolver();
return await createPerson(uri, resolver);
}
const isPropertyValue = (x: {
type: string,
name?: string,
value?: string
}) =>
x &&
x.type === 'PropertyValue' &&
typeof x.name === 'string' &&
typeof x.value === 'string';
const services: {
[x: string]: (id: string, username: string) => any
} = {
'misskey:authentication:twitter': (userId, screenName) => ({ userId, screenName }),
'misskey:authentication:github': (id, login) => ({ id, login }),
'misskey:authentication:discord': (id, name) => $discord(id, name)
};
const $discord = (id: string, name: string) => {
if (typeof name !== 'string')
name = 'unknown#0000';
const [username, discriminator] = name.split('#');
return { id, username, discriminator };
};
function addService(target: { [x: string]: any }, source: IIdentifier) {
const service = services[source.name];
if (typeof source.value !== 'string')
source.value = 'unknown';
const [id, username] = source.value.split('@');
if (service)
target[source.name.split(':')[2]] = service(id, username);
}
export function analyzeAttachments(attachments: ITag[]) {
const fields: {
name: string,
value: string
}[] = [];
const services: { [x: string]: any } = {};
if (Array.isArray(attachments)) {
for (const attachment of attachments.filter(isPropertyValue)) {
if (isPropertyValue(attachment.identifier!)) {
addService(services, attachment.identifier!);
} else {
fields.push({
name: attachment.name!,
value: fromHtml(attachment.value!)
});
}
}
}
return { fields, services };
}
export async function updateFeatured(userId: User['id']) {
const user = await Users.findOne(userId).then(ensure);
if (!Users.isRemoteUser(user)) return;
if (!user.featured) return;
logger.info(`Updating the featured: ${user.uri}`);
const resolver = new Resolver();
// Resolve to (Ordered)Collection Object
const collection = await resolver.resolveCollection(user.featured);
if (!isCollectionOrOrderedCollection(collection)) throw new Error(`Object is not Collection or OrderedCollection`);
// Resolve to Object(may be Note) arrays
const unresolvedItems = isCollection(collection) ? collection.items : collection.orderedItems;
const items = await resolver.resolve(unresolvedItems);
if (!Array.isArray(items)) throw new Error(`Collection items is not an array`);
// Resolve and regist Notes
const limit = promiseLimit<Note | null>(2);
const featuredNotes = await Promise.all(items
.filter(item => item.type === 'Note')
.slice(0, 5)
.map(item => limit(() => resolveNote(item, resolver))));
// delete
await UserNotePinings.delete({ userId: user.id });
// とりあえずidを別の時間で生成して順番を維持
let td = 0;
for (const note of featuredNotes.filter(note => note != null)) {
td -= 1000;
UserNotePinings.save({
id: genId(new Date(Date.now() + td)),
createdAt: new Date(),
userId: user.id,
noteId: note!.id
} as UserNotePining);
}
} | the_stack |
'use strict'
// **Github:** https://github.com/fidm/quic
//
// **License:** MIT
import { inspect } from 'util'
import { BufferVisitor, readUFloat16, writeUFloat16} from './common'
import { QuicError, QUICError, QUICStreamError } from './error'
import { PacketNumber, Offset, StreamID } from './protocol'
// Frame Types
// | Typefield value | Control Frametype |
//
// ----- Regular Frame Types
// | 00000000B (0x00) | PADDING |
// | 00000001B (0x01) | RST_STREAM |
// | 00000010B (0x02) | CONNECTION_CLOSE |
// | 00000011B (0x03) | GOAWAY |
// | 00000100B (0x04) | WINDOW_UPDATE |
// | 00000101B (0x05) | BLOCKED |
// | 00000110B (0x06) | STOP_WAITING |
// | 00000111B (0x07) | PING |
//
// ----- Special Frame Types
// | 001xxxxxB | CONGESTION_FEEDBACK |
// | 01ntllmmB | ACK |
// | 1fdooossB | STREAM |
// -----
export function isCongestionType (flag: number): boolean {
return (flag & 0b11100000) === 0b00100000
}
export function isACKType (flag: number): boolean {
return (flag & 0b11000000) === 0b01000000
}
export function isStreamType (flag: number): boolean {
return flag > 0b10000000
}
export function parseFrame (bufv: BufferVisitor, headerPacketNumber: PacketNumber): Frame {
bufv.walk(0) // align start and end
const type = bufv.buf.readUInt8(bufv.start)
if (type >= 128) {
return StreamFrame.fromBuffer(bufv)
}
if (type >= 64) {
return AckFrame.fromBuffer(bufv)
}
if (type >= 32) {
return CongestionFeedbackFrame.fromBuffer(bufv)
}
switch (type) {
case 0:
return PaddingFrame.fromBuffer(bufv)
case 1:
return RstStreamFrame.fromBuffer(bufv)
case 2:
return ConnectionCloseFrame.fromBuffer(bufv)
case 3:
return GoAwayFrame.fromBuffer(bufv)
case 4:
return WindowUpdateFrame.fromBuffer(bufv)
case 5:
return BlockedFrame.fromBuffer(bufv)
case 6:
return StopWaitingFrame.fromBuffer(bufv, headerPacketNumber)
case 7:
return PingFrame.fromBuffer(bufv)
default:
throw new QuicError('QUIC_INVALID_FRAME_DATA')
}
}
/** Frame representing a QUIC frame. */
export abstract class Frame {
static fromBuffer (_bufv: BufferVisitor, _headerPacketNumber?: PacketNumber): Frame {
throw new Error(`class method "fromBuffer" is not implemented`)
}
type: number
name: string
constructor (type: number, name: string) {
this.type = type
this.name = name
}
valueOf () {
return {
name: this.name,
type: this.type,
}
}
toString (): string {
return JSON.stringify(this.valueOf())
}
isRetransmittable (): boolean {
return this.name !== 'ACK' && this.name !== 'STOP_WAITING'
}
[inspect.custom] (_depth: any, _options: any): string {
return `<${this.constructor.name} ${this.toString()}>`
}
abstract byteLen (): number
abstract writeTo (bufv: BufferVisitor): BufferVisitor
}
/** StreamFrame representing a QUIC STREAM frame. */
export class StreamFrame extends Frame {
// STREAM Frame
//
// The STREAM frame is used to both implicitly create a stream and to send data on it, and is as follows:
// --- src
// 0 1 … SLEN
// +--------+--------+--------+--------+--------+
// |Type (8)| Stream ID (8, 16, 24, or 32 bits) |
// | | (Variable length SLEN bytes) |
// +--------+--------+--------+--------+--------+
//
// SLEN+1 SLEN+2 … SLEN+OLEN
// +--------+--------+--------+--------+--------+--------+--------+--------+
// | Offset (0, 16, 24, 32, 40, 48, 56, or 64 bits) (variable length) |
// | (Variable length: OLEN bytes) |
// +--------+--------+--------+--------+--------+--------+--------+--------+
//
// SLEN+OLEN+1 SLEN+OLEN+2
// +-------------+-------------+
// | Data length (0 or 16 bits)|
// | Optional(maybe 0 bytes) |
// +------------+--------------+
// ---
//
// The fields in the STREAM frame header are as follows:
// * Frame Type: The Frame Type byte is an 8-bit value containing various flags (1fdooossB):
// - The leftmost bit must be set to 1 indicating that this is a STREAM frame.
// - The 'f' bit is the FIN bit. When set to 1, this bit indicates the sender is done
// sending on this stream and wishes to "half-close" (described in more detail later.)
// - The 'd' bit indicates whether a Data Length is present in the STREAM header. When set to 0,
// this field indicates that the STREAM frame extends to the end of the Packet.
// - The next three 'ooo' bits encode the length of the Offset header field as
// 0, 16, 24, 32, 40, 48, 56, or 64 bits long.
// - The next two 'ss' bits encode the length of the Stream ID header field as 8, 16, 24, or 32 bits long.
// * Stream ID: A variable-sized unsigned ID unique to this stream.
// * Offset: A variable-sized unsigned number specifying the byte offset in the stream for this block of data.
// * Data length: An optional 16-bit unsigned number specifying the length of the data in this stream frame.
// The option to omit the length should only be used when the packet is a "full-sized" Packet,
// to avoid the risk of corruption via padding.
//
// A stream frame must always have either non-zero data length or the FIN bit set.
static fromBuffer (bufv: BufferVisitor): StreamFrame {
bufv.walk(1)
const type = bufv.buf[bufv.start]
if (!isStreamType(type)) {
throw new QuicError('QUIC_INVALID_STREAM_DATA')
}
const isFIN = (type & 0b1000000) > 0
const streamID = StreamID.fromBuffer(bufv, StreamID.flagToByteLen(type & 0b11))
const offset = Offset.fromBuffer(bufv, Offset.flagToByteLen((type & 0b11100) >> 2))
let data = null
if ((type & 0b100000) > 0) {
// a Data Length is present in the STREAM header
bufv.mustWalk(2, 'QUIC_INVALID_STREAM_DATA')
const len = bufv.buf.readUInt16BE(bufv.start)
if (len > 0) {
bufv.mustWalk(len, 'QUIC_INVALID_STREAM_DATA')
data = Buffer.allocUnsafe(len) // should copy to release socket buffer
bufv.buf.copy(data, 0, bufv.start, bufv.end)
}
} else if (bufv.length > bufv.end) {
// the STREAM frame extends to the end of the Packet.
bufv.walk(bufv.length - bufv.end)
data = Buffer.allocUnsafe(bufv.end - bufv.start) // should copy to release socket buffer
bufv.buf.copy(data, 0, bufv.start, bufv.end)
}
const frame = new StreamFrame(streamID, offset, isFIN)
frame.setData(data)
frame.type = type
return frame
}
streamID: StreamID
offset: Offset
isFIN: boolean
data: Buffer | null
constructor (streamID: StreamID, offset: Offset, isFIN: boolean = false) {
super(0b10000000, 'STREAM')
this.streamID = streamID
this.offset = offset
this.isFIN = isFIN
this.data = null
}
setData (data: Buffer | null) {
if (data != null && data.length === 0) {
data = null
}
if (data == null) {
this.isFIN = true
}
this.data = data
return this
}
valueOf () {
return {
name: this.name,
type: this.type,
isFIN: this.isFIN,
streamID: this.streamID.valueOf(),
offset: this.offset.valueOf(),
data: this.data,
}
}
headerLen (hasDataLen: boolean): number {
const len = hasDataLen ? 2 : 0
return 1 + this.streamID.byteLen() + this.offset.byteLen() + len
}
byteLen (): number {
const dataLen = this.data != null ? this.data.length : 0
return this.headerLen(dataLen > 0) + dataLen
}
writeTo (bufv: BufferVisitor): BufferVisitor {
if (this.isFIN) {
this.type |= 0b1000000
}
if (this.data != null) {
this.type |= 0b00100000
}
this.type |= this.offset.flagBits() << 2
this.type |= this.streamID.flagBits()
bufv.walk(1)
bufv.buf.writeUInt8(this.type, bufv.start)
this.streamID.writeTo(bufv)
this.offset.writeTo(bufv)
if (this.data != null) {
bufv.walk(2)
bufv.buf.writeUInt16BE(this.data.length, bufv.start)
bufv.walk(this.data.length)
this.data.copy(bufv.buf, bufv.start, 0, this.data.length)
}
return bufv
}
}
/** AckRange representing a range for ACK. */
export class AckRange {
last: number
first: number
constructor (firstPacketNumberValue: number, lastPacketNumberValue: number) {
this.last = lastPacketNumberValue // last >= first
this.first = firstPacketNumberValue // PacketNumber value
}
len (): number {
return this.last - this.first + 1
}
}
/** AckFrame representing a QUIC ACK frame. */
export class AckFrame extends Frame {
// ACK Frame
//
// Section Offsets
// 0: Start of the ack frame.
// T: Byte offset of the start of the timestamp section.
// A: Byte offset of the start of the ack block section.
// N: Length in bytes of the largest acked.
//
// --- src
// 0 1 => N N+1 => A(aka N + 3)
// +---------+-------------------------------------------------+--------+--------+
// | Type | Largest Acked | Largest Acked |
// | (8) | (8, 16, 32, or 48 bits, determined by ll) | Delta Time (16) |
// |01nullmm | | |
// +---------+-------------------------------------------------+--------+--------+
//
// A A + 1 ==> A + N
// +--------+----------------------------------------+
// | Number | First Ack |
// |Blocks-1| Block Length |
// | (opt) |(8, 16, 32 or 48 bits, determined by mm)|
// +--------+----------------------------------------+
//
// A + N + 1 A + N + 2 ==> T(aka A + 2N + 1)
// +------------+-------------------------------------------------+
// | Gap to next| Ack Block Length |
// | Block (8) | (8, 16, 32, or 48 bits, determined by mm) |
// | (Repeats) | (repeats Number Ranges times) |
// +------------+-------------------------------------------------+
//
// T T+1 T+2 (Repeated Num Timestamps)
// +----------+--------+---------------------+ ... --------+------------------+
// | Num | Delta | Time Since | | Delta | Time |
// |Timestamps|Largest | Largest Acked | |Largest | Since Previous |
// | (8) | Acked | (32 bits) | | Acked |Timestamp(16 bits)|
// +----------+--------+---------------------+ +--------+------------------+
// ---
//
// The fields in the ACK frame are as follows:
// * Frame Type: The Frame Type byte is an 8-bit value containing various flags (01nullmmB).
// - The first two bits must be set to 01 indicating that this is an ACK frame.
// - The 'n' bit indicates whether the frame has more than 1 ack range.
// - The 'u' bit is unused.
// - The two 'll' bits encode the length of the Largest Observed field as 1, 2, 4, or 6 bytes long.
// - The two 'mm' bits encode the length of the Missing Packet Sequence Number Delta field as
// 1, 2, 4, or 6 bytes long.
// * Largest Acked: A variable-sized unsigned value representing the largest packet number the peer has observed.
// * Largest Acked Delta Time: A 16-bit unsigned float with 11 explicit bits of mantissa and 5 bits of
// explicit exponent, specifying the time elapsed in microseconds from when largest acked was received until
// this Ack frame was sent. The bit format is loosely modeled after IEEE 754. For example, 1 microsecond is
// represented as 0x1, which has an exponent of zero, presented in the 5 high order bits, and mantissa of 1,
// presented in the 11 low order bits. When the explicit exponent is greater than zero, an implicit high-order
// 12th bit of 1 is assumed in the mantissa. For example, a floating value of 0x800 has an explicit exponent of 1,
// as well as an explicit mantissa of 0, but then has an effective mantissa of 4096 (12th bit is assumed to be 1).
// Additionally, the actual exponent is one-less than the explicit exponent, and the value represents
// 4096 microseconds. Any values larger than the representable range are clamped to 0xFFFF.
// * Ack Block Section:
// - Num Blocks: An optional 8-bit unsigned value specifying one less than the number of ack blocks.
// Only present if the 'n' flag bit is 1.
// - Ack block length: A variable-sized packet number delta. For the first missing packet range,
// the ack block starts at largest acked. For the first ack block, the length of the ack block is
// 1 + this value. For subsequent ack blocks, it is the length of the ack block. For non-first blocks,
// a value of 0 indicates more than 256 packets in a row were lost.
// - Gap to next block: An 8-bit unsigned value specifying the number of packets between ack blocks.
// * Timestamp Section:
// - Num Timestamp: An 8-bit unsigned value specifying the number of timestamps that are included
// in this ack frame. There will be this many pairs of <packet number, timestamp> following in the timestamps.
// - Delta Largest Observed: An 8-bit unsigned value specifying the packet number delta from the
// first timestamp to the largest observed. Therefore, the packet number is the largest observed minus
// the delta largest observed.
// - First Timestamp: A 32-bit unsigned value specifying the time delta in microseconds, from the beginning
// of the connection of the arrival of the packet specified by Largest Observed minus Delta Largest Observed.
// - Delta Largest Observed (Repeated): (Same as above.)
// - Time Since Previous Timestamp (Repeated): A 16-bit unsigned value specifying delta from the previous
// timestamp. It is encoded in the same format as the Ack Delay Time.
//
static fromBuffer (bufv: BufferVisitor): AckFrame {
bufv.walk(1)
const type = bufv.buf[bufv.start]
if (!isACKType(type)) {
throw new QuicError('QUIC_INVALID_ACK_DATA')
}
const frame = new AckFrame()
const hasMissingRanges = (type & 0b00100000) > 0
const missingNumberDeltaLen = PacketNumber.flagToByteLen(type & 0b11)
const largestAckedNumber = PacketNumber.fromBuffer(bufv, PacketNumber.flagToByteLen((type >> 2) & 0b11))
frame.largestAcked = largestAckedNumber.valueOf()
bufv.mustWalk(2, 'QUIC_INVALID_ACK_DATA')
frame.delayTime = readUFloat16(bufv.buf, bufv.start)
let numAckBlocks = 0
if (hasMissingRanges) {
bufv.mustWalk(1, 'QUIC_INVALID_ACK_DATA')
numAckBlocks = bufv.buf.readUInt8(bufv.start)
}
if (hasMissingRanges && numAckBlocks === 0) {
throw new QuicError('QUIC_INVALID_ACK_DATA')
}
bufv.mustWalk(missingNumberDeltaLen, 'QUIC_INVALID_ACK_DATA')
let ackBlockLength = bufv.buf.readUIntBE(bufv.start, missingNumberDeltaLen)
if ((frame.largestAcked > 0 && ackBlockLength < 1) || ackBlockLength > frame.largestAcked) {
throw new QuicError('QUIC_INVALID_ACK_DATA')
}
if (hasMissingRanges) {
let ackRange = new AckRange(frame.largestAcked - ackBlockLength + 1, frame.largestAcked)
frame.ackRanges.push(ackRange)
let inLongBlock = false
let lastRangeComplete = false
for (let i = 0; i < numAckBlocks; i++) {
bufv.mustWalk(1, 'QUIC_INVALID_ACK_DATA')
const gap = bufv.buf.readUInt8(bufv.start)
bufv.mustWalk(missingNumberDeltaLen, 'QUIC_INVALID_ACK_DATA')
ackBlockLength = bufv.buf.readUIntBE(bufv.start, missingNumberDeltaLen)
const lastAckRange = frame.ackRanges[frame.ackRanges.length - 1]
if (inLongBlock) {
lastAckRange.first -= gap + ackBlockLength
lastAckRange.last -= gap
} else {
lastRangeComplete = false
ackRange = new AckRange(0, lastAckRange.first - gap - 1)
ackRange.first = ackRange.last - ackBlockLength + 1
frame.ackRanges.push(ackRange)
}
if (ackBlockLength > 0) {
lastRangeComplete = true
}
inLongBlock = (ackBlockLength === 0)
}
// if the last range was not complete, firstNum and lastNum make no sense
// remove the range from frame.ackRanges
if (!lastRangeComplete) {
frame.ackRanges = frame.ackRanges.slice(0, -1)
}
frame.lowestAcked = frame.ackRanges[frame.ackRanges.length - 1].first
} else {
if (frame.largestAcked === 0) {
frame.lowestAcked = 0
} else {
frame.lowestAcked = frame.largestAcked - ackBlockLength + 1
}
}
if (!frame.validateAckRanges()) {
throw new QuicError('QUIC_INVALID_ACK_DATA')
}
bufv.mustWalk(1, 'QUIC_INVALID_ACK_DATA')
const numTimestamp = bufv.buf.readUInt8(bufv.start)
if (numTimestamp > 0) { // TODO
// Delta Largest acked
bufv.mustWalk(1, 'QUIC_INVALID_ACK_DATA')
// buf.readUInt8(v.start)
// First Timestamp
bufv.mustWalk(4, 'QUIC_INVALID_ACK_DATA')
// buf.readUInt32BE(v.start)
for (let i = 0; i < numTimestamp - 1; i++) {
// Delta Largest acked
bufv.mustWalk(1, 'QUIC_INVALID_ACK_DATA')
// buf.readUInt8(v.start)
// Time Since Previous Timestamp
bufv.mustWalk(2, 'QUIC_INVALID_ACK_DATA')
// buf.readUInt16BE(v.start)
}
}
return frame
}
largestAcked: number
lowestAcked: number
ackRanges: AckRange[]
delayTime: number
largestAckedTime: number
constructor () {
super(0b01000000, 'ACK')
this.largestAcked = 0 // largest PacketNumber Value
this.lowestAcked = 0 // lowest PacketNumber Value
// has to be ordered. The ACK range with the highest firstNum goes first,
// the ACK range with the lowest firstNum goes last
this.ackRanges = []
this.delayTime = 0 // microseconds
// time when the LargestAcked was received, this field Will not be set for received ACKs frames
this.largestAckedTime = 0 // millisecond, timestamp
}
valueOf () {
return {
name: this.name,
type: this.type,
largestAcked: this.largestAcked,
lowestAcked: this.lowestAcked,
delayTime: this.delayTime,
ackRanges: this.ackRanges,
}
}
hasMissingRanges (): boolean {
return this.ackRanges.length > 0
}
validateAckRanges (): boolean {
if (this.ackRanges.length === 0) {
return true
}
// if there are missing packets, there will always be at least 2 ACK ranges
if (this.ackRanges.length === 1) {
return false
}
if (this.ackRanges[0].last !== this.largestAcked) {
return false
}
// check the validity of every single ACK range
for (const ackRange of this.ackRanges) {
if (ackRange.first > ackRange.last || ackRange.first <= 0) {
return false
}
}
// check the consistency for ACK with multiple NACK ranges
for (let i = 1, l = this.ackRanges.length; i < l; i++) {
const lastAckRange = this.ackRanges[i - 1]
if (lastAckRange.first <= this.ackRanges[i].first) {
return false
}
if (lastAckRange.first <= (this.ackRanges[i].last + 1)) {
return false
}
}
return true
}
numWritableNackRanges (): number {
if (this.ackRanges.length === 0) {
return 0
}
let numRanges = 0
for (let i = 1, l = this.ackRanges.length; i < l; i++) {
const lastAckRange = this.ackRanges[i - 1]
const gap = lastAckRange.first - this.ackRanges[i].last - 1
let rangeLength = 1 + Math.floor(gap / 0xff)
if (gap % 0xff === 0) {
rangeLength--
}
if (numRanges + rangeLength < 0xff) {
numRanges += rangeLength
} else {
break
}
}
return numRanges + 1
}
getMissingNumberDeltaFlagBits (): number {
let maxRangeLength = 0
if (this.hasMissingRanges()) {
for (const ackRange of this.ackRanges) {
const rangeLength = ackRange.len()
if (rangeLength > maxRangeLength) {
maxRangeLength = rangeLength
}
}
} else {
maxRangeLength = this.largestAcked - this.lowestAcked + 1
}
if (maxRangeLength <= 0xff) {
return 0
}
if (maxRangeLength <= 0xffff) {
return 1
}
if (maxRangeLength <= 0xffffff) {
return 2
}
return 3
}
setDelay () {
this.delayTime = (Date.now() - this.largestAckedTime) * 1000 // microsecond
}
acksPacket (val: number): boolean {
if (val < this.lowestAcked || val > this.largestAcked) {
return false
}
if (this.hasMissingRanges()) {
// TODO: this could be implemented as a binary search
for (const ackRange of this.ackRanges) {
if (val >= ackRange.first && val <= ackRange.last) {
return true
}
}
return false
}
// if packet doesn't have missing ranges
return (val >= this.lowestAcked && val <= this.largestAcked)
}
byteLen (): number {
const hasMissingRanges = this.hasMissingRanges()
const largestAckedNum = new PacketNumber(this.largestAcked)
const flagBits = this.getMissingNumberDeltaFlagBits()
const largestAckedLen = largestAckedNum.byteLen()
const missingNumberDeltaLen = PacketNumber.flagToByteLen(flagBits)
let frameLen = 1 + largestAckedLen + 2
let numRanges = 0
// Blocks
if (!hasMissingRanges) {
frameLen += missingNumberDeltaLen
} else {
numRanges = this.numWritableNackRanges()
if (numRanges > 0xff) {
throw new Error('AckFrame: Too many ACK ranges')
}
frameLen += missingNumberDeltaLen + 1
frameLen += (missingNumberDeltaLen + 1) * (numRanges - 1)
}
// Timestamps
return frameLen + 1
}
writeTo (bufv: BufferVisitor): BufferVisitor {
const hasMissingRanges = this.hasMissingRanges()
if (hasMissingRanges) {
this.type |= 0b100000
}
const largestAckedNum = new PacketNumber(this.largestAcked)
this.type |= largestAckedNum.flagBits() << 2
const flagBits = this.getMissingNumberDeltaFlagBits()
this.type |= flagBits
const missingNumberDeltaLen = PacketNumber.flagToByteLen(flagBits)
let numRanges = 0
bufv.walk(1)
bufv.buf.writeUInt8(this.type, bufv.start)
largestAckedNum.writeTo(bufv)
bufv.walk(2)
writeUFloat16(bufv.buf, this.delayTime, bufv.start)
let numRangesWritten = 0
if (hasMissingRanges) {
numRanges = this.numWritableNackRanges()
if (numRanges > 0xff) {
throw new QuicError('AckFrame: Too many ACK ranges')
}
bufv.walk(1)
bufv.buf.writeUInt8(numRanges - 1, bufv.start)
}
let firstAckBlockLength = 0
if (!hasMissingRanges) {
firstAckBlockLength = this.largestAcked - this.lowestAcked + 1
} else {
if (this.largestAcked !== this.ackRanges[0].last) {
throw new QuicError('AckFrame: largestAcked does not match ACK ranges')
}
if (this.lowestAcked !== this.ackRanges[this.ackRanges.length - 1].first) {
throw new QuicError('AckFrame: lowestAcked does not match ACK ranges')
}
firstAckBlockLength = this.largestAcked - this.ackRanges[0].first + 1
numRangesWritten++
}
bufv.walk(missingNumberDeltaLen)
bufv.buf.writeUIntBE(firstAckBlockLength, bufv.start, missingNumberDeltaLen)
for (let i = 1, l = this.ackRanges.length; i < l; i++) {
const length = this.ackRanges[i].len()
const gap = this.ackRanges[i - 1].first - this.ackRanges[i].last - 1
let num = Math.floor(gap / 0xff) + 1
if (gap % 0xff === 0) {
num--
}
if (num === 1) {
bufv.walk(1)
bufv.buf.writeUInt8(gap, bufv.start)
bufv.walk(missingNumberDeltaLen)
bufv.buf.writeUIntBE(length, bufv.start, missingNumberDeltaLen)
numRangesWritten++
} else {
for (let j = 0; j < num; j++) {
let lengthWritten = 0
let gapWritten = 0
if (j === num - 1) { // last block
lengthWritten = length
gapWritten = 1 + ((gap - 1) % 255)
} else {
lengthWritten = 0
gapWritten = 0xff
}
bufv.walk(1)
bufv.buf.writeUInt8(gapWritten, bufv.start)
bufv.walk(missingNumberDeltaLen)
bufv.buf.writeUIntBE(lengthWritten, bufv.start, missingNumberDeltaLen)
numRangesWritten++
}
}
// this is needed if not all AckRanges can be written to the ACK frame (if there are more than 0xFF)
if (numRangesWritten >= numRanges) {
break
}
}
if (numRanges !== numRangesWritten) {
throw new QuicError('AckFrame: Inconsistent number of ACK ranges written')
}
bufv.walk(1)
bufv.buf.writeUInt8(0, bufv.start) // no timestamps
return bufv
}
}
/** StopWaitingFrame representing a QUIC STOP_WAITING frame. */
export class StopWaitingFrame extends Frame {
// STOP_WAITING Frame
//
// --- src
// 0 1 2 3 4 5 6
// +--------+--------+--------+--------+--------+-------+-------+
// |Type (8)| Least unacked delta (8, 16, 32, or 48 bits) |
// | | (variable length) |
// +--------+--------+--------+--------+--------+--------+------+
// ---
//
// The fields in the STOP_WAITING frame are as follows:
// * Frame Type: The Frame Type byte is an 8-bit value that must be set to 0x06 indicating
// that this is a STOP_WAITING frame.
// * Least Unacked Delta: A variable length packet number delta with the same length as the
// packet header's packet number. Subtract it from the header's packet number to determine
// the least unacked. The resulting least unacked is the smallest packet number of any packet
// for which the sender is still awaiting an ack. If the receiver is missing any packets smaller
// than this value, the receiver should consider those packets to be irrecoverably lost.
//
static fromBuffer (bufv: BufferVisitor, packetNumber: PacketNumber): StopWaitingFrame {
bufv.walk(1)
const type = bufv.buf[bufv.start]
if (type !== 0x06) {
throw new QuicError('QUIC_INVALID_STOP_WAITING_DATA')
}
const len = packetNumber.byteLen()
bufv.mustWalk(len, 'QUIC_INVALID_STOP_WAITING_DATA')
const delta = bufv.buf.readIntBE(bufv.start, len, false)
return new StopWaitingFrame(packetNumber, packetNumber.valueOf() - delta)
}
packetNumber: PacketNumber
leastUnacked: number
constructor (packetNumber: PacketNumber, leastUnacked: number) {
super(0x06, 'STOP_WAITING')
this.packetNumber = packetNumber // packetNumber.valueOf() > leastUnacked
this.leastUnacked = leastUnacked
}
valueOf () {
return {
name: this.name,
type: this.type,
packetNumber: this.packetNumber.valueOf(),
leastUnacked: this.leastUnacked,
}
}
byteLen (): number {
return 1 + this.packetNumber.byteLen()
}
writeTo (bufv: BufferVisitor): BufferVisitor {
const len = this.packetNumber.byteLen()
bufv.walk(1)
bufv.buf.writeUInt8(this.type, bufv.start)
bufv.walk(len)
bufv.buf.writeUIntBE(this.packetNumber.valueOf() - this.leastUnacked, bufv.start, len)
return bufv
}
}
/** WindowUpdateFrame representing a QUIC WINDOW_UPDATE frame. */
export class WindowUpdateFrame extends Frame {
// WINDOW_UPDATE Frame
//
// --- src
// 0 1 4 5 12
// +--------+--------+-- ... --+-------+--------+-- ... --+-------+
// |Type(8) | Stream ID (32 bits) | Byte offset (64 bits) |
// +--------+--------+-- ... --+-------+--------+-- ... --+-------+
// ---
// The fields in the WINDOW_UPDATE frame are as follows:
// * Frame Type: The Frame Type byte is an 8-bit value that must be set to 0x04
// indicating that this is a WINDOW_UPDATE frame.
// * Stream ID: ID of the stream whose flow control windows is being updated,
// or 0 to specify the connection-level flow control window.
// * Byte offset: A 64-bit unsigned integer indicating the absolute byte offset of data
// which can be sent on the given stream. In the case of connection level flow control,
// the cumulative number of bytes which can be sent on all currently open streams.
//
static fromBuffer (bufv: BufferVisitor): WindowUpdateFrame {
bufv.walk(1)
const type = bufv.buf[bufv.start]
if (type !== 0x04) {
throw new QuicError('QUIC_INVALID_WINDOW_UPDATE_DATA')
}
const streamID = StreamID.fromBuffer(bufv, 4)
const offset = Offset.fromBuffer(bufv, 8)
return new WindowUpdateFrame(streamID, offset)
}
streamID: StreamID
offset: Offset
constructor (streamID: StreamID, offset: Offset) {
super(0x04, 'WINDOW_UPDATE')
this.streamID = streamID
this.offset = offset
}
valueOf () {
return {
name: this.name,
type: this.type,
streamID: this.streamID.valueOf(),
offset: this.offset.valueOf(),
}
}
byteLen (): number {
return 13
}
writeTo (bufv: BufferVisitor): BufferVisitor {
bufv.walk(1)
bufv.buf.writeUInt8(this.type, bufv.start)
this.streamID.writeTo(bufv, true)
this.offset.writeTo(bufv, true)
return bufv
}
}
/** BlockedFrame representing a QUIC BLOCKED frame. */
export class BlockedFrame extends Frame {
// BLOCKED Frame
//
// --- src
// 0 1 2 3 4
// +--------+--------+--------+--------+--------+
// |Type(8) | Stream ID (32 bits) |
// +--------+--------+--------+--------+--------+
// ---
//
// The fields in the BLOCKED frame are as follows:
// * Frame Type: The Frame Type byte is an 8-bit value that must be set
// to 0x05 indicating that this is a BLOCKED frame.
// * Stream ID: A 32-bit unsigned number indicating the stream which is flow control blocked.
// A non-zero Stream ID field specifies the stream that is flow control blocked. When zero,
// the Stream ID field indicates that the connection is flow control blocked at the connection level.
//
static fromBuffer (bufv: BufferVisitor): BlockedFrame {
bufv.walk(1)
const type = bufv.buf[bufv.start]
if (type !== 0x05) {
throw new QuicError('QUIC_INVALID_BLOCKED_DATA')
}
const streamID = StreamID.fromBuffer(bufv, 4)
return new BlockedFrame(streamID)
}
streamID: StreamID
constructor (streamID: StreamID) {
super(0x05, 'BLOCKED')
this.streamID = streamID
}
valueOf () {
return {
name: this.name,
type: this.type,
streamID: this.streamID.valueOf(),
}
}
byteLen (): number {
return 5
}
writeTo (bufv: BufferVisitor): BufferVisitor {
bufv.walk(1)
bufv.buf.writeUInt8(this.type, bufv.start)
this.streamID.writeTo(bufv, true)
return bufv
}
}
/** CongestionFeedbackFrame representing a QUIC CONGESTION_FEEDBACK frame. */
export class CongestionFeedbackFrame extends Frame {
// CONGESTION_FEEDBACK Frame
// The CONGESTION_FEEDBACK frame is an experimental frame currently not used.
// It is intended to provide extra congestion feedback information outside the scope of
// the standard ack frame. A CONGESTION_FEEDBACK frame must have the first three bits of
// the Frame Type set to 001. The last 5 bits of the Frame Type field are reserved for future use.
static fromBuffer (bufv: BufferVisitor): CongestionFeedbackFrame {
bufv.walk(1)
const type = bufv.buf[bufv.start]
if (!isCongestionType(type)) {
throw new QuicError('QUIC_INVALID_FRAME_DATA')
}
return new CongestionFeedbackFrame()
}
constructor () {
super(0b00100000, 'CONGESTION_FEEDBACK')
}
byteLen (): number {
return 1
}
writeTo (bufv: BufferVisitor): BufferVisitor {
bufv.walk(1)
bufv.buf.writeUInt8(this.type, bufv.start)
return bufv
}
}
/** PaddingFrame representing a QUIC PADDING frame. */
export class PaddingFrame extends Frame {
// PADDING Frame
// The PADDING frame pads a packet with 0x00 bytes. When this frame is encountered,
// the rest of the packet is expected to be padding bytes. The frame contains 0x00 bytes
// and extends to the end of the QUIC packet. A PADDING frame only has a Frame Type field,
// and must have the 8-bit Frame Type field set to 0x00.
static fromBuffer (bufv: BufferVisitor): PaddingFrame {
bufv.walk(1)
const type = bufv.buf[bufv.start]
if (type > 0) {
throw new QuicError('QUIC_INVALID_FRAME_DATA')
}
return new PaddingFrame()
}
constructor () {
super(0x00, 'PADDING')
}
byteLen (): number {
return 1
}
writeTo (bufv: BufferVisitor): BufferVisitor {
bufv.walk(1)
bufv.buf.writeUInt8(0, bufv.start)
return bufv
}
}
/** RstStreamFrame representing a QUIC RST_STREAM frame. */
export class RstStreamFrame extends Frame {
// RST_STREAM Frame
//
// --- src
// 0 1 4 5 12 8 16
// +-------+--------+-- ... ----+--------+-- ... ------+-------+-- ... ------+
// |Type(8)| StreamID (32 bits) | Byte offset (64 bits)| Error code (32 bits)|
// +-------+--------+-- ... ----+--------+-- ... ------+-------+-- ... ------+
// ---
//
// The fields in a RST_STREAM frame are as follows:
// * Frame type: The Frame Type is an 8-bit value that must be set to 0x01 specifying that this is a RST_STREAM frame.
// * Stream ID: The 32-bit Stream ID of the stream being terminated.
// * Byte offset: A 64-bit unsigned integer indicating the absolute byte offset of the end of data for this stream.
// * Error code: A 32-bit QuicErrorCode which indicates why the stream is being closed.
// QuicErrorCodes are listed later in this document.
//
static fromBuffer (bufv: BufferVisitor): RstStreamFrame {
bufv.walk(1)
const type = bufv.buf[bufv.start]
if (type !== 0x01 || bufv.length < (bufv.end + 16)) {
throw new QuicError('QUIC_INVALID_RST_STREAM_DATA')
}
const streamID = StreamID.fromBuffer(bufv, 4)
const offset = Offset.fromBuffer(bufv, 8)
const error = QuicError.fromBuffer(bufv)
return new RstStreamFrame(streamID, offset, error)
}
streamID: StreamID
offset: Offset
error: QUICStreamError
constructor (streamID: StreamID, offset: Offset, error: QUICStreamError) {
super(0x01, 'RST_STREAM')
this.streamID = streamID
this.offset = offset
this.error = error
}
valueOf () {
return {
name: this.name,
type: this.type,
streamID: this.streamID.valueOf(),
offset: this.offset.valueOf(),
error: this.error.valueOf(),
}
}
byteLen (): number {
return 17
}
writeTo (bufv: BufferVisitor): BufferVisitor {
bufv.walk(1)
bufv.buf.writeUInt8(this.type, bufv.start)
this.streamID.writeTo(bufv, true)
this.offset.writeTo(bufv, true)
this.error.writeTo(bufv)
return bufv
}
}
/** PingFrame representing a QUIC PING frame. */
export class PingFrame extends Frame {
// PING frame
// The PING frame can be used by an endpoint to verify that
// a peer is still alive. The PING frame contains no payload.
// The receiver of a PING frame simply needs to ACK the packet containing this frame.
// The PING frame should be used to keep a connection alive when a stream is open.
// The default is to do this after 15 seconds of quiescence,
// which is much shorter than most NATs time out. A PING frame only
// has a Frame Type field, and must have the 8-bit Frame Type field set to 0x07.
static fromBuffer (bufv: BufferVisitor): PingFrame {
bufv.walk(1)
const type = bufv.buf[bufv.start]
if (type !== 0x07) {
throw new QuicError('QUIC_INVALID_FRAME_DATA')
}
return new PingFrame()
}
constructor () {
super(0x07, 'PING')
}
byteLen (): number {
return 1
}
writeTo (bufv: BufferVisitor): BufferVisitor {
bufv.walk(1)
bufv.buf.writeUInt8(this.type, bufv.start)
return bufv
}
}
/** ConnectionCloseFrame representing a QUIC CONNECTION_CLOSE frame. */
export class ConnectionCloseFrame extends Frame {
// CONNECTION_CLOSE frame
//
// --- src
// 0 1 4 5 6 7
// +--------+--------+-- ... -----+--------+--------+--------+----- ...
// |Type(8) | Error code (32 bits)| Reason phrase | Reason phrase
// | | | length (16 bits)|(variable length)
// +--------+--------+-- ... -----+--------+--------+--------+----- ...
// ---
//
// The fields of a CONNECTION_CLOSE frame are as follows:
// * Frame Type: An 8-bit value that must be set to 0x02 specifying that this is a CONNECTION_CLOSE frame.
// * Error Code: A 32-bit field containing the QuicErrorCode which indicates the reason for closing this connection.
// * Reason Phrase Length: A 16-bit unsigned number specifying the length of the reason phrase.
// This may be zero if the sender chooses to not give details beyond the QuicErrorCode.
// * Reason Phrase: An optional human-readable explanation for why the connection was closed.
//
static fromBuffer (bufv: BufferVisitor): ConnectionCloseFrame {
bufv.walk(1)
const type = bufv.buf[bufv.start]
if (type !== 0x02 || bufv.length < (bufv.end + 6)) {
throw new QuicError('QUIC_INVALID_CONNECTION_CLOSE_DATA')
}
const error = QuicError.fromBuffer(bufv)
bufv.walk(2)
const reasonPhraseLen = bufv.buf.readUInt16BE(bufv.start)
if (reasonPhraseLen > 0) {
bufv.mustWalk(reasonPhraseLen, 'QUIC_INVALID_CONNECTION_CLOSE_DATA')
error.message = bufv.buf.toString('utf8', bufv.start, bufv.end)
}
return new ConnectionCloseFrame(error)
}
error: QUICError
constructor (error: QUICError) {
super(0x02, 'CONNECTION_CLOSE')
this.error = error
}
valueOf () {
return {
name: this.name,
type: this.type,
error: this.error.valueOf(),
}
}
byteLen (): number {
const reasonPhrase = this.error.message
const reasonPhraseLen = reasonPhrase !== '' ? Buffer.byteLength(reasonPhrase) : 0
return 7 + reasonPhraseLen
}
writeTo (bufv: BufferVisitor): BufferVisitor {
const reasonPhrase = this.error.message
const reasonPhraseLen = reasonPhrase !== '' ? Buffer.byteLength(reasonPhrase) : 0
bufv.walk(1)
bufv.buf.writeUInt8(this.type, bufv.start)
this.error.writeTo(bufv)
bufv.walk(2)
bufv.buf.writeUInt16BE(reasonPhraseLen, bufv.start)
if (reasonPhrase !== '') {
bufv.walk(reasonPhraseLen)
bufv.buf.write(reasonPhrase, bufv.start, reasonPhraseLen)
}
return bufv
}
}
/** GoAwayFrame representing a QUIC GOAWAY frame. */
export class GoAwayFrame extends Frame {
// GOAWAY Frame
//
// --- src
// 0 1 4 5 6 7 8
// +--------+--------+-- ... -----+-------+-------+-------+------+
// |Type(8) | Error code (32 bits)| Last Good Stream ID (32 bits)| ->
// +--------+--------+-- ... -----+-------+-------+-------+------+
//
// 9 10 11
// +--------+--------+--------+----- ...
// | Reason phrase | Reason phrase
// | length (16 bits)|(variable length)
// +--------+--------+--------+----- ...
// ---
//
// The fields of a GOAWAY frame are as follows:
// * Frame type: An 8-bit value that must be set to 0x03 specifying that this is a GOAWAY frame.
// * Error Code: A 32-bit field containing the QuicErrorCode which indicates the reason for closing this connection.
// * Last Good Stream ID: The last Stream ID which was accepted by the sender of the GOAWAY message.
// If no streams were replied to, this value must be set to 0.
// * Reason Phrase Length: A 16-bit unsigned number specifying the length of the reason phrase.
// This may be zero if the sender chooses to not give details beyond the error code.
// * Reason Phrase: An optional human-readable explanation for why the connection was closed.
//
static fromBuffer (bufv: BufferVisitor): GoAwayFrame {
bufv.walk(1)
const type = bufv.buf[bufv.start]
if (type !== 0x03) {
throw new QuicError('QUIC_INVALID_GOAWAY_DATA')
}
const error = QuicError.fromBuffer(bufv)
const streamID = StreamID.fromBuffer(bufv, 4)
bufv.mustWalk(2, 'QUIC_INVALID_GOAWAY_DATA')
const reasonPhraseLen = bufv.buf.readUInt16BE(bufv.start)
if (reasonPhraseLen > 0) {
bufv.mustWalk(reasonPhraseLen, 'QUIC_INVALID_GOAWAY_DATA')
error.message = bufv.buf.toString('utf8', bufv.start, bufv.end)
}
return new GoAwayFrame(streamID, error)
}
streamID: StreamID
error: QUICError
constructor (lastGoodStreamID: StreamID, error: QUICError) {
super(0x03, 'GOAWAY')
this.streamID = lastGoodStreamID
this.error = error
}
valueOf () {
return {
name: this.name,
type: this.type,
streamID: this.streamID.valueOf(),
error: this.error.valueOf(),
}
}
byteLen (): number {
const reasonPhrase = this.error.message
const reasonPhraseLen = reasonPhrase !== '' ? Buffer.byteLength(reasonPhrase) : 0
return 11 + reasonPhraseLen
}
writeTo (bufv: BufferVisitor): BufferVisitor {
const reasonPhrase = this.error.message
const reasonPhraseLen = reasonPhrase !== '' ? Buffer.byteLength(reasonPhrase) : 0
bufv.walk(1)
bufv.buf.writeUInt8(this.type, bufv.start)
this.error.writeTo(bufv)
this.streamID.writeTo(bufv, true)
bufv.walk(2)
bufv.buf.writeUInt16BE(reasonPhraseLen, bufv.start)
if (reasonPhrase !== '') {
bufv.walk(reasonPhraseLen)
bufv.buf.write(reasonPhrase, bufv.start, reasonPhraseLen)
}
return bufv
}
} | the_stack |
import { App, Platform, NavParams, LoadingController, ModalController } from 'ionic-angular';
import { ViewChild, Component } from '@angular/core';
//Components
import { InstrumentPanelChart } from '../../components/instrument-panel-chart/instrument-panel-chart.component';
import { TriggerComponent } from '../../components/trigger/trigger.component';
import { FgenComponent } from '../../components/function-gen/function-gen.component';
import { DigitalIoComponent } from '../../components/digital-io/digital-io.component';
import { DcSupplyComponent } from '../../components/dc-supply/dc-supply.component';
import { YAxisComponent } from '../../components/yaxis-controls/yaxis-controls.component';
//Services
import { DeviceManagerService, DeviceService } from 'dip-angular2/services';
import { StorageService } from '../../services/storage/storage.service';
import { ToastService } from '../../services/toast/toast.service';
import { TooltipService } from '../../services/tooltip/tooltip.service';
//Interfaces
import { PreviousLaSettings, PreviousOscSettings, PreviousTrigSettings } from './instrument-panel.interface';
@Component({
templateUrl: 'instrument-panel.html'
})
export class InstrumentPanelPage {
@ViewChild('chart1') chart1: InstrumentPanelChart;
@ViewChild('triggerComponent') triggerComponent: TriggerComponent;
@ViewChild('gpioComponent') gpioComponent: DigitalIoComponent;
@ViewChild('fgenComponent') fgenComponent: FgenComponent;
@ViewChild('dcComponent') dcComponent: DcSupplyComponent;
@ViewChild('yaxisComponent') yaxisComponent: YAxisComponent;
public app: App;
public platform: Platform;
public params: NavParams;
public tooltipService: TooltipService;
public controlsVisible = false;
public botVisible = false;
public sideVisible = false;
public running: boolean = false;
public triggerStatus: string = 'Idle';
public tutorialMode: boolean = false;
public tutorialStage: number = 0;
public deviceManagerService: DeviceManagerService;
public activeDevice: DeviceService;
public storage: StorageService;
public chartReady: boolean = false;
public toastService: ToastService;
public clickBindReference;
public readAttemptCount: number = 0;
public errorCount: number = 0;
public previousOscSettings: PreviousOscSettings[] = [];
public previousTrigSettings: PreviousTrigSettings = {
instrument: null,
channel: null,
type: null,
lowerThreshold: null,
upperThreshold: null,
bitmask: null
};
public previousLaSettings: PreviousLaSettings[] = [];
public theoreticalAcqTime: number;
public readingOsc: boolean = false;
public readingLa: boolean = false;
public currentOscReadArray: number[];
public currentLaReadArray: number[];
public forceTriggerInterval: number = 100;
public currentTriggerType: 'rising' | 'falling' | 'off';
//TODO: REMOVE?
public currentSamplingFrequencies: number[] = [];
constructor(
_deviceManagerService: DeviceManagerService,
_storage: StorageService,
_toastService: ToastService,
_tooltipService: TooltipService,
_app: App,
_params: NavParams,
_platform: Platform,
public loadingCtrl: LoadingController,
public modalCtrl: ModalController
) {
this.toastService = _toastService;
this.tooltipService = _tooltipService;
this.app = _app;
this.params = _params;
this.tutorialMode = this.params.get('tutorialMode') || false;
this.platform = _platform;
this.deviceManagerService = _deviceManagerService;
this.activeDevice = this.deviceManagerService.getActiveDevice();
this.storage = _storage;
let awgData;
this.getOscStatus()
.then(() => {
return this.getAwgStatus();
})
.then((data) => {
awgData = data;
return this.getTriggerStatus();
})
.then(() => {
return this.readCurrentGpioStates();
})
.then(() => {
if (this.activeDevice.deviceModel === 'OpenScope MZ' && awgData.awg["1"][0].state === 'running') {
return Promise.resolve();
}
else {
return this.applyLaBitmask();
}
})
.then(() => {
return this.getVoltages();
})
.catch((e) => {
console.log(e);
});
for (let i = 0; i < this.activeDevice.instruments.osc.numChans; i++) {
this.currentSamplingFrequencies.push(0);
}
console.log(this.deviceManagerService.devices[0]);
}
resetDevice() {
let loading = this.displayLoading();
if (this.running) {
this.stopClick();
}
this.chart1.initializeValues();
this.chart1.clearExtraSeries([]);
this.chart1.flotDrawWaveform(true, false);
this.previousLaSettings = [];
this.previousOscSettings = [];
this.previousTrigSettings = {
instrument: null,
channel: null,
type: null,
lowerThreshold: null,
upperThreshold: null,
bitmask: null
};
this.fgenComponent.initializeValues();
this.activeDevice.resetInstruments().subscribe(
(data) => {
setTimeout(() => {
this.gpioComponent.gpioDirections.forEach((val, index, array) => {
this.gpioComponent.gpioDirections[index] = false;
this.gpioComponent.gpioVals[index] = false;
});
this.setGpioToInputs('input').then(() => {
loading.dismiss();
}).catch((e) => {
console.log('error setting gpio to inputs');
console.log(e);
});
}, data.device[0].wait);
},
(err) => {
loading.dismiss();
this.toastService.createToast('deviceResetError');
},
() => { }
);
}
displayLoading(message?: string) {
message = message == undefined ? 'Resetting Device...' : message;
let loading = this.loadingCtrl.create({
content: message,
spinner: 'crescent',
cssClass: 'custom-loading-indicator'
});
loading.present();
return loading;
}
getVoltages(): Promise<any> {
let chans = [];
for (let i = 0; i < this.activeDevice.instruments.dc.numChans; i++) {
chans.push(i + 1);
}
return new Promise((resolve, reject) => {
this.activeDevice.instruments.dc.getVoltages(chans).subscribe(
(data) => {
this.dcComponent.initializeFromGetStatus(data);
resolve(data);
},
(err) => {
console.log(err);
reject(err);
},
() => {
//console.log('getVoltage Done');
}
);
});
}
getOscStatus(): Promise<any> {
return new Promise((resolve, reject) => {
let chans = [];
for (let i = 0; i < this.activeDevice.instruments.osc.numChans; i++) {
chans.push(i + 1);
}
this.activeDevice.instruments.osc.getCurrentState(chans).subscribe(
(data) => {
this.chart1.initializeFromGetStatus(data);
resolve(data);
},
(err) => {
console.log('error getting osc status');
console.log(err);
reject(err);
},
() => { }
);
});
}
getAwgStatus(): Promise<any> {
return new Promise((resolve, reject) => {
let chans = [];
for (let i = 0; i < this.activeDevice.instruments.awg.numChans; i++) {
chans.push(i + 1);
}
this.activeDevice.instruments.awg.getCurrentState(chans).subscribe(
(data) => {
console.log(data);
this.fgenComponent.initializeFromGetStatus(data);
resolve(data);
},
(err) => {
console.log('error getting awg status');
console.log(err);
reject(err);
},
() => { }
);
});
}
readCurrentGpioStates(): Promise<any> {
return new Promise((resolve, reject) => {
let chanArray = [];
for (let i = 0; i < this.activeDevice.instruments.gpio.numChans; i++) {
chanArray.push(i + 1);
}
this.activeDevice.instruments.gpio.read(chanArray).subscribe(
(data) => {
console.log(data);
resolve(data);
},
(err) => {
console.log(err);
if (err.gpio) {
let setToInputChanArray = [];
let inputStringArray = [];
for (let channel in err.gpio) {
for (let command in err.gpio[channel]) {
if (err.gpio[channel][command].statusCode === 1073741826 && err.gpio[channel][command].direction === 'tristate') {
setToInputChanArray.push(parseInt(channel));
inputStringArray.push('input');
}
else if (err.gpio[channel][command].statusCode === 1073741826 && err.gpio[channel][command].direction === 'output') {
this.gpioComponent.gpioVals[parseInt(channel) - 1] = err.gpio[channel][command].value !== 0;
this.gpioComponent.gpioDirections[parseInt(channel) - 1] = true;
}
}
}
if (setToInputChanArray.length > 0) {
this.activeDevice.instruments.gpio.setParameters(setToInputChanArray, inputStringArray).subscribe(
(data) => {
console.log(data);
resolve(data);
},
(err) => {
console.log(err);
reject(err);
},
() => { }
);
}
else {
resolve(err);
}
}
else {
reject(err);
}
},
() => { }
);
});
}
setGpioToInputs(direction: 'input' | 'output'): Promise<any> {
return new Promise((resolve, reject) => {
let chanArray = [];
let valArray = [];
for (let i = 0; i < this.activeDevice.instruments.gpio.numChans; i++) {
chanArray.push(i + 1);
valArray.push(direction);
}
this.activeDevice.instruments.gpio.setParameters(chanArray, valArray).subscribe(
(data) => {
resolve(data);
},
(err) => {
console.log(err);
reject(err);
},
() => {
}
);
});
}
applyLaBitmask(): Promise<any> {
return new Promise((resolve, reject) => {
let chanArray: number[] = [];
for (let i = 0; i < this.activeDevice.instruments.la.numChans; i++) {
chanArray.push(i + 1);
}
this.activeDevice.instruments.la.getCurrentState(chanArray).subscribe(
(data) => {
for (let group in data.la) {
let binaryString = data.la[group][0].bitmask.toString(2);
for (let i = 0; i < binaryString.length; i++) {
if (binaryString[i] === '1') {
let channel = binaryString.length - i - 1;
this.gpioComponent.toggleLaChan(channel);
}
}
}
resolve();
},
(err) => {
console.log(err);
reject(err);
},
() => { }
);
});
}
getTriggerStatus() {
return new Promise((resolve, reject) => {
this.activeDevice.instruments.trigger.getCurrentState([1]).subscribe(
(data) => {
this.triggerComponent.initializeFromGetStatus(data);
this.yaxisComponent.initializeFromGetStatus(data);
resolve(data);
},
(err) => {
console.log('error getting trigger status');
console.log(err);
reject(err);
},
() => { }
);
});
}
executeHelp() {
this.tutorialMode = false;
this.fgenComponent.finishTutorial();
this.triggerComponent.endTutorial();
}
startTutorial() {
this.tutorialStage = 1;
}
startFgenTutorial() {
this.tutorialStage = 0;
this.fgenComponent.startTutorial();
}
fgenTutorialFinished(event) {
this.startTriggerTutorial();
}
startTriggerTutorial() {
this.tutorialStage = 0;
this.triggerComponent.startTutorial();
}
triggerTutorialFinished(event) {
this.tutorialStage = 3;
}
tutorialFinished() {
this.tutorialMode = false;
this.tutorialStage = 0;
}
proceedToNextStage() {
this.tutorialStage++;
}
requestFullscreen() {
let conf = confirm("Fullscreen mode?");
let docelem: any = document.documentElement;
if (conf == true) {
if (docelem.requestFullscreen) {
docelem.requestFullscreen();
}
else if (docelem.mozRequestFullScreen) {
docelem.mozRequestFullScreen();
}
else if (docelem.webkitRequestFullScreen) {
docelem.webkitRequestFullScreen();
}
else if (docelem.msRequestFullscreen) {
docelem.msRequestFullscreen();
}
}
document.getElementById('instrument-panel-container').removeEventListener('click', this.clickBindReference);
}
ngOnDestroy() {
if (this.running) {
this.running = false;
}
this.readingLa = false;
this.readingOsc = false;
}
//Alert user with toast if no active device is set
ngOnInit() {
if (this.deviceManagerService.activeDeviceIndex === undefined) {
this.toastService.createToast('noActiveDevice', true);
}
else {
this.chartReady = true;
this.chart1.loadDeviceSpecificValues(this.activeDevice);
for (let i = 0; i < this.activeDevice.instruments.osc.numChans; i++) {
this.previousOscSettings.push({
offset: null,
gain: null,
sampleFreqMax: null,
bufferSizeMax: null,
delay: null,
active: false
});
}
for (let i = 0; i < this.activeDevice.instruments.la.numChans; i++) {
this.previousLaSettings.push({
sampleFreq: null,
bufferSize: null,
bitmask: null,
triggerDelay: null,
active: false
});
}
}
}
ionViewDidEnter() {
this.app.setTitle('Instrument Panel');
if (this.platform.is('android') && this.platform.is('mobileweb')) {
//Have to create bind reference to remove listener since .bind creates new function reference
this.clickBindReference = this.requestFullscreen.bind(this);
document.getElementById('instrument-panel-container').addEventListener('click', this.clickBindReference);
}
if (this.tutorialMode) {
this.startTutorial();
}
}
abortSingle(ignoreResponse?: boolean) {
ignoreResponse = ignoreResponse == undefined ? false : ignoreResponse;
this.activeDevice.instruments.trigger.stop([1]).subscribe(
(data) => {
if (this.running) {
this.running = false;
}
this.readingLa = false;
this.readingOsc = false;
this.triggerStatus = 'Idle';
},
(err) => {
console.log(err);
if (ignoreResponse) {
if (this.running) {
this.running = false;
}
this.readingLa = false;
this.readingOsc = false;
this.triggerStatus = 'Idle';
if (err === 'TX Error: ') {
this.toastService.createToast('timeout', true);
}
return;
}
this.toastService.createToast('triggerStopError', true);
},
() => { }
);
}
//Toggle sidecontrols
toggleControls() {
this.controlsVisible = !this.controlsVisible;
}
//Toggle bot controls
toggleBotControls() {
this.botVisible = !this.botVisible;
}
generateOscReadArray() {
}
//Run osc single
singleClick(forceWholeCommand?: boolean) {
if (this.tutorialMode) {
this.proceedToNextStage();
}
this.readAttemptCount = 0;
forceWholeCommand = forceWholeCommand == undefined ? false : forceWholeCommand;
let tempOscPrevSettings: PreviousOscSettings[] = this.createTempOscPrevSettings();
let tempLaPrevSettings: PreviousLaSettings[] = this.createTempLaPrevSettings();
if (this.chart1.oscopeChansActive.indexOf(true) === -1 && this.gpioComponent.laActiveChans.indexOf(true) === -1) {
this.toastService.createToast('noChannelsActive', true);
return;
}
this.triggerStatus = 'Armed';
let setTrigParams = false;
let setOscParams = false;
let setLaParams = false;
let trigSourceArr = this.triggerComponent.triggerSource.split(' ');
if (trigSourceArr[2] === undefined) {
trigSourceArr[2] = '1';
}
let trigType;
switch (this.triggerComponent.edgeDirection) {
case 'rising': trigType = 'risingEdge'; break;
case 'falling': trigType = 'fallingEdge'; break;
default: trigType = 'risingEdge';
}
this.currentTriggerType = this.triggerComponent.edgeDirection;
let thresholds = this.triggerComponent.getThresholdsInMillivolts();
this.theoreticalAcqTime = 0;
let triggerDelay = Math.max(Math.min(parseFloat(this.chart1.base.toString()), this.activeDevice.instruments.osc.chans[0].delayMax / Math.pow(10, 12)), this.activeDevice.instruments.osc.chans[0].delayMin / Math.pow(10, 12));
if (this.previousTrigSettings.instrument !== trigSourceArr[0] || this.previousTrigSettings.channel !== parseInt(trigSourceArr[2]) ||
this.previousTrigSettings.type !== this.triggerComponent.edgeDirection || this.previousTrigSettings.lowerThreshold !== thresholds.lowerThreshold ||
this.previousTrigSettings.upperThreshold !== thresholds.upperThreshold || this.previousTrigSettings.bitmask !== this.triggerComponent.bitmask) {
setTrigParams = true;
}
let oscArray = [[], [], [], [], [], []];
for (let i = 0; i < this.chart1.oscopeChansActive.length; i++) {
let range = this.chart1.voltDivision[i] * 10;
let j = 0;
while (range * this.activeDevice.instruments.osc.chans[i].gains[j] > this.activeDevice.instruments.osc.chans[i].adcVpp / 1000 &&
j < this.activeDevice.instruments.osc.chans[i].gains.length
) {
j++;
}
if (j > this.activeDevice.instruments.osc.chans[i].gains.length - 1) {
j--;
}
let samplingParams: { sampleFreq: number, bufferSize: number } = this.chart1.calculateDataFromWindow();
if (!this.yaxisComponent.lockedSampleState[i].sampleFreqLocked) {
samplingParams.sampleFreq = this.yaxisComponent.lockedSampleState[i].manualSampleFreq;
}
if (!this.yaxisComponent.lockedSampleState[i].sampleSizeLocked) {
samplingParams.bufferSize = this.yaxisComponent.lockedSampleState[i].manualSampleSize;
}
let vOffset = this.chart1.voltBase[i];
let maxOffsetAmp = this.activeDevice.instruments.osc.chans[i].adcVpp / (2000 * this.activeDevice.instruments.osc.chans[i].gains[j]);
vOffset = Math.max(Math.min(vOffset, maxOffsetAmp), -1 * maxOffsetAmp);
if (this.previousOscSettings[i] == undefined || this.previousOscSettings[i].offset !== vOffset ||
this.previousOscSettings[i].gain !== this.activeDevice.instruments.osc.chans[i].gains[j] ||
this.previousOscSettings[i].sampleFreqMax !== samplingParams.sampleFreq ||
this.previousOscSettings[i].bufferSizeMax !== samplingParams.bufferSize ||
this.previousOscSettings[i].delay !== triggerDelay ||
this.previousOscSettings[i].active !== this.chart1.oscopeChansActive[i]) {
setOscParams = true;
setTrigParams = true;
this.currentSamplingFrequencies[i] = samplingParams.sampleFreq;
}
if (this.chart1.oscopeChansActive[i]) {
let tempTheoreticalAcqTime = 1000 * (samplingParams.bufferSize / samplingParams.sampleFreq);
if (tempTheoreticalAcqTime > this.theoreticalAcqTime) {
this.theoreticalAcqTime = tempTheoreticalAcqTime;
}
oscArray[0].push(i + 1);
oscArray[1].push(vOffset);
oscArray[2].push(this.activeDevice.instruments.osc.chans[i].gains[j]);
oscArray[3].push(samplingParams.sampleFreq);
oscArray[4].push(samplingParams.bufferSize);
oscArray[5].push(triggerDelay);
}
tempOscPrevSettings[i] = {
offset: vOffset,
gain: this.activeDevice.instruments.osc.chans[i].gains[j],
sampleFreqMax: samplingParams.sampleFreq,
bufferSizeMax: samplingParams.bufferSize,
delay: triggerDelay,
active: this.chart1.oscopeChansActive[i]
}
}
let laArray = [[], [], [], [], []];
let bitmask = this.calculateBitmask();
for (let i = 0; i < this.gpioComponent.laActiveChans.length; i++) {
let samplingParams: { sampleFreq: number, bufferSize: number } = this.chart1.calculateDataFromWindow();
if (this.previousLaSettings[i] == undefined || this.previousLaSettings[i].sampleFreq !== samplingParams.sampleFreq ||
this.previousLaSettings[i].bufferSize !== samplingParams.bufferSize ||
this.previousLaSettings[i].active !== this.gpioComponent.laActiveChans[i] ||
this.previousLaSettings[i].bitmask !== bitmask ||
this.previousLaSettings[i].triggerDelay !== triggerDelay) {
setLaParams = true;
setTrigParams = true;
}
if (this.gpioComponent.laActiveChans[i]) {
laArray[0] = [1]; //TODO actually setup chans for multiple groups
laArray[1].push(samplingParams.sampleFreq);
laArray[2].push(samplingParams.bufferSize);
laArray[3].push(bitmask);
laArray[4].push(triggerDelay);
}
tempLaPrevSettings[i] = {
bitmask: bitmask,
triggerDelay: triggerDelay,
sampleFreq: samplingParams.sampleFreq,
bufferSize: samplingParams.bufferSize,
active: this.gpioComponent.laActiveChans[i]
}
}
this.currentLaReadArray = laArray[0];
this.currentOscReadArray = oscArray[0];
let singleCommand = {};
let targetsObject = {};
if (oscArray[0].length > 0) {
targetsObject['osc'] = oscArray[0];
this.readingOsc = true;
}
if (laArray[0].length > 0) {
targetsObject['la'] = laArray[0];
this.readingLa = true;
}
if ((setOscParams || forceWholeCommand) && oscArray[0].length > 0) {
singleCommand['osc'] = {};
singleCommand['osc']['setParameters'] = [oscArray[0], oscArray[1], oscArray[2], oscArray[3], oscArray[4], oscArray[5]];
}
if ((setLaParams || forceWholeCommand) && laArray[0].length > 0) {
singleCommand['la'] = {};
singleCommand['la']['setParameters'] = [laArray[0], laArray[3], laArray[1], laArray[2], laArray[4]];
}
singleCommand['trigger'] = {};
if (setTrigParams || forceWholeCommand) {
let sourceObject;
if (trigSourceArr[0] === 'LA') {
let fallingBitmask = this.triggerComponent.getFallingBitmask();
let risingBitmask = this.triggerComponent.getRisingBitmask();
if (fallingBitmask === 0 && risingBitmask === 0) {
sourceObject = {
instrument: 'force'
};
}
else {
sourceObject = {
instrument: 'la',
channel: 1,
risingEdge: risingBitmask,
fallingEdge: fallingBitmask
};
}
}
else {
if (this.triggerComponent.edgeDirection === 'off') {
sourceObject = {
instrument: 'force'
};
}
else {
sourceObject = {
instrument: trigSourceArr[0].toLowerCase(),
channel: parseInt(trigSourceArr[2]),
type: trigType,
lowerThreshold: thresholds.lowerThreshold,
upperThreshold: thresholds.upperThreshold
};
}
}
singleCommand['trigger']['setParameters'] = [
[1],
[
sourceObject
],
[
targetsObject
]
];
}
//TODO if trigger single error, send whole set parameter multi command.
singleCommand['trigger']['single'] = [[1]];
/*if (this.triggerComponent.edgeDirection === 'off') {
singleCommand['trigger']['forceTrigger'] = [[1]];
}*/
console.log(singleCommand);
this.activeDevice.multiCommand(singleCommand).subscribe(
(data) => {
console.log(data);
},
(err) => {
console.log(err);
if (this.running) {
this.running = false;
this.readingOsc = false;
this.readingLa = false;
}
if (err.agent != undefined) {
this.toastService.createToast('agentNoActiveDevice');
}
else if (err.command) {
if (err.statusCode === 2684354573) {
this.toastService.createToast('deviceInstrumentInUse', true, undefined, 5000);
}
else {
this.displayErrorFromCommand(err.command);
}
}
else {
this.toastService.createToast('deviceDroppedConnection', true);
}
//Might still acquiring from previous session
this.abortSingle(true);
},
() => {
this.previousOscSettings = tempOscPrevSettings;
this.previousLaSettings = tempLaPrevSettings;
if (this.activeDevice.transport.getType() !== 'local') {
setTimeout(() => {
this.readBuffers();
}, this.theoreticalAcqTime);
}
else {
this.readBuffers();
}
}
);
this.previousTrigSettings = {
instrument: trigSourceArr[0],
channel: parseInt(trigSourceArr[2]),
type: this.triggerComponent.edgeDirection,
lowerThreshold: thresholds.lowerThreshold,
upperThreshold: thresholds.upperThreshold,
bitmask: this.triggerComponent.bitmask
};
}
displayErrorFromCommand(command) {
let errorToDisplay = 'genericSingleError';
switch (command) {
case 'setParameters':
errorToDisplay = 'oscSetParamError';
break;
default:
break;
}
this.toastService.createToast(errorToDisplay, true);
}
readBuffers() {
console.log('READING OSCOPE');
this.readOscope(this.currentOscReadArray)
.then(() => {
console.log('READING LA');
return this.readLa(this.currentLaReadArray);
})
.then(() => {
console.log('CHECKING READ STATUS');
this.checkReadStatusAndDraw();
})
.catch((e) => {
this.running = false;
this.readingOsc = false;
this.readingLa = false;
console.log(e);
});
}
calculateBitmask(): number {
let sum = 0;
for (let i = 0; i < this.gpioComponent.laActiveChans.length; i++) {
if (this.gpioComponent.laActiveChans[i]) {
sum += Math.pow(2, i);
}
}
return sum;
}
readLa(readArray: number[]): Promise<any> {
/*for (let i = 0; i < this.gpioComponent.laActiveChans.length; i++) {
if (this.gpioComponent.laActiveChans[i]) {
readArray.push(i + 1);
}
}*/
return new Promise((resolve, reject) => {
if (readArray.length < 1) {
this.readingLa = false;
resolve();
return;
}
this.activeDevice.instruments.la.read(readArray).subscribe(
(data) => {
this.readingLa = false;
console.log(data);
this.readAttemptCount = 0;
resolve();
//this.checkReadStatusAndDraw();
},
(err) => {
if (err === 'corrupt transfer') {
if (this.errorCount % 5 === 0) {
this.displaySlowUSBMessage();
}
this.errorCount++;
}
if (this.readingLa) {
console.log('attempting read again');
this.readAttemptCount++;
let waitTime = this.readAttemptCount * 100 > 1000 ? 1000 : this.readAttemptCount * 100;
setTimeout(() => {
this.readLa(readArray)
.then(() => {
resolve();
})
.catch((e) => {
reject(e);
});
}, waitTime);
}
},
() => { }
);
});
}
checkReadStatusAndDraw() {
console.log('check read status and draw');
if (this.readingOsc || this.readingLa) {
return;
}
/*if (this.chart1.oscopeChansActive.indexOf(true) === -1 && this.gpioComponent.laActiveChans.indexOf(true) === -1) {
if (this.running) {
this.running = false;
}
return;
}*/
let numSeries = [];
for (let i = 0; i < this.currentOscReadArray.length; i++) {
numSeries.push(this.currentOscReadArray[i] - 1);
}
for (let i = 0; i < this.currentLaReadArray.length; i++) {
let channelNum = 0;
for (let j = 0; j < this.activeDevice.instruments.la.chans[i].numDataBits; j++) {
channelNum++;
if (this.activeDevice.instruments.la.dataBuffer[this.activeDevice.instruments.la.dataBufferReadIndex][j] && this.activeDevice.instruments.la.dataBuffer[this.activeDevice.instruments.la.dataBufferReadIndex][j].data) {
numSeries.push(channelNum - 1 + this.chart1.oscopeChansActive.length);
}
}
}
this.chart1.clearExtraSeries(numSeries);
let currentBufferArray;
let oscBufferArray = [];
let laBufferArray = null;
if (this.currentOscReadArray.length > 0) {
oscBufferArray = this.activeDevice.instruments.osc.dataBuffer[this.activeDevice.instruments.osc.dataBufferReadIndex];
}
for (let i = 0; i < this.chart1.oscopeChansActive.length; i++) {
if (oscBufferArray[i] == undefined) {
oscBufferArray[i] = [];
}
}
currentBufferArray = oscBufferArray;
if (this.currentLaReadArray.length > 0) {
laBufferArray = this.activeDevice.instruments.la.dataBuffer[this.activeDevice.instruments.la.dataBufferReadIndex];
currentBufferArray = currentBufferArray.concat(laBufferArray);
}
/*if (oscBufferArray == null) {
currentBufferArray = oscFillerBuff.concat(laBufferArray);
}
else {
currentBufferArray = laBufferArray ? oscBufferArray.concat(oscFillerBuff).concat(laBufferArray) : oscBufferArray.concat(oscFillerBuff);
}*/
this.chart1.setCurrentBuffer(currentBufferArray);
let start = performance.now();
this.chart1.flotDrawWaveform(true, false);
let finish = performance.now();
console.log('decimate and draw: ' + (finish - start));
this.triggerStatus = 'Idle';
if (this.running) {
this.runClick();
}
}
readOscope(readArray: number[]): Promise<any> {
/*let readArray = [];*/
/*for (let i = 0; i < this.chart1.oscopeChansActive.length; i++) {
if (this.chart1.oscopeChansActive[i]) {
readArray.push(i + 1);
}
}*/
return new Promise((resolve, reject) => {
if (readArray.length < 1) {
this.readingOsc = false;
resolve();
return;
}
this.activeDevice.instruments.osc.read(readArray).subscribe(
(data) => {
this.readingOsc = false;
this.readAttemptCount = 0;
resolve();
//this.checkReadStatusAndDraw();
},
(err) => {
if (err === 'corrupt transfer') {
if ((this.errorCount % 5) === 0) {
this.displaySlowUSBMessage();
}
this.errorCount++;
}
if (this.readingOsc) {
console.log('attempting read again');
this.readAttemptCount++;
let waitTime = this.readAttemptCount * 100 > 1000 ? 1000 : this.readAttemptCount * 100;
setTimeout(() => {
this.readOscope(readArray)
.then(() => {
resolve();
})
.catch((e) => {
reject(e);
});
}, waitTime);
}
},
() => {
}
);
});
}
createTempOscPrevSettings(): PreviousOscSettings[] {
//Need to copy previous instead of setting equal so that setting values on temp doesn't set values on the perm
let tempOscPrevSettings: PreviousOscSettings[] = [];
for (let i = 0; i < this.previousOscSettings.length; i++) {
let settingsCopy: PreviousOscSettings = Object.assign({}, this.previousOscSettings[i]);
tempOscPrevSettings.push(settingsCopy);
}
return tempOscPrevSettings
}
createTempLaPrevSettings(): PreviousLaSettings[] {
//Need to copy previous instead of setting equal so that setting values on temp doesn't set values on the perm
let tempLaPrevSettings: PreviousLaSettings[] = [];
for (let i = 0; i < this.previousLaSettings.length; i++) {
let settingsCopy: PreviousLaSettings = Object.assign({}, this.previousLaSettings[i]);
tempLaPrevSettings.push(settingsCopy);
}
return tempLaPrevSettings;
}
checkAndSetParams(): Promise<any> {
return new Promise((resolve, reject) => {
let setOscParams = false;
let setLaParams = false;
let currentTheoreticalAcqTime = this.theoreticalAcqTime;
let tempOscPrevSettings: PreviousOscSettings[] = this.createTempOscPrevSettings();
let tempLaPrevSettings: PreviousLaSettings[] = this.createTempLaPrevSettings();
//Recalc acq time
this.theoreticalAcqTime = 0;
for (let i = 0; i < this.currentOscReadArray.length; i++) {
let samplingParams: { sampleFreq: number, bufferSize: number } = this.chart1.calculateDataFromWindow();
if (!this.yaxisComponent.lockedSampleState[i].sampleFreqLocked) {
samplingParams.sampleFreq = this.yaxisComponent.lockedSampleState[i].manualSampleFreq;
}
if (!this.yaxisComponent.lockedSampleState[i].sampleSizeLocked) {
samplingParams.bufferSize = this.yaxisComponent.lockedSampleState[i].manualSampleSize;
}
if (this.previousOscSettings[this.currentOscReadArray[i] - 1].sampleFreqMax !== samplingParams.sampleFreq ||
this.previousOscSettings[this.currentOscReadArray[i] - 1].bufferSizeMax !== samplingParams.bufferSize) {
setOscParams = true;
this.currentSamplingFrequencies[this.currentOscReadArray[i] - 1] = samplingParams.sampleFreq;
let tempTheoreticalAcqTime = 1000 * (samplingParams.bufferSize / samplingParams.sampleFreq);
if (tempTheoreticalAcqTime > this.theoreticalAcqTime) {
this.theoreticalAcqTime = tempTheoreticalAcqTime;
}
tempOscPrevSettings[this.currentOscReadArray[i] - 1].sampleFreqMax = samplingParams.sampleFreq;
tempOscPrevSettings[this.currentOscReadArray[i] - 1].bufferSizeMax = samplingParams.bufferSize;
/*this.previousOscSettings[this.currentOscReadArray[i] - 1].sampleFreqMax = samplingParams.sampleFreq;
this.previousOscSettings[this.currentOscReadArray[i] - 1].bufferSizeMax = samplingParams.bufferSize;*/
}
}
for (let i = 0; i < this.currentLaReadArray.length; i++) {
let samplingParams: { sampleFreq: number, bufferSize: number } = this.chart1.calculateDataFromWindow();
if (this.previousLaSettings[this.currentLaReadArray[i] - 1].sampleFreq !== samplingParams.sampleFreq ||
this.previousLaSettings[this.currentLaReadArray[i] - 1].bufferSize !== samplingParams.bufferSize) {
setLaParams = true;
}
tempLaPrevSettings[this.currentLaReadArray[i] - 1].sampleFreq = samplingParams.sampleFreq;
tempLaPrevSettings[this.currentLaReadArray[i] - 1].bufferSize = samplingParams.bufferSize;
/*this.previousLaSettings[this.currentLaReadArray[i] - 1].sampleFreq = samplingParams.sampleFreq;
this.previousLaSettings[this.currentLaReadArray[i] - 1].bufferSize = samplingParams.bufferSize;*/
}
if (setOscParams) {
let params: { chans: number[], offsets: number[], gains: number[], sampleFreqs: number[], bufferSizes: number[], delays: number[] } = {
chans: [],
offsets: [],
gains: [],
sampleFreqs: [],
bufferSizes: [],
delays: []
};
for (let i = 0; i < this.currentOscReadArray.length; i++) {
params.chans.push(this.currentOscReadArray[i] - 1);
params.offsets.push(tempOscPrevSettings[this.currentOscReadArray[i] - 1].offset);
params.gains.push(tempOscPrevSettings[this.currentOscReadArray[i] - 1].gain);
params.sampleFreqs.push(tempOscPrevSettings[this.currentOscReadArray[i] - 1].sampleFreqMax);
params.bufferSizes.push(tempOscPrevSettings[this.currentOscReadArray[i] - 1].bufferSizeMax);
params.delays.push(tempOscPrevSettings[this.currentOscReadArray[i] - 1].delay);
}
this.activeDevice.instruments.osc.setParameters(this.currentOscReadArray, params.offsets, params.gains, params.sampleFreqs, params.bufferSizes, params.delays)
.flatMap((data) => {
console.log(data);
if (setLaParams) {
let params: { chans: number[], bitmasks: number[], sampleFreqs: number[], bufferSizes: number[], delays: number[] } = {
chans: [],
bitmasks: [],
sampleFreqs: [],
bufferSizes: [],
delays: []
};
for (let i = 0; i < this.currentLaReadArray.length; i++) {
params.chans.push(this.currentLaReadArray[i] - 1);
params.bitmasks.push(tempLaPrevSettings[this.currentLaReadArray[i] - 1].bitmask);
params.sampleFreqs.push(tempLaPrevSettings[this.currentLaReadArray[i] - 1].sampleFreq);
params.bufferSizes.push(tempLaPrevSettings[this.currentLaReadArray[i] - 1].bufferSize);
params.delays.push(tempLaPrevSettings[this.currentLaReadArray[i] - 1].triggerDelay);
}
return this.activeDevice.instruments.la.setParameters(this.currentLaReadArray, params.bitmasks, params.sampleFreqs, params.bufferSizes, params.delays);
}
else {
return Promise.resolve(data);
}
})
.subscribe(
(data) => {
console.log(data);
this.previousOscSettings = tempOscPrevSettings;
this.previousLaSettings = tempLaPrevSettings;
resolve();
},
(err) => {
console.log(err);
reject(err);
},
() => { }
);
}
if (setLaParams && !setOscParams) {
let params: { chans: number[], bitmasks: number[], sampleFreqs: number[], bufferSizes: number[], delays: number[] } = {
chans: [],
bitmasks: [],
sampleFreqs: [],
bufferSizes: [],
delays: []
};
for (let i = 0; i < this.currentLaReadArray.length; i++) {
params.chans.push(this.currentLaReadArray[i] - 1);
params.bitmasks.push(tempLaPrevSettings[this.currentLaReadArray[i] - 1].bitmask);
params.sampleFreqs.push(tempLaPrevSettings[this.currentLaReadArray[i] - 1].sampleFreq);
params.bufferSizes.push(tempLaPrevSettings[this.currentLaReadArray[i] - 1].bufferSize);
params.delays.push(tempLaPrevSettings[this.currentLaReadArray[i] - 1].triggerDelay);
}
this.activeDevice.instruments.la.setParameters(this.currentLaReadArray, params.bitmasks, params.sampleFreqs, params.bufferSizes, params.delays).subscribe(
(data) => {
console.log(data);
this.previousLaSettings = tempLaPrevSettings;
resolve();
},
(err) => {
console.log(err);
reject(err);
},
() => { }
);
}
if (!setOscParams && !setLaParams) {
this.theoreticalAcqTime = currentTheoreticalAcqTime;
resolve();
}
});
}
//Stream osc buffers
runClick() {
if (this.readingOsc || this.readingLa) { return; }
if (!this.running) {
//first iteration
this.running = true;
this.singleClick();
return;
}
this.checkAndSetParams()
.then(() => {
this.activeDevice.instruments.trigger.single([1]).subscribe(
(data) => {
},
(err) => {
this.runClick(); // check once more
console.log('error trigger single', err);
},
() => {
this.triggerStatus = 'Armed';
for (let i = 0; i < this.gpioComponent.laActiveChans.length; i++) {
if (this.gpioComponent.laActiveChans[i]) {
this.readingLa = true;
break;
}
}
for (let i = 0; i < this.chart1.oscopeChansActive.length; i++) {
if (this.chart1.oscopeChansActive[i]) {
this.readingOsc = true;
break;
}
}
setTimeout(() => {
this.readBuffers();
}, this.theoreticalAcqTime);
}
);
})
.catch((e) => {
console.log('ERROR SETTINGS OSC PARAMS DURING RUN');
console.log(e);
for (let instrument in e) {
for (let channel in e[instrument]) {
e[instrument][channel].forEach((value, index, array) => {
if (value.command) {
this.displayErrorFromCommand(value.command);
}
});
}
}
if (this.running) {
this.running = false;
}
this.readingLa = false;
this.readingOsc = false;
});
}
//Stop dc stream
stopClick() {
console.log('stop click!');
if (!this.running) {
return;
}
this.running = false;
this.abortSingle(true);
}
//Enable cursors and timeline view
initSettings() {
this.chart1.enableCursors();
this.chart1.enableTimelineView();
this.chart1.enableMath();
}
public displaySlowUSBMessage(): Promise<void> {
return new Promise<void>((resolve, reject) => {
// display a toast because it is less obtrusive than a modal
let toast = this.toastService.toastCtrl.create({
message: 'Data Transfer Issue: Some data chunks were lost. Visit the Digilent Forums for more info.',
duration: 5000,
showCloseButton: true
});
toast.present();
resolve();
});
}
} | the_stack |
import React, { Component } from 'react'
import Taro, { createSelectorQuery, getSystemInfoSync } from '@tarojs/taro'
import { View, ScrollView, Block } from '@tarojs/components'
import PropTypes, { InferProps } from 'prop-types'
import { VirtualListProps, VirtualListState } from "../../../@types/virtualList"
import { throttle, isH5 } from '../../common/utils'
export default class VirtialList extends Component<VirtualListProps, VirtualListState> {
public static propTypes: InferProps<VirtualListProps>
public static defaultProps: VirtualListProps
constructor(props: VirtualListProps) {
super(props)
this.state = {
wholePageIndex: 0, // 每一屏为一个单位,屏幕索引
twoList: [], // 二维数组
isComplete: false, // 数据是否全部加载完成
innerScrollTop: 0, // 记录组件内部的滚动高度
} as VirtualListState
}
componentDidMount(): void {
const { list, listType } = this.props
this.getSystemInformation()
if (listType === "single") {
this.formatList(list)
} else if (listType === "multi") {
this.formatMultiList(list)
}
}
UNSAFE_componentWillReceiveProps(nextProps: VirtualListProps): void {
const { list, listType } = this.props
if (listType === "single") {
// 提前把innerScrollTop置为不是0,防止列表置顶失效
this.setState({
innerScrollTop: 1,
})
if (JSON.stringify(nextProps.list) !== JSON.stringify(list)) {
this.pageHeightArr = []
this.setState({
wholePageIndex: 0,
isComplete: false,
twoList: [],
innerScrollTop: 0,
}, () => {
if (nextProps.list?.length) {
this.formatList(nextProps.list)
} else {
this.handleComplete()
}
})
}
} else if (listType === "multi") {
if (JSON.stringify(nextProps.list) !== JSON.stringify(list)) {
this.formatMultiList(nextProps.list, nextProps.pageNum)
}
}
if (!nextProps.list?.length) {
// list为空
this.handleComplete()
}
}
private pageHeightArr: number[] = [] // 用来装每一屏的高度
private initList: any[] = [] // 承载初始化的二维数组
private windowHeight = 0 // 当前屏幕的高度
private currentPage: any = Taro.getCurrentInstance()
private observer: IntersectionObserver
getSystemInformation = ():void => {
try {
const res = getSystemInfoSync()
this.windowHeight = res.windowHeight
} catch (err) {
console.error(`获取系统信息失败:${err}`)
}
}
/**
* 列表数据渲染完成
*/
handleComplete = ():void => {
const { onComplete } = this.props
this.setState({
isComplete: true,
}, () => {
onComplete?.()
})
}
/**
* 当list是通过服务端分页获取的时候,对list进行处理
* @param list 外部list
* @param pageNum 当前页码
*/
formatMultiList(list: any[] = [], pageNum = 1): void {
const { twoList} = this.state
if (!list?.length) return
this.segmentList(list)
twoList[pageNum - 1] = this.initList[pageNum - 1]
this.setState({
twoList: [...twoList],
wholePageIndex: pageNum - 1,
}, () => {
Taro.nextTick(() => {
this.setHeight(list)
})
})
}
/**
* 按规则分割list,存在私有变量initList,备用
*/
segmentList(list: any[] = []): void {
const { segmentNum } = this.props
let arr: any[] = []
const _list: any[] = []
list.forEach((item, index) => {
arr.push(item)
if ((index + 1) % segmentNum === 0) {
_list.push(arr)
arr = []
}
})
// 将分段不足segmentNum的剩余数据装入_list
const restList = list.slice(_list.length * segmentNum)
if (restList?.length) {
_list.push(restList)
if (_list.length <= 1) {
// 如果数据量少,不足一个segmentNum,则触发完成回调
this.handleComplete()
}
}
this.initList = _list
}
/**
* 将列表格式化为二维
* @param list 列表
*/
formatList(list: any[] = []): void {
this.segmentList(list)
this.setState({
twoList: this.initList.slice(0, 1),
}, () => {
Taro.nextTick(() => {
this.setHeight(list)
})
})
}
renderNext = (): void => {
const { onBottom, listType, scrollViewProps, list } = this.props
if (listType === "single") {
const page_index = this.state.wholePageIndex + 1
if (!this.initList[page_index]?.length) {
this.handleComplete()
return
}
onBottom?.()
this.setState({
wholePageIndex: page_index,
}, () => {
const { wholePageIndex, twoList } = this.state
twoList[wholePageIndex] = this.initList[wholePageIndex]
this.setState({
twoList: [...twoList],
}, () => {
Taro.nextTick(() => {
this.setHeight(list)
})
})
})
} else if (listType === "multi") {
scrollViewProps?.onScrollToLower?.()
}
}
/**
* 设置每一个维度的数据渲染完成之后所占的高度
*/
setHeight(list: any[] = []):void {
const { wholePageIndex } = this.state
const { listId } = this.props
const query = createSelectorQuery()
query.select(`#${listId} .wrap_${wholePageIndex}`).boundingClientRect()
query.exec((res) => {
// 有数据的时候才去收集高度,不然页面初始化渲染(在H5中无数据)收集到的高度是错误的
if (list?.length) {
this.pageHeightArr.push(res?.[0]?.height)
}
})
this.handleObserve()
}
webObserve = (): void => {
const { listId } = this.props
const $targets = document.querySelectorAll(`#${listId} .zt-main-list>taro-view-core`)
const options = {
root: document.querySelector(`#${listId}`),
rootMargin: "500px 0px",
// threshold: [0.5],
}
this.observer = new IntersectionObserver(this.observerCallBack, options)
$targets.forEach($item => {
this.observer?.observe($item)
})
}
observerCallBack = (entries: IntersectionObserverEntry[]): void => {
const { twoList } = this.state
entries.forEach((item ) => {
const screenIndex = item.target['data-index']
if (item.isIntersecting) {
// 如果有相交区域,则将对应的维度进行赋值
twoList[screenIndex] = this.initList[screenIndex]
this.setState({
twoList: [...twoList],
})
} else {
// 当没有与当前视口有相交区域,则将改屏的数据置为该屏的高度占位
twoList[screenIndex] = { height: this.pageHeightArr[screenIndex] }
this.setState({
twoList: [...twoList],
})
}
})
}
/**
* 监听可视区域
*/
handleObserve = (): void => {
if (isH5) {
this.webObserve()
} else {
this.miniObserve()
}
}
/**
* 小程序平台监听
*/
miniObserve = (): void => {
const { wholePageIndex } = this.state
const { scrollViewProps, listId, screenNum } = this.props
// 以传入的scrollView的高度为相交区域的参考边界,若没传,则默认使用屏幕高度
const scrollHeight = scrollViewProps?.style?.height || this.windowHeight
const observer = Taro.createIntersectionObserver(this.currentPage.page).relativeToViewport({
top: screenNum * scrollHeight,
bottom: screenNum * scrollHeight,
})
observer.observe(`#${listId} .wrap_${wholePageIndex}`, (res) => {
const { twoList } = this.state
if (res?.intersectionRatio <= 0) {
// 当没有与当前视口有相交区域,则将改屏的数据置为该屏的高度占位
twoList[wholePageIndex] = { height: this.pageHeightArr[wholePageIndex] }
this.setState({
twoList: [...twoList],
})
} else if (!twoList[wholePageIndex]?.length) {
// 如果有相交区域,则将对应的维度进行赋值
twoList[wholePageIndex] = this.initList[wholePageIndex]
this.setState({
twoList: [...twoList],
})
}
})
}
handleScroll = throttle((event: any): void => {
const { listId } = this.props
this.props.onGetScrollData?.({
[`${listId}`]: event,
})
this.props.scrollViewProps?.onScroll?.(event)
}, 300, 300)
render(): JSX.Element {
const {
twoList,
isComplete,
innerScrollTop,
} = this.state
const {
segmentNum,
scrollViewProps,
onRenderTop,
onRenderBottom,
onRender,
onRenderLoad,
listId,
className,
autoScrollTop,
} = this.props
const scrollStyle = {
height: '100%',
}
const _scrollViewProps = {
...scrollViewProps,
scrollTop: autoScrollTop ? (innerScrollTop === 0 ? 0 : "") : scrollViewProps?.scrollTop,
}
return (
<ScrollView
scrollY
id={listId}
style={scrollStyle}
onScrollToLower={this.renderNext}
lowerThreshold={250}
className={`zt-virtual-list-container ${className}`}
{..._scrollViewProps}
onScroll={this.handleScroll}
>
{onRenderTop?.()}
<View className="zt-main-list">
{
twoList?.map((item, pageIndex) => {
return (
<View key={pageIndex} data-index={pageIndex} className={`zt-wrap-item wrap_${pageIndex}`}>
{
item?.length > 0 ? (
<Block>
{
item.map((el, index) => {
return onRender?.(el, (pageIndex * segmentNum + index), pageIndex)
})
}
</Block>
) : (
<View style={{'height': `${item?.height}px`}}></View>
)
}
</View>
)
})
}
</View>
{
onRenderLoad?.() && (
<View className="zt-loading-text">
{onRenderLoad()}
</View>
)
}
{isComplete && onRenderBottom?.()}
</ScrollView>
)
}
}
VirtialList.defaultProps = {
list: [],
pageNum: 1,
listId: "zt-virtial-list",
listType: 'single',
segmentNum: 10,
screenNum: 2,
scrollViewProps: {},
className: "",
autoScrollTop: true,
onRender: function render() {
return (<View />)
},
}
VirtialList.propTypes = {
list: PropTypes.array.isRequired,
listId: PropTypes.string,
listType: PropTypes.string,
segmentNum: PropTypes.number,
screenNum: PropTypes.number,
autoScrollTop: PropTypes.bool,
scrollViewProps: PropTypes.object,
onRender: PropTypes.func.isRequired,
onBottom: PropTypes.func,
onComplete: PropTypes.func,
onRenderTop: PropTypes.func,
onRenderBottom: PropTypes.func,
onGetScrollData: PropTypes.func,
} | the_stack |
import * as cdk from '@aws-cdk/core';
import { CfnRoute } from './appmesh.generated';
import { HeaderMatch } from './header-match';
import { HttpRouteMethod } from './http-route-method';
import { HttpRoutePathMatch } from './http-route-path-match';
import { validateGrpcRouteMatch, validateGrpcMatchArrayLength, validateHttpMatchArrayLength } from './private/utils';
import { QueryParameterMatch } from './query-parameter-match';
import { GrpcTimeout, HttpTimeout, Protocol, TcpTimeout } from './shared-interfaces';
import { IVirtualNode } from './virtual-node';
// keep this import separate from other imports to reduce chance for merge conflicts with v2-main
// eslint-disable-next-line no-duplicate-imports, import/order
import { Construct } from '@aws-cdk/core';
/**
* Properties for the Weighted Targets in the route
*/
export interface WeightedTarget {
/**
* The VirtualNode the route points to
*/
readonly virtualNode: IVirtualNode;
/**
* The weight for the target
*
* @default 1
*/
readonly weight?: number;
}
/**
* The criterion for determining a request match for this Route
*/
export interface HttpRouteMatch {
/**
* Specifies how is the request matched based on the path part of its URL.
*
* @default - matches requests with all paths
*/
readonly path?: HttpRoutePathMatch;
/**
* Specifies the client request headers to match on. All specified headers
* must match for the route to match.
*
* @default - do not match on headers
*/
readonly headers?: HeaderMatch[];
/**
* The HTTP client request method to match on.
*
* @default - do not match on request method
*/
readonly method?: HttpRouteMethod;
/**
* The client request protocol to match on. Applicable only for HTTP2 routes.
*
* @default - do not match on HTTP2 request protocol
*/
readonly protocol?: HttpRouteProtocol;
/**
* The query parameters to match on.
* All specified query parameters must match for the route to match.
*
* @default - do not match on query parameters
*/
readonly queryParameters?: QueryParameterMatch[];
}
/**
* Supported :scheme options for HTTP2
*/
export enum HttpRouteProtocol {
/**
* Match HTTP requests
*/
HTTP = 'http',
/**
* Match HTTPS requests
*/
HTTPS = 'https',
}
/**
* The criterion for determining a request match for this Route.
* At least one match type must be selected.
*/
export interface GrpcRouteMatch {
/**
* Create service name based gRPC route match.
*
* @default - do not match on service name
*/
readonly serviceName?: string;
/**
* Create metadata based gRPC route match.
* All specified metadata must match for the route to match.
*
* @default - do not match on metadata
*/
readonly metadata?: HeaderMatch[];
/**
* The method name to match from the request.
* If the method name is specified, service name must be also provided.
*
* @default - do not match on method name
*/
readonly methodName?: string;
}
/**
* Base options for all route specs.
*/
export interface RouteSpecOptionsBase {
/**
* The priority for the route. When a Virtual Router has multiple routes, route match is performed in the
* order of specified value, where 0 is the highest priority, and first matched route is selected.
*
* @default - no particular priority
*/
readonly priority?: number;
}
/**
* Properties specific for HTTP Based Routes
*/
export interface HttpRouteSpecOptions extends RouteSpecOptionsBase {
/**
* The criterion for determining a request match for this Route
*
* @default - matches on '/'
*/
readonly match?: HttpRouteMatch;
/**
* List of targets that traffic is routed to when a request matches the route
*/
readonly weightedTargets: WeightedTarget[];
/**
* An object that represents a http timeout
*
* @default - None
*/
readonly timeout?: HttpTimeout;
/**
* The retry policy
*
* @default - no retry policy
*/
readonly retryPolicy?: HttpRetryPolicy;
}
/**
* HTTP retry policy
*/
export interface HttpRetryPolicy {
/**
* Specify HTTP events on which to retry. You must specify at least one value
* for at least one types of retry events.
*
* @default - no retries for http events
*/
readonly httpRetryEvents?: HttpRetryEvent[];
/**
* The maximum number of retry attempts
*/
readonly retryAttempts: number;
/**
* The timeout for each retry attempt
*/
readonly retryTimeout: cdk.Duration;
/**
* TCP events on which to retry. The event occurs before any processing of a
* request has started and is encountered when the upstream is temporarily or
* permanently unavailable. You must specify at least one value for at least
* one types of retry events.
*
* @default - no retries for tcp events
*/
readonly tcpRetryEvents?: TcpRetryEvent[];
}
/**
* HTTP events on which to retry.
*/
export enum HttpRetryEvent {
/**
* HTTP status codes 500, 501, 502, 503, 504, 505, 506, 507, 508, 510, and 511
*/
SERVER_ERROR = 'server-error',
/**
* HTTP status codes 502, 503, and 504
*/
GATEWAY_ERROR = 'gateway-error',
/**
* HTTP status code 409
*/
CLIENT_ERROR = 'client-error',
/**
* Retry on refused stream
*/
STREAM_ERROR = 'stream-error',
}
/**
* TCP events on which you may retry
*/
export enum TcpRetryEvent {
/**
* A connection error
*/
CONNECTION_ERROR = 'connection-error',
}
/**
* Properties specific for a TCP Based Routes
*/
export interface TcpRouteSpecOptions extends RouteSpecOptionsBase {
/**
* List of targets that traffic is routed to when a request matches the route
*/
readonly weightedTargets: WeightedTarget[];
/**
* An object that represents a tcp timeout
*
* @default - None
*/
readonly timeout?: TcpTimeout;
}
/**
* Properties specific for a GRPC Based Routes
*/
export interface GrpcRouteSpecOptions extends RouteSpecOptionsBase {
/**
* The criterion for determining a request match for this Route
*/
readonly match: GrpcRouteMatch;
/**
* An object that represents a grpc timeout
*
* @default - None
*/
readonly timeout?: GrpcTimeout;
/**
* List of targets that traffic is routed to when a request matches the route
*/
readonly weightedTargets: WeightedTarget[];
/**
* The retry policy
*
* @default - no retry policy
*/
readonly retryPolicy?: GrpcRetryPolicy;
}
/** gRPC retry policy */
export interface GrpcRetryPolicy extends HttpRetryPolicy {
/**
* gRPC events on which to retry. You must specify at least one value
* for at least one types of retry events.
*
* @default - no retries for gRPC events
*/
readonly grpcRetryEvents?: GrpcRetryEvent[];
}
/**
* gRPC events
*/
export enum GrpcRetryEvent {
/**
* Request was cancelled
*
* @see https://grpc.github.io/grpc/core/md_doc_statuscodes.html
*/
CANCELLED = 'cancelled',
/**
* The deadline was exceeded
*
* @see https://grpc.github.io/grpc/core/md_doc_statuscodes.html
*/
DEADLINE_EXCEEDED = 'deadline-exceeded',
/**
* Internal error
*
* @see https://grpc.github.io/grpc/core/md_doc_statuscodes.html
*/
INTERNAL_ERROR = 'internal',
/**
* A resource was exhausted
*
* @see https://grpc.github.io/grpc/core/md_doc_statuscodes.html
*/
RESOURCE_EXHAUSTED = 'resource-exhausted',
/**
* The service is unavailable
*
* @see https://grpc.github.io/grpc/core/md_doc_statuscodes.html
*/
UNAVAILABLE = 'unavailable',
}
/**
* All Properties for Route Specs
*/
export interface RouteSpecConfig {
/**
* The spec for an http route
*
* @default - no http spec
*/
readonly httpRouteSpec?: CfnRoute.HttpRouteProperty;
/**
* The spec for an http2 route
*
* @default - no http2 spec
*/
readonly http2RouteSpec?: CfnRoute.HttpRouteProperty;
/**
* The spec for a grpc route
*
* @default - no grpc spec
*/
readonly grpcRouteSpec?: CfnRoute.GrpcRouteProperty;
/**
* The spec for a tcp route
*
* @default - no tcp spec
*/
readonly tcpRouteSpec?: CfnRoute.TcpRouteProperty;
/**
* The priority for the route. When a Virtual Router has multiple routes, route match is performed in the
* order of specified value, where 0 is the highest priority, and first matched route is selected.
*
* @default - no particular priority
*/
readonly priority?: number;
}
/**
* Used to generate specs with different protocols for a RouteSpec
*/
export abstract class RouteSpec {
/**
* Creates an HTTP Based RouteSpec
*/
public static http(options: HttpRouteSpecOptions): RouteSpec {
return new HttpRouteSpec(options, Protocol.HTTP);
}
/**
* Creates an HTTP2 Based RouteSpec
*
*/
public static http2(options: HttpRouteSpecOptions): RouteSpec {
return new HttpRouteSpec(options, Protocol.HTTP2);
}
/**
* Creates a TCP Based RouteSpec
*/
public static tcp(options: TcpRouteSpecOptions): RouteSpec {
return new TcpRouteSpec(options);
}
/**
* Creates a GRPC Based RouteSpec
*/
public static grpc(options: GrpcRouteSpecOptions): RouteSpec {
return new GrpcRouteSpec(options);
}
/**
* Called when the RouteSpec type is initialized. Can be used to enforce
* mutual exclusivity with future properties
*/
public abstract bind(scope: Construct): RouteSpecConfig;
}
class HttpRouteSpec extends RouteSpec {
public readonly priority?: number;
public readonly protocol: Protocol;
public readonly match?: HttpRouteMatch;
public readonly timeout?: HttpTimeout;
public readonly weightedTargets: WeightedTarget[];
/**
* The retry policy
*/
public readonly retryPolicy?: HttpRetryPolicy;
constructor(props: HttpRouteSpecOptions, protocol: Protocol) {
super();
this.protocol = protocol;
this.match = props.match;
this.weightedTargets = props.weightedTargets;
this.timeout = props.timeout;
this.priority = props.priority;
if (props.retryPolicy) {
const httpRetryEvents = props.retryPolicy.httpRetryEvents ?? [];
const tcpRetryEvents = props.retryPolicy.tcpRetryEvents ?? [];
if (httpRetryEvents.length + tcpRetryEvents.length === 0) {
throw new Error('You must specify one value for at least one of `httpRetryEvents` or `tcpRetryEvents`');
}
this.retryPolicy = {
...props.retryPolicy,
httpRetryEvents: httpRetryEvents.length > 0 ? httpRetryEvents : undefined,
tcpRetryEvents: tcpRetryEvents.length > 0 ? tcpRetryEvents : undefined,
};
}
}
public bind(scope: Construct): RouteSpecConfig {
const pathMatchConfig = (this.match?.path ?? HttpRoutePathMatch.startsWith('/')).bind(scope);
// Set prefix path match to '/' if none of path matches are defined.
const headers = this.match?.headers;
const queryParameters = this.match?.queryParameters;
validateHttpMatchArrayLength(headers, queryParameters);
const httpConfig: CfnRoute.HttpRouteProperty = {
action: {
weightedTargets: renderWeightedTargets(this.weightedTargets),
},
match: {
prefix: pathMatchConfig.prefixPathMatch,
path: pathMatchConfig.wholePathMatch,
headers: headers?.map(header => header.bind(scope).headerMatch),
method: this.match?.method,
scheme: this.match?.protocol,
queryParameters: queryParameters?.map(queryParameter => queryParameter.bind(scope).queryParameterMatch),
},
timeout: renderTimeout(this.timeout),
retryPolicy: this.retryPolicy ? renderHttpRetryPolicy(this.retryPolicy) : undefined,
};
return {
priority: this.priority,
httpRouteSpec: this.protocol === Protocol.HTTP ? httpConfig : undefined,
http2RouteSpec: this.protocol === Protocol.HTTP2 ? httpConfig : undefined,
};
}
}
class TcpRouteSpec extends RouteSpec {
/**
* The priority for the route.
*/
public readonly priority?: number;
/*
* List of targets that traffic is routed to when a request matches the route
*/
public readonly weightedTargets: WeightedTarget[];
/**
* The criteria for determining a timeout configuration
*/
public readonly timeout?: TcpTimeout;
constructor(props: TcpRouteSpecOptions) {
super();
this.weightedTargets = props.weightedTargets;
this.timeout = props.timeout;
this.priority = props.priority;
}
public bind(_scope: Construct): RouteSpecConfig {
return {
priority: this.priority,
tcpRouteSpec: {
action: {
weightedTargets: renderWeightedTargets(this.weightedTargets),
},
timeout: renderTimeout(this.timeout),
},
};
}
}
class GrpcRouteSpec extends RouteSpec {
/**
* The priority for the route.
*/
public readonly priority?: number;
public readonly weightedTargets: WeightedTarget[];
public readonly match: GrpcRouteMatch;
public readonly timeout?: GrpcTimeout;
/**
* The retry policy.
*/
public readonly retryPolicy?: GrpcRetryPolicy;
constructor(props: GrpcRouteSpecOptions) {
super();
this.weightedTargets = props.weightedTargets;
this.match = props.match;
this.timeout = props.timeout;
this.priority = props.priority;
if (props.retryPolicy) {
const grpcRetryEvents = props.retryPolicy.grpcRetryEvents ?? [];
const httpRetryEvents = props.retryPolicy.httpRetryEvents ?? [];
const tcpRetryEvents = props.retryPolicy.tcpRetryEvents ?? [];
if (grpcRetryEvents.length + httpRetryEvents.length + tcpRetryEvents.length === 0) {
throw new Error('You must specify one value for at least one of `grpcRetryEvents`, `httpRetryEvents` or `tcpRetryEvents`');
}
this.retryPolicy = {
...props.retryPolicy,
grpcRetryEvents: grpcRetryEvents.length > 0 ? grpcRetryEvents : undefined,
httpRetryEvents: httpRetryEvents.length > 0 ? httpRetryEvents : undefined,
tcpRetryEvents: tcpRetryEvents.length > 0 ? tcpRetryEvents : undefined,
};
}
}
public bind(scope: Construct): RouteSpecConfig {
const serviceName = this.match.serviceName;
const methodName = this.match.methodName;
const metadata = this.match.metadata;
validateGrpcRouteMatch(this.match);
validateGrpcMatchArrayLength(metadata);
if (methodName && !serviceName) {
throw new Error('If you specify a method name, you must also specify a service name');
}
return {
priority: this.priority,
grpcRouteSpec: {
action: {
weightedTargets: renderWeightedTargets(this.weightedTargets),
},
match: {
serviceName: serviceName,
methodName: methodName,
metadata: metadata?.map(singleMetadata => singleMetadata.bind(scope).headerMatch),
},
timeout: renderTimeout(this.timeout),
retryPolicy: this.retryPolicy ? renderGrpcRetryPolicy(this.retryPolicy) : undefined,
},
};
}
}
/**
* Utility method to add weighted route targets to an existing route
*/
function renderWeightedTargets(weightedTargets: WeightedTarget[]): CfnRoute.WeightedTargetProperty[] {
const renderedTargets: CfnRoute.WeightedTargetProperty[] = [];
for (const t of weightedTargets) {
renderedTargets.push({
virtualNode: t.virtualNode.virtualNodeName,
weight: t.weight || 1,
});
}
return renderedTargets;
}
/**
* Utility method to construct a route timeout object
*/
function renderTimeout(timeout?: HttpTimeout): CfnRoute.HttpTimeoutProperty | undefined {
return timeout
? {
idle: timeout?.idle !== undefined
? {
unit: 'ms',
value: timeout?.idle.toMilliseconds(),
}
: undefined,
perRequest: timeout?.perRequest !== undefined
? {
unit: 'ms',
value: timeout?.perRequest.toMilliseconds(),
}
: undefined,
}
: undefined;
}
function renderHttpRetryPolicy(retryPolicy: HttpRetryPolicy): CfnRoute.HttpRetryPolicyProperty {
return {
maxRetries: retryPolicy.retryAttempts,
perRetryTimeout: {
unit: 'ms',
value: retryPolicy.retryTimeout.toMilliseconds(),
},
httpRetryEvents: retryPolicy.httpRetryEvents,
tcpRetryEvents: retryPolicy.tcpRetryEvents,
};
}
function renderGrpcRetryPolicy(retryPolicy: GrpcRetryPolicy): CfnRoute.GrpcRetryPolicyProperty {
return {
...renderHttpRetryPolicy(retryPolicy),
grpcRetryEvents: retryPolicy.grpcRetryEvents,
};
} | the_stack |
import { AudioTrack, Track, TrackType, VideoTrack } from '../types/remux';
const UINT32_MAX = Math.pow(2, 32) - 1;
const BOX_HEAD_LEN = 8;
type DestData = {
data: Uint8Array;
offset: number;
}
const HDLR: Record<string, Uint8Array> = {
video: new Uint8Array([
0, 0, 0, 45,
104, 100, 108, 114,
0, 0, 0, 0,
0, 0, 0, 0,
118, 105, 100, 101,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
86, 105, 100, 101,
111, 72, 97, 110,
100, 108, 101, 114,
0
]),
audio: new Uint8Array([
0, 0, 0, 45,
104, 100, 108, 114,
0, 0, 0, 0,
0, 0, 0, 0,
115, 111, 117, 110,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
83, 111, 117, 110,
100, 72, 97, 110,
100, 108, 101, 114,
0
])
};
const FTYP = new Uint8Array([
0, 0, 0, 24,
102, 116, 121, 112,
105, 115, 111, 109,
0, 0, 0, 1,
105, 115, 111, 109,
97, 118, 99, 49
]);
const STTS = new Uint8Array([
0, 0, 0, 16,
115, 116, 116, 115,
0, 0, 0, 0,
0, 0, 0, 0
]);
const STSC = new Uint8Array([
0, 0, 0, 16,
115, 116, 115, 99,
0, 0, 0, 0,
0, 0, 0, 0
]);
const STCO = new Uint8Array([
0, 0, 0, 16,
115, 116, 99, 111,
0, 0, 0, 0,
0, 0, 0, 0
]);
const STSZ = new Uint8Array([
0, 0, 0, 20,
115, 116, 115, 122,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0
]);
const DINF = new Uint8Array([
0, 0, 0, 36,
100, 105, 110, 102,
0, 0, 0, 28,
100, 114, 101, 102,
0, 0, 0, 0,
0, 0, 0, 1,
0, 0, 0, 12,
117, 114, 108, 32,
0, 0, 0, 1
]);
const VMHD = new Uint8Array([
0, 0, 0, 20,
118, 109, 104, 100,
0, 0, 0, 1,
0, 0, 0, 0,
0, 0, 0, 0
]);
const SMHD = new Uint8Array([
0, 0, 0, 16,
115, 109, 104, 100,
0, 0, 0, 0,
0, 0, 0, 0
]);
const BTRT = new Uint8Array([
0, 0, 0, 20,
98, 116, 114, 116,
0, 28, 156, 128,
0, 45, 198, 192,
0, 45, 198, 192
]);
const MVHD_TPL = new Uint8Array([
0, 0, 0, 120,
109, 118, 104, 100,
1, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 2,
0, 0, 0, 0,
0, 0, 0, 3,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 1, 0, 0,
1, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 1, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 1, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
64, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
255, 255, 255, 255
]);
const TKHD_TPL = new Uint8Array([
0, 0, 0, 104,
116, 107, 104, 100,
1, 0, 0, 7,
0, 0, 0, 0,
0, 0, 0, 2,
0, 0, 0, 0,
0, 0, 0, 3,
0, 0, 0, 2,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 1, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 1, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
64, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0
]);
const TREX_TPL = new Uint8Array([
0, 0, 0, 32,
116, 114, 101, 120,
0, 0, 0, 0,
0, 0, 0, 2,
0, 0, 0, 1,
0, 0, 0, 0,
0, 0, 0, 0,
0, 1, 0, 1
]);
const MDHD_TPL = new Uint8Array([
0, 0, 0, 44,
109, 100, 104, 100,
1, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 2,
0, 0, 0, 0,
0, 0, 0, 3,
0, 0, 172, 68,
0, 0, 0, 0,
0, 0, 0, 0,
85, 196, 0, 0
]);
const MP4A_STSD_TPL = new Uint8Array([
0, 0, 0, 93,
115, 116, 115, 100,
0, 0, 0, 0,
0, 0, 0, 1,
0, 0, 0, 77,
109, 112, 52, 97,
0, 0, 0, 0,
0, 0, 0, 1,
0, 0, 0, 0,
0, 0, 0, 0,
0, 2, 0, 16,
0, 0, 0, 0,
172, 68, 0, 0,
0, 0, 0, 41,
101, 115, 100, 115,
0, 0, 0, 0,
3, 27, 0, 1,
0, 4, 19, 64,
21, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
5
]);
const AVC1_STSD_TPL = new Uint8Array([
0, 0, 0, 185,
115, 116, 115, 100,
0, 0, 0, 0,
0, 0, 0, 1,
0, 0, 0, 169,
97, 118, 99, 49,
0, 0, 0, 0,
0, 0, 0, 1,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
5, 0, 2, 208,
0, 72, 0, 0,
0, 72, 0, 0,
0, 0, 0, 0,
0, 1, 18, 100,
97, 105, 108, 121,
109, 111, 116, 105,
111, 110, 47, 104,
108, 115, 46, 106,
115, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 24,
17, 17
])
const PASP_TPL = new Uint8Array([
0, 0, 0, 16,
112, 97, 115, 112,
0, 0, 0, 1,
0, 0, 0, 1
]);
class MP4 {
static types: Record<string, number[]> = {
'avc1': [97, 118, 99, 49],
'avcC': [97, 118, 99, 67],
'btrt': [98, 116, 114, 116],
'dinf': [100, 105, 110, 102],
'dref': [100, 114, 101, 102],
'esds': [101, 115, 100, 115],
'ftyp': [102, 116, 121, 112],
'hdlr': [104, 100, 108, 114],
'mdat': [109, 100, 97, 116],
'mdhd': [109, 100, 104, 100],
'mdia': [109, 100, 105, 97],
'mfhd': [109, 102, 104, 100],
'minf': [109, 105, 110, 102],
'moof': [109, 111, 111, 102],
'moov': [109, 111, 111, 118],
'mp4a': [109, 112, 52, 97],
'mvex': [109, 118, 101, 120],
'mvhd': [109, 118, 104, 100],
'pasp': [112, 97, 115, 112],
'sdtp': [115, 100, 116, 112],
'stbl': [115, 116, 98, 108],
'stco': [115, 116, 99, 111],
'stsc': [115, 116, 115, 99],
'stsd': [115, 116, 115, 100],
'stsz': [115, 116, 115, 122],
'stts': [115, 116, 116, 115],
'tfdt': [116, 102, 100, 116],
'tfhd': [116, 102, 104, 100],
'traf': [116, 114, 97, 102],
'trak': [116, 114, 97, 107],
'trun': [116, 114, 117, 110],
'trex': [116, 114, 101, 120],
'tkhd': [116, 107, 104, 100],
'vmhd': [118, 109, 104, 100],
'smhd': [115, 109, 104, 100]
};
/**
* 获取当前音视频的moov
* @param tracks 音视频描述数据
*/
public static moov<T extends Track>(tracks: T[]): Uint8Array {
// 建立空moov
const len = FTYP.byteLength + MP4._getMoovLen(tracks);
const dest = { data: new Uint8Array(len), offset: 0 };
// 写入
dest.data.set(FTYP, 0);
dest.offset += FTYP.byteLength;
MP4._writeMoov(dest, tracks);
return dest.data;
}
/**
* 获取当前视频的segment数据
* @param sn sn
* @param baseMediaDecodeTime baseMediaDecodeTime
* @param track 视频数据
* @param moov moov box数据
*/
public static videoMediaSegment(sn: number, baseMediaDecodeTime: number, track: Track, moov?: Uint8Array): Uint8Array {
// 计算mdat长度
let mdatLen = 8 + (<VideoTrack>track).mp4Samples.reduce((prev, item) => {
return prev + item.units.reduce((unitLen, unit) => {
return unitLen + unit.byteLength + 4;
}, 0);
}, 0);
let d = MP4._getMediaSegmentData(track, mdatLen, moov);
MP4._mediaSegmentHead(d, sn, baseMediaDecodeTime, track, mdatLen, moov);
(<VideoTrack>track).samples.forEach(sample => {
sample.units.forEach(unitData => {
const unitDataLen = unitData.byteLength;
d.data[d.offset] = unitDataLen >> 24 & 0xff;
d.data[d.offset + 1] = unitDataLen >> 16 & 0xff;
d.data[d.offset + 2] = unitDataLen >> 8 & 0xff;
d.data[d.offset + 3] = unitDataLen & 0xff;
d.data.set(unitData, d.offset + 4);
d.offset += 4 + unitDataLen;
});
delete sample.units;
});
return d.data;
}
/**
* 获取当前音频的segment数据
* @param sn sn
* @param baseMediaDecodeTime baseMediaDecodeTime
* @param track 音频数据
* @param moov moov
*/
public static audioMediaSegment(sn: number, baseMediaDecodeTime: number, track: Track, moov?: Uint8Array): Uint8Array {
let mdatLen = 8 + (<AudioTrack>track).mp4Samples.reduce((prev, item) => {
return prev + item.unit.byteLength;
}, 0);
let d = MP4._getMediaSegmentData(track, mdatLen, moov);
MP4._mediaSegmentHead(d, sn, baseMediaDecodeTime, track, mdatLen, moov);
(<AudioTrack>track).mp4Samples.forEach(sample => {
d.data.set(sample.unit, d.offset);
d.offset += sample.unit.byteLength;
delete sample.unit;
});
return d.data;
}
/**
* 计算moov头的长度
* @param tracks 音视频轨数据
*/
private static _getMoovLen(tracks: Track[]): number {
const trakLen = tracks.reduce((prev, item) => {
return prev + MP4._getTrakLen(item)
}, 0);
return BOX_HEAD_LEN + MVHD_TPL.byteLength + trakLen + MP4._getMvexLen(tracks);
}
/**
* 向目标数据写入moov
* @param dest 写入目标
* @param tracks 音视频轨数据
*/
private static _writeMoov(dest: DestData, tracks: Track[]): void {
let moovLen = MP4._getMoovLen(tracks);
MP4._writeBoxHead(dest, MP4.types.moov, moovLen);
MP4._writeMvhd(dest, tracks[0].timescale, tracks[0].duration);
tracks.forEach(item => {
MP4._writeTrak(dest, item);
});
MP4._writeMvex(dest, tracks);
}
/**
* 计算moof box长度
* @param sampleCount sample数量
*/
private static _getMoofLen(sampleCount: number): number {
return 100 + 17 * sampleCount;
}
/**
* 处理mp4 segment头部数据,主要是moof
* @param dest 写入目标
* @param sn sn
* @param baseMediaDecodeTime baseMediaDecodeTime
* @param track 音视频描述数据
* @param mdatLen mdatLen
* @param initSegment moov头
*/
private static _mediaSegmentHead(dest: DestData, sn: number, baseMediaDecodeTime: number, track: Track, mdatLen: number, initSegment?: Uint8Array): void {
if (initSegment) {
dest.data.set(initSegment);
dest.offset = initSegment.byteLength;
}
MP4._writeMoof(dest, sn, baseMediaDecodeTime, track);
MP4._writeBoxHead(dest, MP4.types.mdat, mdatLen);
}
/**
* 生成一个数据块用于承载mp4Segment数据
* @param track 音视频描述数据
* @param mdatLen mdat长度
* @param moov moov
*/
private static _getMediaSegmentData(track: Track, mdatLen: number, moov?: Uint8Array): DestData {
let moofLen = MP4._getMoofLen(track.mp4Samples.length);
return { data: new Uint8Array(moofLen + mdatLen + (moov ? moov.byteLength : 0)), offset: 0 };
}
/**
* 向目标数据写入mvhd
* @param dest 写入目标
* @param timescale timescale
* @param duration duration
*/
private static _writeMvhd(dest: DestData, timescale: number, duration: number): void {
duration *= timescale;
const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
const mvhd = MVHD_TPL;
mvhd[28] = timescale >> 24 & 0xff;
mvhd[29] = timescale >> 16 & 0xff;
mvhd[30] = timescale >> 8 & 0xff;
mvhd[31] = timescale & 0xff;
mvhd[32] = upperWordDuration >> 24;
mvhd[33] = upperWordDuration >> 16 & 0xff;
mvhd[34] = upperWordDuration >> 8 & 0xff;
mvhd[35] = upperWordDuration & 0xff;
mvhd[36] = lowerWordDuration >> 24;
mvhd[37] = lowerWordDuration >> 16 & 0xff;
mvhd[38] = lowerWordDuration >> 8 & 0xff;
mvhd[39] = lowerWordDuration & 0xff;
dest.data.set(mvhd, dest.offset);
dest.offset += MVHD_TPL.byteLength;
}
/**
* 向目标数据写入tkhd
* @param dest 写入目标
* @param track 音视频描述数据
*/
private static _writeTkhd(dest: DestData, track: AudioTrack & VideoTrack): void {
const id = track.id,
duration = track.duration * track.timescale,
upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)),
lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
let width = 0,
height = 0;
if (track.hasOwnProperty('width')) {
width = track.width;
}
if (track.hasOwnProperty('height')) {
height = track.height;
}
const tkhd = TKHD_TPL;
tkhd[28] = id >> 24 & 0xff;
tkhd[29] = id >> 16 & 0xff;
tkhd[30] = id >> 8 & 0xff;
tkhd[31] = id & 0xff;
tkhd[36] = upperWordDuration >> 24;
tkhd[37] = upperWordDuration >> 16 & 0xff;
tkhd[38] = upperWordDuration >> 8 & 0xff;
tkhd[39] = upperWordDuration & 0xff;
tkhd[40] = lowerWordDuration >> 24;
tkhd[41] = lowerWordDuration >> 16 & 0xff;
tkhd[42] = lowerWordDuration >> 8 & 0xff;
tkhd[43] = lowerWordDuration & 0xff;
tkhd[96] = width >> 8 & 0xff;
tkhd[97] = width & 0xff;
tkhd[100] = height >> 8 & 0xff;
tkhd[101] = height & 0xff;
dest.data.set(tkhd, dest.offset);
dest.offset += TKHD_TPL.byteLength;
}
/**
* 计算trak box长度
* @param track 音视频描述数据
*/
private static _getTrakLen(track: Track): number {
return BOX_HEAD_LEN + TKHD_TPL.byteLength + MP4._getMdiaLen(track);
}
/**
* 向目标数据写入trak
* @param dest 写入目标
* @param track 音视频描述数据
*/
private static _writeTrak(dest: DestData, track: Track): void {
const trakLen = MP4._getTrakLen(track);
this._writeBoxHead(dest, MP4.types.trak, trakLen);
this._writeTkhd(dest, <AudioTrack & VideoTrack>track);
this._writeMdia(dest, track);
}
/**
* 计算mdia长度
* @param track 音视频描述数据
*/
private static _getMdiaLen(track: Track): number {
return BOX_HEAD_LEN + MDHD_TPL.byteLength + HDLR[track.type].byteLength + MP4._getMinfLen(track);
}
/**
* 向目标数据写入mdia
* @param dest 写入目标
* @param track 音视频描述数据
*/
private static _writeMdia(dest: DestData, track: Track): void {
const mdiaLen = MP4._getMdiaLen(track);
this._writeBoxHead(dest, MP4.types.mdia, mdiaLen);
this._writeMdhd(dest, track.timescale, track.duration);
dest.data.set(HDLR[track.type], dest.offset);
dest.offset += HDLR[track.type].byteLength;
this._writeMinf(dest, track);
}
/**
* 向目标数据写入mdhd
* @param dest 写入目标
* @param timescale timescale
* @param duration duration
*/
private static _writeMdhd(dest: DestData, timescale: number, duration: number): void {
duration *= timescale;
const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
const mdhd = MDHD_TPL;
mdhd[28] = timescale >> 24 & 0xff;
mdhd[29] = timescale >> 16 & 0xff;
mdhd[30] = timescale >> 8 & 0xff;
mdhd[31] = timescale & 0xff; // timescale
mdhd[32] = upperWordDuration >> 24;
mdhd[33] = upperWordDuration >> 16 & 0xff;
mdhd[34] = upperWordDuration >> 8 & 0xff;
mdhd[35] = upperWordDuration & 0xff;
mdhd[36] = lowerWordDuration >> 24;
mdhd[37] = lowerWordDuration >> 16 & 0xff;
mdhd[38] = lowerWordDuration >> 8 & 0xff;
mdhd[39] = lowerWordDuration & 0xff;
dest.data.set(mdhd, dest.offset);
dest.offset += mdhd.byteLength;
}
/**
* 计算minf长度
* @param track 音视频描述数据
*/
private static _getMinfLen(track: Track): number {
if (track.type === TrackType.audio) {
return BOX_HEAD_LEN + SMHD.byteLength + DINF.byteLength + MP4._getStblLen(track);
}
return BOX_HEAD_LEN + VMHD.byteLength + DINF.byteLength + MP4._getStblLen(track);
}
/**
* 向目标数据写入minf
* @param dest 写入目标
* @param track 音视频描述数据
*/
private static _writeMinf(dest: DestData, track: Track) {
this._writeBoxHead(dest, MP4.types.minf, MP4._getMinfLen(track));
if (track.type === 'audio') {
dest.data.set(SMHD, dest.offset);
dest.offset += SMHD.byteLength;
dest.data.set(DINF, dest.offset);
dest.offset += DINF.byteLength;
this._writeStbl(dest, track);
return;
}
dest.data.set(VMHD, dest.offset);
dest.offset += VMHD.byteLength;
dest.data.set(DINF, dest.offset);
dest.offset += DINF.byteLength;
this._writeStbl(dest, track);
return;
}
/**
* 计算stbl长度
* @param track 音视频描述数据
*/
private static _getStblLen(track: Track): number {
return BOX_HEAD_LEN + this._getStsdLen(track) + STTS.byteLength + STSC.byteLength + STSZ.byteLength + STCO.byteLength;
}
/**
* 向目标数据写入stbl
* @param dest 写入目标
* @param track 音视频描述数据
*/
private static _writeStbl(dest: DestData, track: Track): void {
let stblLen = this._getStblLen(track);
this._writeBoxHead(dest, MP4.types.stbl, stblLen);
this._writeStsd(dest, track);
dest.data.set(STTS, dest.offset);
dest.offset += STTS.byteLength;
dest.data.set(STSC, dest.offset);
dest.offset += STSC.byteLength;
dest.data.set(STSZ, dest.offset);
dest.offset += STSZ.byteLength;
dest.data.set(STCO, dest.offset);
dest.offset += STCO.byteLength;
}
/**
* 计算stsd长度
* @param track 音视频描述数据
*/
private static _getStsdLen(track: Track): number {
if (track.type === TrackType.audio) {
return MP4._getMp4aStsdLen(<AudioTrack>track);
} else {
return MP4._getAvc1StsdLen(<VideoTrack>track);
}
}
/**
* 向目标数据写入stsd
* @param dest 写入目标
* @param track 音视频描述数据
*/
private static _writeStsd(dest: DestData, track: Track): void {
if (track.type === TrackType.audio) {
this._writeMp4aStsd(dest, <AudioTrack>track);
return;
}
this._writeAvc1Stsd(dest, <VideoTrack>track);
}
/**
* 计算avcC长度
* @param track 音视频描述数据
*/
private static _getAvcCLen(track: VideoTrack): number {
const spsLen = track.sps.reduce((prev, item) => {
return prev + item.byteLength + 2;
}, 0);
const ppsLen = track.pps.reduce((prev, item) => {
return prev + item.byteLength + 2;
}, 0);
// 8 + 5 + sps + 1 + pps
return 15 + spsLen + ppsLen;
}
/**
* 计算avc1长度
* @param track 音视频描述数据
*/
private static _getAvc1Len(track: VideoTrack): number {
// avc1 + avcc + btrt + pasp
return 86 + MP4._getAvcCLen(track) + 20 + 16;
}
/**
* 计算stsd + avc1长度
* @param track 音视频描述数据
*/
private static _getAvc1StsdLen(track: VideoTrack): number {
// stsd + avc1
return 16 + this._getAvc1Len(track);
}
/**
* 向目标数据写入stsd(avc1)
* @param dest 写入目标
* @param track 音视频描述数据
*/
private static _writeAvc1Stsd(dest: DestData, track: VideoTrack): void {
let sps: number[] = [],
pps: number[] = [],
i,
data,
len;
for (i = 0; i < track.sps.length; i++) {
data = track.sps[i];
len = data.byteLength;
sps.push(len >>> 8 & 0xff);
sps.push(len & 0xff);
sps = sps.concat(Array.prototype.slice.call(data));
}
for (i = 0; i < track.pps.length; i++) {
data = track.pps[i];
len = data.byteLength;
pps.push(len >>> 8 & 0xff);
pps.push(len & 0xff);
pps = pps.concat(Array.prototype.slice.call(data));
}
const avcCLen = this._getAvcCLen(track);
const avc1Len = this._getAvc1Len(track);
const stsdLen = this._getAvc1StsdLen(track);
const avc1Stsd = AVC1_STSD_TPL;
let width = track.width,
height = track.height,
hSpacing = track.pixelRatio[0],
vSpacing = track.pixelRatio[1];
avc1Stsd[0] = stsdLen >> 24 & 0xff;
avc1Stsd[1] = stsdLen >> 16 & 0xff;
avc1Stsd[2] = stsdLen >> 8 & 0xff;
avc1Stsd[3] = stsdLen & 0xff;
avc1Stsd[16] = avc1Len >> 24 & 0xff;
avc1Stsd[17] = avc1Len >> 16 & 0xff;
avc1Stsd[18] = avc1Len >> 8 & 0xff;
avc1Stsd[19] = avc1Len & 0xff;
avc1Stsd[48] = width >> 8 & 0xff;
avc1Stsd[49] = width & 0xff; // width
avc1Stsd[50] = height >> 8 & 0xff;
avc1Stsd[51] = height & 0xff; // height
dest.data.set(avc1Stsd, dest.offset);
dest.offset += avc1Stsd.byteLength;
this._writeBoxHead(dest, MP4.types.avcC, avcCLen);
const avcc = [
0x01, sps[3], sps[4], sps[5],
0xfc | 3, 0xe0 | track.sps.length
]
.concat(sps)
.concat([
track.pps.length
])
.concat(pps);
dest.data.set(avcc, dest.offset);
dest.offset += avcc.length;
dest.data.set(BTRT, dest.offset);
dest.offset += BTRT.byteLength;
const pasp = PASP_TPL;
pasp[8] = hSpacing >> 24; // hSpacing
pasp[9] = hSpacing >> 16 & 0xff;
pasp[10] = hSpacing >> 8 & 0xff;
pasp[11] = hSpacing & 0xff;
pasp[12] = vSpacing >> 24; // vSpacing
pasp[13] = vSpacing >> 16 & 0xff;
pasp[14] = vSpacing >> 8 & 0xff;
pasp[15] = vSpacing & 0xff;
dest.data.set(pasp, dest.offset);
dest.offset += pasp.byteLength;
}
/**
* 计算mp4 esds长度
* @param track 音视频描述数据
*/
private static _getMp4aEsdsLen(track: AudioTrack): number {
const configLen = track.config.length;
return BOX_HEAD_LEN + 25 + configLen + 4;
}
/**
* 计算stsd + mp4a + esds长度
* @param track 音视频描述数据
*/
private static _getMp4aStsdLen(track: AudioTrack): number {
// stsd + mp4a + esds
return 16 + 36 + MP4._getMp4aEsdsLen(track);
}
/**
* 向目标数据写入stsd(mp4a)
* @param dest 写入目标
* @param track 音视频描述数据
*/
private static _writeMp4aStsd(dest: DestData, track: AudioTrack): void {
const configLen = track.config.length;
const esdsLen = MP4._getMp4aEsdsLen(track);
const stsdLen = MP4._getMp4aStsdLen(track);
const mp4aLen = stsdLen - 16;
const mp4a = MP4A_STSD_TPL;
mp4a[0] = stsdLen >> 24 & 0xff;
mp4a[1] = stsdLen >> 16 & 0xff;
mp4a[2] = stsdLen >> 8 & 0xff;
mp4a[3] = stsdLen & 0xff;
mp4a[16] = mp4aLen >> 24 & 0xff;
mp4a[17] = mp4aLen >> 16 & 0xff;
mp4a[18] = mp4aLen >> 8 & 0xff;
mp4a[19] = mp4aLen & 0xff;
mp4a[41] = track.channelCount;
mp4a[48] = track.samplerate >> 8 & 0xff;
mp4a[49] = track.samplerate & 0xff;
mp4a[52] = esdsLen >> 24 & 0xff;
mp4a[53] = esdsLen >> 16 & 0xff;
mp4a[54] = esdsLen >> 8 & 0xff;
mp4a[55] = esdsLen & 0xff;
mp4a[65] = 23 + configLen;
mp4a[70] = 15 + configLen;
dest.data.set(mp4a, dest.offset);
dest.offset += mp4a.byteLength;
let tmp = [configLen].concat(track.config).concat([0x06, 0x01, 0x02]);
dest.data.set(tmp, dest.offset);
dest.offset += tmp.length;
}
/**
* 计算mvex长度
* @param tracks 音视频描述数据
*/
private static _getMvexLen(tracks: Track[]): number {
return BOX_HEAD_LEN + tracks.length * TREX_TPL.byteLength;
}
/**
* 向目标数据写入mvex
* @param dest 写入目标
* @param tracks 音视频描述数据
*/
private static _writeMvex(dest: DestData, tracks: Track[]): void {
let mvexLen = MP4._getMvexLen(tracks);
this._writeBoxHead(dest, MP4.types.mvex, mvexLen);
tracks.forEach(item => {
MP4._writeTrex(dest, item);
})
}
/**
* 向目标数据写入trex
* @param dest 写入目标
* @param track 音视频描述数据
*/
private static _writeTrex(dest: DestData, track: Track): void {
const id = track.id;
const trex = TREX_TPL;
trex[12] = id >> 24;
trex[13] = id >> 16 & 0xff;
trex[14] = id >> 8 & 0xff;
trex[15] = id & 0xff; // track_ID
dest.data.set(trex, dest.offset);
dest.offset += trex.byteLength;
}
/**
* 写入moof头
* @param dest 写入目标
* @param sn sn
* @param baseMediaDecodeTime baseMediaDecodeTime
* @param track 音视频描述数据
* @param mdatLen mdat box 长度
*/
private static _writeMoof(dest: DestData, sn: number, baseMediaDecodeTime: number, track: Track): void {
// mooflen = 8 + mfhd(8 + 8 ) + traf(8 + tfhd(8 + 8) + tfdt(8 + 12) + trun(8 + 12 + 16 * sample.len) + sdtp(8 + 4 + sample.len)) = 100 + 17 * track.samples.length;
// trunOffset = moof + mdat header
let len = track.mp4Samples.length,
moofLen = MP4._getMoofLen(len),
trafLen = moofLen - 24,
sdtpLen = 12 + len,
trunLen = 20 + 16 * len,
trunOffset = moofLen + 8,
id = track.id,
samples = track.mp4Samples || [],
upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)),
lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
// moof
MP4._writeBoxHead(dest, MP4.types.moof, moofLen);
// mfhd
MP4._writeBoxHead(dest, MP4.types.mfhd, 16);
dest.data[dest.offset + 4] = sn >> 24;
dest.data[dest.offset + 5] = sn >> 16 & 0xff;
dest.data[dest.offset + 6] = sn >> 8 & 0xff;
dest.data[dest.offset + 7] = sn & 0xff;
dest.offset += 8;
// traf
MP4._writeBoxHead(dest, MP4.types.traf, trafLen);
// tfhd
MP4._writeBoxHead(dest, MP4.types.tfhd, 16);
dest.data[dest.offset + 4] = id >> 24;
dest.data[dest.offset + 5] = id >> 16 & 0xff;
dest.data[dest.offset + 6] = id >> 8 & 0xff;
dest.data[dest.offset + 7] = id & 0xff;
dest.offset += 8;
// tfdt
MP4._writeBoxHead(dest, MP4.types.tfdt, 20);
dest.data[dest.offset] = 1;
dest.data[dest.offset + 4] = upperWordBaseMediaDecodeTime >> 24;
dest.data[dest.offset + 5] = upperWordBaseMediaDecodeTime >> 16 & 0xff;
dest.data[dest.offset + 6] = upperWordBaseMediaDecodeTime >> 8 & 0xff;
dest.data[dest.offset + 7] = upperWordBaseMediaDecodeTime & 0xff;
dest.data[dest.offset + 8] = lowerWordBaseMediaDecodeTime >> 24;
dest.data[dest.offset + 9] = lowerWordBaseMediaDecodeTime >> 16 & 0xff;
dest.data[dest.offset + 10] = lowerWordBaseMediaDecodeTime >> 8 & 0xff;
dest.data[dest.offset + 11] = lowerWordBaseMediaDecodeTime & 0xff;
dest.offset += 12;
// sdtp
MP4._writeBoxHead(dest, MP4.types.sdtp, sdtpLen);
dest.offset += 4;
samples.forEach((sample, index) => {
let flags = sample.flags;
dest.data[dest.offset + index] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
});
dest.offset += len;
// trun
MP4._writeBoxHead(dest, MP4.types.trun, trunLen);
dest.data[dest.offset + 2] = 15;
dest.data[dest.offset + 3] = 1;
dest.data[dest.offset + 4] = len >>> 24 & 0xff;
dest.data[dest.offset + 5] = len >>> 16 & 0xff;
dest.data[dest.offset + 6] = len >>> 8 & 0xff;
dest.data[dest.offset + 7] = len & 0xff;
dest.data[dest.offset + 8] = trunOffset >>> 24 & 0xff;
dest.data[dest.offset + 9] = trunOffset >>> 16 & 0xff;
dest.data[dest.offset + 10] = trunOffset >>> 8 & 0xff;
dest.data[dest.offset + 11] = trunOffset & 0xff;
dest.offset += 12;
samples.forEach((sample, index) => {
dest.data.set([
sample.duration >>> 24 & 0xff,
sample.duration >>> 16 & 0xff,
sample.duration >>> 8 & 0xff,
sample.duration & 0xff, // sample_duration
sample.len >>> 24 & 0xff,
sample.len >>> 16 & 0xff,
sample.len >>> 8 & 0xff,
sample.len & 0xff, // sample_len
sample.flags.isLeading << 2 | sample.flags.dependsOn,
sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.isNonSync,
sample.flags.degradPrio & 0xf0 << 8,
sample.flags.degradPrio & 0x0f, // sample_flags
sample.cts >>> 24 & 0xff,
sample.cts >>> 16 & 0xff,
sample.cts >>> 8 & 0xff,
sample.cts & 0xff // sample_composition_time_offset
], dest.offset + 16 * index
);
});
dest.offset += len * 16;
}
/**
* 写入box头
* @param dest 写入目标
* @param type box type
* @param len box len
*/
private static _writeBoxHead(dest: DestData, type: number[], len: number): void {
dest.data[dest.offset] = len >> 24 & 0xff;
dest.data[dest.offset + 1] = len >> 16 & 0xff;
dest.data[dest.offset + 2] = len >> 8 & 0xff;
dest.data[dest.offset + 3] = len & 0xff;
dest.data.set(type, dest.offset + 4);
dest.offset += 8;
}
}
export default MP4; | the_stack |
import {Readable} from 'stream';
import {escapeMySqlIdentifier} from '@databases/escape-identifier';
import {SQLQuery, FormatConfig, isSqlQuery} from '@databases/sql';
import {Driver} from '@databases/shared';
import {Connection as MySqlClient} from 'mysql2/promise';
import pushToAsyncIterable from '@databases/push-to-async-iterable';
import TransactionOptions from './types/TransactionOptions';
import EventHandlers from './types/EventHandlers';
import {CoreConnection} from './raw';
import QueryStreamOptions from './types/QueryStreamOptions';
const {codeFrameColumns} = require('@babel/code-frame');
const mysqlFormat: FormatConfig = {
escapeIdentifier: (str) => escapeMySqlIdentifier(str),
formatValue: (value) => ({placeholder: '?', value}),
};
export default class MySqlDriver
implements Driver<TransactionOptions, QueryStreamOptions>
{
public readonly acquireLockTimeoutMilliseconds: number;
public readonly client: MySqlClient;
private readonly _handlers: EventHandlers;
private _endCalled = false;
constructor(
client: MySqlClient,
handlers: EventHandlers,
acquireLockTimeoutMilliseconds: number,
) {
this.acquireLockTimeoutMilliseconds = acquireLockTimeoutMilliseconds;
this.client = client;
this._handlers = handlers;
}
private _removeFromPool: undefined | (() => void);
private _idleErrorEventHandler: undefined | ((err: Error) => void);
private readonly _onIdleError = (err: Error) => {
if (this._endCalled) {
return;
}
this.client.removeListener('error', this._onIdleError);
if (this._removeFromPool) {
this._removeFromPool();
}
if (this._idleErrorEventHandler) {
this._idleErrorEventHandler(err);
}
};
onAddingToPool(
removeFromPool: undefined | (() => void),
idleErrorEventHandler: undefined | ((err: Error) => void),
) {
this._removeFromPool = removeFromPool;
this._idleErrorEventHandler = idleErrorEventHandler;
}
onActive() {
this.client.removeListener('error', this._onIdleError);
}
onIdle() {
this.client.on('error', this._onIdleError);
}
async dispose(): Promise<void> {
if (!this._endCalled) {
this._endCalled = true;
this.client.on('error', this._onIdleError);
this.client.destroy();
}
}
async canRecycleConnectionAfterError(_err: Error) {
try {
let timeout: any | undefined;
const result: undefined | {1?: {rows?: {0?: {result?: number}}}} =
await Promise.race([
this.client.query(
'BEGIN TRANSACTION READ ONLY;SELECT 1 AS result;COMMIT;',
) as any,
new Promise((r) => {
timeout = setTimeout(r, 100);
}),
]);
if (timeout !== undefined) {
clearTimeout(timeout);
}
return result?.[1]?.rows?.[0]?.result === 1;
} catch (ex) {
return false;
}
}
async beginTransaction(options?: TransactionOptions) {
const parameters = [];
if (options) {
if (options.readOnly) {
parameters.push('READ ONLY');
} else if (options.readOnly === false) {
parameters.push('READ WRITE');
}
if (options.withConsistentSnapshot) {
parameters.push('WITH CONSISTENT SNAPSHOT');
}
}
if (parameters.length) {
await execute(this.client, `START TRANSACTION ${parameters.join(', ')}`);
} else {
await execute(this.client, `BEGIN`);
}
}
async commitTransaction() {
await execute(this.client, `COMMIT`);
}
async rollbackTransaction() {
await execute(this.client, `ROLLBACK`);
}
async shouldRetryTransactionFailure(
_transactionOptions: TransactionOptions | undefined,
_ex: Error,
_failureCount: number,
) {
return false;
}
async createSavepoint(savepointName: string) {
await execute(this.client, `SAVEPOINT ${savepointName}`);
}
async releaseSavepoint(savepointName: string) {
await execute(this.client, `RELEASE SAVEPOINT ${savepointName}`);
}
async rollbackToSavepoint(savepointName: string) {
await execute(this.client, `ROLLBACK TO SAVEPOINT ${savepointName}`);
}
private async _executeQuery(query: SQLQuery): Promise<any[]> {
const q = query.format(mysqlFormat);
if (this._handlers.onQueryStart) {
enforceUndefined(this._handlers.onQueryStart(query, q));
}
const results = await executeQueryInternal(
this.client,
query,
q,
this._handlers,
);
if (this._handlers.onQueryResults) {
enforceUndefined(this._handlers.onQueryResults(query, q, results));
}
return results;
}
async executeAndReturnAll(queries: SQLQuery[]): Promise<any[][]> {
const results = new Array(queries.length);
for (let i = 0; i < queries.length; i++) {
results[i] = await this._executeQuery(queries[i]);
}
return results;
}
async executeAndReturnLast(queries: SQLQuery[]): Promise<any[]> {
if (queries.length === 0) {
return [];
}
for (let i = 0; i < queries.length - 1; i++) {
await this._executeQuery(queries[i]);
}
return await this._executeQuery(queries[queries.length - 1]);
}
queryStream(query: SQLQuery, options?: QueryStreamOptions) {
if (!isSqlQuery(query)) {
throw new Error(
'Invalid query, you must use @databases/sql to create your queries.',
);
}
const {text, values} = query.format(mysqlFormat);
const highWaterMark = (options && options.highWaterMark) || 5;
const connection: CoreConnection = (this.client as any).connection;
return pushToAsyncIterable<any>((handlers) => {
const stream = connection.query(text, values);
stream.on('result', handlers.onData);
stream.on('error', handlers.onError);
stream.on('end', handlers.onEnd);
return {
dispose: () => {
connection.resume();
},
pause: () => {
connection.pause();
},
resume: () => {
connection.resume();
},
highWaterMark,
};
});
}
queryNodeStream(query: SQLQuery, options?: QueryStreamOptions): Readable {
if (!isSqlQuery(query)) {
throw new Error(
'Invalid query, you must use @databases/sql to create your queries.',
);
}
const {text, values} = query.format(mysqlFormat);
const connection: CoreConnection = (this.client as any).connection;
const result = connection.query(text, values).stream(options);
// tslint:disable-next-line:no-unbound-method
const on = result.on;
const handlers = this._handlers;
return Object.assign(result, {
on(event: string, cb: (...args: any[]) => void) {
if (event !== 'error') return on.call(this, event, cb);
return on.call(this, event, (ex) => {
// TODO: consider using https://github.com/Vincit/db-errors
try {
handleError(ex, query, {text, values}, handlers);
} catch (ex) {
cb(ex);
}
});
},
}) as any;
}
}
async function execute(client: MySqlClient, query: string): Promise<void> {
try {
await client.query(query);
} catch (ex: any) {
throw Object.assign(new Error(ex.message), ex);
}
}
async function executeQueryInternal(
client: MySqlClient,
query: SQLQuery,
q: {text: string; values: unknown[]},
handlers: EventHandlers,
): Promise<any[]> {
try {
// const result: [RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[] | ResultSetHeader, FieldPacket[]]
const [result] = await client.query(q.text, q.values);
return result as any[];
} catch (ex) {
handleError(ex, query, q, handlers);
}
}
function handleError(
ex: unknown,
query: SQLQuery,
q: {text: string; values: unknown[]},
handlers: EventHandlers,
): never {
let err;
const mySqlError = parseMySqlError(ex, q.text);
if (mySqlError) {
const {start, end, message: oldMessage} = mySqlError;
const message = oldMessage.replace(
/ near \'((?:.|\n)+)\' at line (\d+)$/,
` near:\n\n${codeFrameColumns(q.text, {start, end})}\n`,
);
err = Object.assign(new Error(message), ex, {message});
} else {
err = Object.assign(new Error(isError(ex) ? ex.message : `${ex}`), ex);
}
if (handlers.onQueryError) {
enforceUndefined(handlers.onQueryError(query, q, err));
}
throw err;
}
function parseMySqlError(ex: unknown, queryText: string) {
if (isMySqlError(ex)) {
const match = / near \'((?:.|\n)+)\' at line (\d+)$/.exec(ex.sqlMessage);
if (match) {
const index = queryText.indexOf(match[1]);
if (index === queryText.lastIndexOf(match[1])) {
const linesUptoStart = queryText.substr(0, index).split('\n');
const line = linesUptoStart.length;
const start = {
line,
column: linesUptoStart[linesUptoStart.length - 1].length + 1,
};
const linesUptoEnd = queryText
.substr(0, index + match[1].length)
.split('\n');
const end = {
line: linesUptoEnd.length,
column: linesUptoEnd[linesUptoEnd.length - 1].length + 1,
};
return {start, end, message: ex.message};
}
}
}
return null;
}
function isError(ex: unknown): ex is {message: string} {
return (
typeof ex === 'object' &&
ex !== null &&
'message' in ex &&
typeof (ex as any).message === 'string'
);
}
function isMySqlError(
ex: unknown,
): ex is {message: string; sqlMessage: string} {
return (
typeof ex === 'object' &&
ex !== null &&
(ex as any).code === 'ER_PARSE_ERROR' &&
(ex as any).sqlState === '42000' &&
typeof (ex as any).sqlMessage === 'string' &&
typeof (ex as any).message === 'string'
);
}
function enforceUndefined(value: void) {
if (value !== undefined) {
throw new Error(
`Your event handlers must return "undefined". This is to allow for the possibility of event handlers being used as hooks with more advanced functionality in the future.`,
);
}
} | the_stack |
import * as NS17716817176095924048 from "./Schema_generated";
/**
* @enum {number}
*/
export namespace org.apache.arrow.flatbuf{
export enum CompressionType{
LZ4_FRAME= 0,
ZSTD= 1
};
}
/**
* Provided for forward compatibility in case we need to support different
* strategies for compressing the IPC message body (like whole-body
* compression rather than buffer-level) in the future
*
* @enum {number}
*/
export namespace org.apache.arrow.flatbuf{
export enum BodyCompressionMethod{
/**
* Each constituent buffer is first compressed with the indicated
* compressor, and then written with the uncompressed length in the first 8
* bytes as a 64-bit little-endian signed integer followed by the compressed
* buffer bytes (and then padding as required by the protocol). The
* uncompressed length may be set to -1 to indicate that the data that
* follows is not compressed, which can be useful for cases where
* compression does not yield appreciable savings.
*/
BUFFER= 0
};
}
/**
* ----------------------------------------------------------------------
* The root Message type
* This union enables us to easily send different message types without
* redundant storage, and in the future we can easily add new message types.
*
* Arrow implementations do not need to implement all of the message types,
* which may include experimental metadata types. For maximum compatibility,
* it is best to send data using RecordBatch
*
* @enum {number}
*/
export namespace org.apache.arrow.flatbuf{
export enum MessageHeader{
NONE= 0,
Schema= 1,
DictionaryBatch= 2,
RecordBatch= 3
};
export function unionToMessageHeader(
type: MessageHeader,
accessor: (obj:NS17716817176095924048.org.apache.arrow.flatbuf.Schema|org.apache.arrow.flatbuf.DictionaryBatch|org.apache.arrow.flatbuf.RecordBatch) => NS17716817176095924048.org.apache.arrow.flatbuf.Schema|org.apache.arrow.flatbuf.DictionaryBatch|org.apache.arrow.flatbuf.RecordBatch|null
): NS17716817176095924048.org.apache.arrow.flatbuf.Schema|org.apache.arrow.flatbuf.DictionaryBatch|org.apache.arrow.flatbuf.RecordBatch|null {
switch(org.apache.arrow.flatbuf.MessageHeader[type]) {
case 'NONE': return null;
case 'Schema': return accessor(new NS17716817176095924048.org.apache.arrow.flatbuf.Schema())! as NS17716817176095924048.org.apache.arrow.flatbuf.Schema;
case 'DictionaryBatch': return accessor(new org.apache.arrow.flatbuf.DictionaryBatch())! as org.apache.arrow.flatbuf.DictionaryBatch;
case 'RecordBatch': return accessor(new org.apache.arrow.flatbuf.RecordBatch())! as org.apache.arrow.flatbuf.RecordBatch;
default: return null;
}
}
export function unionListToMessageHeader(
type: MessageHeader,
accessor: (index: number, obj:NS17716817176095924048.org.apache.arrow.flatbuf.Schema|org.apache.arrow.flatbuf.DictionaryBatch|org.apache.arrow.flatbuf.RecordBatch) => NS17716817176095924048.org.apache.arrow.flatbuf.Schema|org.apache.arrow.flatbuf.DictionaryBatch|org.apache.arrow.flatbuf.RecordBatch|null,
index: number
): NS17716817176095924048.org.apache.arrow.flatbuf.Schema|org.apache.arrow.flatbuf.DictionaryBatch|org.apache.arrow.flatbuf.RecordBatch|null {
switch(org.apache.arrow.flatbuf.MessageHeader[type]) {
case 'NONE': return null;
case 'Schema': return accessor(index, new NS17716817176095924048.org.apache.arrow.flatbuf.Schema())! as NS17716817176095924048.org.apache.arrow.flatbuf.Schema;
case 'DictionaryBatch': return accessor(index, new org.apache.arrow.flatbuf.DictionaryBatch())! as org.apache.arrow.flatbuf.DictionaryBatch;
case 'RecordBatch': return accessor(index, new org.apache.arrow.flatbuf.RecordBatch())! as org.apache.arrow.flatbuf.RecordBatch;
default: return null;
}
}
}
/**
* ----------------------------------------------------------------------
* Data structures for describing a table row batch (a collection of
* equal-length Arrow arrays)
* Metadata about a field at some level of a nested type tree (but not
* its children).
*
* For example, a List<Int16> with values `[[1, 2, 3], null, [4], [5, 6], null]`
* would have {length: 5, null_count: 2} for its List node, and {length: 6,
* null_count: 0} for its Int16 node, as separate FieldNode structs
*
* @constructor
*/
export namespace org.apache.arrow.flatbuf{
export class FieldNode {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos:number = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns FieldNode
*/
__init(i:number, bb:flatbuffers.ByteBuffer):FieldNode {
this.bb_pos = i;
this.bb = bb;
return this;
};
/**
* The number of value slots in the Arrow array at this level of a nested
* tree
*
* @returns flatbuffers.Long
*/
length():flatbuffers.Long {
return this.bb!.readInt64(this.bb_pos);
};
/**
* The number of observed nulls. Fields with null_count == 0 may choose not
* to write their physical validity bitmap out as a materialized buffer,
* instead setting the length of the bitmap buffer to 0.
*
* @returns flatbuffers.Long
*/
nullCount():flatbuffers.Long {
return this.bb!.readInt64(this.bb_pos + 8);
};
/**
* @returns number
*/
static sizeOf():number {
return 16;
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Long length
* @param flatbuffers.Long null_count
* @returns flatbuffers.Offset
*/
static createFieldNode(builder:flatbuffers.Builder, length: flatbuffers.Long, null_count: flatbuffers.Long):flatbuffers.Offset {
builder.prep(8, 16);
builder.writeInt64(null_count);
builder.writeInt64(length);
return builder.offset();
};
}
}
/**
* Optional compression for the memory buffers constituting IPC message
* bodies. Intended for use with RecordBatch but could be used for other
* message types
*
* @constructor
*/
export namespace org.apache.arrow.flatbuf{
export class BodyCompression {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos:number = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns BodyCompression
*/
__init(i:number, bb:flatbuffers.ByteBuffer):BodyCompression {
this.bb_pos = i;
this.bb = bb;
return this;
};
/**
* @param flatbuffers.ByteBuffer bb
* @param BodyCompression= obj
* @returns BodyCompression
*/
static getRootAsBodyCompression(bb:flatbuffers.ByteBuffer, obj?:BodyCompression):BodyCompression {
return (obj || new BodyCompression()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
};
/**
* @param flatbuffers.ByteBuffer bb
* @param BodyCompression= obj
* @returns BodyCompression
*/
static getSizePrefixedRootAsBodyCompression(bb:flatbuffers.ByteBuffer, obj?:BodyCompression):BodyCompression {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new BodyCompression()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
};
/**
* Compressor library
*
* @returns org.apache.arrow.flatbuf.CompressionType
*/
codec():org.apache.arrow.flatbuf.CompressionType {
var offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? /** */ (this.bb!.readInt8(this.bb_pos + offset)) : org.apache.arrow.flatbuf.CompressionType.LZ4_FRAME;
};
/**
* Indicates the way the record batch body was compressed
*
* @returns org.apache.arrow.flatbuf.BodyCompressionMethod
*/
method():org.apache.arrow.flatbuf.BodyCompressionMethod {
var offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? /** */ (this.bb!.readInt8(this.bb_pos + offset)) : org.apache.arrow.flatbuf.BodyCompressionMethod.BUFFER;
};
/**
* @param flatbuffers.Builder builder
*/
static startBodyCompression(builder:flatbuffers.Builder) {
builder.startObject(2);
};
/**
* @param flatbuffers.Builder builder
* @param org.apache.arrow.flatbuf.CompressionType codec
*/
static addCodec(builder:flatbuffers.Builder, codec:org.apache.arrow.flatbuf.CompressionType) {
builder.addFieldInt8(0, codec, org.apache.arrow.flatbuf.CompressionType.LZ4_FRAME);
};
/**
* @param flatbuffers.Builder builder
* @param org.apache.arrow.flatbuf.BodyCompressionMethod method
*/
static addMethod(builder:flatbuffers.Builder, method:org.apache.arrow.flatbuf.BodyCompressionMethod) {
builder.addFieldInt8(1, method, org.apache.arrow.flatbuf.BodyCompressionMethod.BUFFER);
};
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endBodyCompression(builder:flatbuffers.Builder):flatbuffers.Offset {
var offset = builder.endObject();
return offset;
};
static createBodyCompression(builder:flatbuffers.Builder, codec:org.apache.arrow.flatbuf.CompressionType, method:org.apache.arrow.flatbuf.BodyCompressionMethod):flatbuffers.Offset {
BodyCompression.startBodyCompression(builder);
BodyCompression.addCodec(builder, codec);
BodyCompression.addMethod(builder, method);
return BodyCompression.endBodyCompression(builder);
}
}
}
/**
* A data header describing the shared memory layout of a "record" or "row"
* batch. Some systems call this a "row batch" internally and others a "record
* batch".
*
* @constructor
*/
export namespace org.apache.arrow.flatbuf{
export class RecordBatch {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos:number = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns RecordBatch
*/
__init(i:number, bb:flatbuffers.ByteBuffer):RecordBatch {
this.bb_pos = i;
this.bb = bb;
return this;
};
/**
* @param flatbuffers.ByteBuffer bb
* @param RecordBatch= obj
* @returns RecordBatch
*/
static getRootAsRecordBatch(bb:flatbuffers.ByteBuffer, obj?:RecordBatch):RecordBatch {
return (obj || new RecordBatch()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
};
/**
* @param flatbuffers.ByteBuffer bb
* @param RecordBatch= obj
* @returns RecordBatch
*/
static getSizePrefixedRootAsRecordBatch(bb:flatbuffers.ByteBuffer, obj?:RecordBatch):RecordBatch {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new RecordBatch()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
};
/**
* number of records / rows. The arrays in the batch should all have this
* length
*
* @returns flatbuffers.Long
*/
length():flatbuffers.Long {
var offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? this.bb!.readInt64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
};
/**
* Nodes correspond to the pre-ordered flattened logical schema
*
* @param number index
* @param org.apache.arrow.flatbuf.FieldNode= obj
* @returns org.apache.arrow.flatbuf.FieldNode
*/
nodes(index: number, obj?:org.apache.arrow.flatbuf.FieldNode):org.apache.arrow.flatbuf.FieldNode|null {
var offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? (obj || new org.apache.arrow.flatbuf.FieldNode()).__init(this.bb!.__vector(this.bb_pos + offset) + index * 16, this.bb!) : null;
};
/**
* @returns number
*/
nodesLength():number {
var offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
};
/**
* Buffers correspond to the pre-ordered flattened buffer tree
*
* The number of buffers appended to this list depends on the schema. For
* example, most primitive arrays will have 2 buffers, 1 for the validity
* bitmap and 1 for the values. For struct arrays, there will only be a
* single buffer for the validity (nulls) bitmap
*
* @param number index
* @param org.apache.arrow.flatbuf.Buffer= obj
* @returns org.apache.arrow.flatbuf.Buffer
*/
buffers(index: number, obj?:NS17716817176095924048.org.apache.arrow.flatbuf.Buffer):NS17716817176095924048.org.apache.arrow.flatbuf.Buffer|null {
var offset = this.bb!.__offset(this.bb_pos, 8);
return offset ? (obj || new NS17716817176095924048.org.apache.arrow.flatbuf.Buffer()).__init(this.bb!.__vector(this.bb_pos + offset) + index * 16, this.bb!) : null;
};
/**
* @returns number
*/
buffersLength():number {
var offset = this.bb!.__offset(this.bb_pos, 8);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
};
/**
* Optional compression of the message body
*
* @param org.apache.arrow.flatbuf.BodyCompression= obj
* @returns org.apache.arrow.flatbuf.BodyCompression|null
*/
compression(obj?:org.apache.arrow.flatbuf.BodyCompression):org.apache.arrow.flatbuf.BodyCompression|null {
var offset = this.bb!.__offset(this.bb_pos, 10);
return offset ? (obj || new org.apache.arrow.flatbuf.BodyCompression()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
};
/**
* @param flatbuffers.Builder builder
*/
static startRecordBatch(builder:flatbuffers.Builder) {
builder.startObject(4);
};
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Long length
*/
static addLength(builder:flatbuffers.Builder, length:flatbuffers.Long) {
builder.addFieldInt64(0, length, builder.createLong(0, 0));
};
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset nodesOffset
*/
static addNodes(builder:flatbuffers.Builder, nodesOffset:flatbuffers.Offset) {
builder.addFieldOffset(1, nodesOffset, 0);
};
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startNodesVector(builder:flatbuffers.Builder, numElems:number) {
builder.startVector(16, numElems, 8);
};
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset buffersOffset
*/
static addBuffers(builder:flatbuffers.Builder, buffersOffset:flatbuffers.Offset) {
builder.addFieldOffset(2, buffersOffset, 0);
};
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startBuffersVector(builder:flatbuffers.Builder, numElems:number) {
builder.startVector(16, numElems, 8);
};
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset compressionOffset
*/
static addCompression(builder:flatbuffers.Builder, compressionOffset:flatbuffers.Offset) {
builder.addFieldOffset(3, compressionOffset, 0);
};
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endRecordBatch(builder:flatbuffers.Builder):flatbuffers.Offset {
var offset = builder.endObject();
return offset;
};
}
}
/**
* For sending dictionary encoding information. Any Field can be
* dictionary-encoded, but in this case none of its children may be
* dictionary-encoded.
* There is one vector / column per dictionary, but that vector / column
* may be spread across multiple dictionary batches by using the isDelta
* flag
*
* @constructor
*/
export namespace org.apache.arrow.flatbuf{
export class DictionaryBatch {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos:number = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns DictionaryBatch
*/
__init(i:number, bb:flatbuffers.ByteBuffer):DictionaryBatch {
this.bb_pos = i;
this.bb = bb;
return this;
};
/**
* @param flatbuffers.ByteBuffer bb
* @param DictionaryBatch= obj
* @returns DictionaryBatch
*/
static getRootAsDictionaryBatch(bb:flatbuffers.ByteBuffer, obj?:DictionaryBatch):DictionaryBatch {
return (obj || new DictionaryBatch()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
};
/**
* @param flatbuffers.ByteBuffer bb
* @param DictionaryBatch= obj
* @returns DictionaryBatch
*/
static getSizePrefixedRootAsDictionaryBatch(bb:flatbuffers.ByteBuffer, obj?:DictionaryBatch):DictionaryBatch {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new DictionaryBatch()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
};
/**
* @returns flatbuffers.Long
*/
id():flatbuffers.Long {
var offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? this.bb!.readInt64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
};
/**
* @param org.apache.arrow.flatbuf.RecordBatch= obj
* @returns org.apache.arrow.flatbuf.RecordBatch|null
*/
data(obj?:org.apache.arrow.flatbuf.RecordBatch):org.apache.arrow.flatbuf.RecordBatch|null {
var offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? (obj || new org.apache.arrow.flatbuf.RecordBatch()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
};
/**
* If isDelta is true the values in the dictionary are to be appended to a
* dictionary with the indicated id. If isDelta is false this dictionary
* should replace the existing dictionary.
*
* @returns boolean
*/
isDelta():boolean {
var offset = this.bb!.__offset(this.bb_pos, 8);
return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false;
};
/**
* @param flatbuffers.Builder builder
*/
static startDictionaryBatch(builder:flatbuffers.Builder) {
builder.startObject(3);
};
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Long id
*/
static addId(builder:flatbuffers.Builder, id:flatbuffers.Long) {
builder.addFieldInt64(0, id, builder.createLong(0, 0));
};
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset dataOffset
*/
static addData(builder:flatbuffers.Builder, dataOffset:flatbuffers.Offset) {
builder.addFieldOffset(1, dataOffset, 0);
};
/**
* @param flatbuffers.Builder builder
* @param boolean isDelta
*/
static addIsDelta(builder:flatbuffers.Builder, isDelta:boolean) {
builder.addFieldInt8(2, +isDelta, +false);
};
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endDictionaryBatch(builder:flatbuffers.Builder):flatbuffers.Offset {
var offset = builder.endObject();
return offset;
};
}
}
/**
* @constructor
*/
export namespace org.apache.arrow.flatbuf{
export class Message {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos:number = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns Message
*/
__init(i:number, bb:flatbuffers.ByteBuffer):Message {
this.bb_pos = i;
this.bb = bb;
return this;
};
/**
* @param flatbuffers.ByteBuffer bb
* @param Message= obj
* @returns Message
*/
static getRootAsMessage(bb:flatbuffers.ByteBuffer, obj?:Message):Message {
return (obj || new Message()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
};
/**
* @param flatbuffers.ByteBuffer bb
* @param Message= obj
* @returns Message
*/
static getSizePrefixedRootAsMessage(bb:flatbuffers.ByteBuffer, obj?:Message):Message {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new Message()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
};
/**
* @returns org.apache.arrow.flatbuf.MetadataVersion
*/
version():NS17716817176095924048.org.apache.arrow.flatbuf.MetadataVersion {
var offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? /** */ (this.bb!.readInt16(this.bb_pos + offset)) : NS17716817176095924048.org.apache.arrow.flatbuf.MetadataVersion.V1;
};
/**
* @returns org.apache.arrow.flatbuf.MessageHeader
*/
headerType():org.apache.arrow.flatbuf.MessageHeader {
var offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? /** */ (this.bb!.readUint8(this.bb_pos + offset)) : org.apache.arrow.flatbuf.MessageHeader.NONE;
};
/**
* @param flatbuffers.Table obj
* @returns ?flatbuffers.Table
*/
header<T extends flatbuffers.Table>(obj:T):T|null {
var offset = this.bb!.__offset(this.bb_pos, 8);
return offset ? this.bb!.__union(obj, this.bb_pos + offset) : null;
};
/**
* @returns flatbuffers.Long
*/
bodyLength():flatbuffers.Long {
var offset = this.bb!.__offset(this.bb_pos, 10);
return offset ? this.bb!.readInt64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
};
/**
* @param number index
* @param org.apache.arrow.flatbuf.KeyValue= obj
* @returns org.apache.arrow.flatbuf.KeyValue
*/
customMetadata(index: number, obj?:NS17716817176095924048.org.apache.arrow.flatbuf.KeyValue):NS17716817176095924048.org.apache.arrow.flatbuf.KeyValue|null {
var offset = this.bb!.__offset(this.bb_pos, 12);
return offset ? (obj || new NS17716817176095924048.org.apache.arrow.flatbuf.KeyValue()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null;
};
/**
* @returns number
*/
customMetadataLength():number {
var offset = this.bb!.__offset(this.bb_pos, 12);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
};
/**
* @param flatbuffers.Builder builder
*/
static startMessage(builder:flatbuffers.Builder) {
builder.startObject(5);
};
/**
* @param flatbuffers.Builder builder
* @param org.apache.arrow.flatbuf.MetadataVersion version
*/
static addVersion(builder:flatbuffers.Builder, version:NS17716817176095924048.org.apache.arrow.flatbuf.MetadataVersion) {
builder.addFieldInt16(0, version, NS17716817176095924048.org.apache.arrow.flatbuf.MetadataVersion.V1);
};
/**
* @param flatbuffers.Builder builder
* @param org.apache.arrow.flatbuf.MessageHeader headerType
*/
static addHeaderType(builder:flatbuffers.Builder, headerType:org.apache.arrow.flatbuf.MessageHeader) {
builder.addFieldInt8(1, headerType, org.apache.arrow.flatbuf.MessageHeader.NONE);
};
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset headerOffset
*/
static addHeader(builder:flatbuffers.Builder, headerOffset:flatbuffers.Offset) {
builder.addFieldOffset(2, headerOffset, 0);
};
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Long bodyLength
*/
static addBodyLength(builder:flatbuffers.Builder, bodyLength:flatbuffers.Long) {
builder.addFieldInt64(3, bodyLength, builder.createLong(0, 0));
};
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset customMetadataOffset
*/
static addCustomMetadata(builder:flatbuffers.Builder, customMetadataOffset:flatbuffers.Offset) {
builder.addFieldOffset(4, customMetadataOffset, 0);
};
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createCustomMetadataVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (var i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
};
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startCustomMetadataVector(builder:flatbuffers.Builder, numElems:number) {
builder.startVector(4, numElems, 4);
};
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endMessage(builder:flatbuffers.Builder):flatbuffers.Offset {
var offset = builder.endObject();
return offset;
};
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset offset
*/
static finishMessageBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {
builder.finish(offset);
};
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset offset
*/
static finishSizePrefixedMessageBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {
builder.finish(offset, undefined, true);
};
static createMessage(builder:flatbuffers.Builder, version:NS17716817176095924048.org.apache.arrow.flatbuf.MetadataVersion, headerType:org.apache.arrow.flatbuf.MessageHeader, headerOffset:flatbuffers.Offset, bodyLength:flatbuffers.Long, customMetadataOffset:flatbuffers.Offset):flatbuffers.Offset {
Message.startMessage(builder);
Message.addVersion(builder, version);
Message.addHeaderType(builder, headerType);
Message.addHeader(builder, headerOffset);
Message.addBodyLength(builder, bodyLength);
Message.addCustomMetadata(builder, customMetadataOffset);
return Message.endMessage(builder);
}
}
} | the_stack |
import {Component, DebugElement, ViewChild} from '@angular/core';
import {async, ComponentFixture, fakeAsync, flush, TestBed, tick} from '@angular/core/testing';
import {FormsModule, NgForm} from '@angular/forms';
import {By} from '@angular/platform-browser';
import * as _moment from 'moment';
import {
DL_DATE_TIME_DISPLAY_FORMAT_DEFAULT,
DlDateTimeInputDirective,
DlDateTimeInputModule,
DlDateTimeNumberModule
} from '../../public-api';
import {OCT} from '../../dl-date-time-picker/specs/month-constants';
let moment = _moment;
if ('default' in _moment) {
moment = _moment['default'];
}
@Component({
template: `
<form>
<input id="dateInput" name="dateValue" type="text" dlDateTimeInput [dlDateTimeInputFilter]="dateTimeFilter"
[(ngModel)]="dateValue"/>
</form>`
})
class DateModelComponent {
dateValue: number;
@ViewChild(DlDateTimeInputDirective, {static: false}) input: DlDateTimeInputDirective<number>;
dateTimeFilter: (value: (number | null)) => boolean = () => true;
}
describe('DlDateTimeInputDirective', () => {
beforeEach(async(() => {
return TestBed.configureTestingModule({
imports: [
FormsModule,
DlDateTimeNumberModule,
DlDateTimeInputModule
],
declarations: [
DateModelComponent,
]
})
.compileComponents();
}));
describe('numeric model', () => {
let component: DateModelComponent;
let fixture: ComponentFixture<DateModelComponent>;
let debugElement: DebugElement;
beforeEach(async(() => {
fixture = TestBed.createComponent(DateModelComponent);
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
component = fixture.componentInstance;
debugElement = fixture.debugElement;
});
}));
it('should be input as text and stored as a number', () => {
const inputElement = debugElement.query(By.directive(DlDateTimeInputDirective)).nativeElement;
inputElement.value = '2018-10-01';
inputElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(component.dateValue).toEqual(moment('2018-10-01').valueOf());
});
it('should be displayed using default format', fakeAsync(() => {
const octoberFirst = moment('2018-10-01');
const expectedValue = octoberFirst.format(DL_DATE_TIME_DISPLAY_FORMAT_DEFAULT);
component.dateValue = octoberFirst.valueOf();
fixture.detectChanges();
flush();
const inputElement = debugElement.query(By.directive(DlDateTimeInputDirective)).nativeElement;
expect(inputElement.value).toEqual(expectedValue);
}));
it('should remove model value when text value is empty string', fakeAsync(() => {
const inputElement = debugElement.query(By.directive(DlDateTimeInputDirective)).nativeElement;
inputElement.value = '2018-10-01';
inputElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
inputElement.value = '';
inputElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(component.dateValue).toBeUndefined();
}));
it('should mark input touched on blur', () => {
const inputElement = fixture.debugElement.query(By.directive(DlDateTimeInputDirective)).nativeElement;
expect(inputElement.classList).toContain('ng-untouched');
inputElement.dispatchEvent(new Event('focus'));
fixture.detectChanges();
expect(inputElement.classList).toContain('ng-untouched');
inputElement.dispatchEvent(new Event('blur'));
fixture.detectChanges();
expect(inputElement.classList).toContain('ng-touched');
});
it('should reformat the input value on blur', fakeAsync(() => {
const inputElement = debugElement.query(By.directive(DlDateTimeInputDirective)).nativeElement;
inputElement.value = '1/1/2001';
inputElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(inputElement.value).toBe('1/1/2001');
inputElement.dispatchEvent(new Event('blur'));
fixture.detectChanges();
expect(inputElement.value).toBe(moment('2001-01-01').format(DL_DATE_TIME_DISPLAY_FORMAT_DEFAULT));
}));
it('should not reformat invalid dates on blur', () => {
const inputElement = debugElement.query(By.directive(DlDateTimeInputDirective)).nativeElement;
inputElement.value = 'very-invalid-date';
inputElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(inputElement.value).toBe('very-invalid-date');
inputElement.dispatchEvent(new Event('blur'));
fixture.detectChanges();
expect(inputElement.value).toBe('very-invalid-date');
});
it('should consider empty input to be valid (for non-required inputs)', () => {
const inputElement = debugElement.query(By.directive(DlDateTimeInputDirective)).nativeElement;
expect(inputElement.classList).toContain('ng-valid');
});
it('should add ng-invalid on invalid input', fakeAsync(() => {
const novemberFirst = moment('2018-11-01');
component.dateValue = novemberFirst.valueOf();
fixture.detectChanges();
flush();
const inputElement = debugElement.query(By.directive(DlDateTimeInputDirective)).nativeElement;
expect(inputElement.classList).toContain('ng-valid');
inputElement.value = 'very-valid-date';
inputElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(inputElement.classList).toContain('ng-invalid');
const control = debugElement.children[0].injector.get(NgForm).control.get('dateValue');
expect(control.hasError('dlDateTimeInputParse')).toBe(true);
expect(control.errors.dlDateTimeInputParse.text).toBe('very-valid-date');
}));
it('should not error if dateTimeFilter is undefined', () => {
component.dateTimeFilter = undefined;
fixture.detectChanges();
const inputElement = debugElement.query(By.directive(DlDateTimeInputDirective)).nativeElement;
inputElement.value = '10/29/2018 05:00 PM';
inputElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(inputElement.classList).toContain('ng-valid');
});
it('should not error if dateTimeFilter is null', () => {
component.dateTimeFilter = null;
fixture.detectChanges();
const inputElement = debugElement.query(By.directive(DlDateTimeInputDirective)).nativeElement;
inputElement.value = '10/29/2018 05:00 PM';
inputElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(inputElement.classList).toContain('ng-valid');
});
it('should add ng-invalid for input of filtered out date', () => {
const expectedErrorValue = moment('2018-10-29T17:00').valueOf();
const allowedValue = moment('2019-10-29T17:00').valueOf();
spyOn(component, 'dateTimeFilter').and.callFake((date: number) => {
return date === allowedValue;
});
const inputElement = debugElement.query(By.directive(DlDateTimeInputDirective)).nativeElement;
inputElement.value = '10/29/2018 05:00 PM';
inputElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(inputElement.classList).toContain('ng-invalid');
const control = debugElement.children[0].injector.get(NgForm).control.get('dateValue');
expect(control.hasError('dlDateTimeInputFilter')).toBe(true);
const value = control.errors.dlDateTimeInputFilter.value;
expect(value).toBe(expectedErrorValue);
});
it('should remove ng-invalid when model is updated with valid date', fakeAsync(() => {
// This is to fix #448, inputting a value that is a disallowed date (but a valid date)
// should change to ng-valid when the model is updated to an allowed date.
const allowedValue = moment('2019-10-29T17:00').valueOf();
spyOn(component, 'dateTimeFilter').and.callFake((date: number) => {
return date === allowedValue;
});
const inputElement = debugElement.query(By.directive(DlDateTimeInputDirective)).nativeElement;
inputElement.value = '10/29/2018 05:00 PM';
inputElement.dispatchEvent(new Event('blur'));
fixture.detectChanges();
expect(inputElement.classList).toContain('ng-invalid');
component.dateValue = allowedValue;
fixture.detectChanges();
tick();
fixture.detectChanges();
expect(inputElement.classList).toContain('ng-valid');
}));
it('should add ng-invalid for non-date input and remove ng-invalid after when model is updated with valid date', fakeAsync(() => {
// This is to fix #448, inputting a completely invalid date value (i.e not a date at all)
// should change to ng-valid when the model is updated to an allowed date.
const allowedValue = moment('2019-10-29T17:00').valueOf();
spyOn(component, 'dateTimeFilter').and.callFake((date: number) => {
return date === allowedValue;
});
const inputElement = debugElement.query(By.directive(DlDateTimeInputDirective)).nativeElement;
inputElement.value = 'very-invalid-date';
inputElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(inputElement.classList).toContain('ng-invalid');
inputElement.dispatchEvent(new Event('blur'));
fixture.detectChanges();
component.dateValue = allowedValue;
fixture.detectChanges();
tick();
fixture.detectChanges();
expect(inputElement.classList).toContain('ng-valid');
}));
it('should disable input when setDisabled is called', () => {
const inputElement = debugElement.query(By.directive(DlDateTimeInputDirective)).nativeElement;
expect(inputElement.disabled).toBe(false);
component.input.setDisabledState(true);
expect(inputElement.disabled).toBe(true);
});
it('should emit a change event when a valid value is entered.', function () {
const changeSpy = jasmine.createSpy('change listener');
component.input.dateChange.subscribe(changeSpy);
const inputElement = debugElement.query(By.directive(DlDateTimeInputDirective)).nativeElement;
inputElement.value = '2018-10-01';
inputElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
inputElement.dispatchEvent(new Event('blur'));
fixture.detectChanges();
inputElement.dispatchEvent(new Event('change'));
fixture.detectChanges();
const expected = new Date(2018, OCT, 1).getTime();
expect(changeSpy).toHaveBeenCalled();
expect(changeSpy.calls.first().args[0].value).toBe(expected);
});
});
}); | the_stack |
import _ from "lodash"
import * as React from "react"
import * as action from "../../src/action/common"
import Session, { dispatch, getState } from "../../src/common/session"
import { Label2dCanvas } from "../../src/components/label2d_canvas"
import { getShapes } from "../../src/functional/state_util"
import { PathPoint2DType } from "../../src/types/state"
import { testJson } from "../test_states/test_image_objects"
import { LabelCollector } from "../util/label_collector"
import {
drawPolygon,
keyDown,
keyUp,
mouseDown,
mouseMove,
mouseMoveClick,
mouseUp,
setUpLabel2dCanvas
} from "./canvas_util"
import { setupTestStore } from "./util"
const canvasRef: React.RefObject<Label2dCanvas> = React.createRef()
beforeEach(() => {
// TODO: Find the reason why 'canvasRef.current' is a null object.
// and remove these code borrowed from beforeAll().
setupTestStore(testJson)
Session.images.length = 0
Session.images.push({ [-1]: new Image(1000, 1000) })
for (let i = 0; i < getState().task.items.length; i++) {
dispatch(action.loadItem(i, -1))
}
setUpLabel2dCanvas(dispatch, canvasRef, 1000, 1000)
// original code
expect(canvasRef.current).not.toBeNull()
canvasRef.current?.clear()
setupTestStore(testJson)
Session.subscribe(() => {
Session.label2dList.updateState(getState())
canvasRef.current?.updateState(getState())
})
})
beforeAll(() => {
setupTestStore(testJson)
Session.images.length = 0
Session.images.push({ [-1]: new Image(1000, 1000) })
for (let i = 0; i < getState().task.items.length; i++) {
dispatch(action.loadItem(i, -1))
}
setUpLabel2dCanvas(dispatch, canvasRef, 1000, 1000)
})
test("Draw 2d polygons to label2d list", () => {
Session.dispatch(action.changeSelect({ labelType: 1 }))
const labelIds = new LabelCollector(getState)
// It has been checked that canvasRef.current is not null
const label2d = canvasRef.current as Label2dCanvas
// Draw the first polygon
mouseMoveClick(label2d, 10, 10)
mouseMoveClick(label2d, 100, 100)
mouseMoveClick(label2d, 200, 100)
/**
* drawing the first polygon
* polygon 1: (10, 10) (100, 100) (200, 100)
*/
let state = Session.getState()
expect(_.size(state.task.items[0].labels)).toEqual(0)
// Drag when drawing
mouseMoveClick(label2d, 100, 0)
mouseMoveClick(label2d, 10, 10)
/**
* polygon 1: (10, 10) (100, 100) (200, 100) (100, 0)
*/
state = Session.getState()
expect(_.size(state.task.items[0].labels)).toEqual(1)
labelIds.collect()
let points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(4)
expect(points[0]).toMatchObject({ x: 10, y: 10, pointType: "line" })
expect(points[1]).toMatchObject({ x: 100, y: 100, pointType: "line" })
expect(points[2]).toMatchObject({ x: 200, y: 100, pointType: "line" })
expect(points[3]).toMatchObject({ x: 100, y: 0, pointType: "line" })
// Draw second polygon
drawPolygon(label2d, [
[500, 500],
[600, 400],
[700, 700]
])
/**
* polygon 1: (10, 10) (100, 100) (200, 100) (100, 0)
* polygon 2: (500, 500) (600, 400) (700, 700)
*/
state = Session.getState()
labelIds.collect()
expect(_.size(state.task.items[0].labels)).toEqual(2)
points = getShapes(state, 0, labelIds[1]) as PathPoint2DType[]
expect(points.length).toEqual(3)
expect(points[0]).toMatchObject({ x: 500, y: 500, pointType: "line" })
expect(points[1]).toMatchObject({ x: 600, y: 400, pointType: "line" })
expect(points[2]).toMatchObject({ x: 700, y: 700, pointType: "line" })
})
test("2d polygons highlighted and selected", () => {
Session.dispatch(action.changeSelect({ labelType: 1 }))
const labelIds = new LabelCollector(getState)
// It has been checked that canvasRef.current is not null
const label2d = canvasRef.current as Label2dCanvas
// Draw first polygon
drawPolygon(label2d, [
[120, 120],
[210, 210],
[310, 260],
[410, 210],
[210, 110]
])
/**
* polygon 1: (120, 120) (210, 210) (310, 260) (410, 210) (210, 110)
*/
labelIds.collect()
let selected = Session.label2dList.selectedLabels
expect(selected[0].labelId).toEqual(labelIds[0])
// Draw second polygon
drawPolygon(label2d, [
[500, 500],
[600, 400],
[700, 700]
])
/**
* polygon 1: (120, 120) (210, 210) (310, 260) (410, 210) (210, 110)
* polygon 2: (500, 500) (600, 400) (700, 700)
*/
// Change selected label
mouseMove(label2d, 120, 120)
mouseDown(label2d, 120, 120)
mouseMove(label2d, 140, 140)
mouseUp(label2d, 140, 140)
selected = Session.label2dList.selectedLabels
labelIds.collect()
expect(selected[0].labelId).toEqual(labelIds[0])
})
test("validation check for polygon2d", () => {
Session.dispatch(action.changeSelect({ labelType: 1 }))
const labelIds = new LabelCollector(getState)
// It has been checked that canvasRef.current is not null
const label2d = canvasRef.current as Label2dCanvas
// Draw a valid polygon
drawPolygon(label2d, [
[120, 120],
[210, 210],
[310, 260],
[410, 210],
[210, 110]
])
labelIds.collect()
/**
* polygon 1: (120, 120) (210, 210) (310, 260) (410, 210) (210, 110)
*/
// Draw one invalid polygon
drawPolygon(label2d, [
[200, 100],
[400, 300],
[300, 200],
[300, 0]
])
/**
* polygon 1: (120, 120) (210, 210) (310, 260) (410, 210) (210, 110)
* polygon 2: (200, 100) (400, 300) (300, 200) (300, 0) invalid
*/
let state = Session.getState()
expect(_.size(state.task.items[0].labels)).toEqual(1)
expect(Session.label2dList.labelList.length).toEqual(1)
// Drag the polygon to an invalid shape
mouseMove(label2d, 310, 260)
mouseDown(label2d, 310, 260)
mouseMove(label2d, 310, 0)
mouseUp(label2d, 310, 0)
/**
* polygon 1: (120, 120) (210, 210) (310, 0) (410, 210) (210, 110)
* polygon 1 is an invalid shape
*/
state = Session.getState()
const points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points[2]).toMatchObject({ x: 310, y: 260, pointType: "line" })
/**
* polygon 1: (120, 120) (210, 210) (310, 260) (410, 210) (210, 110)
*/
// Draw a too small polygon
drawPolygon(label2d, [
[0, 0],
[1, 0],
[0, 1]
])
/**
* polygon 1: (120, 120) (210, 210) (310, 260) (410, 210) (210, 110)
* polygon 2: (0, 0) (1, 0) (0, 1) too small, invalid
*/
state = Session.getState()
expect(_.size(state.task.items[0].labels)).toEqual(1)
expect(Session.label2dList.labelList.length).toEqual(1)
})
test("2d polygons drag vertices, midpoints and edges", () => {
Session.dispatch(action.changeSelect({ labelType: 1 }))
const labelIds = new LabelCollector(getState)
// It has been checked that canvasRef.current is not null
const label2d = canvasRef.current as Label2dCanvas
drawPolygon(label2d, [
[10, 10],
[100, 100],
[200, 100],
[100, 0]
])
/**
* polygon 1: (10, 10) (100, 100) (200, 100) (100, 0)
*/
labelIds.collect()
// Drag a vertex
mouseMove(label2d, 200, 100)
mouseDown(label2d, 200, 100)
mouseMove(label2d, 300, 100)
mouseUp(label2d, 300, 100)
let state = Session.getState()
let points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points[2]).toMatchObject({ x: 300, y: 100, pointType: "line" })
/**
* polygon 1: (10, 10) (100, 100) (300, 100) (100, 0)
*/
// Drag midpoints
mouseMove(label2d, 200, 100)
mouseDown(label2d, 200, 100)
mouseMove(label2d, 200, 150)
mouseUp(label2d, 200, 150)
state = Session.getState()
points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points[2]).toMatchObject({ x: 200, y: 150, pointType: "line" })
expect(points.length).toEqual(5)
/**
* polygon 1: (10, 10) (100, 100) (200, 150) (300, 100) (100, 0)
*/
// Drag edges
mouseMove(label2d, 20, 20)
mouseDown(label2d, 20, 20)
mouseMove(label2d, 120, 120)
mouseUp(label2d, 120, 120)
state = Session.getState()
points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points[0]).toMatchObject({ x: 110, y: 110, pointType: "line" })
expect(points.length).toEqual(5)
/**
* polygon 1: (110, 110) (200, 200) (300, 250) (400, 200) (200, 100)
*/
})
test("2d polygons delete vertex and draw bezier curve", () => {
Session.dispatch(action.changeSelect({ labelType: 1 }))
const labelIds = new LabelCollector(getState)
// It has been checked that canvasRef.current is not null
const label2d = canvasRef.current as Label2dCanvas
// Draw a polygon and delete vertex when drawing
mouseMoveClick(label2d, 200, 100)
keyDown(label2d, "d")
keyUp(label2d, "d")
mouseMoveClick(label2d, 250, 100)
mouseMoveClick(label2d, 300, 0)
mouseMoveClick(label2d, 350, 100)
mouseMoveClick(label2d, 300, 200)
mouseMove(label2d, 320, 130)
keyDown(label2d, "d")
keyUp(label2d, "d")
mouseDown(label2d, 320, 130)
mouseUp(label2d, 320, 130)
mouseMoveClick(label2d, 300, 150)
mouseMoveClick(label2d, 250, 100)
/**
* polygon: (250, 100) (300, 0) (350, 100) (320, 130) (300, 150)
*/
labelIds.collect()
let state = Session.getState()
expect(_.size(state.task.items[0].labels)).toEqual(1)
expect(Session.label2dList.labelList.length).toEqual(1)
let points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(5)
expect(points[0]).toMatchObject({ x: 250, y: 100, pointType: "line" })
expect(points[1]).toMatchObject({ x: 300, y: 0, pointType: "line" })
expect(points[2]).toMatchObject({ x: 350, y: 100, pointType: "line" })
expect(points[3]).toMatchObject({ x: 320, y: 130, pointType: "line" })
expect(points[4]).toMatchObject({ x: 300, y: 150, pointType: "line" })
// Delete vertex when closed
keyDown(label2d, "d")
mouseMove(label2d, 275, 125)
mouseDown(label2d, 275, 125)
mouseUp(label2d, 2750, 1250)
mouseMoveClick(label2d, 300, 150)
keyUp(label2d, "d")
/**
* polygon: (250, 100) (300, 0) (350, 100) (320, 130)
*/
state = Session.getState()
points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(4)
expect(points[3]).toMatchObject({ x: 320, y: 130, pointType: "line" })
// Draw bezier curve
keyDown(label2d, "c")
mouseMoveClick(label2d, 335, 115)
keyUp(label2d, "c")
/**
* polygon: (250, 100) (300, 0) (350, 100)
* [ (340, 110) (330, 120) <bezier curve control points>]
* (320, 130)
*/
state = Session.getState()
points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(6)
expect(points[3]).toMatchObject({ x: 340, y: 110, pointType: "bezier" })
expect(points[4]).toMatchObject({ x: 330, y: 120, pointType: "bezier" })
// Drag bezier curve control points
mouseMove(label2d, 340, 110)
mouseDown(label2d, 340, 110)
mouseMove(label2d, 340, 90)
mouseUp(label2d, 340, 90)
/**
* polygon: (250, 100) (300, 0) (350, 100)
* [ (340, 90) (330, 120) <bezier curve control points>]
* (320, 130)
*/
state = Session.getState()
points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(6)
expect(points[2]).toMatchObject({ x: 350, y: 100, pointType: "line" })
expect(points[3]).toMatchObject({ x: 340, y: 90, pointType: "bezier" })
expect(points[4]).toMatchObject({ x: 330, y: 120, pointType: "bezier" })
// Delete vertex on bezier curve
keyDown(label2d, "d")
mouseMoveClick(label2d, 350, 100)
keyUp(label2d, "d")
/**
* polygon: (250, 100) (300, 0) (320, 130)
*/
state = Session.getState()
points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points.length).toEqual(3)
})
test("2d polygons multi-select and multi-label moving", () => {
Session.dispatch(action.changeSelect({ labelType: 1 }))
const labelIds = new LabelCollector(getState)
// It has been checked that canvasRef.current is not null
const label2d = canvasRef.current as Label2dCanvas
// Draw first polygon
drawPolygon(label2d, [
[10, 10],
[100, 100],
[200, 100]
])
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
*/
labelIds.collect()
// Draw second polygon
drawPolygon(label2d, [
[500, 500],
[600, 400],
[700, 700]
])
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
*/
labelIds.collect()
// Draw third polygon
drawPolygon(label2d, [
[250, 250],
[300, 250],
[350, 350]
])
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
* polygon 3: (250, 250) (300, 250) (350, 350)
*/
labelIds.collect()
let state = Session.getState()
expect(_.size(state.task.items[0].labels)).toEqual(3)
// Select label 1
mouseMoveClick(label2d, 600, 600)
state = Session.getState()
expect(state.user.select.labels[0].length).toEqual(1)
expect(Session.label2dList.selectedLabels.length).toEqual(1)
expect(Session.label2dList.selectedLabels[0].labelId).toEqual(
state.user.select.labels[0][0]
)
// Select label 1, 2, 3
keyDown(label2d, "Meta")
mouseMoveClick(label2d, 300, 250)
mouseMoveClick(label2d, 50, 50)
keyUp(label2d, "Meta")
state = Session.getState()
expect(state.user.select.labels[0].length).toEqual(3)
expect(Session.label2dList.selectedLabels.length).toEqual(3)
// Unselect label 3
keyDown(label2d, "Meta")
mouseMoveClick(label2d, 300, 250)
keyUp(label2d, "Meta")
mouseMove(label2d, 0, 0)
state = Session.getState()
expect(state.user.select.labels[0].length).toEqual(2)
expect(Session.label2dList.selectedLabels.length).toEqual(2)
expect(Session.label2dList.labelList[2].highlighted).toEqual(false)
// Select three labels
keyDown(label2d, "Meta")
mouseMoveClick(label2d, 300, 250)
keyUp(label2d, "Meta")
state = Session.getState()
expect(state.user.select.labels[0].length).toEqual(3)
expect(Session.label2dList.selectedLabels.length).toEqual(3)
// Move
mouseMove(label2d, 20, 20)
mouseDown(label2d, 20, 20)
mouseMove(label2d, 60, 60)
mouseMove(label2d, 120, 120)
mouseUp(label2d, 120, 120)
/**
* polygon 1: (110, 110) (200, 200) (300, 200)
* polygon 2: (600, 600) (700, 500) (800, 800)
* polygon 3: (350, 350) (400, 350) (450, 450)
*/
state = Session.getState()
let points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points[0]).toMatchObject({ x: 110, y: 110 })
points = getShapes(state, 0, labelIds[1]) as PathPoint2DType[]
expect(points[0]).toMatchObject({ x: 600, y: 600 })
points = getShapes(state, 0, labelIds[2]) as PathPoint2DType[]
expect(points[0]).toMatchObject({ x: 350, y: 350 })
})
test("2d polygons linking labels and moving", () => {
Session.dispatch(action.changeSelect({ labelType: 1 }))
const labelIds = new LabelCollector(getState)
// It has been checked that canvasRef.current is not null
const label2d = canvasRef.current as Label2dCanvas
// Draw first polygon
drawPolygon(label2d, [
[10, 10],
[100, 100],
[200, 100]
])
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
*/
labelIds.collect()
// Draw second polygon
drawPolygon(label2d, [
[500, 500],
[600, 400],
[700, 700]
])
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
*/
labelIds.collect()
// Draw third polygon
drawPolygon(label2d, [
[250, 250],
[300, 250],
[350, 350]
])
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
* polygon 3: (250, 250) (300, 250) (350, 350)
*/
labelIds.collect()
let state = Session.getState()
expect(_.size(state.task.items[0].labels)).toEqual(3)
// Select label 2 and 0
mouseMoveClick(label2d, 300, 300)
keyDown(label2d, "Meta")
mouseMoveClick(label2d, 100, 100)
keyUp(label2d, "Meta")
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
* polygon 3: (250, 250) (300, 250) (350, 350)
*/
state = Session.getState()
expect(state.user.select.labels[0].length).toEqual(2)
expect(Session.label2dList.selectedLabels.length).toEqual(2)
expect(Session.label2dList.selectedLabels[0].labelId).toEqual(
state.user.select.labels[0][0]
)
expect(Session.label2dList.selectedLabels[1].labelId).toEqual(
state.user.select.labels[0][1]
)
// Select label 1 and 2
mouseMoveClick(label2d, 600, 600)
keyDown(label2d, "Meta")
mouseMoveClick(label2d, 50, 50)
keyUp(label2d, "Meta")
// Link label 1 and 2
keyDown(label2d, "l")
keyUp(label2d, "l")
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
* polygon 3: (250, 250) (300, 250) (350, 350)
* group 1: 1, 2
*/
state = Session.getState()
expect(_.size(state.task.items[0].labels)).toEqual(4)
expect(_.size(Session.label2dList.labelList)).toEqual(3)
expect(Session.label2dList.labelList[0].color).toEqual(
Session.label2dList.labelList[1].color
)
// Reselect label 1 and 2
mouseMoveClick(label2d, 300, 250)
mouseMoveClick(label2d, 50, 50)
state = Session.getState()
expect(state.user.select.labels[0].length).toEqual(2)
expect(Session.label2dList.selectedLabels.length).toEqual(2)
// Moving group 1
mouseMove(label2d, 20, 20)
mouseDown(label2d, 20, 20)
mouseMove(label2d, 60, 60)
mouseMove(label2d, 120, 120)
mouseUp(label2d, 120, 120)
/**
* polygon 1: (110, 110) (200, 200) (300, 200)
* polygon 2: (600, 600) (700, 500) (800, 800)
* polygon 3: (250, 250) (300, 250) (350, 350)
* group 1: 1, 2
*/
state = Session.getState()
let points = getShapes(state, 0, labelIds[0]) as PathPoint2DType[]
expect(points[0]).toMatchObject({ x: 110, y: 110 })
points = getShapes(state, 0, labelIds[1]) as PathPoint2DType[]
expect(points[0]).toMatchObject({ x: 600, y: 600 })
points = getShapes(state, 0, labelIds[2]) as PathPoint2DType[]
expect(points[0]).toMatchObject({ x: 250, y: 250 })
})
test("2d polygons unlinking", () => {
Session.dispatch(action.changeSelect({ labelType: 1 }))
// It has been checked that canvasRef.current is not null
const label2d = canvasRef.current as Label2dCanvas
// Draw first polygon
drawPolygon(label2d, [
[10, 10],
[100, 100],
[200, 100]
])
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
*/
// Draw second polygon
drawPolygon(label2d, [
[500, 500],
[600, 400],
[700, 700]
])
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
*/
// Draw third polygon
drawPolygon(label2d, [
[250, 250],
[300, 250],
[350, 350]
])
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
* polygon 3: (250, 250) (300, 250) (350, 350)
*/
let state = Session.getState()
expect(_.size(state.task.items[0].labels)).toEqual(3)
// Select polygon 1 and 3
keyDown(label2d, "Meta")
mouseMoveClick(label2d, 100, 100)
keyUp(label2d, "Meta")
// Link polygon 1 and 3
keyDown(label2d, "l")
keyUp(label2d, "l")
state = Session.getState()
expect(_.size(state.task.items[0].labels)).toEqual(4)
expect(_.size(Session.label2dList.labelList)).toEqual(3)
expect(Session.label2dList.labelList[0].color).toEqual(
Session.label2dList.labelList[2].color
)
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
* polygon 3: (250, 250) (300, 250) (350, 350)
* group 1: polygon 1, 3
*/
// Select polygon 1, 2, 3
mouseMoveClick(label2d, 550, 550)
keyDown(label2d, "Meta")
mouseMoveClick(label2d, 100, 100)
keyUp(label2d, "Meta")
// Unlink polygon 1 and 3
keyDown(label2d, "L")
keyUp(label2d, "L")
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
* polygon 3: (250, 250) (300, 250) (350, 350)
*/
state = Session.getState()
expect(_.size(state.task.items[0].labels)).toEqual(3)
expect(_.size(Session.label2dList.labelList)).toEqual(3)
// Unselect polygon 1
keyDown(label2d, "Meta")
mouseMoveClick(label2d, 100, 100)
keyUp(label2d, "Meta")
// Link polygon 2 and 3
keyDown(label2d, "l")
keyUp(label2d, "l")
/**
* polygon 1: (10, 10) (100, 100) (200, 100)
* polygon 2: (500, 500) (600, 400) (700, 700)
* polygon 3: (250, 250) (300, 250) (350, 350)
* group 1: polygon 2, 3
*/
state = Session.getState()
expect(_.size(state.task.items[0].labels)).toEqual(4)
expect(_.size(Session.label2dList.labelList)).toEqual(3)
expect(Session.label2dList.labelList[1].color).toEqual(
Session.label2dList.labelList[2].color
)
}) | the_stack |
import { FSWatcher, Dirent } from 'fs';
import { IFS } from './fs';
import { Readable, Writable } from 'stream';
const { fsAsyncMethods, fsSyncMethods } = require('fs-monkey/lib/util/lists');
export interface IUnionFsError extends Error {
prev?: IUnionFsError | null;
}
type readdirEntry = string | Buffer | Dirent;
const SPECIAL_METHODS = new Set([
'existsSync',
'readdir',
'readdirSync',
'createReadStream',
'createWriteStream',
'watch',
'watchFile',
'unwatchFile',
]);
const createFSProxy = (watchers: FSWatcher[]) =>
new Proxy(
{},
{
get(_obj, property) {
const funcCallers: Array<[FSWatcher, Function]> = [];
let prop: Function | undefined;
for (const watcher of watchers) {
prop = watcher[property];
// if we're a function we wrap it in a bigger caller;
if (typeof prop === 'function') {
funcCallers.push([watcher, prop]);
}
}
if (funcCallers.length) {
return (...args) => {
for (const [watcher, func] of funcCallers) {
func.apply(watcher, args);
}
};
} else {
return prop;
}
},
},
);
const fsPromisesMethods = [
'access',
'copyFile',
'open',
'opendir',
'rename',
'truncate',
'rmdir',
'mkdir',
'readdir',
'readlink',
'symlink',
'lstat',
'stat',
'link',
'unlink',
'chmod',
'lchmod',
'lchown',
'chown',
'utimes',
'realpath',
'mkdtemp',
'writeFile',
'appendFile',
'readFile',
] as const;
/**
* Union object represents a stack of filesystems
*/
export class Union {
private fss: IFS[] = [];
public ReadStream: typeof Readable | (new (...args: any[]) => Readable) = Readable;
public WriteStream: typeof Writable | (new (...args: any[]) => Writable) = Writable;
private promises: {} = {};
constructor() {
for (let method of fsSyncMethods) {
if (!SPECIAL_METHODS.has(method)) {
// check we don't already have a property for this method
this[method] = (...args) => this.syncMethod(method, args);
}
}
for (let method of fsAsyncMethods) {
if (!SPECIAL_METHODS.has(method)) {
// check we don't already have a property for this method
this[method] = (...args) => this.asyncMethod(method, args);
}
}
for (let method of fsPromisesMethods) {
if (method === 'readdir') {
this.promises[method] = this.readdirPromise;
continue;
}
this.promises[method] = (...args) => this.promiseMethod(method, args);
}
for (let method of SPECIAL_METHODS.values()) {
// bind special methods to support
// const { method } = ufs;
this[method] = this[method].bind(this);
}
}
public unwatchFile = (...args) => {
throw new Error('unwatchFile is not supported, please use watchFile');
};
public watch = (...args) => {
const watchers: FSWatcher[] = [];
for (const fs of this.fss) {
try {
const watcher = fs.watch.apply(fs, args);
watchers.push(watcher);
} catch (e) {
// dunno what to do here...
}
}
// return a proxy to call functions on these props
return createFSProxy(watchers);
};
public watchFile = (...args) => {
for (const fs of this.fss) {
try {
fs.watchFile.apply(fs, args);
} catch (e) {
// dunno what to do here...
}
}
};
public existsSync = (path: string) => {
for (const fs of this.fss) {
try {
if (fs.existsSync(path)) {
return true;
}
} catch (e) {
// ignore
}
}
return false;
};
public readdir = (...args): void => {
let lastarg = args.length - 1;
let cb = args[lastarg];
if (typeof cb !== 'function') {
cb = null;
lastarg++;
}
let lastError: IUnionFsError | null = null;
let result = new Map<string, readdirEntry>();
const iterate = (i = 0, error?: IUnionFsError | null) => {
if (error) {
error.prev = lastError;
lastError = error;
}
// Already tried all file systems, return the last error.
if (i >= this.fss.length) {
// last one
if (cb) {
cb(error || Error('No file systems attached.'));
}
return;
}
// Replace `callback` with our intermediate function.
args[lastarg] = (err, resArg: readdirEntry[]) => {
if (result.size === 0 && err) {
return iterate(i + 1, err);
}
if (resArg) {
for (const res of resArg) {
result.set(this.pathFromReaddirEntry(res), res);
}
}
if (i === this.fss.length - 1) {
return cb(null, this.sortedArrayFromReaddirResult(result));
} else {
return iterate(i + 1, error);
}
};
const j = this.fss.length - i - 1;
const fs = this.fss[j];
const func = fs.readdir;
if (!func) iterate(i + 1, Error('Method not supported: readdir'));
else func.apply(fs, args);
};
iterate();
};
public readdirSync = (...args): Array<readdirEntry> => {
let lastError: IUnionFsError | null = null;
let result = new Map<string, readdirEntry>();
for (let i = this.fss.length - 1; i >= 0; i--) {
const fs = this.fss[i];
try {
if (!fs.readdirSync) throw Error(`Method not supported: "readdirSync" with args "${args}"`);
for (const res of fs.readdirSync.apply(fs, args)) {
result.set(this.pathFromReaddirEntry(res), res);
}
} catch (err) {
err.prev = lastError;
lastError = err;
if (result.size === 0 && !i) {
// last one
throw err;
} else {
// Ignore error...
// continue;
}
}
}
return this.sortedArrayFromReaddirResult(result);
};
public readdirPromise = async (...args): Promise<Array<readdirEntry>> => {
let lastError: IUnionFsError | null = null;
let result = new Map<string, readdirEntry>();
for (let i = this.fss.length - 1; i >= 0; i--) {
const fs = this.fss[i];
try {
if (!fs.promises || !fs.promises.readdir)
throw Error(`Method not supported: "readdirSync" with args "${args}"`);
for (const res of await fs.promises.readdir.apply(fs, args)) {
result.set(this.pathFromReaddirEntry(res), res);
}
} catch (err) {
err.prev = lastError;
lastError = err;
if (result.size === 0 && !i) {
// last one
throw err;
} else {
// Ignore error...
// continue;
}
}
}
return this.sortedArrayFromReaddirResult(result);
};
private pathFromReaddirEntry = (readdirEntry: readdirEntry): string => {
if (readdirEntry instanceof Buffer || typeof readdirEntry === 'string') {
return String(readdirEntry);
}
return readdirEntry.name;
};
private sortedArrayFromReaddirResult = (readdirResult: Map<string, readdirEntry>): readdirEntry[] => {
const array: readdirEntry[] = [];
for (const key of Array.from(readdirResult.keys()).sort()) {
const value = readdirResult.get(key);
if (value !== undefined) array.push(value);
}
return array;
};
public createReadStream = (path: string) => {
let lastError = null;
for (const fs of this.fss) {
try {
if (!fs.createReadStream) throw Error(`Method not supported: "createReadStream"`);
if (fs.existsSync && !fs.existsSync(path)) {
throw new Error(`file "${path}" does not exists`);
}
const stream = fs.createReadStream(path);
if (!stream) {
throw new Error('no valid stream');
}
this.ReadStream = fs.ReadStream;
return stream;
} catch (err) {
lastError = err;
}
}
throw lastError;
};
public createWriteStream = (path: string) => {
let lastError = null;
for (const fs of this.fss) {
try {
if (!fs.createWriteStream) throw Error(`Method not supported: "createWriteStream"`);
fs.statSync(path); //we simply stat first to exit early for mocked fs'es
//TODO which filesystem to write to?
const stream = fs.createWriteStream(path);
if (!stream) {
throw new Error('no valid stream');
}
this.WriteStream = fs.WriteStream;
return stream;
} catch (err) {
lastError = err;
}
}
throw lastError;
};
/**
* Adds a filesystem to the list of filesystems in the union
* The new filesystem object is added as the last filesystem used
* when searching for a file.
*
* @param fs the filesystem interface to be added to the queue of FS's
* @returns this instance of a unionFS
*/
use(fs: IFS): this {
this.fss.push(fs);
return this;
}
private syncMethod(method: string, args: any[]) {
let lastError: IUnionFsError | null = null;
for (let i = this.fss.length - 1; i >= 0; i--) {
const fs = this.fss[i];
try {
if (!fs[method]) throw Error(`Method not supported: "${method}" with args "${args}"`);
return fs[method].apply(fs, args);
} catch (err) {
err.prev = lastError;
lastError = err;
if (!i) {
// last one
throw err;
} else {
// Ignore error...
// continue;
}
}
}
}
private asyncMethod(method: string, args: any[]) {
let lastarg = args.length - 1;
let cb = args[lastarg];
if (typeof cb !== 'function') {
cb = null;
lastarg++;
}
let lastError: IUnionFsError | null = null;
const iterate = (i = 0, err?: IUnionFsError) => {
if (err) {
err.prev = lastError;
lastError = err;
}
// Already tried all file systems, return the last error.
if (i >= this.fss.length) {
// last one
if (cb) cb(err || Error('No file systems attached.'));
return;
}
// Replace `callback` with our intermediate function.
args[lastarg] = function(err) {
if (err) return iterate(i + 1, err);
if (cb) cb.apply(cb, arguments);
};
const j = this.fss.length - i - 1;
const fs = this.fss[j];
const func = fs[method];
if (!func) iterate(i + 1, Error('Method not supported: ' + method));
else func.apply(fs, args);
};
iterate();
}
async promiseMethod(method: string, args: any[]) {
let lastError = null;
for (let i = this.fss.length - 1; i >= 0; i--) {
const theFs = this.fss[i];
const promises = theFs.promises;
try {
if (!promises || !promises[method]) {
throw Error(`Promise of method not supported: "${String(method)}" with args "${args}"`);
}
// return promises[method](...args);
return await promises[method].apply(promises, args);
} catch (err) {
err.prev = lastError;
lastError = err;
if (!i) {
// last one
throw err;
} else {
// Ignore error...
// continue;
}
}
}
}
} | the_stack |
import * as assert from "@esfx/internal-assert";
import { HashMap } from '@esfx/collections-hashmap';
import { HashSet } from '@esfx/collections-hashset';
import { Equaler } from '@esfx/equatable';
import { T } from '@esfx/fn';
import { Hierarchical, HierarchyIterable, HierarchyProvider, OrderedHierarchyIterable } from "@esfx/iter-hierarchy";
import { OrderedIterable } from '@esfx/iter-ordered';
import { Axis } from '@esfx/iter-hierarchy/axis';
import { toArray } from './scalars';
function isHierarchyElement<T>(provider: HierarchyProvider<T>, value: T) {
return value !== undefined && (provider.owns === undefined || provider.owns(value));
}
function createHierarchyIterable(tag: string, axis: <TNode>(provider: HierarchyProvider<TNode>, element: TNode) => Iterable<TNode>) {
return {
[tag]: class <TNode> implements HierarchyIterable<TNode> {
private _source: HierarchyIterable<TNode>;
private _predicate: (element: TNode) => boolean;
private _axis: (provider: HierarchyProvider<TNode>, element: TNode) => Iterable<TNode>;
constructor(source: HierarchyIterable<TNode>, predicate: (element: TNode) => boolean) {
this._source = source;
this._predicate = predicate;
this._axis = axis;
}
*[Symbol.iterator](): Iterator<TNode> {
const source = this._source;
const hierarchy = source[Hierarchical.hierarchy]();
const predicate = this._predicate;
const axis = this._axis;
for (const element of source) {
if (isHierarchyElement(hierarchy, element)) {
for (const related of axis(hierarchy, element)) {
if (predicate(related)) {
yield related;
}
}
}
}
}
[Hierarchical.hierarchy]() {
return this._source[Hierarchical.hierarchy]();
}
}
}[tag];
}
const RootHierarchyIterable = createHierarchyIterable("RootHierarchyIterable", Axis.root);
/**
* Selects the root element of each node in the iterable. This is equivalent to the `/` selector in XPath, or the `:root` selector in CSS.
* @category Hierarchy
*/
export function root<TNode, U extends TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): HierarchyIterable<TNode, U>;
export function root<TNode>(source: HierarchyIterable<TNode>, predicate?: (element: TNode) => boolean): HierarchyIterable<TNode>;
export function root<TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => boolean = T): HierarchyIterable<TNode> {
assert.mustBeType(HierarchyIterable.hasInstance, source, "source");
assert.mustBeFunction(predicate, "predicate");
return new RootHierarchyIterable(source, predicate);
}
const AncestorsHierarchyIterable = createHierarchyIterable("AncestorsHierarchyIterable", Axis.ancestors);
/**
* Selects the ancestors of each node in the iterable. This is equivalent to the `ancestor::*` selector in XPath.
* @category Hierarchy
*/
export function ancestors<TNode, U extends TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): HierarchyIterable<TNode, U>;
export function ancestors<TNode>(source: HierarchyIterable<TNode>, predicate?: (element: TNode) => boolean): HierarchyIterable<TNode>;
export function ancestors<TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => boolean = T): HierarchyIterable<TNode> {
assert.mustBeType(HierarchyIterable.hasInstance, source, "source");
assert.mustBeFunction(predicate, "predicate");
return new AncestorsHierarchyIterable(source, predicate);
}
const AncestorsAndSelfHierarchyIterable = createHierarchyIterable("AncestorsAndSelfHierarchyIterable", Axis.ancestorsAndSelf);
/**
* Selects the ancestors of each node in the iterable, along with the node itself. This is equivalent to the `ancestor-or-self::*` selector in XPath.
* @category Hierarchy
*/
export function ancestorsAndSelf<TNode, U extends TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): HierarchyIterable<TNode, U>;
export function ancestorsAndSelf<TNode>(source: HierarchyIterable<TNode>, predicate?: (element: TNode) => boolean): HierarchyIterable<TNode>;
export function ancestorsAndSelf<TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => boolean = T): HierarchyIterable<TNode> {
assert.mustBeType(HierarchyIterable.hasInstance, source, "source");
assert.mustBeFunction(predicate, "predicate");
return new AncestorsAndSelfHierarchyIterable(source, predicate);
}
const DescendantsHierarchyIterable = createHierarchyIterable("DescendantsHierarchyIterable", Axis.descendants);
/**
* Selects the descendents of each node in the iterable. This is equivalent to the `descendant::*` selector in XPath, or the ` ` (space) combinator in CSS.
* @category Hierarchy
*/
export function descendants<TNode, U extends TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): HierarchyIterable<TNode, U>;
export function descendants<TNode>(source: HierarchyIterable<TNode>, predicate?: (element: TNode) => boolean): HierarchyIterable<TNode>;
export function descendants<TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => boolean = T): HierarchyIterable<TNode> {
assert.mustBeType(HierarchyIterable.hasInstance, source, "source");
assert.mustBeFunction(predicate, "predicate");
return new DescendantsHierarchyIterable(source, predicate);
}
const DescendantsAndSelfHierarchyIterable = createHierarchyIterable("DescendantsAndSelfHierarchyIterable", Axis.descendantsAndSelf);
/**
* Selects the descendents of each node in the iterable, along with the node itself. This is equivalent to the `descendant-or-self::*` selector in XPath.
* @category Hierarchy
*/
export function descendantsAndSelf<TNode, U extends TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): HierarchyIterable<TNode, U>;
export function descendantsAndSelf<TNode>(source: HierarchyIterable<TNode>, predicate?: (element: TNode) => boolean): HierarchyIterable<TNode>;
export function descendantsAndSelf<TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => boolean = T): HierarchyIterable<TNode> {
assert.mustBeType(HierarchyIterable.hasInstance, source, "source");
assert.mustBeFunction(predicate, "predicate");
return new DescendantsAndSelfHierarchyIterable(source, predicate);
}
const ParentsHierarchyIterable = createHierarchyIterable("ParentsHierarchyIterable", Axis.parents);
/**
* Selects the parent of each node in the iterable. This is equivalent to the `parent::*` or `..` selectors in XPath.
* @category Hierarchy
*/
export function parents<TNode, U extends TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): HierarchyIterable<TNode, U>;
export function parents<TNode>(source: HierarchyIterable<TNode>, predicate?: (element: TNode) => boolean): HierarchyIterable<TNode>;
export function parents<TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => boolean = T): HierarchyIterable<TNode> {
assert.mustBeType(HierarchyIterable.hasInstance, source, "source");
assert.mustBeFunction(predicate, "predicate");
return new ParentsHierarchyIterable(source, predicate);
}
const SelfHierarchyIterable = createHierarchyIterable("SelfHierarchyIterable", Axis.self);
/**
* Selects each node in the iterable. This is equivalent to the `self::*` or `.` selectors in XPath.
* @category Hierarchy
*/
export function self<TNode, T extends TNode, U extends T>(source: HierarchyIterable<TNode, T>, predicate: (element: T) => element is U): HierarchyIterable<TNode, U>;
export function self<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, predicate?: (element: T) => boolean): HierarchyIterable<TNode, T>;
export function self<TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => boolean = T): HierarchyIterable<TNode> {
assert.mustBeType(HierarchyIterable.hasInstance, source, "source");
assert.mustBeFunction(predicate, "predicate");
return new SelfHierarchyIterable(source, predicate);
}
const SiblingsHierarchyIterable = createHierarchyIterable("SiblingsHierarchyIterable", Axis.siblings);
/**
* Selects the siblings of each node in the iterable, excluding the node itself.
* @category Hierarchy
*/
export function siblings<TNode, U extends TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): HierarchyIterable<TNode, U>;
export function siblings<TNode>(source: HierarchyIterable<TNode>, predicate?: (element: TNode) => boolean): HierarchyIterable<TNode>;
export function siblings<TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => boolean = T): HierarchyIterable<TNode> {
assert.mustBeType(HierarchyIterable.hasInstance, source, "source");
assert.mustBeFunction(predicate, "predicate");
return new SiblingsHierarchyIterable(source, predicate);
}
const SiblingsAndSelfHierarchyIterable = createHierarchyIterable("SiblingsAndSelfHierarchyIterable", Axis.siblingsAndSelf);
/**
* Selects the siblings of each node in the iterable, including the node itself. This equivalent to the `../*` selector in XPath.
* @category Hierarchy
*/
export function siblingsAndSelf<TNode, U extends TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): HierarchyIterable<TNode, U>;
export function siblingsAndSelf<TNode>(source: HierarchyIterable<TNode>, predicate?: (element: TNode) => boolean): HierarchyIterable<TNode>;
export function siblingsAndSelf<TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => boolean = T): HierarchyIterable<TNode> {
assert.mustBeType(HierarchyIterable.hasInstance, source, "source");
assert.mustBeFunction(predicate, "predicate");
return new SiblingsAndSelfHierarchyIterable(source, predicate);
}
const PrecedingSiblingsHierarchyIterable = createHierarchyIterable("PrecedingSiblingsHierarchyIterable", Axis.precedingSiblings);
/**
* Selects the siblings that precede each node in the iterable. This is equivalent to the `preceding-sibling::**` selector in XPath.
* @category Hierarchy
*/
export function precedingSiblings<TNode, U extends TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): HierarchyIterable<TNode, U>;
export function precedingSiblings<TNode>(source: HierarchyIterable<TNode>, predicate?: (element: TNode) => boolean): HierarchyIterable<TNode>;
export function precedingSiblings<TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => boolean = T): HierarchyIterable<TNode> {
assert.mustBeType(HierarchyIterable.hasInstance, source, "source");
assert.mustBeFunction(predicate, "predicate");
return new PrecedingSiblingsHierarchyIterable(source, predicate);
}
export { precedingSiblings as siblingsBeforeSelf };
export { followingSiblings as siblingsAfterSelf };
const FollowingSiblingsHierarchyIterable = createHierarchyIterable("FollowingSiblingsHierarchyIterable", Axis.followingSiblings);
/**
* Selects the siblings that follow each node in the iterable. This is equivalent to the `following-sibling::*` selector in XPath or the `~` combinator in CSS.
* @category Hierarchy
*/
export function followingSiblings<TNode, U extends TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): HierarchyIterable<TNode, U>;
export function followingSiblings<TNode>(source: HierarchyIterable<TNode>, predicate?: (element: TNode) => boolean): HierarchyIterable<TNode>;
export function followingSiblings<TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => boolean = T): HierarchyIterable<TNode> {
assert.mustBeType(HierarchyIterable.hasInstance, source, "source");
assert.mustBeFunction(predicate, "predicate");
return new FollowingSiblingsHierarchyIterable(source, predicate);
}
const PrecedingHierarchyIterable = createHierarchyIterable("PrecedingHierarchyIterable", Axis.preceding);
/**
* Selects the nodes that precede each node in the iterable. This is equivalent to the `preceding::**` selector in XPath.
* @category Hierarchy
*/
export function preceding<TNode, U extends TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): HierarchyIterable<TNode, U>;
export function preceding<TNode>(source: HierarchyIterable<TNode>, predicate?: (element: TNode) => boolean): HierarchyIterable<TNode>;
export function preceding<TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => boolean = T): HierarchyIterable<TNode> {
assert.mustBeType(HierarchyIterable.hasInstance, source, "source");
assert.mustBeFunction(predicate, "predicate");
return new PrecedingHierarchyIterable(source, predicate);
}
const FollowingHierarchyIterable = createHierarchyIterable("FollowingHierarchyIterable", Axis.following);
/**
* Selects the nodes that follow each node in the iterable. This is equivalent to the `following-sibling::*` selector in XPath or the `~` combinator in CSS.
* @category Hierarchy
*/
export function following<TNode, U extends TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): HierarchyIterable<TNode, U>;
export function following<TNode>(source: HierarchyIterable<TNode>, predicate?: (element: TNode) => boolean): HierarchyIterable<TNode>;
export function following<TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => boolean = T): HierarchyIterable<TNode> {
assert.mustBeType(HierarchyIterable.hasInstance, source, "source");
assert.mustBeFunction(predicate, "predicate");
return new FollowingHierarchyIterable(source, predicate);
}
const ChildrenHierarchyIterable = createHierarchyIterable("ChildrenHierarchyIterable", Axis.children);
/**
* Selects the children of each node in the iterable. This is equivalent to the `child::*` selector in XPath, or the `>` combinator in CSS.
* @category Hierarchy
*/
export function children<TNode, U extends TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): HierarchyIterable<TNode, U>;
export function children<TNode>(source: HierarchyIterable<TNode>, predicate?: (element: TNode) => boolean): HierarchyIterable<TNode>;
export function children<TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => boolean = T): HierarchyIterable<TNode> {
assert.mustBeType(HierarchyIterable.hasInstance, source, "source");
assert.mustBeFunction(predicate, "predicate");
return new ChildrenHierarchyIterable(source, predicate);
}
const FirstChildHierarchyIterable = createHierarchyIterable("FirstChildHierarchyIterable", Axis.firstChild);
/**
* Selects the first child of each node in the iterable. This is equivalent to the `child::*[first()]` selector in XPath, or the `:first-child` pseudo class in CSS.
* @category Hierarchy
*/
export function firstChild<TNode, U extends TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): HierarchyIterable<TNode, U>;
export function firstChild<TNode>(source: HierarchyIterable<TNode>, predicate?: (element: TNode) => boolean): HierarchyIterable<TNode>;
export function firstChild<TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => boolean = T): HierarchyIterable<TNode> {
assert.mustBeType(HierarchyIterable.hasInstance, source, "source");
assert.mustBeFunction(predicate, "predicate");
return new FirstChildHierarchyIterable(source, predicate);
}
const LastChildHierarchyIterable = createHierarchyIterable("LastChildHierarchyIterable", Axis.lastChild);
/**
* Selects the last child of each node in the iterable. This is equivalent to the `child::*[last()]` selector in XPath, or the `:last-child` pseudo class in CSS.
* @category Hierarchy
*/
export function lastChild<TNode, U extends TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): HierarchyIterable<TNode, U>;
export function lastChild<TNode>(source: HierarchyIterable<TNode>, predicate?: (element: TNode) => boolean): HierarchyIterable<TNode>;
export function lastChild<TNode>(source: HierarchyIterable<TNode>, predicate: (element: TNode) => boolean = T): HierarchyIterable<TNode> {
assert.mustBeType(HierarchyIterable.hasInstance, source, "source");
assert.mustBeFunction(predicate, "predicate");
return new LastChildHierarchyIterable(source, predicate);
}
class NthChildHierarchyIterable<TNode> implements Iterable<TNode> {
private _source: HierarchyIterable<TNode>;
private _predicate: (element: TNode) => boolean;
private _offset: number;
constructor(source: HierarchyIterable<TNode>, offset: number, predicate: (element: TNode) => boolean) {
this._source = source;
this._offset = offset;
this._predicate = predicate;
}
*[Symbol.iterator](): Iterator<TNode> {
const source = this._source;
const provider = source[Hierarchical.hierarchy]();
const offset = this._offset;
const predicate = this._predicate;
for (const element of source) {
if (isHierarchyElement(provider, element)) {
for (const child of Axis.nthChild(provider, element, offset)) {
if (predicate(child)) {
yield child;
}
}
}
}
}
[Hierarchical.hierarchy]() {
return this._source[Hierarchical.hierarchy]();
}
}
/**
* Creates a `HierarchyIterable` for the child of each element at the specified offset. A negative offset
* starts from the last child. This is equivalent to the `:nth-child()` pseudo-class in CSS.
*
* @param source A `HierarchyIterable` object.
* @param offset The offset for the child.
* @param predicate An optional callback used to filter the results.
* @category Hierarchy
*/
export function nthChild<TNode, U extends TNode>(source: HierarchyIterable<TNode>, offset: number, predicate: (element: TNode) => element is U): HierarchyIterable<TNode, U>;
export function nthChild<TNode>(source: HierarchyIterable<TNode>, offset: number, predicate?: (element: TNode) => boolean): HierarchyIterable<TNode>;
export function nthChild<TNode>(source: HierarchyIterable<TNode>, offset: number, predicate: (element: TNode) => boolean = T): HierarchyIterable<TNode> {
assert.mustBeType(HierarchyIterable.hasInstance, source, "source");
assert.mustBeInteger(offset, "offset");
assert.mustBeFunction(predicate, "predicate");
return new NthChildHierarchyIterable(source, offset, T);
}
class TopMostIterable<TNode, T extends TNode> implements HierarchyIterable<TNode, T> {
private _source: HierarchyIterable<TNode, T>;
private _predicate: (value: T) => boolean;
private _equaler: Equaler<TNode> | undefined;
constructor(source: HierarchyIterable<TNode, T>, predicate: (value: T) => boolean, equaler: Equaler<TNode> | undefined) {
this._source = source;
this._predicate = predicate;
this._equaler = equaler;
}
*[Symbol.iterator](): Iterator<T> {
const source = this._source;
const predicate = this._predicate;
const equaler = this._equaler;
const hierarchy = source[Hierarchical.hierarchy]();
const topMostNodes = toArray(source);
const ancestors = new HashMap<TNode, HashSet<TNode>>(equaler);
for (let i = topMostNodes.length - 1; i >= 1; i--) {
const node = topMostNodes[i];
for (let j = i - 1; j >= 0; j--) {
const other = topMostNodes[j];
let ancestorsOfNode = ancestors.get(node);
if (!ancestorsOfNode) {
ancestorsOfNode = new HashSet(Axis.ancestors(hierarchy, node), equaler);
ancestors.set(node, ancestorsOfNode);
}
if (ancestorsOfNode.has(other)) {
topMostNodes.splice(i, 1);
break;
}
let ancestorsOfOther = ancestors.get(other);
if (!ancestorsOfOther) {
ancestorsOfOther = new HashSet(Axis.ancestors(hierarchy, other), equaler);
ancestors.set(other, ancestorsOfOther);
}
if (ancestorsOfOther.has(node)) {
topMostNodes.splice(j, 1);
i--;
}
}
}
for (const node of topMostNodes) {
if (predicate(node)) yield node;
}
}
[Hierarchical.hierarchy]() {
return this._source[Hierarchical.hierarchy]();
}
}
/**
* Filters a `HierarchyIterable` to the top-most elements. Elements that are a descendant of any other
* element in the iterable are removed.
*
* @param source A `HierarchyIterable` object.
* @param predicate An optional callback used to filter the results.
* @param equaler An optional `Equaler` used to compare equality between nodes.
* @category Hierarchy
*/
export function topMost<TNode, T extends TNode, U extends T>(source: HierarchyIterable<TNode, T>, predicate: (value: T) => value is U, equaler?: Equaler<TNode>): HierarchyIterable<TNode, U>;
/**
* Creates a `HierarchyIterable` for the top-most elements. Elements that are a descendant of any other
* element are removed.
*
* @param source A `HierarchyIterable` object.
* @param predicate An optional callback used to filter the results.
* @param equaler An optional `Equaler` used to compare equality between nodes.
* @category Hierarchy
*/
export function topMost<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, predicate?: (value: T) => boolean, equaler?: Equaler<TNode>): HierarchyIterable<TNode, T>;
export function topMost<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, predicate: (value: T) => boolean = T, equaler: Equaler<TNode> = Equaler.defaultEqualer): HierarchyIterable<TNode, T> {
assert.mustBeType(HierarchyIterable.hasInstance, source, "source");
assert.mustBeFunction(predicate, "predicate");
assert.mustBeType(Equaler.hasInstance, equaler, "equaler");
return new TopMostIterable<TNode, T>(source, predicate, equaler);
}
class BottomMostIterable<TNode, T extends TNode> implements HierarchyIterable<TNode, T> {
private _source: HierarchyIterable<TNode, T>;
private _predicate: (value: T) => boolean;
private _equaler: Equaler<TNode> | undefined;
constructor(source: HierarchyIterable<TNode, T>, predicate: (value: T) => boolean, equaler: Equaler<TNode> | undefined) {
this._source = source;
this._predicate = predicate;
this._equaler = equaler;
}
*[Symbol.iterator](): Iterator<T> {
const source = this._source;
const predicate = this._predicate;
const equaler = this._equaler;
const hierarchy = source[Hierarchical.hierarchy]();
const bottomMostNodes = toArray(source);
const ancestors = new HashMap<TNode, HashSet<TNode>>(equaler);
for (let i = bottomMostNodes.length - 1; i >= 1; i--) {
const node = bottomMostNodes[i];
for (let j = i - 1; j >= 0; j--) {
const other = bottomMostNodes[j];
let ancestorsOfOther = ancestors.get(other);
if (!ancestorsOfOther) {
ancestorsOfOther = new HashSet(Axis.ancestors(hierarchy, other), equaler);
ancestors.set(other, ancestorsOfOther);
}
if (ancestorsOfOther.has(node)) {
bottomMostNodes.splice(i, 1);
break;
}
let ancestorsOfNode = ancestors.get(node);
if (!ancestorsOfNode) {
ancestorsOfNode = new HashSet(Axis.ancestors(hierarchy, node), equaler);
ancestors.set(node, ancestorsOfNode);
}
if (ancestorsOfNode.has(other)) {
bottomMostNodes.splice(j, 1);
i--;
}
}
}
for (const node of bottomMostNodes) {
if (predicate(node)) yield node;
}
}
[Hierarchical.hierarchy]() {
return this._source[Hierarchical.hierarchy]();
}
}
/**
* Creates a `HierarchyIterable` for the bottom-most elements of a `HierarchyIterable`.
* Elements of `source` that are an ancestor of any other element of `source` are removed.
*
* @param source A `HierarchyIterable` object.
* @param predicate An optional callback used to filter the results.
* @category Hierarchy
*/
export function bottomMost<TNode, T extends TNode, U extends T>(source: HierarchyIterable<TNode, T>, predicate: (value: T) => value is U, equaler?: Equaler<TNode>): HierarchyIterable<TNode, U>;
/**
* Creates a `HierarchyIterable` for the bottom-most elements of a `HierarchyIterable`.
* Elements of `source` that are an ancestor of any other element of `source` are removed.
*
* @param source A `HierarchyIterable` object.
* @param predicate An optional callback used to filter the results.
* @param equaler An optional `Equaler` used to compare equality between nodes.
* @category Hierarchy
*/
export function bottomMost<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, predicate?: (value: T) => boolean, equaler?: Equaler<TNode>): HierarchyIterable<TNode, T>;
export function bottomMost<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, predicate: (value: T) => boolean = T, equaler: Equaler<TNode> = Equaler.defaultEqualer): HierarchyIterable<TNode, T> {
assert.mustBeType(HierarchyIterable.hasInstance, source, "source");
assert.mustBeFunction(predicate, "predicate");
assert.mustBeType(Equaler.hasInstance, equaler, "equaler");
return new BottomMostIterable<TNode, T>(source, predicate, equaler);
}
/**
* Creates a `HierarchyIterable` using the provided `HierarchyProvider`.
*
* @param source An `Iterable` object.
* @param hierarchy A `HierarchyProvider`.
* @param equaler An optional `Equaler` used to compare equality between nodes.
* @category Hierarchy
*/
export function toHierarchy<TNode, T extends TNode = TNode>(iterable: OrderedIterable<T>, provider: HierarchyProvider<TNode>): OrderedHierarchyIterable<TNode, T>;
export function toHierarchy<TNode, T extends TNode = TNode>(iterable: Iterable<T>, provider: HierarchyProvider<TNode>): HierarchyIterable<TNode, T>;
export function toHierarchy<TNode, T extends TNode = TNode>(iterable: Iterable<T> | OrderedIterable<T>, provider: HierarchyProvider<TNode>) {
return HierarchyIterable.create(iterable, provider);
} | the_stack |
import * as React from 'react';
import { AppState } from '../States/AppState';
import * as $ from 'jquery';
import * as Utility from '../Utility';
import { UbbContainer } from './UbbContainer';
import { Link } from 'react-router-dom';
import DocumentTitle from './DocumentTitle';
import { CountDown } from './CountDown'
/**
* 全站公告组件
**/
export class AnnouncementComponent extends React.Component<{ data }, {}> {
render() {
const data = this.props.data;
if (data == "") return <div></div>
else return <div className="announcement">
<div className="mainPageTitle1">
<div className="mainPageTitleRow" style={{ width: '100%' }}>
<i className="fa fa-volume-up"></i>
<div style={{ flexGrow: 1 }} className="mainPageTitleText">全站公告</div>
{/*<CountDown endDate={new Date('05/26/2018 05:30 PM')} />*/}
</div>
</div>
<div className="announcementContent"><UbbContainer code={data} /></div>
</div>
}
}
/**
* 推荐阅读组件
**/
export class RecommendedReadingComponent extends React.Component<{ data }, { index: number }> {
constructor(props) {
super(props);
this.state = {
index: 0,
};
this.handleMouseEnter = this.handleMouseEnter.bind(this);
this.convertButton = this.convertButton.bind(this);
}
async componentWillReceiveProps(nextProps) {
const length: number = nextProps.data.length;
this.setState({
index: Math.floor(Math.random() * length),
})
}
handleMouseEnter(index) {
this.setState({
index: index,
})
}
convertButton(value: number, index: number, array: number[]) {
const className: string = value ? "recommendedReadingButtonSelected" : "recommendedReadingButton";
return <div className={className} onMouseEnter={() => { this.handleMouseEnter(index) }}></div>
}
render() {
const recommendedReading = this.props.data;
const length = recommendedReading.length; //推荐阅读的长度
const index = this.state.index;
let styles = new Array(length);
styles.fill(0); //将数组元素全部填充为0
styles[index] = 1; //选中下标的内容对应的数组元素值为1
const buttons = styles.map(this.convertButton);
const imageUrl = length ? recommendedReading[index].imageUrl : "";
const url = length ? recommendedReading[index].url : "";
const title = length ? recommendedReading[index].title : "";
const content = length ? recommendedReading[index].content : "";
return <div className="recommendedReading">
<div className="mainPageTitle2">
<div className="mainPageTitleRow">
<i className="fa fa-volume-up"></i>
<div className="mainPageTitleText">推荐阅读</div>
</div>
</div>
<div className="recommendedReadingContent">
<div className="recommendedReadingImage">
<img src={imageUrl} />
</div>
<div className="column" style={{ flexGrow: 1 }}>
<div className="recommendedReadingTitle"><a href={url} target="_blank">{title}</a></div>
<div className="recommendedReadingAbstract">{content}</div>
<div className="recommendedReadingButtons">{buttons}</div>
</div>
</div>
</div>
}
}
/**
* 首页热门话题类
* 用于首页的热门话题(十大),该类的对象(一条热门话题)需要标题,id,所在版面,及所在版面id等几个属性
**/
export class HotTopicState {
//属性
title: string;
id: number;
boardName: string;
boardId: number;
//构造方法
constructor(title, id, boardName, boardId) {
this.title = title;
this.id = id;
this.boardName = boardName;
this.boardId = boardId;
}
}
/**
* 热门话题组件
**/
export class HotTopicComponent extends React.Component<{ data }, { mainPageTopicState: HotTopicState[] }> {
convertMainPageTopic(item: HotTopicState) {
if (!item.id) return <div>{item.title}</div>
const boardUrl = `/board/${item.boardId}`;
const topicUrl = `/topic/${item.id}/1`;
return <div className="mainPageListRow">
<div className="mainPageListBoardName"> <a href={boardUrl} target="_blank">[{item.boardName}]</a></div>
<div className="mainPageListTitle"><a href={topicUrl} target="_blank">{item.title}</a></div>
</div >;
}
render() {
// 数据库计算新的十大需要一定时间,这时API去查询更新,就会查到空的十大(返回一个空数组)
// 因此这里检查获得的十大是否为空数组,如果是,则显示上一次获取非空十大时的缓存
let data = this.props.data;
if (data === []) {
const hotTopic = Utility.getLocalStorage("mainPageHotTopic")
const defaultData = {
title: "数据库正在计算新的十大数据,请前辈等会再来~",
id: 0,
boardName: "错误提示",
boardId: 0
}
data = hotTopic ? hotTopic : [defaultData]
}
return <div className="mainPageList">
<div className="mainPageTitle1">
<div className="mainPageTitleRow">
<i className="fa fa-volume-up"></i>
<div className="mainPageTitleText">热门话题</div>
</div>
<div className="mainPageTitleRow">
<div className="mainPageTitleText"><a href="/topic/hot-weekly" target="_blank">本周</a></div>
<div className="mainPageTitleText"><a href="/topic/hot-monthly" target="_blank">本月</a></div>
<div className="mainPageTitleText"><a href="/topic/hot-history" target="_blank">历史上的今天</a></div>
</div>
</div>
<div className="mainPageListContent1">
{data.map(this.convertMainPageTopic)}
</div>
</div>
}
}
/**
* 首页话题类
* 用于首页左侧下方的几栏,该类的对象(一条主题)需要标题和id
**/
export class MainPageTopicState {
//属性
title: string;
id: number;
//构造方法
constructor(title, id) {
this.title = title;
this.id = id;
}
}
/**
* 首页话题更多参数
* 拥有名称和链接两个属性
*/
export class MainPageTopicMoreProps {
name: string;
url: string;
constructor(name, url) {
this.name = name;
this.url = url;
}
}
/**
* 首页话题组件
* 需要列表名,fetchUrl和样式三个参数
**/
export class MainPageTopicComponent extends React.Component<{ data, name: string, fetchUrl: string, style: string, mores: MainPageTopicMoreProps[] }, {}>{
convertMainPageTopic(item: MainPageTopicState) {
const topicUrl = `/topic/${item.id}/1`;
return <div className="mainPageListRow">
<div className="mainPageListTitle"><a href={topicUrl} target="_blank">{item.title}</a></div>
</div>
}
render() {
let moresHTML = this.props.mores.map((item) => {
return <div className="mainPageTitleText"><a href={item.url} target="_blank">{item.name}</a></div>
})
const style: string = this.props.style;
if (style === "black") {
return <div className="mainPageList">
<div className="mainPageTitle2">
<div className="mainPageTitleRow">
<i className="fa fa-volume-up"></i>
<div className="mainPageTitleText">{this.props.name}</div>
</div>
<div className="mainPageTitleRow">{moresHTML}</div>
</div>
<div className="mainPageListContent2">
{this.props.data.map(this.convertMainPageTopic)}
</div>
</div>
} else if (style === "blue") {
return <div className="mainPageList">
<div className="mainPageTitle1">
<div className="mainPageTitleRow">
<i className="fa fa-volume-up"></i>
<div className="mainPageTitleText">{this.props.name}</div>
</div>
<div className="mainPageTitleRow">{moresHTML}</div>
</div>
<div className="mainPageListContent1">
{this.props.data.map(this.convertMainPageTopic)}
</div>
</div>
}
}
}
/**
* 测试用组件~
**/
export class Test extends React.Component<{}, { testContent: string }>{
constructor(props) {
super(props);
this.state = {
testContent: '',
};
this.handleChange = this.handleChange.bind(this);
this.urlTextHanderler = this.urlTextHanderler.bind(this);
}
handleChange(e) {
this.setState({
testContent: e.target.value
});
}
async urlTextHanderler() {
const reg = /[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+/gim;
const reg2 = /cc98\.org/i;
const reg3 = /zju\.edu\.cn/i;
const reg4 = /nexushd\.org/i;
const url = this.state.testContent;
const matchResult = url.match(reg);
if (matchResult) {
const domainName = matchResult[0];
let isInternalLink = reg2.test(domainName) || reg3.test(domainName) || reg4.test(domainName);
//return isInternalLink;
} else {
//console.log("这不是链接!");
}
}
async postAd() {
const url = `/index/column/24`;
const content = {
type: 4,
title: "一个图片不一样的广告",
url: "www.cc98.org",
imageUrl: "/images/推荐功能.jpg",
enable: true,
days: 10,
}
const postForumIndexColumnInfo = JSON.stringify(content);
const token = Utility.getLocalStorage("accessToken");
let myHeaders = new Headers();
myHeaders.append("Authorization", token);
myHeaders.append("Content-Type", 'application/json');
let response = await Utility.cc98Fetch(url, {
method: 'PUT',
headers: myHeaders,
body: postForumIndexColumnInfo,
});
//console.log("发送成功!")
}
async signIn() {
const url = `/me/signin`;
const token = Utility.getLocalStorage("accessToken");
let myHeaders = new Headers();
myHeaders.append("Authorization", token);
myHeaders.append("Content-Type", 'application/json');
myHeaders.append("Content-Type", "application/json");
let content = "日常";
const response = await Utility.cc98Fetch(url, { method: "POST", headers: myHeaders, body: content });
}
render() {
return <div className="mainPageList">
<div className="mainPageTitle2">
<div className="mainPageTitleRow">
<i className="fa fa-volume-up"></i>
<div className="mainPageTitleText">测试区</div>
</div>
</div>
<div className="mainPageListContent2">
<div>这里是可爱的adddna测试的地方~</div>
<input name="testContent" type="text" id="loginName" onChange={this.handleChange} value={this.state.testContent} />
<div>封印封印</div>
</div>
</div>
}
}
/**
* 首页栏目类
* 用于首页的栏目,包括推荐阅读、推荐功能以及校园新闻。
* 该类的成员对象包括:图片url(校园新闻不需要),标题,url,以及摘要(仅推荐阅读需要)
* 这部分栏目均设置在新窗口打开链接
**/
export class MainPageColumn {
//属性
imageUrl: string;
title: string;
url: string;
content: string;
//构造方法
constructor(imageUrl, title, url, content) {
this.imageUrl = imageUrl;
this.title = title;
this.url = url;
this.content = content;
}
}
/**
* 推荐功能组件
*/
export class RecommendedFunctionComponent extends React.Component<{ data }, {}>{
convertRecommendedFunction(item: MainPageColumn) {
return <div className="recommendedFunctionRow">
<div className="recommendedFunctionImage"><img src={item.imageUrl}></img></div>
<div className="recommendedFunctionTitle"><a href={item.url} target="_blank">{item.title}</a></div>
</div>
}
render() {
return <div className="recommendedFunction">
<div className="mainPageTitle1">
<div className="mainPageTitleRow">
<i className="fa fa-volume-up"></i>
<div className="mainPageTitleText">推荐功能</div>
</div>
</div>
<div className="recommendedFunctionContent">
{this.props.data.map(this.convertRecommendedFunction)}
</div>
</div>
}
}
/**
* 校园新闻组件
*/
export class SchoolNewsComponent extends React.Component<{ data }, {}>{
convertSchoolNews(item: MainPageColumn) {
return <div className="schoolNewsRow">
<div className="schoolNewsTitle"><a href={item.url} target="_blank">{item.title}</a></div>
</div>
}
render() {
return <div className="schoolNews">
<div className="mainPageTitle2">
<div className="mainPageTitleRow">
<i className="fa fa-volume-up"></i>
<div className="mainPageTitleText">校园新闻</div>
</div>
</div>
<div className="schoolNewsContent">
{this.props.data.map(this.convertSchoolNews)}
</div>
</div>
}
}
/**
* 首页广告组件
* 每20s切换一条
*/
export class AdsComponent extends React.Component<{}, { ads: MainPageColumn[], index: number }>{
private timer: any;
constructor(props) {
super(props);
let data = Utility.getStorage('mainAds');
if (!data) { data = new Array<MainPageColumn>(); }
this.state = {
ads: data,
index: 0,
};
this.changeIndex = this.changeIndex.bind(this);
this.handleMouseEnter = this.handleMouseEnter.bind(this);
this.convertButton = this.convertButton.bind(this);
}
async getAds() {
let ads: MainPageColumn[] = Utility.getStorage('mainAds');
if (ads) { return ads }
else {
ads = new Array<MainPageColumn>();
const response = await Utility.cc98Fetch('/config/global/advertisement');
const data = await response.json();
for (let i = 0; i < data.length; i++) {
ads[i] = new MainPageColumn(data[i].imageUrl, data[i].title, data[i].url, data[i].content);
}
Utility.setStorage('mainAds', ads);
return ads;
}
}
async componentWillMount() {
const x = await this.getAds();
const length = x.length;
this.setState({
ads: x,
index: Math.floor(Math.random() * length)
});
}
//设定定时器 每20s调用一次changeIndex()
componentDidMount() {
this.timer = setInterval(() => { this.changeIndex(this.state.index) }, 20000);
}
//当组件从页面上移除时移除定时器
componentWillUnmount() {
clearInterval(this.timer);
}
//根据当前广告角标返回下一角标
changeIndex(index) {
let total = this.state.ads.length;
let nextIndex = index + 1;
if (nextIndex >= total) nextIndex = 0;
this.setState({
index: nextIndex,
})
}
//绑定鼠标进入事件
handleMouseEnter(index) {
this.setState({
index: index,
})
}
convertButton(value: number, index: number, array: number[]) {
let className: string = value ? "adButtonSelected" : "adButton";
return <div key={index} className={className} onMouseEnter={() => { this.handleMouseEnter(index) }}></div>
}
render() {
let ads = this.state.ads;
let index = this.state.index;
let length = ads.length;
let styles = new Array(length);
styles.fill(0); //将数组元素全部填充为0
styles[index] = 1; //选中下标的内容对应的数组元素值为1
let buttons = styles.map(this.convertButton);
let url = ads.length ? ads[index].url : "";
let imageUrl = ads.length ? ads[index].imageUrl : "";
return <div style={{ position: 'relative', width: '18.75rem', height: '6.25rem' }}>
<div><a href={url} target="_blank"><img src={imageUrl} style={{ width: '18.75rem', height: '6.25rem' }} /></a></div>
<div className="adButtons" style={{ position: 'absolute', left: '50%', marginLeft: '-8rem', bottom: '0.25rem' }}>{buttons}</div>
</div>;
}
}
/**
* 论坛统计组件
**/
export class MainPageCountComponent extends React.Component<{ data }, {}> {
render() {
const data = this.props.data;
return <div className="mainPageCount">
<div className="mainPageTitle1">
<div className="mainPageTitleRow">
<i className="fa fa-volume-up"></i>
<div className="mainPageTitleText">论坛统计</div>
</div>
</div>
<div className="mainPageCountContent">
<div className="mainPageCountRow">
<div className="mainPageCountTitle">今日帖数</div>
<div className="mainPageCountTitle">{data.todayCount || 0}</div>
</div>
<div className="mainPageCountRow">
<div className="mainPageCountTitle">今日主题数</div>
<div className="mainPageCountTitle">{data.todayTopicCount || 0}</div>
</div>
<div className="mainPageCountRow">
<div className="mainPageCountTitle">论坛总主题数</div>
<div className="mainPageCountTitle">{data.topicCount || 0}</div>
</div>
<div className="mainPageCountRow">
<div className="mainPageCountTitle">论坛总回复数</div>
<div className="mainPageCountTitle">{data.postCount || 0}</div>
</div>
<div className="mainPageCountRow">
<div className="mainPageCountTitle">在线用户数</div>
<div className="mainPageCountTitle">{data.onlineUserCount || 0}</div>
</div>
<div className="mainPageCountRow">
<div className="mainPageCountTitle">总用户数</div>
<div className="mainPageCountTitle">{data.userCount || 0}</div>
</div>
<div className="mainPageCountRow">
<div className="mainPageCountTitle">欢迎新用户</div>
<div className="mainPageCountTitle"><Link to={`/user/name/${encodeURIComponent(data.lastUserName)}`}>{data.lastUserName}</Link></div>
</div>
</div>
</div>
}
}
/**
* 推荐版面组件
*/
export class RecommendedBoardComponent extends React.Component<{}, {}>{
render() {
return <div></div>
}
}
/**
*首页统计类
*包括今日帖数,总主题数,总回复数,总用户数,最新用户
*/
export class MainPageCountProps {
//属性
todayCount: number;
todayTopicCount:number;
topicCount: number;
postCount: number;
onlineUserCount: number;
userCount: number;
lastUserName: string;
//构造方法
constructor(todayCount,todayTopicCount, topicCount, postCount, onlineUserCount, userCount, lastUserName) {
this.todayCount = todayCount;
this.todayTopicCount = todayTopicCount;
this.topicCount = topicCount;
this.postCount = postCount;
this.onlineUserCount = onlineUserCount;
this.userCount = userCount;
this.lastUserName = lastUserName;
}
}
/**
* 小程序二维码
*/
export class QRCode extends React.Component<{}, {}>{
render() {
return <div
style={{
display: "flex",
flexDirection: "column",
marginTop: "2rem",
}}
>
<div className="mainPageTitle2">
<div className="mainPageTitleRow">
<i className="fa fa-volume-up"></i>
<div className="mainPageTitleText">CC98小程序</div>
</div>
</div>
<div style={{ marginTop: "1rem" }} >
<img style={{ width: "100%" }} src="/static/images/QRCode.png"></img>
</div>
</div>
}
}
/**
* 主页
*/
export class MainPage extends React.Component<{}, { data }> {
constructor(props) { //为组件定义构造方法,其中设置 this.state = 初始状态
super(props); //super 表示调用基类(Component系统类型)构造方法
let data = {
academics: [],
announcement: "",
emotion: [],
fleaMarket: [],
fullTimeJob: [],
hotTopic: [],
lastUserName: "",
partTimeJob: [],
postCount: 0,
recommendationFunction: [],
recommendationReading: [],
schoolEvent: [],
schoolNews: [],
study: [],
todayCount: 0,
topicCount: 0,
userCount: 0
};
this.state = {
data: data
};
}
async getData() {
let data = Utility.getLocalStorage("mainPageData");
if (!data) {
const response = await Utility.cc98Fetch('/config/index');
data = await response.json();
let hotTopicData = data.hotTopic;
//若获取到的首页数据中的十大数据为空,则不缓存首页数据,这样用户立即刷新页面就可以获取最新的十大数据
//当然,该次获取的十大数据为空,这则由十大组件处理(显示之前缓存的十大数据)
//若获取了正常的首页数据(十大不为空),则缓存60s,这样可以避免用户短时间内频繁访问首页产生大量请求
if (hotTopicData && hotTopicData.length) {
Utility.setLocalStorage("mainPageData", data, 60);
Utility.setLocalStorage("mainPageHotTopic", data);
}
return data;
} else {
return data
}
}
async componentDidMount() {
const x = await this.getData();
this.setState({
data: x,
});
}
render() {
let data = this.state.data;
let study: MainPageTopicMoreProps[] = new Array({ name: "学习", url: "/board/68" }, { name: "外语", url: "/board/304" }, { name: "考研", url: "/board/263" }, { name: "出国", url: "/board/102" });
let emotion: MainPageTopicMoreProps[] = new Array({ name: "缘分", url: "/board/152" }, { name: "小屋", url: "/board/114" }, { name: "感性", url: "/board/81" });
let fleaMarket: MainPageTopicMoreProps[] = new Array({ name: "数码", url: "/board/562" }, { name: "生活", url: "/board/80" }, { name: "服饰", url: "/board/563" });
let fullTimeJob: MainPageTopicMoreProps[] = new Array({ name: "更多", url: "/board/235" });
let partTimeJob: MainPageTopicMoreProps[] = new Array({ name: "更多", url: "/board/459" });
let count: MainPageCountProps = new MainPageCountProps(data.todayCount,data.todayTopicCount, data.topicCount, data.postCount, data.onlineUserCount, data.userCount, data.lastUserName);
return <div className="mainPage">
<DocumentTitle title={`CC98论坛`} />
<div className="leftPart">
<AnnouncementComponent data={data.announcement} />
<RecommendedReadingComponent data={data.recommendationReading} />
<div className="row" style={{ justifyContent: "space-between" }}>
<HotTopicComponent data={data.hotTopic} />
<MainPageTopicComponent data={data.schoolEvent} name="校园活动" fetchUrl="/topic/school-event" style="blue" mores={[]} />
</div>
<div className="row" style={{ justifyContent: "space-between" }}>
<MainPageTopicComponent data={data.academics} name="学术信息" fetchUrl="/topic/academics" style="black" mores={[]} />
<MainPageTopicComponent data={data.study} name="学习园地" fetchUrl="/topic/study" style="black" mores={study} />
</div>
<div className="row" style={{ justifyContent: "space-between" }}>
<MainPageTopicComponent data={data.emotion} name="感性·情感" fetchUrl="/topic/emotion" style="blue" mores={emotion} />
<MainPageTopicComponent data={data.fleaMarket} name="跳蚤市场" fetchUrl="/topic/flea-market" style="blue" mores={fleaMarket} />
</div>
<div className="row" style={{ justifyContent: "space-between" }}>
<MainPageTopicComponent data={data.fullTimeJob} name="求职广场" fetchUrl="/topic/full-time-job" style="black" mores={fullTimeJob} />
<MainPageTopicComponent data={data.partTimeJob} name="实习兼职" fetchUrl="/topic/part-time-job" style="black" mores={partTimeJob} />
</div>
</div>
<div className="rightPart">
<RecommendedFunctionComponent data={data.recommendationFunction} />
<SchoolNewsComponent data={data.schoolNews} />
<AdsComponent />
<MainPageCountComponent data={count} />
<QRCode />
</div>
</div>;
}
} | the_stack |
import browser from "../../../common/polyfill";
import { getUserTheme, UserTheme } from "../../../common/storage";
import { createStylesheetLink } from "../../../common/stylesheets";
import {
activeColorThemeVariable,
applySaveThemeOverride,
autoBackgroundThemeVariable,
backgroundColorThemeVariable,
colorThemeToBackgroundColor,
darkThemeTextColor,
fontSizeThemeVariable,
pageWidthThemeVariable,
setCssThemeVariable,
themeName,
} from "../../../common/theme";
import {
getBrightness,
HSLA,
hslToString,
parse,
rgbToHSL,
} from "../../../common/util/color";
import { getOutlineIframe } from "../../../overlay/outline/common";
import AnnotationsModifier from "../annotations/annotationsModifier";
import BodyStyleModifier from "../bodyStyle";
import TextContainerModifier from "../DOM/textContainer";
import { PageModifier, trackModifierExecution } from "../_interface";
import CSSOMProvider, { isMediaRule, isStyleRule } from "./_provider";
@trackModifierExecution
export default class ThemeModifier implements PageModifier {
private domain: string;
private cssomProvider: CSSOMProvider;
private annotationsModifer: AnnotationsModifier;
private textContainerModifier: TextContainerModifier;
private bodyStyleModifier: BodyStyleModifier;
public theme: UserTheme;
private darkModeActive = false; // seperate from theme -- auto theme enables and disable dark mode
public activeColorTheme: themeName;
public activeColorThemeListeners: ((newTheme: themeName) => void)[] = [];
constructor(
cssomProvider: CSSOMProvider,
annotationsModifer: AnnotationsModifier,
textContainerModifier: TextContainerModifier,
bodyStyleModifier: BodyStyleModifier
) {
this.cssomProvider = cssomProvider;
this.annotationsModifer = annotationsModifer;
this.textContainerModifier = textContainerModifier;
this.bodyStyleModifier = bodyStyleModifier;
}
private systemDarkModeQuery: MediaQueryList;
async prepare(domain: string) {
this.domain = domain;
// Get saved user theme
this.theme = await getUserTheme();
this.activeColorTheme = this.theme.colorTheme;
setCssThemeVariable(pageWidthThemeVariable, this.theme.pageWidth);
// Listen to system dark mode preference
this.systemDarkModeQuery = window.matchMedia(
"(prefers-color-scheme: dark)"
);
this.systemDarkModeQuery.addEventListener(
"change",
this.onSystemDarkThemeChange.bind(this)
);
}
setThemeVariables() {
// basic heuristic whether to enable dark mode, to show it earlier
// const darkModeActive =
// this.darkModeActive ||
// this.activeColorTheme === "dark" ||
// (this.activeColorTheme === "auto" &&
// this.systemDarkModeQuery.matches);
// if (darkModeActive) {
// document.documentElement.style.setProperty(
// "background",
// "#131516",
// "important"
// );
// document.body.style.setProperty(
// "background",
// colorThemeToBackgroundColor("dark"),
// "important"
// );
// }
// look at background color and modify if necessary
// do now to avoid visible changes later
this.processBackgroundColor();
setCssThemeVariable(backgroundColorThemeVariable, this.backgroundColor);
if (this.theme.fontSize) {
setCssThemeVariable(fontSizeThemeVariable, this.theme.fontSize);
}
}
public backgroundColor: string;
private siteUsesDefaultDarkMode: boolean = false;
private processBackgroundColor() {
// use detected site color to keep personality
this.backgroundColor =
this.textContainerModifier.originalBackgroundColor ||
this.bodyStyleModifier.originalBackgroundColor ||
"white";
// TODO test color distance to background color (brightness alone doesn't look nice)
// but only known case is https://arstechnica.com/science/2022/05/rocket-report-starliner-soars-into-orbit-about-those-raptor-ruds-in-texas/
if (this.backgroundColor === "rgb(240, 241, 242)") {
this.backgroundColor = "white";
}
// test if dark mode enabled
const backgroundBrightness = getBrightness(this.backgroundColor);
const textBrightness = this.textContainerModifier.mainTextColor
? getBrightness(this.textContainerModifier.mainTextColor)
: null;
if (backgroundBrightness < 0.6 && !this.darkModeActive) {
if (!textBrightness || textBrightness > 0.5) {
// Site uses dark mode by default
this.siteUsesDefaultDarkMode = true;
if (backgroundBrightness < 0.1) {
// so dark that it conflicts with the html background, e.g. https://wale.id.au/posts/iviewed-your-api-keys/
this.backgroundColor = colorThemeToBackgroundColor("dark");
}
} else {
// we likely picked the wrong background color
this.backgroundColor = "white";
}
}
// this.siteUsesDefaultDarkMode read in applyActiveColorTheme() below
}
transitionOut() {
if (this.darkModeActive) {
this.disableDarkMode();
}
this.systemDarkModeQuery.removeEventListener(
"change",
this.onSystemDarkThemeChange.bind(this)
);
}
private onSystemDarkThemeChange({ matches: isDarkMode }: MediaQueryList) {
this.applyActiveColorTheme();
}
async changeColorTheme(newColorThemeName: themeName) {
// apply theme change
this.activeColorTheme = newColorThemeName;
this.applyActiveColorTheme();
// save in storage
applySaveThemeOverride(
this.domain,
activeColorThemeVariable,
newColorThemeName
);
}
applyActiveColorTheme(): boolean {
// State for UI switch
setCssThemeVariable(activeColorThemeVariable, this.activeColorTheme);
this.activeColorThemeListeners.map((listener) =>
listener(this.activeColorTheme)
);
// Determine if should use dark mode
const prevDarkModeState = this.darkModeActive;
this.darkModeActive = this.activeColorTheme === "dark";
if (this.activeColorTheme === "auto") {
this.darkModeActive = this.systemDarkModeQuery.matches;
}
if (this.siteUsesDefaultDarkMode) {
// turn ui dark
this.darkModeActive = true;
}
// enable or disable dark mode if there's been a change
if (this.darkModeActive && !prevDarkModeState) {
this.enableDarkMode();
} else if (!this.darkModeActive && prevDarkModeState) {
this.disableDarkMode();
}
// apply other background colors
if (!this.darkModeActive) {
let concreteColor: string;
if (this.activeColorTheme === "auto") {
concreteColor = this.backgroundColor;
} else {
concreteColor = colorThemeToBackgroundColor(
this.activeColorTheme
);
}
setCssThemeVariable(backgroundColorThemeVariable, concreteColor);
this.annotationsModifer.setSidebarCssVariable(
backgroundColorThemeVariable,
concreteColor
);
}
this.updateAutoModeColor();
// return if enabled dark mode
return this.darkModeActive;
}
// Update auto state (shown in theme switcher)
private updateAutoModeColor() {
if (this.systemDarkModeQuery.matches) {
const darkColor = colorThemeToBackgroundColor("dark");
setCssThemeVariable(autoBackgroundThemeVariable, darkColor);
} else {
setCssThemeVariable(
autoBackgroundThemeVariable,
this.backgroundColor
);
}
}
private enableDarkMode() {
// trigger html background change immediately (loading css takes time)
document.documentElement.style.setProperty(
"background",
"#131516",
"important"
);
createStylesheetLink(
browser.runtime.getURL("overlay/indexDark.css"),
"dark-mode-ui-style"
);
createStylesheetLink(
browser.runtime.getURL("overlay/outline/outlineDark.css"),
"dark-mode-ui-style",
getOutlineIframe()?.head.lastChild as HTMLElement
);
// global tweaks (not used right now)
// createStylesheetLink(
// browser.runtime.getURL("content-script/pageview/contentDark.css"),
// "dark-mode-ui-style",
// // insert at beginning of header to not override site dark styles
// document.head.firstChild as HTMLElement
// );
this.annotationsModifer.setSidebarDarkMode(true);
// enable site dark mode styles if present, but always run our css tweaks too
this.detectSiteDarkMode(true);
const siteSupportsDarkMode = false;
// set our text color even if using site style (need for headings)
// (setting the variable always would override other text container styles)
this.textContainerModifier.setTextDarkModeVariable(true);
if (this.siteUsesDefaultDarkMode) {
// use default background elsewhere
setCssThemeVariable(
backgroundColorThemeVariable,
this.backgroundColor
);
this.annotationsModifer.setSidebarCssVariable(
backgroundColorThemeVariable,
this.backgroundColor
);
} else if (siteSupportsDarkMode) {
// parse background color from site dark mode styles
let backgroundColor: string;
this.enabledSiteDarkModeRules.map((mediaRule) => {
for (const styleRule of mediaRule.cssRules) {
if (!isStyleRule(styleRule)) {
return;
}
if (styleRule.style.background) {
backgroundColor = styleRule.style.background;
}
}
});
// TODO handle opacity
if (!backgroundColor) {
// this may not always work (e.g. if css variables are used), so use default fallback
backgroundColor = colorThemeToBackgroundColor("dark");
}
setCssThemeVariable(backgroundColorThemeVariable, backgroundColor);
this.annotationsModifer.setSidebarCssVariable(
backgroundColorThemeVariable,
backgroundColor
);
if (this.activeColorTheme === "auto") {
setCssThemeVariable(
autoBackgroundThemeVariable,
backgroundColor
);
}
} else {
// Background color
const concreteColor = colorThemeToBackgroundColor("dark");
setCssThemeVariable(backgroundColorThemeVariable, concreteColor);
this.annotationsModifer.setSidebarCssVariable(
backgroundColorThemeVariable,
concreteColor
);
this.enableDarkModeStyleTweaks();
}
// always dark text color for ui elements
const darkTextColor = "rgb(232, 230, 227)";
setCssThemeVariable(darkThemeTextColor, darkTextColor);
this.annotationsModifer.setSidebarCssVariable(
darkThemeTextColor,
darkTextColor
);
}
private disableDarkMode() {
document.documentElement.style.removeProperty("color");
document.documentElement.style.removeProperty("background");
document.documentElement.style.removeProperty(darkThemeTextColor);
this.textContainerModifier.setTextDarkModeVariable(false);
// undo dark mode style tweaks
this.disableDarkModeStyleTweaks();
document
.querySelectorAll(".dark-mode-ui-style")
.forEach((e) => e.remove());
getOutlineIframe()
?.querySelectorAll(".dark-mode-ui-style")
.forEach((e) => e.remove());
this.annotationsModifer.setSidebarDarkMode(false);
}
private enabledSiteDarkModeRules: CSSMediaRule[] = [];
private detectSiteDarkMode(enableIfFound = false): boolean {
let siteSupportsDarkMode = false;
if (this.domain === "theatlantic.com") {
// their dark styles do not work for some reason
return false;
}
// iterate only top level for performance
// also don't iterate the rules we added
this.cssomProvider.stylesheets.map((sheet) => {
for (const rule of sheet.cssRules) {
if (!isMediaRule(rule)) {
continue;
}
if (
!rule.media.mediaText.includes(
"prefers-color-scheme: dark"
) ||
rule.media.mediaText.includes("prefers-color-scheme: light")
) {
continue;
}
siteSupportsDarkMode = true;
if (enableIfFound) {
// insert rule copy that's always active
const newCssText = `@media screen ${rule.cssText.replace(
/@media[^{]*/,
""
)}`;
const newIndex = rule.parentStyleSheet.insertRule(
newCssText,
rule.parentStyleSheet.cssRules.length
);
const newRule = rule.parentStyleSheet.cssRules[newIndex];
this.enabledSiteDarkModeRules.push(newRule as CSSMediaRule);
}
}
});
return siteSupportsDarkMode;
}
private activeDarkModeStyleTweaks: [CSSStyleRule, object][] = [];
private enableDarkModeStyleTweaks() {
// patch site stylesheet colors
this.cssomProvider.iterateRules((rule) => {
if (!isStyleRule(rule)) {
return;
}
const modifications = darkModeStyleRuleMap(rule);
if (modifications) {
// save properties for restoration later
const obj = {};
for (const key of rule.style) {
obj[key] = rule.style.getPropertyValue(key);
}
this.activeDarkModeStyleTweaks.push([rule, obj]);
// apply modifications
for (const [key, val] of Object.entries(modifications)) {
rule.style.setProperty(
key,
val,
rule.style.getPropertyPriority(key)
);
}
}
});
}
private disableDarkModeStyleTweaks() {
this.activeDarkModeStyleTweaks.map(([rule, originalStyle]) => {
for (const [key, value] of Object.entries(originalStyle)) {
rule.style.setProperty(key, value);
}
});
this.activeDarkModeStyleTweaks = [];
this.enabledSiteDarkModeRules.map((mediaRule) => {
for (const styleRule of mediaRule.cssRules) {
styleRule.style = {};
}
});
this.enabledSiteDarkModeRules = [];
}
}
function darkModeStyleRuleMap(rule: CSSStyleRule): object {
const modifications = {};
if (rule.style.color) {
modifications["color"] = changeTextColor(
rule.style.color,
rule.selectorText
);
}
if (rule.style.backgroundColor) {
modifications["background-color"] = changeBackgroundColor(
rule.style.backgroundColor,
rule.selectorText
);
}
if (rule.style.boxShadow) {
modifications["box-shadow"] = "none";
}
// TODO parse CSS variables better, e.g. ones set via JS or inline styles
if (
rule.selectorText === ":root" ||
rule.selectorText === "*, :after, :before" // tailwind
) {
for (const key of rule.style) {
if (key.startsWith("--")) {
const value = rule.style.getPropertyValue(key);
// ideally transform the variables where used
if (key.includes("background")) {
modifications[key] = changeBackgroundColor(
value,
rule.selectorText
);
} else {
modifications[key] = changeTextColor(
value,
rule.selectorText
);
}
}
}
}
return modifications;
}
// TODO cache
function changeTextColor(colorString: string, selectorText): string {
if (colorString === "initial") {
return `var(${darkThemeTextColor})`;
}
const hslColor = parseHslColor(colorString);
if (!hslColor) {
return colorString;
}
let newColor = colorString;
if (hslColor.l < 0.4) {
// main text
// standardize most text around this
// l e.g. 0.35 at https://fly.io/blog/a-foolish-consistency/
newColor = `var(${darkThemeTextColor})`;
} else {
// make other colors more visible
if (hslColor.s > 0.9) {
hslColor.s = 0.9;
}
if (hslColor.l < 0.6) {
hslColor.l = 0.6;
}
newColor = hslToString(hslColor);
}
// console.log(
// `%c %c -> %c %c\t${colorString}\t -> ${newColor} \t${selectorText}`,
// `background: ${colorString}`,
// `background: inherit`,
// `background: ${newColor}`,
// `background: inherit`
// );
return newColor;
}
function changeBackgroundColor(colorString: string, selectorText) {
const hslColor = parseHslColor(colorString);
if (!hslColor) {
return colorString;
}
let newColor = colorString;
if (hslColor.l > 0.8) {
// main background
// show through background element
newColor = "transparent";
} else {
// darken other colors
if (hslColor.s > 0.7) {
hslColor.s = 0.7;
}
if (hslColor.l > 0.2) {
hslColor.l = 0.2;
}
newColor = hslToString(hslColor);
}
// console.log(
// `%c %c -> %c %c\t${hslToString(
// parseHslColor(colorString)
// )}\t -> ${newColor} \t${selectorText}`,
// `background: ${colorString}`,
// `background: inherit`,
// `background: ${newColor}`,
// `background: inherit`
// );
return newColor;
}
const unparsableColors = new Set([
"inherit",
"transparent",
"initial",
"currentcolor",
"none",
"unset",
]);
function parseHslColor(colorString: string): HSLA | null {
if (unparsableColors.has(colorString.toLowerCase())) {
return null;
}
if (colorString.includes("var(")) {
// remove for now
// could still be a valid color string, e.g. rgb(59 130 246/var(--x)) at https://fly.io/blog/a-foolish-consistency/
colorString = colorString.replace(/var\(--.*?\)/, "");
}
try {
const rgbColor = parse(colorString);
return rgbToHSL(rgbColor);
} catch (err) {
// console.error(colorString, err);
return null;
}
} | the_stack |
import enhancedResolve from 'enhanced-resolve';
import _ from 'lodash';
import MemoryFS from 'memory-fs';
import path from 'path';
import validate from 'validate-npm-package-name';
import webpack from 'webpack';
import { isExternal } from '../bundler/externals';
import getResolverConfig from '../bundler/getResolverConfig';
import makeConfig from '../bundler/makeConfig';
import logger from '../logger';
import { Package } from '../types';
import installDependencies from './installDependencies';
// TODO: find the typescript definitions for this package, `@types/sander` doesn't exists
const { stat, readFile } = require('sander');
type UnsafeOptions = {
pkg: Package;
cwd: string;
deep?: string | null;
base: string;
externals: string[]; // array of peerDependencies. e.g. `["graphql"]`
platforms: string[];
};
type Options = {
pkg: Package;
cwd: string;
deep?: string | null;
base: string;
externalDependencies: { [key: string]: string | null };
platforms: string[];
};
type ResolvedEntry = {
platform: string;
entry: string;
error?: Error | null;
};
async function packageBundleUnsafe({
pkg,
cwd,
deep,
externals,
platforms,
base,
}: UnsafeOptions): Promise<{ [key: string]: { [key: string]: Buffer } }> {
const content = await readFile(path.join(cwd, 'package.json'));
const packageJson = JSON.parse(content);
const entries = await Promise.all(
platforms.map(
(platform) =>
new Promise<ResolvedEntry>((resolve) => {
// TODO: check why the types doesn't match here
const resolveEntry = enhancedResolve.create(getResolverConfig(platform) as any);
resolveEntry(path.join(cwd, deep ?? ''), '', (err, res) =>
resolve({
platform,
entry: err ? '' : res,
error: err,
})
);
})
)
);
const validEntries = entries.filter(({ error }) => !error);
const invalidEntries = entries.filter(({ error }) => error);
// If we couldn't resolve any entry file, check if it's a TypeScript definition package
if (invalidEntries.length === entries.length) {
try {
const file = path.join(cwd, packageJson.types || packageJson.typings || 'index');
await stat(file.endsWith('.d.ts') ? file : `${file}.d.ts`);
logger.warn(
{ pkg, platforms },
`no valid entry found, assuming this is a TypeScript definition package`
);
return platforms.reduce(
(acc, platform) => ({
...acc,
[platform]: '',
}),
{}
);
} catch (err) {
throw entries.length ? entries[0].error : err;
}
}
// Warn about entries that could not be resolved
if (invalidEntries.length) {
logger.warn(
{ pkg, platforms },
`entry for platforms "${invalidEntries
.map(({ platform }) => platform)
.join(', ')}" could not be found. Proceeding with platforms "${validEntries
.map(({ platform }) => platform)
.join(', ')}".`
);
}
const configs = validEntries.map(({ entry, platform }) =>
makeConfig({
root: cwd,
entry,
output: {
path: `/${platform}`,
filename: 'bundle.js',
library: `${pkg.name}${deep ? `/${deep}` : ''}`,
publicPath: `${base}-${platform}`,
},
externals,
platform,
// The reanimated2 plugin scans the package for worklets and converts
// them so they can be executed directly on the UI thread.
// This is currently only done for the reanimated package itsself, but
// in the future third-party packages may also contain worklets that would
// need to be converted.
reanimatedPlugin:
(pkg.name === 'react-native-reanimated' && pkg.version >= '2') ||
pkg.name === 'moti' ||
pkg.name.startsWith('@motify/') ||
externals.includes('react-native-reanimated'),
})
);
logger.info(
{
pkg,
packageJson: {
...packageJson,
keywords: undefined,
scripts: undefined,
},
platforms,
},
`creating bundle with webpack`
);
const compiler = webpack(configs);
const memoryFs = new MemoryFS();
compiler.outputFileSystem = memoryFs;
let status: webpack.MultiStats;
try {
status = await new Promise((resolve, reject) =>
compiler.run((err, stats) => {
if (err) {
reject(err);
} else {
resolve(stats!);
}
})
);
} catch (error) {
logger.error({ error }, 'error running compiler');
throw error;
}
const result = status.toJson();
if (result.errors?.length) {
throw new Error(result.errors.map((error) => error.message).join('\n'));
}
logger.info({ pkg }, `bundle generated`);
const list = (
root: string,
items: { [key: string]: Buffer },
replace: RegExp | string
): { [key: string]: Buffer } => {
memoryFs.readdirSync(root).forEach((name) => {
const stat = memoryFs.statSync(path.join(root, name));
if (stat.isDirectory()) {
list(path.join(root, name), items, replace);
} else {
const key = `${root}/${name}`.replace(replace, '');
items[key] = memoryFs.readFileSync(path.join(root, name));
// Remove internal directory paths encoded by certain plugins like reanimated2
if (name.endsWith('.js')) {
const code = items[key].toString('utf8');
items[key] = Buffer.from(code.split(cwd).join(''), 'utf8');
}
}
});
return items;
};
const files = validEntries.reduce(
(acc, { platform }) => ({
...acc,
[platform]: list(path.join('/', platform), {}, new RegExp(`^/${platform}/`)),
}),
{}
);
return files;
}
export default (async function packageBundle({
pkg,
cwd,
deep,
externalDependencies,
platforms,
base,
}: Options): Promise<{ [key: string]: { [key: string]: Buffer } }> {
let externals = Object.keys(externalDependencies);
const logMetadata = { pkg };
const initialPlatforms = platforms;
let installedDependencies: string[] = [];
for (let i = 0; i < 10; i++) {
try {
const files = await packageBundleUnsafe({
pkg,
cwd,
deep,
externals,
platforms,
base,
});
initialPlatforms.forEach((platform) => {
if (!files[platform]) {
files[platform] = { 'bundle.js': Buffer.alloc(0) };
}
});
return files;
} catch (e) {
try {
// A lot of packages have a missing peerDep.
// For example 'react-native-responsive-grid@0.32.4' has a dependency
// on prop-types but no peerDep listed in package.json. We try to catch
// these errors and then list those dependencies as a Webpack external
// (https://webpack.js.org/configuration/externals/). This means that it
// waits until runtime to resolve the invalid import, which should
// be closer to matching the behavior in a standard RN project.
const errorMessage = e.message;
if (errorMessage) {
const regex = /Module not found: Error: Can't resolve '(\S+)'/g;
let match: RegExpExecArray | null = null;
const matches: string[] = [];
while ((match = regex.exec(e.message)) != null) {
if (match && match.length > 1) {
matches.push(match[1]);
}
}
const packageUsesSources: { [key: string]: boolean } = {};
const missingPackages = _.uniq(
_.uniq(matches).map((module) => {
// Parse the package-name from the import (e.g. "react-native-web/src/modules" => "react-native-web")
const comps = module.split('/');
const packageName =
module.startsWith('@') && comps.length >= 2 ? `${comps[0]}/${comps[1]}` : comps[0];
const result = validate(packageName);
if (!result.validForNewPackages && !result.validForOldPackages) {
throw new Error(`Invalid module ${module} - ${e.message.split('\n')[0]}`);
}
if (installedDependencies.includes(packageName)) {
throw new Error(
`Cannot resolve module ${module} after installing it as a dependency`
);
}
// When the import contains more than just the package-name (e.g. "react-native-web/src/modules/normalizeColor"),
// then we need to install the package as a dependency so the import can be resolved using the source-code of the package.
if (comps.length > (module.startsWith('@') ? 2 : 1)) {
packageUsesSources[packageName] = true;
}
return packageName;
})
);
if (missingPackages.length) {
const missingDependencies: { [key: string]: string } = {};
externals = [...externals];
missingPackages.forEach((packageName) => {
// Install all missing packages that either require the source-code
// to be present, or which are not marked as external
if (
packageUsesSources[packageName] ||
(!externals.includes(packageName) && !isExternal(packageName))
) {
let version = '*';
if (pkg.dependencies?.[packageName]) {
version = pkg.dependencies[packageName];
} else if (externalDependencies[packageName]) {
version = externalDependencies[packageName]!;
} else if (pkg.devDependencies?.[packageName]) {
version = pkg.devDependencies[packageName];
} else {
logger.warn(
logMetadata,
`Dependency found on "${packageName}" that is required for bundling, but its version is not defined in package.json. Using "*" instead.`
);
}
missingDependencies[packageName] = version;
}
// Update the externals for the webpack bundler
if (!externals.includes(packageName) && isExternal(packageName)) {
externals.push(packageName);
}
});
// Install dependencies and re-try bundling
if (Object.keys(missingDependencies).length) {
await installDependencies(pkg, cwd, missingDependencies);
installedDependencies = [
...installedDependencies,
...Object.keys(missingDependencies),
];
}
} else {
// Bundling failed and no "Missing modules" were found
throw e;
}
} else {
// No error.message
throw e;
}
} catch (err) {
// Not all packages bundle correctly on the web platform.
// An example is "react-native-screens/native-stack" which imports
// "react-native/Libraries/ReactNative/AppContainer". This import depends on
// "../../Utilities/Platform.ios.js" or "../../Utilities/Platform.android.js",
// but fails to resolve on web. When bundling for web fails, continue with
// the other platforms.
if (e.message.includes('.web.') && platforms.includes('web') && platforms.length > 1) {
platforms = platforms.filter((platform) => platform !== 'web');
logger.warn(
logMetadata,
`An error occured "${
err.message.split('\n')[0]
}" when bundling the "web" platform. Proceeding with platforms "${platforms.join(
', '
)}".`
);
} else {
throw err;
}
}
}
}
// Abort when the bundler takes many cycles to complete.
// This is a fail-safe situation in case the installation of dependencies
// does not resolve the "Missing modules" reported by the bundler.
throw new Error('Bundling failed, too many cycles');
}); | the_stack |
import {
arrayForEach
} from '@tko/utils'
import {
observable, isSubscribable, isObservable,
isWriteableObservable, isWritableObservable, subscribable,
unwrap
} from '../dist'
describe('Observable', function () {
it('Should be subscribable', function () {
var instance = observable()
expect(isSubscribable(instance)).toEqual(true)
})
it('should have an `undefined` length', function () {
expect(observable().length).toEqual(undefined)
})
it('Should advertise that instances are observable', function () {
var instance = observable()
expect(isObservable(instance)).toEqual(true)
})
it('Should not advertise that ko.observable is observable', function () {
expect(isObservable(observable)).toEqual(false)
})
it('ko.isObservable should return false for non-observable values', function () {
arrayForEach([
undefined,
null,
'x',
{},
function () {},
new subscribable()
], function (value) {
expect(isObservable(value)).toEqual(false)
})
})
it('ko.isObservable should throw exception for value that has fake observable pointer', function () {
var x = observable()
x.__ko_proto__ = {}
expect(() => isObservable(x)).toThrow()
})
it('Should be able to write values to it', function () {
var instance = observable()
instance(123)
})
it('Should be able to write to multiple observable properties on a model object using chaining syntax', function () {
var model = {
prop1: observable(),
prop2: observable()
}
model.prop1('A').prop2('B')
expect(model.prop1()).toEqual('A')
expect(model.prop2()).toEqual('B')
})
it('Should be able to use Function.prototype methods to access/update', function () {
var instance = observable('A')
var obj = {}
expect(instance.call(null)).toEqual('A')
expect(instance.call(obj, 'B')).toBe(obj)
expect(instance.apply(null, [])).toBe('B')
})
it('Should advertise that instances can have values written to them', function () {
var instance = observable(function () { })
expect(isWriteableObservable(instance)).toEqual(true)
expect(isWritableObservable(instance)).toEqual(true)
})
it('Should be able to read back most recent value', function () {
var instance = observable()
instance(123)
instance(234)
expect(instance()).toEqual(234)
})
it('Should initially have undefined value', function () {
var instance = observable()
expect(instance()).toEqual(undefined)
})
it('Should be able to set initial value as constructor param', function () {
var instance = observable('Hi!')
expect(instance()).toEqual('Hi!')
})
it('Should notify subscribers about each new value', function () {
var instance = observable()
var notifiedValues = []
instance.subscribe(function (value) {
notifiedValues.push(value)
})
instance('A')
instance('B')
expect(notifiedValues).toEqual([ 'A', 'B' ])
})
it('Should notify "spectator" subscribers about each new value', function () {
var instance = observable()
var notifiedValues = []
instance.subscribe(function (value) {
notifiedValues.push(value)
}, null, 'spectate')
instance('A')
instance('B')
expect(notifiedValues).toEqual([ 'A', 'B' ])
})
it('Should be able to tell it that its value has mutated, at which point it notifies subscribers', function () {
var instance = observable()
var notifiedValues = []
instance.subscribe(function (value) {
notifiedValues.push(value.childProperty)
})
var someUnderlyingObject = { childProperty: 'A' }
instance(someUnderlyingObject)
expect(notifiedValues.length).toEqual(1)
expect(notifiedValues[0]).toEqual('A')
someUnderlyingObject.childProperty = 'B'
instance.valueHasMutated()
expect(notifiedValues.length).toEqual(2)
expect(notifiedValues[1]).toEqual('B')
})
it('Should notify "beforeChange" subscribers before each new value', function () {
var instance = observable()
var notifiedValues = []
instance.subscribe(function (value) {
notifiedValues.push(value)
}, null, 'beforeChange')
instance('A')
instance('B')
expect(notifiedValues.length).toEqual(2)
expect(notifiedValues[0]).toEqual(undefined)
expect(notifiedValues[1]).toEqual('A')
})
it('Should be able to tell it that its value will mutate, at which point it notifies "beforeChange" subscribers', function () {
var instance = observable()
var notifiedValues = []
instance.subscribe(function (value) {
notifiedValues.push(value ? value.childProperty : value)
}, null, 'beforeChange')
var someUnderlyingObject = { childProperty: 'A' }
instance(someUnderlyingObject)
expect(notifiedValues.length).toEqual(1)
expect(notifiedValues[0]).toEqual(undefined)
instance.valueWillMutate()
expect(notifiedValues.length).toEqual(2)
expect(notifiedValues[1]).toEqual('A')
someUnderlyingObject.childProperty = 'B'
instance.valueHasMutated()
expect(notifiedValues.length).toEqual(2)
expect(notifiedValues[1]).toEqual('A')
})
it('Should ignore writes when the new value is primitive and strictly equals the old value', function () {
var instance = observable()
var notifiedValues = []
instance.subscribe(notifiedValues.push, notifiedValues)
for (var i = 0; i < 3; i++) {
instance('A')
expect(instance()).toEqual('A')
expect(notifiedValues).toEqual(['A'])
}
instance('B')
expect(instance()).toEqual('B')
expect(notifiedValues).toEqual(['A', 'B'])
})
it('Should ignore writes when both the old and new values are strictly null', function () {
var instance = observable(null)
var notifiedValues = []
instance.subscribe(notifiedValues.push, notifiedValues)
instance(null)
expect(notifiedValues).toEqual([])
})
it('Should ignore writes when both the old and new values are strictly undefined', function () {
var instance = observable(undefined)
var notifiedValues = []
instance.subscribe(notifiedValues.push, notifiedValues)
instance(undefined)
expect(notifiedValues).toEqual([])
})
it('Should notify subscribers of a change when an object value is written, even if it is identical to the old value', function () {
// Because we can't tell whether something further down the object graph has changed, we regard
// all objects as new values. To override this, set an "equalityComparer" callback
var constantObject = {}
var instance = observable(constantObject)
var notifiedValues = []
instance.subscribe(notifiedValues.push, notifiedValues)
instance(constantObject)
expect(notifiedValues).toEqual([constantObject])
})
it('Should notify subscribers of a change even when an identical primitive is written if you\'ve set the equality comparer to null', function () {
var instance = observable('A')
var notifiedValues = []
instance.subscribe(notifiedValues.push, notifiedValues)
// No notification by default
instance('A')
expect(notifiedValues).toEqual([])
// But there is a notification if we null out the equality comparer
instance.equalityComparer = null
instance('A')
expect(notifiedValues).toEqual(['A'])
})
it('Should ignore writes when the equalityComparer callback states that the values are equal', function () {
var instance = observable()
instance.equalityComparer = function (a, b) {
return !(a && b) ? a === b : a.id == b.id
}
var notifiedValues = []
instance.subscribe(notifiedValues.push, notifiedValues)
instance({ id: 1 })
expect(notifiedValues.length).toEqual(1)
// Same key - no change
instance({ id: 1, ignoredProp: 'abc' })
expect(notifiedValues.length).toEqual(1)
// Different key - change
instance({ id: 2, ignoredProp: 'abc' })
expect(notifiedValues.length).toEqual(2)
// Null vs not-null - change
instance(null)
expect(notifiedValues.length).toEqual(3)
// Null vs null - no change
instance(null)
expect(notifiedValues.length).toEqual(3)
// Null vs undefined - change
instance(undefined)
expect(notifiedValues.length).toEqual(4)
// undefined vs object - change
instance({ id: 1 })
expect(notifiedValues.length).toEqual(5)
})
it('Should expose a "notify" extender that can configure the observable to notify on all writes, even if the value is unchanged', function () {
var instance = observable()
var notifiedValues = []
instance.subscribe(notifiedValues.push, notifiedValues)
instance(123)
expect(notifiedValues.length).toEqual(1)
// Typically, unchanged values don't trigger a notification
instance(123)
expect(notifiedValues.length).toEqual(1)
// ... but you can enable notifications regardless of change
instance.extend({ notify: 'always' })
instance(123)
expect(notifiedValues.length).toEqual(2)
// ... or later disable that
instance.extend({ notify: null })
instance(123)
expect(notifiedValues.length).toEqual(2)
})
it('Should be possible to replace notifySubscribers with a custom handler', function () {
var instance = observable(123)
var interceptedNotifications = []
instance.subscribe(function () { throw new Error('Should not notify subscribers by default once notifySubscribers is overridden') })
instance.notifySubscribers = function (newValue, eventName) {
interceptedNotifications.push({ eventName: eventName || 'None', value: newValue })
}
instance(456)
// This represents the current set of events that are generated for an observable. This set might
// expand in the future.
expect(interceptedNotifications).toEqual([
{ eventName: 'beforeChange', value: 123 },
{ eventName: 'spectate', value: 456 },
{ eventName: 'None', value: 456 }
])
})
it('Should inherit any properties defined on subscribable.fn or observable.fn', function () {
this.after(function () {
delete subscribable.fn.customProp // Will be able to reach this
delete subscribable.fn.customFunc // Overridden on observable.fn
delete observable.fn.customFunc // Will be able to reach this
})
subscribable.fn.customProp = 'subscribable value'
subscribable.fn.customFunc = function () { throw new Error('Shouldn\'t be reachable') }
observable.fn.customFunc = function () { return this() }
var instance = observable(123)
expect(instance.customProp).toEqual('subscribable value')
expect(instance.customFunc()).toEqual(123)
})
it('Should have access to functions added to "fn" on existing instances on supported browsers', function () {
// On unsupported browsers, there's nothing to test
if (!jasmine.browserSupportsProtoAssignment) {
return
}
this.after(function () {
delete subscribable.fn.customFunction1
delete observable.fn.customFunction2
})
var myObservable = observable()
var customFunction1 = function () {}
var customFunction2 = function () {}
subscribable.fn.customFunction1 = customFunction1
myObservable.fn.customFunction2 = customFunction2
expect(myObservable.customFunction1).toBe(customFunction1)
expect(myObservable.customFunction2).toBe(customFunction2)
})
it('immediately emits any value when called with {next: ...}', function () {
const instance = observable(1)
let x
instance.subscribe({next: v => (x = v)})
expect(x).toEqual(1)
observable(2)
expect(x).toEqual(1)
})
})
describe('unwrap', function () {
it('Should return the supplied value for non-observables', function () {
var someObject = { abc: 123 }
expect(unwrap(123)).toBe(123)
expect(unwrap(someObject)).toBe(someObject)
expect(unwrap(null)).toBe(null)
expect(unwrap(undefined)).toBe(undefined)
})
}) | the_stack |
import * as defaults from "./defaults";
import { BaseInterpreter, Interpreter } from "./interpreter";
export type Specifier = "const" | "inline" | "_stdcall" | "extern" | "static" | "auto" | "register";
export type CCharType = "char" | "signed char" | "unsigned char" | "wchar_t" | "unsigned wchar_t" | "char16_t" | "unsigned char16_t" | "char32_t" | "unsigned char32_t";
export type CIntType = "short" | "short int" | "signed short" | "signed short int" | "unsigned short" | "unsigned short int" | "int" | "signed int" | "unsigned" | "unsigned int" | "long" | "long int" | "long int" | "signed long" | "signed long int" | "unsigned long" | "unsigned long int" | "long long" | "long long int" | "long long int" | "signed long long" | "signed long long int" | "unsigned long long" | "unsigned long long int" | "bool";
export type CFloatType = "float" | "double";
export type CBasicType = CCharType | CIntType | CFloatType | "void";
export type TypeSignature = "global" | "(char)" | "(signed char)" | "(unsigned char)" | "(short)" | "(short int)" | "(signed short)" | "(signed short int)" | "(unsigned short)" | "(unsigned short int)" | "(int)" | "(signed int)" | "(unsigned)" | "(unsigned int)" | "(long)" | "(long int)" | "(long int)" | "(signed long)" | "(signed long int)" | "(unsigned long)" | "(unsigned long int)" | "(long long)" | "(long long int)" | "(long long int)" | "(signed long long)" | "(signed long long int)" | "(unsigned long long)" | "(unsigned long long int)" | "(float)" | "(double)" | "(bool)";
export interface IncludeModule {
load(rt: CRuntime): void;
}
export interface JSCPPConfig {
specifiers?: Specifier[];
charTypes?: CCharType[];
intTypes?: CIntType[];
limits?: {
[typeName in CBasicType | "pointer"]?: {
max: number;
min: number;
bytes: number;
}
};
includes?: { [fileName: string]: IncludeModule };
loadedLibraries?: string[];
stdio?: {
drain?: () => string;
write: (s: string) => void;
};
unsigned_overflow?: "error" | "warn" | "ignore";
maxTimeout?: number;
debug?: boolean;
}
export type OpHandler = {
functions?: { [paramSignature: string]: CFunction };
reg?: FunctionRegistry;
default?: CFunction;
};
export type OpSignature = "o(--)" | "o(-)" | "o(-=)" | "o(->)" | "o(,)" | "o(!)" | "o(!=)" | "o(())" | "o([])" | "o(*)" | "o(*=)" | "o(/)" | "o(/=)" | "o(&)" | "o(&=)" | "o(%)" | "o(%=)" | "o(^)" | "o(^=)" | "o(+)" | "o(++)" | "o(+=)" | "o(<)" | "o(<<)" | "o(<<=)" | "o(<=)" | "o(=)" | "o(==)" | "o(>)" | "o(>=)" | "o(>>)" | "o(>>=)" | "o(|)" | "o(|=)" | "o(~)";
export interface FunctionRegistry {
[signature: string]: {
args: (VariableType | "?")[]; // question mark ignores further parameter type compatibility check, useful for functions like "printf" and "scanf"
optionalArgs: OptionalArg[];
}
}
export interface Member {
type: VariableType;
name: string;
initialize?: (rt: CRuntime, _this: Variable) => Variable;
}
export interface OpHandlerMap {
handlers: { [opSignature: string]: OpHandler; };
cConstructor?: (rt: CRuntime, _this: Variable) => void;
members?: Member[];
father?: string;
};
export interface BoolType {
type: "primitive";
name: "bool";
}
export interface IntType {
type: "primitive";
name: CCharType | CIntType;
}
export interface FloatType {
type: "primitive";
name: CFloatType;
}
export interface VoidType {
type: "primitive";
name: "void";
}
type PrimitiveType = BoolType | IntType | FloatType | VoidType;
export interface NormalPointerType {
type: "pointer";
ptrType: "normal";
targetType: VariableType;
}
export interface ArrayType {
type: "pointer";
ptrType: "array";
size: number;
eleType: VariableType;
}
export interface FunctionPointerType {
type: "pointer";
ptrType: "function";
targetType: FunctionType;
}
export type PointerType = NormalPointerType | ArrayType | FunctionPointerType;
export interface OperatorFunctionType {
type: "function";
}
export interface FunctionType {
type: "function";
retType?: VariableType;
signature?: (VariableType | "?")[];
}
export interface ClassType {
type: "class";
name: string;
}
export type VariableType = PrimitiveType | PointerType | FunctionType | ClassType;
export type BasicValue = number | boolean;
export interface NormalPointerValue {
target: Variable | null;
}
export interface ArrayValue {
position: number;
target: Variable[];
}
export type PointerValue = NormalPointerValue | ArrayValue | FunctionPointerValue;
export interface ObjectValue {
members?: { [name: string]: Variable };
}
export type VariableValue = PointerValue | ObjectValue | BasicValue | FunctionValue;
export interface BoolVariable {
t: PrimitiveType;
v: boolean;
}
export interface IntVariable {
t: PrimitiveType;
v: number;
}
export interface FloatVariable {
t: FloatType;
v: number;
}
type PrimitiveVariable = BoolVariable | IntVariable | FloatVariable;
export interface NormalPointerVariable {
t: NormalPointerType;
v: NormalPointerValue;
}
export interface ArrayVariable {
t: ArrayType;
v: ArrayValue;
}
export interface FunctionPointerValue {
target: FunctionVariable,
name: string,
defineType: VariableType | "global",
args: (VariableType | "?")[],
retType: VariableType,
};
export interface FunctionPointerVariable {
t: FunctionPointerType;
v: FunctionPointerValue;
}
// Dummy is used to differentiate "pre-" or "post-" ++/-- operator
export interface DummyVariable {
t: "dummy";
v: null;
}
type PointerVariable = NormalPointerVariable | ArrayVariable | FunctionPointerVariable;
export interface ObjectVariable {
t: ClassType;
v: ObjectValue;
left?: boolean;
}
export interface FunctionValue {
target?: CFunction;
defineType: VariableType | "global";
name: string;
bindThis: Variable;
}
export interface FunctionVariable {
t: FunctionType | OperatorFunctionType;
v: FunctionValue;
}
export interface ArrayElementVariable {
t: VariableType;
v: VariableValue;
array: Variable[];
arrayIndex: number;
}
export type Variable = {
left?: boolean;
} & (PrimitiveVariable | PointerVariable | ObjectVariable | FunctionVariable | ArrayElementVariable);
export interface RuntimeScope {
"$name": string;
variables: {
[name: string]: Variable;
};
}
export interface OptionalArg { name: string, type: VariableType, expression: any }
type CFunction = (rt: CRuntime, _this: Variable, ...args: (Variable | DummyVariable)[]) => any;
export interface MakeValueStringOptions {
noArray?: boolean;
noPointer?: boolean;
}
export function mergeConfig(a: any, b: any) {
for (const o in b) {
if (b.hasOwnProperty(o)) {
if (o in a && (typeof b[o] === "object")) {
mergeConfig(a[o], b[o]);
} else {
a[o] = b[o];
}
}
}
};
export class CRuntime {
config: JSCPPConfig;
numericTypeOrder: string[];
types: { [typeSignature: string]: OpHandlerMap }
intTypeLiteral: IntType;
unsignedintTypeLiteral: IntType;
longTypeLiteral: IntType;
floatTypeLiteral: FloatType;
doubleTypeLiteral: FloatType;
charTypeLiteral: IntType;
unsignedcharTypeLiteral: IntType;
boolTypeLiteral: IntType;
voidTypeLiteral: VoidType;
nullPointerValue: PointerValue;
voidPointerType: PointerType;
nullPointer: PointerVariable;
scope: RuntimeScope[];
typedefs: { [name: string]: VariableType };
interp: BaseInterpreter;
constructor(config: JSCPPConfig) {
this.config = defaults.getDefaultConfig();
mergeConfig(this.config, config);
this.numericTypeOrder = defaults.numericTypeOrder;
this.types = defaults.getDefaultTypes();
this.intTypeLiteral = this.primitiveType("int") as IntType;
this.unsignedintTypeLiteral = this.primitiveType("unsigned int") as IntType;
this.longTypeLiteral = this.primitiveType("long") as IntType;
this.floatTypeLiteral = this.primitiveType("float") as FloatType;
this.doubleTypeLiteral = this.primitiveType("double") as FloatType;
this.charTypeLiteral = this.primitiveType("char") as IntType;
this.unsignedcharTypeLiteral = this.primitiveType("unsigned char") as IntType;
this.boolTypeLiteral = this.primitiveType("bool") as IntType;
this.voidTypeLiteral = this.primitiveType("void") as VoidType;
this.nullPointerValue = this.makeNormalPointerValue(null);
this.voidPointerType = this.normalPointerType(this.voidTypeLiteral);
this.nullPointer = this.val(this.voidPointerType, this.nullPointerValue) as PointerVariable;
this.scope = [{ "$name": "global", variables: {} }];
this.typedefs = {};
}
include(name: string) {
const {
includes
} = this.config;
if (name in includes) {
const lib = includes[name];
if (this.config.loadedLibraries.includes(name)) {
return;
}
this.config.loadedLibraries.push(name);
lib.load(this);
} else {
this.raiseException("cannot find library: " + name);
}
};
getSize(element: Variable) {
let ret = 0;
if (this.isArrayType(element) && (element.v.position === 0)) {
let i = 0;
while (i < element.v.target.length) {
ret += this.getSize(element.v.target[i]);
i++;
}
} else {
ret += this.getSizeByType(element.t);
}
return ret;
};
getSizeByType(t: VariableType) {
if (this.isPointerType(t)) {
return this.config.limits["pointer"].bytes;
} else if (this.isPrimitiveType(t)) {
return this.config.limits[t.name].bytes;
} else {
this.raiseException("not implemented");
}
};
getMember(l: Variable, r: string): Variable {
const lt = l.t;
if (this.isClassType(l)) {
const ltsig = this.getTypeSignature(lt);
if (this.types.hasOwnProperty(ltsig)) {
const t = this.types[ltsig].handlers;
if (t.hasOwnProperty(r)) {
return {
t: {
type: "function",
},
v: {
defineType: lt,
name: r,
bindThis: l
}
};
} else {
const lv = l.v;
if (lv.members.hasOwnProperty(r)) {
return lv.members[r];
}
}
} else {
this.raiseException("type " + this.makeTypeString(lt) + " is unknown");
}
} else {
this.raiseException("only a class can have members");
}
};
defFunc(lt: VariableType, name: string, retType: VariableType, argTypes: VariableType[], argNames: string[], stmts: any, interp: Interpreter, optionalArgs: OptionalArg[]) {
if (stmts != null) {
const f = function* (rt: CRuntime, _this: Variable, ...args: Variable[]) {
// logger.warn("calling function: %j", name);
rt.enterScope("function " + name);
argNames.forEach(function (argName, i) {
rt.defVar(argName, argTypes[i], args[i]);
});
for (let i = 0, end = optionalArgs.length; i < end; i++) {
const optionalArg = optionalArgs[i];
if (args[argNames.length + i] != null) {
rt.defVar(optionalArg.name, optionalArg.type, args[argNames.length + i]);
} else {
const argValue = yield* interp.visit(interp, optionalArg.expression);
rt.defVar(optionalArg.name, optionalArg.type, rt.cast(optionalArg.type, argValue));
}
}
let ret = yield* interp.run(stmts, interp.source, { scope: "function" });
if (!rt.isTypeEqualTo(retType, rt.voidTypeLiteral)) {
if (ret instanceof Array && (ret[0] === "return")) {
ret = rt.cast(retType, ret[1]);
} else {
rt.raiseException("you must return a value");
}
} else {
if (Array.isArray(ret)) {
if ((ret[0] === "return") && ret[1]) {
rt.raiseException("you cannot return a value from a void function");
}
}
ret = undefined;
}
rt.exitScope("function " + name);
// logger.warn("function: returing %j", ret);
return ret;
};
this.regFunc(f, lt, name, argTypes, retType, optionalArgs);
} else {
this.regFuncPrototype(lt, name, argTypes, retType, optionalArgs);
}
};
makeParametersSignature(args: (VariableType | "?" | "dummy")[]) {
const ret = new Array(args.length);
let i = 0;
while (i < args.length) {
const arg = args[i];
ret[i] = this.getTypeSignature(arg);
i++;
}
return ret.join(",");
};
getCompatibleFunc(lt: VariableType | "global", name: string, args: (Variable | DummyVariable)[]) {
let ret;
const ltsig = this.getTypeSignature(lt);
if (ltsig in this.types) {
const t = this.types[ltsig].handlers;
if (name in t) {
// logger.info("method found");
const ts = args.map(v => v.t);
const sig = this.makeParametersSignature(ts);
if (sig in t[name].functions) {
ret = t[name].functions[sig];
} else {
const compatibles: CFunction[] = [];
const reg = t[name].reg;
Object.keys(reg).forEach(signature => {
let newTs: (VariableType | "dummy")[];
const regArgInfo = reg[signature];
const dts = regArgInfo.args;
let newDts: (VariableType | "dummy")[];
const {
optionalArgs
} = regArgInfo;
if ((dts[dts.length - 1] === "?") && ((dts.length - 1) <= ts.length)) {
newTs = ts.slice(0, dts.length - 1);
newDts = dts.slice(0, -1) as VariableType[];
} else {
newTs = ts;
newDts = dts as VariableType[];
}
if (newDts.length <= newTs.length) {
let ok = true;
let i = 0;
while (ok && (i < newDts.length)) {
ok = this.castable(newTs[i], newDts[i]);
i++;
}
while (ok && (i < newTs.length)) {
ok = this.castable(newTs[i], optionalArgs[i - newDts.length].type);
i++;
}
if (ok) {
compatibles.push(t[name].functions[this.makeParametersSignature(regArgInfo.args)]);
}
}
});
if (compatibles.length === 0) {
if ("#default" in t[name]) {
ret = t[name].functions["#default"];
} else {
const argsStr = ts.map(v => {
return this.makeTypeString(v);
}).join(", ");
this.raiseException("no method " + name + " in " + this.makeTypeString(lt) + " accepts " + argsStr);
}
} else if (compatibles.length > 1) {
this.raiseException("ambiguous method invoking, " + compatibles.length + " compatible methods");
} else {
ret = compatibles[0];
}
}
} else {
this.raiseException("method " + name + " is not defined in " + this.makeTypeString(lt));
}
} else {
this.raiseException("type " + this.makeTypeString(lt) + " is unknown");
}
if ((ret == null)) {
this.raiseException("method " + name + " does not seem to be implemented");
}
return ret;
};
matchVarArg(methods: OpHandler, sig: string) {
for (let _sig in methods) {
if (_sig[_sig.length - 1] === "?") {
_sig = _sig.slice(0, -1);
if (sig.startsWith(_sig)) {
return methods.functions[_sig];
}
}
}
return null;
};
getFunc(lt: (VariableType | "global"), name: string, args: (VariableType | "dummy")[]) {
if (lt !== "global" && (this.isPointerType(lt) || this.isFunctionType(lt))) {
let f;
if (this.isArrayType(lt)) {
f = "pointer_array";
} else if (this.isFunctionType(lt)) {
f = "function";
} else {
f = "pointer_normal";
}
let t = null;
if (name in this.types[f].handlers) {
t = this.types[f].handlers;
} else if (name in this.types["pointer"].handlers) {
t = this.types["pointer"].handlers;
}
if (t) {
const sig = this.makeParametersSignature(args);
let method;
if (t[name].functions != null && sig in t[name].functions) {
return t[name].functions[sig];
} else if ((method = this.matchVarArg(t[name], sig)) !== null) {
return method;
} else if (t[name].default) {
return t[name].default;
} else {
this.raiseException("no method " + name + " in " + this.makeTypeString(lt) + " accepts (" + sig + ")");
}
}
}
const ltsig = this.getTypeSignature(lt);
if (ltsig in this.types) {
const t = this.types[ltsig].handlers;
if (name in t) {
const sig = this.makeParametersSignature(args);
let method;
if (t[name].functions != null && sig in t[name].functions) {
return t[name].functions[sig];
} else if ((method = this.matchVarArg(t[name], sig)) !== null) {
return method;
} else if (t[name].default) {
return t[name].default;
} else {
this.raiseException("no method " + name + " in " + this.makeTypeString(lt) + " accepts (" + sig + ")");
}
} else {
this.raiseException("method " + name + " is not defined in " + this.makeTypeString(lt));
}
} else {
if (lt !== "global" && this.isPointerType(lt)) {
this.raiseException("this pointer has no proper method overload");
} else {
this.raiseException("type " + this.makeTypeString(lt) + " is not defined");
}
}
};
makeOperatorFuncName = (name: string) => `o(${name})`;
regOperator(f: CFunction, lt: VariableType, name: string, args: VariableType[], retType: VariableType) {
return this.regFunc(f, lt, this.makeOperatorFuncName(name), args, retType);
};
regFuncPrototype(lt: VariableType | "global", name: string, args: VariableType[], retType: VariableType, optionalArgs?: OptionalArg[]) {
const ltsig = this.getTypeSignature(lt);
if (ltsig in this.types) {
const t = this.types[ltsig].handlers;
if (!(name in t)) {
t[name] = {
functions: {},
reg: {},
};
}
if (!("reg" in t[name])) {
t[name]["reg"] = {};
}
const sig = this.makeParametersSignature(args);
if (sig in t[name]) {
this.raiseException("method " + name + " with parameters (" + sig + ") is already defined");
}
const type = this.functionType(retType, args);
if (lt === "global") {
this.defVar(name, type, this.val(type, {
bindThis: null,
defineType: lt,
name,
target: null
}));
}
t[name].functions[sig] = null;
if (t[name].reg[sig] == null) {
t[name].reg[sig] = {
args,
optionalArgs
};
}
} else {
this.raiseException("type " + this.makeTypeString(lt) + " is unknown");
}
};
regFunc(f: CFunction, lt: VariableType | "global", name: string, args: (VariableType | "?")[], retType: VariableType, optionalArgs?: OptionalArg[]) {
const ltsig = this.getTypeSignature(lt);
if (ltsig in this.types) {
if (!optionalArgs) { optionalArgs = []; }
const t = this.types[ltsig].handlers;
if (!(name in t)) {
t[name] = {
functions: {},
reg: {},
};
}
if (t[name].functions == null) {
t[name].functions = {};
}
if (t[name].reg == null) {
t[name].reg = {};
}
const sig = this.makeParametersSignature(args);
// console.log("regFunc " + name + "(" + sig + ")");
if (t[name].functions[sig] != null && t[name].reg[sig] != null) {
this.raiseException("method " + name + " with parameters (" + sig + ") is already defined");
}
const type = this.functionType(retType, args);
if (lt === "global") {
if (this.varAlreadyDefined(name)) {
const func = this.scope[0].variables[name];
if (this.isFunctionType(func)) {
const v = func.v;
if (v.target !== null) {
this.raiseException("global method " + name + " with parameters (" + sig + ") is already defined");
} else {
v.target = f;
}
} else {
this.raiseException(name + " is already defined as " + this.makeTypeString(func.t));
}
} else {
this.defVar(name, type, this.val(type, {
bindThis: null,
defineType: lt,
name,
target: f
}));
}
}
t[name].functions[sig] = f;
t[name].reg[sig] = {
args,
optionalArgs
};
} else {
this.raiseException("type " + this.makeTypeString(lt) + " is unknown");
}
};
registerTypedef(basttype: VariableType, name: string) {
return this.typedefs[name] = basttype;
};
promoteNumeric(l: VariableType, r: VariableType) {
if (this.isNumericType(l) && this.isNumericType(r)) {
if (this.isTypeEqualTo(l, r)) {
if (this.isTypeEqualTo(l, this.boolTypeLiteral)) {
return this.intTypeLiteral;
}
if (this.isTypeEqualTo(l, this.charTypeLiteral)) {
return this.intTypeLiteral;
}
if (this.isTypeEqualTo(l, this.unsignedcharTypeLiteral)) {
return this.unsignedintTypeLiteral;
}
return l;
} else if (this.isIntegerType(l) && this.isIntegerType(r)) {
let rett;
const slt = this.getSignedType(l);
const srt = this.getSignedType(r);
if (this.isTypeEqualTo(slt, srt)) {
rett = slt;
} else {
const slti = this.numericTypeOrder.indexOf(slt.name);
const srti = this.numericTypeOrder.indexOf(srt.name);
if (slti <= srti) {
if (this.isUnsignedType(l) && this.isUnsignedType(r)) {
rett = r;
} else {
rett = srt;
}
} else {
if (this.isUnsignedType(l) && this.isUnsignedType(r)) {
rett = l;
} else {
rett = slt;
}
}
}
return rett;
} else if (!this.isIntegerType(l) && this.isIntegerType(r)) {
return l;
} else if (this.isIntegerType(l) && !this.isIntegerType(r)) {
return r;
} else if (!this.isIntegerType(l) && !this.isIntegerType(r)) {
return this.primitiveType("double");
}
} else {
this.raiseException("you cannot promote (to) a non numeric type");
}
};
readVar(varname: string) {
let i = this.scope.length - 1;
while (i >= 0) {
const vc = this.scope[i];
if (vc.variables[varname] != null) {
const ret = vc.variables[varname];
return ret;
}
i--;
}
this.raiseException("variable " + varname + " does not exist");
};
varAlreadyDefined(varname: string) {
const vc = this.scope[this.scope.length - 1];
return varname in vc;
};
defVar(varname: string, type: VariableType, initval: Variable) {
if (varname == null) {
this.raiseException("cannot define a variable without name");
}
if (this.varAlreadyDefined(varname)) {
this.raiseException("variable " + varname + " already defined");
}
const vc = this.scope[this.scope.length - 1];
// logger.log("defining variable: %j, %j", varname, type);
initval = this.clone(this.cast(type, initval), true);
if (initval === undefined) {
vc.variables[varname] = this.defaultValue(type);
vc.variables[varname].left = true;
} else {
vc.variables[varname] = initval;
vc.variables[varname].left = true;
}
};
booleanToNumber(b: BasicValue) {
if (typeof (b) === "boolean") {
return b ? 1 : 0;
}
return b;
}
inrange(type: VariableType, value: BasicValue, errorMsg?: string) {
if (this.isPrimitiveType(type)) {
value = this.booleanToNumber(value);
const limit = this.config.limits[type.name];
const overflow = !((value <= limit.max) && (value >= limit.min));
if (errorMsg && overflow) {
if (this.isUnsignedType(type)) {
if (this.config.unsigned_overflow === "error") {
this.raiseException(errorMsg);
return false;
} else if (this.config.unsigned_overflow === "warn") {
console.error(errorMsg);
return true;
} else {
return true;
}
} else {
this.raiseException(errorMsg);
}
}
return !overflow;
} else {
return true;
}
};
ensureUnsigned(type: VariableType, value: BasicValue) {
value = this.booleanToNumber(value);
if (this.isUnsignedType(type)) {
const limit = this.config.limits[type.name];
const period = limit.max - limit.min;
if (value < limit.min) {
value += period * Math.ceil((limit.min - value) / period);
}
if (value > limit.max) {
value = ((value - limit.min) % period) + limit.min;
}
}
return value;
};
isNumericType(type: VariableType): type is PrimitiveType;
isNumericType(type: Variable | DummyVariable): type is PrimitiveVariable;
isNumericType(type: string): boolean;
isNumericType(type: VariableType | Variable | DummyVariable | string) {
if (typeof type === "string") {
return this.isFloatType(type) || this.isIntegerType(type);
}
if ('t' in type) {
return type.t !== "dummy" && this.isNumericType(type.t);
}
return this.isFloatType(type) || this.isIntegerType(type);
};
isUnsignedType(type: VariableType): type is PrimitiveType;
isUnsignedType(type: string): boolean;
isUnsignedType(type: VariableType | string): boolean {
if (typeof type === "string") {
switch (type) {
case "unsigned char": case "unsigned short": case "unsigned short int": case "unsigned": case "unsigned int": case "unsigned long": case "unsigned long int": case "unsigned long long": case "unsigned long long int":
return true;
default:
return false;
}
} else {
return (type.type === "primitive") && this.isUnsignedType(type.name);
}
};
isIntegerType(type: Variable): type is (IntVariable | BoolVariable);
isIntegerType(type: VariableType): type is (IntType | BoolType);
isIntegerType(type: string): boolean;
isIntegerType(type: Variable | VariableType | string) {
if (typeof type === "string") {
return this.config.charTypes.includes(type as CCharType) || this.config.intTypes.includes(type as CIntType);
} else if ('t' in type) {
return this.isIntegerType(type.t);
} else {
return (type.type === "primitive") && this.isIntegerType(type.name);
}
};
isFloatType(type: Variable): type is FloatVariable;
isFloatType(type: VariableType): type is FloatType;
isFloatType(type: string): boolean;
isFloatType(type: Variable | VariableType | string): boolean {
if (typeof type === "string") {
switch (type) {
case "float": case "double":
return true;
default:
return false;
}
} else if ('t' in type) {
return this.isFloatType(type.t);
} else {
return (type.type === "primitive") && this.isFloatType(type.name);
}
};
getSignedType(type: VariableType): PrimitiveType {
if (type.type === "primitive") {
return this.primitiveType(type.name.replace("unsigned", "").trim() as CBasicType);
} else {
this.raiseException("Cannot get signed type from non-primitive type " + this.makeTypeString(type));
}
};
castable(type1: VariableType | "dummy", type2: VariableType | "dummy") {
if (type1 === "dummy" || type2 === "dummy") {
this.raiseException("Unexpected dummy");
return;
}
if (this.isTypeEqualTo(type1, type2)) {
return true;
}
if (this.isPrimitiveType(type1) && this.isPrimitiveType(type2)) {
return this.isNumericType(type2) && this.isNumericType(type1);
} else if (this.isPointerType(type1) && this.isPointerType(type2)) {
if (this.isFunctionType(type1)) {
return this.isPointerType(type2);
}
return !this.isFunctionType(type2);
} else if (this.isClassType(type1) || this.isClassType(type2)) {
this.raiseException("not implemented");
}
return false;
};
cast(type: IntType, value: Variable | DummyVariable): IntVariable;
cast(type: VariableType, value: Variable | DummyVariable): Variable;
cast(type: VariableType, value: Variable | DummyVariable) {
// TODO: looking for global overload
let v;
if (value.t !== "dummy") {
} else {
this.raiseException(this.makeValString(value) + " is dummy");
return;
}
if (this.isTypeEqualTo(value.t, type)) {
return value;
}
if (this.isPrimitiveType(type) && this.isPrimitiveType(value.t)) {
if (type.name === "bool") {
return this.val(type, value.v ? 1 : 0);
} else if (["float", "double"].includes(type.name)) {
if (!this.isNumericType(value)) {
this.raiseException("cannot cast " + this.makeValueString(value) + " to " + this.makeTypeString(type));
} else if (this.inrange(type, value.v, "overflow when casting " + this.makeTypeString(value.t) + " to " + this.makeTypeString(type))) {
value.v = this.ensureUnsigned(type, value.v);
return this.val(type, value.v);
}
} else {
if (type.name.slice(0, 8) === "unsigned") {
if (!this.isNumericType(value)) {
this.raiseException("cannot cast " + this.makeValueString(value) + " to " + this.makeTypeString(type));
} else if (value.v < 0) {
const { bytes } = this.config.limits[type.name];
let newValue = this.booleanToNumber(value.v) & ((1 << (8 * bytes)) - 1); // truncates
if (this.inrange(type, newValue, `cannot cast negative value ${newValue} to ` + this.makeTypeString(type))) {
newValue = this.ensureUnsigned(type, newValue);
// unsafe! bitwise truncation is platform dependent
return this.val(type, newValue);
}
}
}
if (!this.isNumericType(value)) {
this.raiseException("cannot cast " + this.makeValueString(value) + " to " + this.makeTypeString(type));
} else if (this.isFloatType(value)) {
v = value.v > 0 ? Math.floor(this.booleanToNumber(value.v)) : Math.ceil(this.booleanToNumber(value.v));
if (this.inrange(type, v, "overflow when casting " + this.makeValString(value) + " to " + this.makeTypeString(type))) {
v = this.ensureUnsigned(type, v);
return this.val(type, v);
}
} else {
if (this.inrange(type, value.v, "overflow when casting " + this.makeValString(value) + " to " + this.makeTypeString(type))) {
value.v = this.ensureUnsigned(type, value.v);
return this.val(type, value.v);
}
}
}
} else if (this.isPointerType(type)) {
if (this.isArrayType(value)) {
if (this.isNormalPointerType(type)) {
if (this.isTypeEqualTo(type.targetType, value.t.eleType)) {
return value;
} else {
this.raiseException(this.makeTypeString(type.targetType) + " is not equal to array element type " + this.makeTypeString(value.t.eleType));
}
} else if (this.isArrayType(type)) {
if (this.isTypeEqualTo(type.eleType, value.t.eleType)) {
return value;
} else {
this.raiseException("array element type " + this.makeTypeString(type.eleType) + " is not equal to array element type " + this.makeTypeString(value.t.eleType));
}
} else {
this.raiseException("cannot cast a function to a regular pointer");
}
} else {
if (this.isNormalPointerType(type)) {
if (this.isNormalPointerType(value)) {
if (this.isTypeEqualTo(type.targetType, value.t.targetType)) {
return value;
} else {
this.raiseException(this.makeTypeString(type.targetType) + " is not equal to " + this.makeTypeString(value.t.targetType));
}
} else {
this.raiseException(this.makeValueString(value) + " is not a normal porinter");
}
} else if (this.isArrayType(type)) {
if (this.isNormalPointerType(value)) {
if (this.isTypeEqualTo(type.eleType, value.t.targetType)) {
return value;
} else {
this.raiseException("array element type " + this.makeTypeString(type.eleType) + " is not equal to " + this.makeTypeString(value.t.targetType));
}
} else {
this.raiseException(this.makeValueString(value) + " is not a normal porinter");
}
} else if (this.isFunctionPointerType(type)) {
if (this.isFunctionPointerType(value.t)) {
if (!this.isTypeEqualTo(type, value.t)) {
this.raiseException("Function pointers do not share the same signature");
}
return value;
} else {
this.raiseException("cannot cast a regular/array pointer to a function pointer");
}
} else {
this.raiseException("cannot cast a function to a regular pointer");
}
}
} else if (this.isFunctionType(type)) {
if (this.isFunctionType(value.t)) {
return this.val(value.t, value.v);
} else {
this.raiseException("cannot cast a regular pointer to a function");
}
} else if (this.isClassType(type)) {
this.raiseException("not implemented");
} else if (this.isClassType(value.t)) {
value = this.getCompatibleFunc(value.t, this.makeOperatorFuncName(type.name), [])(this, value);
return value;
} else {
this.raiseException("cast failed from type " + this.makeTypeString(type) + " to " + this.makeTypeString(value.t));
}
};
clone(v: Variable, isInitializing?: boolean) {
return this.val(v.t, v.v, false, isInitializing);
};
enterScope(scopename: string) {
this.scope.push({ "$name": scopename, variables: {} });
};
exitScope(scopename: string) {
// logger.info("%j", this.scope);
while (true) {
const s = this.scope.pop();
if (!scopename || !(this.scope.length > 1) || (s["$name"] === scopename)) {
break;
}
}
};
val(t: IntType, v: BasicValue, left?: boolean, isInitializing?: boolean): IntVariable;
val(t: PointerType, v: PointerValue, left?: boolean, isInitializing?: boolean): PointerVariable;
val(t: VariableType, v: VariableValue, left?: boolean, isInitializing?: boolean): Variable;
val(t: VariableType, v: VariableValue, left = false, isInitializing = false): Variable {
if (this.isNumericType(t)) {
let checkRange: boolean;
if (isInitializing) {
if (typeof (v) !== "number" || isNaN(v)) {
checkRange = false;
} else {
checkRange = true;
}
} else {
checkRange = true;
}
if (checkRange) {
this.inrange(t, v as BasicValue, `overflow of ${this.makeValString({ t, v } as Variable)}`);
v = this.ensureUnsigned(t, v as BasicValue);
}
}
if (left === undefined) {
left = false;
}
return {
t,
v,
left
} as Variable;
};
isTypeEqualTo(type1: (VariableType | "?"), type2: (VariableType | "?")): boolean {
if (type1 === "?" || type2 === "?") {
return type1 === type2;
}
if (type1.type === type2.type) {
switch (type1.type) {
case "primitive":
return type1.name === (type2 as any).name;
break;
case "class":
return type1.name === (type2 as any).name;
break;
case "pointer":
type2 = type2 as PointerType;
if ((type1.ptrType === type2.ptrType) || ((type1.ptrType !== "function") && (type2.ptrType !== "function"))) {
switch (type1.ptrType) {
case "array":
return this.isTypeEqualTo(type1.eleType, (type2 as ArrayType).eleType || (type2 as NormalPointerType).targetType);
break;
case "function":
return this.isTypeEqualTo((type1 as FunctionPointerType).targetType, (type2 as FunctionPointerType).targetType);
break;
case "normal":
return this.isTypeEqualTo(type1.targetType, (type2 as ArrayType).eleType || (type2 as NormalPointerType).targetType);
break;
}
}
break;
case "function":
if (this.isTypeEqualTo(type1.retType, (type2 as FunctionType).retType) && (type1.signature.length === (type2 as FunctionType).signature.length)) {
return type1.signature.every((type, index, arr) => {
const x = this.isTypeEqualTo(type, (type2 as FunctionType).signature[index]);
return x;
});
}
break;
}
}
return type1 === type2;
};
isBoolType(type: VariableType | string): boolean {
if (typeof type === "string") {
return type === "bool";
} else {
return (type.type === "primitive") && this.isBoolType(type.name);
}
};
isVoidType(type: VariableType | string): boolean {
if (typeof type === "string") {
return type === "void";
} else {
return (type.type === "primitive") && this.isVoidType(type.name);
}
};
isPrimitiveType(type: VariableType): type is PrimitiveType;
isPrimitiveType(type: string): type is CBasicType;
isPrimitiveType(type: Variable | DummyVariable): type is PrimitiveVariable;
isPrimitiveType(type: VariableType | Variable | DummyVariable | string) {
if (typeof type === "string") {
return this.isNumericType(type) || this.isBoolType(type) || this.isVoidType(type);
}
if ('t' in type) {
return type.t !== "dummy" && this.isPrimitiveType(type.t);
}
return this.isNumericType(type) || this.isBoolType(type) || this.isVoidType(type);
};
isArrayType(type: VariableType): type is ArrayType;
isArrayType(type: Variable | DummyVariable): type is ArrayVariable;
isArrayType(type: VariableType | Variable | DummyVariable) {
if ('t' in type) {
return type.t !== "dummy" && this.isArrayType(type.t);
}
return this.isPointerType(type) && (type.ptrType === "array");
};
isArrayElementType(type: Variable | DummyVariable): type is ArrayElementVariable;
isArrayElementType(type: Variable | DummyVariable) {
return type.t !== "dummy" && "array" in type.t;
};
isFunctionPointerType(type: VariableType): type is FunctionPointerType;
isFunctionPointerType(type: Variable | DummyVariable): type is FunctionPointerVariable;
isFunctionPointerType(type: VariableType | Variable | DummyVariable) {
if ('t' in type) {
return type.t !== "dummy" && this.isFunctionPointerType(type.t);
}
return this.isPointerType(type) && type.ptrType === "function";
};
isFunctionType(type: VariableType): type is FunctionType;
isFunctionType(type: Variable | DummyVariable): type is FunctionVariable;
isFunctionType(type: VariableType | Variable | DummyVariable) {
if ('t' in type) {
return type.t !== "dummy" && this.isFunctionType(type.t);
}
return type.type === "function";
};
isNormalPointerType(type: VariableType): type is NormalPointerType;
isNormalPointerType(type: Variable | DummyVariable): type is NormalPointerVariable;
isNormalPointerType(type: Variable | DummyVariable | VariableType): type is NormalPointerType {
if ('t' in type) {
return type.t !== "dummy" && this.isNormalPointerType(type.t);
}
return this.isPointerType(type) && (type.ptrType === "normal");
};
isPointerType(type: VariableType): type is PointerType;
isPointerType(type: Variable | DummyVariable): type is PointerVariable;
isPointerType(type: Variable | DummyVariable | VariableType) {
if ('t' in type) {
return type.t !== "dummy" && this.isPointerType(type.t);
}
return type.type === "pointer"
};
isClassType(type: VariableType): type is ClassType;
isClassType(type: Variable | DummyVariable): type is ObjectVariable;
isClassType(type: VariableType | DummyVariable | Variable): type is ClassType {
if ('t' in type) {
return type.t !== "dummy" && this.isClassType(type.t);
}
return type.type === "class";
};
arrayPointerType(eleType: VariableType, size: number): ArrayType {
return {
type: "pointer",
ptrType: "array",
eleType,
size
};
};
makeArrayPointerValue(arr: Variable[], position: number): ArrayValue {
return {
target: arr,
position
}
};
functionPointerType(retType: VariableType, signature: (VariableType | "?")[]): FunctionPointerType {
return {
type: "pointer",
ptrType: "function",
targetType: this.functionType(retType, signature)
};
};
functionType(retType: VariableType, signature: (VariableType | "?")[]): FunctionType {
return {
type: "function",
retType,
signature
};
};
makeFunctionPointerValue(f: FunctionVariable, name: string, lt: VariableType | "global", args: (VariableType | "?")[], retType: VariableType): FunctionPointerValue {
return {
target: f,
name,
defineType: lt,
args,
retType
};
};
normalPointerType(targetType: VariableType): PointerType {
if (targetType.type === "function") {
return {
type: "pointer",
ptrType: "function",
targetType,
}
}
return {
type: "pointer",
ptrType: "normal",
targetType
};
};
makeNormalPointerValue(target: Variable): PointerValue {
return {
target
};
};
simpleType(type: string | string[]): VariableType {
if (Array.isArray(type)) {
if (type.length > 1) {
const typeStr = type.filter(t => {
return !this.config.specifiers.includes(t as Specifier);
}).join(" ");
return this.simpleType(typeStr);
} else {
return this.typedefs[type[0]] || this.simpleType(type[0]);
}
} else {
if (this.isPrimitiveType(type)) {
return this.primitiveType(type);
} else {
const clsType: ClassType = {
type: "class",
name: type
};
if (this.getTypeSignature(clsType) in this.types) {
return clsType;
} else {
this.raiseException("type " + type + " is not defined");
}
}
}
};
newClass(classname: string, members: Member[]) {
const clsType: ClassType = {
type: "class",
name: classname
};
const sig = this.getTypeSignature(clsType);
if (sig in this.types) {
this.raiseException(this.makeTypeString(clsType) + " is already defined");
}
this.types[sig] = {
cConstructor(rt, _this) {
const v = _this.v as ObjectValue;
v.members = {};
let i = 0;
while (i < members.length) {
const member = members[i];
v.members[member.name] = (member.initialize != null) ?
member.initialize(rt, _this)
:
rt.defaultValue(member.type, true);
i++;
}
},
members,
handlers: {},
};
return clsType;
};
primitiveType(type: CBasicType): PrimitiveType {
return {
type: "primitive",
name: type,
} as PrimitiveType;
};
isCharType(type: VariableType) {
return "name" in type && this.config.charTypes.indexOf(type.name as CCharType) !== -1;
};
isStringType(type: Variable): type is ArrayVariable;
isStringType(type: VariableType): type is ArrayType;
isStringType(type: Variable | VariableType) {
if ("t" in type) {
return this.isStringType(type.t);
}
return this.isArrayType(type) && this.isCharType(type.eleType);
};
getStringFromCharArray(element: ArrayVariable) {
if (this.isStringType(element.t)) {
const {
target
} = element.v;
let result = "";
let i = 0;
while (i < target.length) {
const charVal = target[i];
if (charVal.v === 0) {
break;
}
result += String.fromCharCode(charVal.v as number);
i++;
}
return result;
} else {
this.raiseException("target is not a string");
}
};
makeCharArrayFromString(str: string, typename?: CBasicType): ArrayVariable {
if (!typename) { typename = "char"; }
const charType = this.primitiveType(typename);
const type = this.arrayPointerType(charType, str.length + 1);
const trailingZero = this.val(charType, 0);
return {
t: type,
v: {
target: str.split("").map(c => this.val(charType, c.charCodeAt(0))).concat([trailingZero]),
position: 0,
}
};
};
getTypeSignature(type: VariableType | "global" | "?" | "dummy") {
// (primitive), [class], {pointer}
if (typeof (type) === "string") {
return type;
}
let ret: string;
if (type.type === "primitive") {
ret = "(" + type.name + ")";
} else if (type.type === "class") {
ret = "[" + type.name + "]";
} else if (type.type === "pointer") {
// !targetType, @size!eleType, !#retType!param1,param2,...
ret = "{";
if (type.ptrType === "normal") {
ret += "!" + this.getTypeSignature(type.targetType);
} else if (type.ptrType === "array") {
ret += "!" + this.getTypeSignature(type.eleType);
} else if (type.ptrType === "function") {
ret += "@" + this.getTypeSignature(type.targetType);
}
ret += "}";
} else if (type.type === "function") {
// #retType!param1,param2,...
ret = "#" + this.getTypeSignature(type.retType) + "!" + type.signature.map(e => {
return this.getTypeSignature(e);
}).join(",");
}
return ret;
};
makeTypeString(type: VariableType | "global" | "dummy" | "?") {
// (primitive), [class], {pointer}
let ret;
if (typeof (type) === "string") {
ret = "$" + type;
} else if (type.type === "primitive") {
ret = type.name;
} else if (type.type === "class") {
ret = type.name;
} else if (type.type === "pointer") {
// !targetType, @size!eleType, #retType!param1,param2,...
ret = "";
if (type.ptrType === "normal") {
ret += this.makeTypeString(type.targetType) + "*";
} else if (type.ptrType === "array") {
ret += this.makeTypeString(type.eleType) + `[${type.size}]`;
} else if (type.ptrType === "function") {
ret += this.makeTypeString(type.targetType.retType) + "(*f)" + "(" + type.targetType.signature.map(e => {
return this.makeTypeString(e);
}).join(",") + ")";
}
}
return ret;
};
makeValueString(l: Variable | DummyVariable, options?: MakeValueStringOptions): string {
let display: string;
if (!options) { options = {}; }
if (this.isPrimitiveType(l)) {
if (this.isTypeEqualTo(l.t, this.charTypeLiteral)) {
display = "'" + String.fromCharCode(l.v as number) + "'";
} else if (this.isBoolType(l.t)) {
display = l.v !== 0 ? "true" : "false";
} else {
display = l.v.toString();
}
} else if (this.isPointerType(l)) {
if (this.isFunctionType(l.t)) {
display = "<function>";
} else if (this.isArrayType(l)) {
if (this.isTypeEqualTo(l.t.eleType, this.charTypeLiteral)) {
// string
display = "\"" + this.getStringFromCharArray(l) + "\"";
} else if (options.noArray) {
display = "[...]";
} else {
options.noArray = true;
const displayList = [];
for (let i = l.v.position, end = l.v.target.length, asc = l.v.position <= end; asc ? i < end : i > end; asc ? i++ : i--) {
displayList.push(this.makeValueString(l.v.target[i], options));
}
display = "[" + displayList.join(",") + "]";
}
} else if (this.isNormalPointerType(l)) {
if (options.noPointer) {
display = "->?";
} else {
options.noPointer = true;
display = "->" + this.makeValueString(l.v.target);
}
} else {
this.raiseException("unknown pointer type");
}
} else if (this.isClassType(l)) {
display = "<object>";
}
return display;
};
makeValString(l: Variable | DummyVariable) {
return this.makeValueString(l) + "(" + this.makeTypeString(l.t) + ")";
};
defaultValue(type: VariableType, left = false): Variable {
if (type.type === "primitive") {
return this.val(type, NaN, left, true);
} else if (type.type === "class") {
const ret = this.val(type, {
members: {}
}, left);
this.types[this.getTypeSignature(type)].cConstructor(this, ret);
return ret;
} else if (type.type === "pointer") {
if (type.ptrType === "normal") {
return this.val(type, this.makeNormalPointerValue(null), left);
} else if (type.ptrType === "array") {
const init = [];
for (let i = 0, end = type.size, asc = 0 <= end; asc ? i < end : i > end; asc ? i++ : i--) {
init[i] = this.defaultValue(type.eleType, true);
}
return this.val(type, this.makeArrayPointerValue(init, 0), left);
} else if (type.ptrType === "function") {
return this.val(this.functionPointerType(type.targetType.retType, type.targetType.signature), this.makeFunctionPointerValue(null, null, null, type.targetType.signature, type.targetType.retType));
}
}
};
raiseException(message: string, currentNode?: any) {
if (this.interp) {
if (currentNode == null) {
({
currentNode
} = this.interp);
}
const posInfo =
(() => {
if (currentNode != null) {
const ln = currentNode.sLine;
const col = currentNode.sColumn;
return ln + ":" + col;
} else {
return "<position unavailable>";
}
})();
throw new Error(posInfo + " " + message);
} else {
throw new Error(message);
}
};
} | the_stack |
import type { Fn, Fn2, ICompare, IContains, ICopy, IEquiv } from "@thi.ng/api";
import { DEFAULT_EPS } from "@thi.ng/api/api";
import { isString } from "@thi.ng/checks/is-string";
import { and, or } from "@thi.ng/dlogic";
import { illegalArgs } from "@thi.ng/errors/illegal-arguments";
export enum Classifier {
DISJOINT_LEFT,
DISJOINT_RIGHT,
EQUIV,
SUBSET,
SUPERSET,
OVERLAP_LEFT,
OVERLAP_RIGHT,
}
export class Interval
implements ICompare<Interval>, IContains<number>, ICopy<Interval>, IEquiv
{
l: number;
r: number;
lopen: boolean;
ropen: boolean;
constructor(l: number, r: number, lopen = false, ropen = false) {
(l > r || (l === r && lopen !== ropen)) &&
illegalArgs(`invalid interval: ${$toString(l, r, lopen, ropen)}`);
this.l = l;
this.r = r;
this.lopen = lopen;
this.ropen = ropen;
}
get size(): number {
return isEmpty(this) ? 0 : this.r - this.l;
}
copy() {
return new Interval(this.l, this.r, this.lopen, this.ropen);
}
/**
* Compares this interval with `i` and returns a comparator value
* (-1, 0 or 1). Comparison order is: LHS, RHS, openness.
*
* @param i -
*/
compare(i: Readonly<Interval>) {
return compare(this, i);
}
equiv(i: any) {
return (
this === i ||
(i instanceof Interval &&
this.l === i.l &&
this.r === i.r &&
this.lopen === i.lopen &&
this.ropen === i.ropen)
);
}
/**
* Returns true if `x` is lies within this interval.
*
* @param x -
*/
contains(x: number) {
return contains(this, x);
}
toString() {
return $toString(this.l, this.r, this.lopen, this.ropen);
}
toJSON() {
return this.toString();
}
}
const BRACES = "()[]";
const RE_INF = /^([-+])?(inf(inity)?|\u221e)$/i;
export function interval(spec: string): Interval;
export function interval(
l: number,
r: number,
lopen?: boolean,
ropen?: boolean
): Interval;
export function interval(
l: number | string,
r?: number,
lopen?: boolean,
ropen?: boolean
) {
return isString(l) ? parse(l) : new Interval(l, r!, lopen, ropen);
}
/**
* Parses given ISO 80000-2 interval notation into a new `Interval`
* instance. In addition to the comma separator, `..` can be used
* alternatively. The following symbols (with optional sign) can be
* used for infinity (case insensitive):
*
* - inf
* - infinity
* - ∞ (\u221e)
*
* An empty LHS defaults to `-Infinity`. The RHS defaults to
* `+Infinity`.
*
* Openness / closedness symbols:
*
* - LHS: open: `]` / `(`, closed: `[`
* - RHS: open: `[` / `)`, closed: `]`
*
* ```
* // semi-open interval between -∞ and +1
* Interval.parse("[,1)")
*
* // closed interval between -1 and +1
* Interval.parse("[-1 .. 1]")
* ```
*
* @param src -
*/
export const parse = (src: string) => {
let l, r, c1, c2;
const n = src.length - 1;
const comma = src.indexOf(",") > 0;
const dot = src.indexOf("..") > 0;
if (n < (dot ? 3 : 2)) illegalArgs(src);
c1 = src.charAt(0);
c2 = src.charAt(n);
if (BRACES.indexOf(c1) < 0 || BRACES.indexOf(c2) < 0 || !(comma || dot)) {
illegalArgs(src);
}
[l, r] = src
.substring(1, n)
.split(dot ? ".." : ",")
.map((x, i) => {
x = x.trim();
const inf = RE_INF.exec(x);
const n =
(x === "" && i === 0) || (inf && inf[1] === "-")
? -Infinity
: (x === "" && i > 0) || (inf && inf[1] !== "-")
? Infinity
: parseFloat(x);
isNaN(n) && illegalArgs(`expected number: '${x}'`);
return n;
});
r === undefined && (r = Infinity);
return new Interval(
l,
r,
c1 === "(" || c1 === "]",
c2 === ")" || c2 === "["
);
};
/**
* Returns new infinite interval `[-∞..∞]`
*/
export const infinity = () => new Interval(-Infinity, Infinity);
/**
* Returns new interval of `[min..∞]` or `(min..∞]` depending on if `open` is
* true (default: false).
*
* @param min -
* @param open -
*/
export const withMin = (min: number, open = false) =>
new Interval(min, Infinity, open, false);
/**
* Returns new interval of `[∞..max]` or `[∞..max)` depending on if `open` is
* true (default: false).
*
* @param max -
* @param open -
*/
export const withMax = (max: number, open = false) =>
new Interval(-Infinity, max, false, open);
/**
* Returns an open interval `(min..max)`
*
* @param min
* @param max
*/
export const open = (min: number, max: number) =>
new Interval(min, max, true, true);
/**
* Returns a semi-open interval `(min..max]`, open on the LHS.
*
* @param min
* @param max
*/
export const openClosed = (min: number, max: number) =>
new Interval(min, max, true, false);
/**
* Returns a semi-open interval `[min..max)`, open on the RHS.
*
* @param min
* @param max
*/
export const closedOpen = (min: number, max: number) =>
new Interval(min, max, false, true);
/**
* Returns a closed interval `(min..max)`.
*
* @param min
* @param max
*/
export const closed = (min: number, max: number) =>
new Interval(min, max, false, false);
/**
* Returns iterator of values in given interval at given `step` size. If the
* interval is open on either side, the first and/or last sample will be
* omitted.
*
* @param i -
* @param step -
*/
export const values = (i: Readonly<Interval>, step: number) =>
samples(i, Math.floor(i.size / step + 1));
/**
* Returns an iterator yielding up to `n` uniformly spaced samples in given
* interval. If the interval is open on either side, the first and/or last
* sample will be omitted.
*
* @example
* ```ts
* [...samples(closed(10, 12), 5)]
* // [10, 10.5, 11, 11.5, 12]
*
* [...samples(open(10, 12), 5)]
* // [10.5, 11, 11.5]
* ```
*
* @param i -
* @param n -
*/
export function* samples(i: Readonly<Interval>, n: number) {
const delta = n > 1 ? (i.r - i.l) / (n - 1) : 0;
for (let x = 0; x < n; x++) {
const y = i.l + delta * x;
if (contains(i, y)) yield y;
}
}
/**
* Returns true, if interval has zero range, i.e. if LHS >= RHS.
*
* @param i -
*/
export const isEmpty = (i: Readonly<Interval>) => i.l >= i.r;
/**
* Returns true iff interval `i` RHS < `x`, taking into account openness. If `x`
* is an interval, then checks `i` RHS is less than LHS of `x` (again with
* openness).
*
* @param i -
* @param x -
*/
export const isBefore = (
i: Readonly<Interval>,
x: number | Readonly<Interval>
) =>
x instanceof Interval
? i.ropen || x.lopen
? i.r <= x.l
: i.r < x.l
: i.ropen
? i.r <= x
: i.r < x;
/**
* Returns true iff interval `i` LHS > `x`, taking into account openness. If `x`
* is an interval, then checks `i` LHS is greater than RHS of `x` (again with
* openness).
*
* @param i -
* @param x -
*/
export const isAfter = (
i: Readonly<Interval>,
x: number | Readonly<Interval>
) =>
x instanceof Interval
? i.lopen || x.ropen
? i.l >= x.r
: i.l > x.r
: i.ropen
? i.l >= x
: i.l > x;
/**
* Compares interval `a` with `b` and returns a comparator value
* (-1, 0 or 1). Comparison order is: LHS, RHS, openness.
*
* @param a -
* @param b -
*/
export const compare = (a: Readonly<Interval>, b: Readonly<Interval>) => {
if (a === b) return 0;
let c: number;
return a.l < b.l
? -1
: a.l > b.l
? 1
: a.r < b.r
? -1
: a.r > b.r
? 1
: (c = ~~a.lopen - ~~b.lopen) === 0
? ~~b.ropen - ~~a.ropen
: c;
};
/**
* Returns true if `x` is lies within interval `i`.
*
* @param i -
* @param x -
*/
export const contains = (i: Readonly<Interval>, x: number) =>
(i.lopen ? x > i.l : x >= i.l) && (i.ropen ? x < i.r : x <= i.r);
export const centroid = (i: Readonly<Interval>) => (i.l + i.r) / 2;
/**
* Returns a new version of interval `i` such that `x` is included. If `x` lies
* outside the current interval, the new one will be extended correspondingly.
*
* @param i -
* @param x -
*/
export const include = (i: Readonly<Interval>, x: number) =>
isAfter(i, x)
? new Interval(x, i.r, false, i.ropen)
: isBefore(i, x)
? new Interval(i.l, x, i.lopen, false)
: i.copy();
/**
* Returns the distance between intervals, or zero if they touch or
* overlap.
*
* @param a -
* @param b -
*/
export const distance = (a: Readonly<Interval>, b: Readonly<Interval>) =>
overlaps(a, b) ? 0 : a.l < b.l ? b.l - a.r : a.l - b.r;
/**
* Applies given `fn` to both sides of interval `i` and returns a new
* {@link Interval} of transformed end points.
*
* @param i -
* @param fn -
*/
export const transform = (i: Readonly<Interval>, fn: Fn<number, number>) =>
new Interval(fn(i.l), fn(i.r), i.lopen, i.ropen);
/**
* Returns classifier for interval `a` WRT given interval `b`. E.g.
* if the result is `Classifier.SUPERSET`, then interval `a` fully
* contains `b`.
*
* ```
* EQUIV
* [ a ]
* [ b ]
*
* DISJOINT_LEFT
* [ b ]
* [ a ]
*
* DISJOINT_RIGHT
* [ a ]
* [ b ]
*
* SUPERSET
* [ a ]
* [ b ]
*
* SUBSET
* [ b ]
* [ a ]
*
* OVERLAP_RIGHT
* [ a ]
* [ b ]
*
* OVERLAP_LEFT
* [ b ]
* [ a ]
* ```
*
* @param a -
* @param b -
*/
export const classify = (a: Readonly<Interval>, b: Readonly<Interval>) =>
a.equiv(b)
? Classifier.EQUIV
: isBefore(a, b)
? Classifier.DISJOINT_LEFT
: isAfter(a, b)
? Classifier.DISJOINT_RIGHT
: contains(a, b.l)
? contains(a, b.r)
? Classifier.SUPERSET
: Classifier.OVERLAP_RIGHT
: contains(a, b.r)
? Classifier.OVERLAP_LEFT
: Classifier.SUBSET;
/**
* Returns true if interval `a` intersects `b` in any way (incl.
* subset / superset).
*
* @param a -
* @param b -
*/
export const overlaps = (a: Readonly<Interval>, b: Readonly<Interval>) =>
classify(a, b) >= Classifier.EQUIV;
/**
* Returns the union of the two given intervals, taken their openness into
* account.
*
* @param a
* @param b
*/
export const union = (a: Readonly<Interval>, b: Readonly<Interval>) => {
if (isEmpty(a)) return b;
if (isEmpty(b)) return a;
const [l, lo] = $min(a.l, b.l, a.lopen, b.lopen, and);
const [r, ro] = $max(a.r, b.r, a.ropen, b.ropen, and);
return new Interval(l, r, lo, ro);
};
/**
* Returns the intersection of the two given intervals, taken their openness
* into account. Returns undefined if `a` and `b` don't overlap.
*
* @param a
* @param b
*/
export const intersection = (a: Readonly<Interval>, b: Readonly<Interval>) => {
if (overlaps(a, b)) {
const [l, lo] = $max(a.l, b.l, a.lopen, b.lopen, or);
const [r, ro] = $min(a.r, b.r, a.ropen, b.ropen, or);
return new Interval(l, r, lo, ro);
}
};
export const prefix = (a: Readonly<Interval>, b: Readonly<Interval>) => {
if (overlaps(a, b)) {
const [l, lo] = $min(a.l, b.l, a.lopen, b.lopen, or);
const [r, ro] = $min(a.r, b.l, a.ropen, b.lopen, or);
return new Interval(l, r, lo, ro);
}
};
export const suffix = (a: Readonly<Interval>, b: Readonly<Interval>) => {
if (overlaps(a, b)) {
const [l, lo] = $max(a.l, b.r, a.lopen, b.ropen, or);
const [r, ro] = $max(a.r, b.r, a.ropen, b.ropen, or);
return new Interval(l, r, lo, ro);
}
};
/**
* Returns the lesser value of either `x` or interval `i`'s RHS value. If
* the interval is open on the RHS, and `x >= r`, then `r - eps` will be
* returned.
*
* @param i -
* @param x -
* @param eps -
*/
export const min = (i: Readonly<Interval>, x: number, eps = DEFAULT_EPS) =>
i.ropen ? (x >= i.r ? i.r - eps : x) : x > i.r ? i.r : x;
/**
* Returns the greater value of either `x` or interval `i`'s LHS value. If
* the interval is open on the LHS, and `x <= l`, then `l + eps` will be
* returned.
*
* @param i -
* @param x -
* @param eps -
*/
export const max = (i: Readonly<Interval>, x: number, eps = DEFAULT_EPS) =>
i.lopen ? (x <= i.l ? i.l + eps : x) : x < i.l ? i.l : x;
/**
* Clamps `x` to interval `i`, using {@link Interval.min} and
* {@link Interval.max}.
*
* @param i -
* @param x -
* @param eps -
*/
export const clamp = (i: Readonly<Interval>, x: number, eps = DEFAULT_EPS) =>
min(i, max(i, x, eps), eps);
/** @internal */
const $min = (
a: number,
b: number,
ao: boolean,
bo: boolean,
op: Fn2<boolean, boolean, boolean>
) => $minmax(a < b, a, b, ao, bo, op);
/** @internal */
const $max = (
a: number,
b: number,
ao: boolean,
bo: boolean,
op: Fn2<boolean, boolean, boolean>
) => $minmax(a > b, a, b, ao, bo, op);
/** @internal */
const $minmax = (
test: boolean,
a: number,
b: number,
ao: boolean,
bo: boolean,
op: Fn2<boolean, boolean, boolean>
): [number, boolean] => (test ? [a, ao] : a === b ? [a, op(ao, bo)] : [b, bo]);
/** @internal */
const $toString = (l: number, r: number, lopen: boolean, ropen: boolean) =>
`${lopen ? "(" : "["}${l} .. ${r}${ropen ? ")" : "]"}`; | the_stack |
import { INumberDictionary, IStringDictionary } from "../../../../../shared/types";
import { FBXReaderNode } from "fbx-parser";
import {
Node, Matrix, AnimationGroup, Vector3, Quaternion, Animation,
Tools as BabylonTools, Bone, TransformNode,
} from "babylonjs";
import { FBXUtils } from "../utils";
import { IFBXLoaderRuntime } from "../loader";
import { IFBXConnections } from "../connections";
import { IFBXSkeleton } from "../mesh/skeleton";
interface IFBXAnimationCurve {
id: number;
times: number[];
values: number[];
}
interface IFBXAnimationRawCurveNode {
id: number;
attrName: string;
curves: IStringDictionary<IFBXAnimationCurve>;
}
interface IFBXLayerCurve {
id: number;
modelId: number;
modelName: string;
eulerOrder: string;
transform: Matrix;
T?: IFBXAnimationRawCurveNode;
R?: IFBXAnimationRawCurveNode;
S?: IFBXAnimationRawCurveNode;
}
interface IFBXClip {
name: string;
layers: IFBXLayerCurve[];
}
export class FBXAnimations {
/**
* Creates the animation groups available in the FBX file, ignored if no clip defined.
* @param runtime defines the reference to the current FBX runtime.
*/
public static ParseAnimationGroups(runtime: IFBXLoaderRuntime): void {
const animationCurveNodes = runtime.objects.nodes("AnimationCurve");
if (!animationCurveNodes.length) {
return;
}
const curveNodesMap = this._PrepareAnimationCurves(runtime.objects);
this._ParseAnimationCurves(runtime.objects, runtime.connections, curveNodesMap);
const layersMap = this._ParseAnimationLayers(runtime.objects, runtime.connections, runtime.cachedModels, runtime.cachedSkeletons, curveNodesMap);
const rawClips = this._ParseAnimationStacks(runtime.objects, runtime.connections, layersMap);
return this._CreateAnimationGroups(runtime, rawClips);
}
/**
* Creates the animation groups according to the given parsed clips.
*/
private static _CreateAnimationGroups(runtime: IFBXLoaderRuntime, clips: Map<number, IFBXClip>): void {
clips.forEach((c) => {
const animationGroup = new AnimationGroup(c.name, runtime.scene);
runtime.result.animationGroups.push(animationGroup);
c.layers.forEach((l) => {
this._AddClip(animationGroup, l, runtime.cachedModels, runtime.cachedSkeletons);
});
});
}
/**
* Adds the given clip to the animation group.
*/
private static _AddClip(animationGroup: AnimationGroup, layer: IFBXLayerCurve, cachedModels: INumberDictionary<Node>, cachedSkeletons: INumberDictionary<IFBXSkeleton>): void {
// Check targets
const targets = this._GetTargets(layer.modelId, cachedModels, cachedSkeletons);
if (!targets.length) {
return;
}
// Initial transform
let position = Vector3.Zero();
let rotation = Quaternion.Identity();
let scaling = Vector3.One();
if (layer.transform) {
layer.transform.decompose(scaling, rotation, position);
}
let initialPosition = position.asArray();
let initialRotation = rotation.toEulerAngles().asArray();
let initialScale = scaling.asArray();
// Position
if (layer.T && Object.keys(layer.T.curves).length > 0) {
const curves = layer.T.curves;
const positionTimes = this._GetTimes(curves);
const positions = this._GetKeyFrameAnimationValues(positionTimes, curves, initialPosition);
positions.forEach((p) => p.x = -p.x);
targets.forEach((t) => {
const animation = new Animation(`${t.name}.position`, "position", 1, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CYCLE, false);
animation.setKeys(positionTimes.map((t, index) => ({
frame: t,
value: positions[index],
})));
animationGroup.addTargetedAnimation(animation, t);
})
}
// Rotation
if (layer.R && Object.keys(layer.R.curves).length > 0) {
const curves = layer.R.curves;
if (curves.x !== undefined) {
this._InterpolateRotations(curves.x);
curves.x.values = curves.x.values.map((v) => BabylonTools.ToRadians(v));
}
if (curves.y !== undefined) {
this._InterpolateRotations(curves.y);
curves.y.values = curves.y.values.map((v) => BabylonTools.ToRadians(v));
}
if (curves.z !== undefined) {
this._InterpolateRotations(curves.z);
curves.z.values = curves.z.values.map((v) => BabylonTools.ToRadians(v));
}
const rotationTimes = this._GetTimes(curves);
const rotations = this._GetKeyFrameAnimationValues(rotationTimes, curves, initialRotation);
const rotationQuaternions = rotations.map((r) => FBXUtils.GetRotationQuaternionFromVector(r, layer.eulerOrder));
targets.forEach((t) => {
const animation = new Animation(`${t.name}.rotationQuaternion`, "rotationQuaternion", 1, Animation.ANIMATIONTYPE_QUATERNION, Animation.ANIMATIONLOOPMODE_CYCLE, false);
animation.setKeys(rotationTimes.map((t, index) => ({
frame: t,
value: rotationQuaternions[index],
})));
animationGroup.addTargetedAnimation(animation, t);
});
}
// Scaling
if (layer.S && Object.keys(layer.S.curves).length > 0) {
const curves = layer.S.curves;
const scalingTimes = this._GetTimes(curves);
const scalings = this._GetKeyFrameAnimationValues(scalingTimes, curves, initialScale);
targets.forEach((t) => {
const animation = new Animation(`${t.name}.scaling`, "scaling", 1, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CYCLE, false);
animation.setKeys(scalingTimes.map((t, index) => ({
frame: t,
value: scalings[index],
})));
animationGroup.addTargetedAnimation(animation, t);
});
}
}
/**
* Interpolates the given rotation curve.
*/
private static _InterpolateRotations(curve: IFBXAnimationCurve): void {
const inject = (a1: number[], index: number, a2: number[]) => {
return a1.slice(0, index).concat(a2).concat(a1.slice(index));
};
for (let i = 1; i < curve.values.length; i++) {
const initialValue = curve.values[i - 1];
const valuesSpan = curve.values[i] - initialValue;
const absoluteSpan = Math.abs(valuesSpan);
if (absoluteSpan >= 180) {
const numSubIntervals = absoluteSpan / 180;
const step = valuesSpan / numSubIntervals;
let nextValue = initialValue + step;
const initialTime = curve.times[i - 1];
const timeSpan = curve.times[i] - initialTime;
const interval = timeSpan / numSubIntervals;
let nextTime = initialTime + interval;
const interpolatedTimes: number[] = [];
const interpolatedValues: number[] = [];
while (nextTime < curve.times[i]) {
interpolatedTimes.push(nextTime);
nextTime += interval;
interpolatedValues.push(nextValue);
nextValue += step;
}
curve.times = inject(curve.times, i, interpolatedTimes);
curve.values = inject(curve.values, i, interpolatedValues);
}
}
}
/**
* Returns the animationt's values as Vector3.
*/
private static _GetKeyFrameAnimationValues(times: number[], curves: IStringDictionary<IFBXAnimationCurve>, initialValue: number[]): Vector3[] {
const values: number[] = [];
const prevValue = initialValue;
let xIndex = - 1;
let yIndex = - 1;
let zIndex = - 1;
times.forEach(function (time) {
if (curves.x) xIndex = curves.x.times.indexOf(time);
if (curves.y) yIndex = curves.y.times.indexOf(time);
if (curves.z) zIndex = curves.z.times.indexOf(time);
if (xIndex !== -1) {
const xValue = curves.x.values[xIndex];
values.push(xValue);
prevValue[0] = xValue;
} else {
values.push(prevValue[0]);
}
if (yIndex !== -1) {
const yValue = curves.y.values[yIndex];
values.push(yValue);
prevValue[1] = yValue;
} else {
values.push(prevValue[1]);
}
if (zIndex !== -1) {
const zValue = curves.z.values[zIndex];
values.push(zValue);
prevValue[2] = zValue;
} else {
values.push(prevValue[2]);
}
});
const result: Vector3[] = [];
for (let i = 0; i < values.length; i += 3) {
result.push(new Vector3(values[i], values[i + 1], values[i + 2]));
}
return result;
}
/**
* Noramlizes times for all axis.
*/
private static _GetTimes(curves: IStringDictionary<IFBXAnimationCurve>): number[] {
let times: number[] = [];
// first join together the times for each axis, if defined
if (curves.x !== undefined) times = times.concat(curves.x.times);
if (curves.y !== undefined) times = times.concat(curves.y.times);
if (curves.z !== undefined) times = times.concat(curves.z.times);
times = times.sort((a, b) => {
return a - b;
});
if (times.length > 1) {
let targetIndex = 1;
let lastValue = times[0];
for (let i = 1; i < times.length; i++) {
const currentValue = times[i];
if (currentValue !== lastValue) {
times[targetIndex] = currentValue;
lastValue = currentValue;
targetIndex++;
}
}
times = times.slice(0, targetIndex);
}
return times;
}
/**
* Parses the animation staks.
*/
private static _ParseAnimationStacks(objects: FBXReaderNode, connections: Map<number, IFBXConnections>, layersMap: Map<number, IFBXLayerCurve[]>): Map<number, IFBXClip> {
const rawClips = new Map<number, IFBXClip>();
const stackNodes = objects.nodes("AnimationStack");
for (const a of stackNodes) {
const id = a.prop(0, "number")!;
const children = connections.get(id)?.children;
if (!children) {
continue;
}
const layers = layersMap.get(children[0].id);
if (!layers) {
continue;
}
rawClips.set(id, {
layers,
name: a.prop(1, "string")!,
});
}
return rawClips;
}
/**
* Parses the animation layers.
*/
private static _ParseAnimationLayers(objects: FBXReaderNode, connections: Map<number, IFBXConnections>, cachedModels: INumberDictionary<Node>, cachedSkeletons: INumberDictionary<IFBXSkeleton>, curveNodesMap: Map<number, IFBXAnimationRawCurveNode>): Map<number, IFBXLayerCurve[]> {
const layersMap = new Map<number, IFBXLayerCurve[]>();
const animationLayerNodes = objects.nodes("AnimationLayer");
for (const a of animationLayerNodes) {
const id = a.prop(0, "number")!;
const layerCurveNodes: IFBXLayerCurve[] = [];
const connection = connections.get(id);
if (!connection?.children.length) {
continue;
}
connection.children.forEach((c, index) => {
const curveNode = curveNodesMap.get(c.id);
if (!curveNode) {
return;
}
if (!curveNode.curves.x && !curveNode.curves.y && !curveNode.curves.z) {
return;
}
if (!layerCurveNodes[index]) {
const modelId = connections.get(c.id)!.parents.filter(function (parent) {
return parent.relationship !== undefined;
})[0].id;
if (modelId !== undefined) {
const model = objects.nodes("Model").find((m) => m.prop(0, "number") === modelId);
if (!model) {
return;
}
const nodeId = model.prop(0, "number")!;
const modelName = model.prop(1, "string")!;
const modelRef = this._GetTargets(nodeId, cachedModels, cachedSkeletons)[0];
let transform = Matrix.Identity();
if (modelRef) {
if (modelRef instanceof Bone) {
transform = modelRef.getRestPose().clone();
} else if (modelRef instanceof TransformNode) {
transform = modelRef._localMatrix.clone();
}
}
const node: IFBXLayerCurve = {
modelId,
transform,
modelName,
id: nodeId,
eulerOrder: modelRef?.metadata?.transformData?.eulerOrder ?? "ZYX",
};
layerCurveNodes[index] = node;
}
}
if (layerCurveNodes[index]) {
layerCurveNodes[index][curveNode.attrName] = curveNode;
}
});
layersMap.set(id, layerCurveNodes);
}
return layersMap;
}
/**
* Returns the list of all animation targets for the given id.
*/
private static _GetTargets(id: number, cachedModels: INumberDictionary<Node>, cachedSkeletons: INumberDictionary<IFBXSkeleton>): (TransformNode | Bone)[] {
const target = cachedModels[id];
if (target && target instanceof TransformNode) {
return [target];
}
// Check shared bones
const targets: (TransformNode | Bone)[] = [];
for (const skeletonId in cachedSkeletons) {
const skeleton = cachedSkeletons[skeletonId];
const targetBone = skeleton.skeletonInstance.bones.find((b) => b.id === id.toString());
if (targetBone) {
targets.push(targetBone);
}
}
return targets;
}
/**
* Parses the animation curves.
*/
private static _ParseAnimationCurves(objects: FBXReaderNode, connections: Map<number, IFBXConnections>, curveNodesMap: Map<number, IFBXAnimationRawCurveNode>): void {
const animationCurves = objects.nodes("AnimationCurve");
for (const a of animationCurves) {
const id = a.prop(0, "number")!;
const animationCurve: IFBXAnimationCurve = {
id,
times: a.node("KeyTime")!.prop(0, "number[]")!.map((t) => t / 46186158000),
values: a.node("KeyValueFloat")!.prop(0, "number[]")!,
};
const relationships = connections.get(animationCurve.id);
if (!relationships?.parents?.[0].relationship) {
continue;
}
const animationCurveId = relationships.parents[0].id;
const animationCurveRelationship = relationships.parents[0].relationship;
const curveNode = curveNodesMap.get(animationCurveId);
if (!curveNode) {
continue;
}
if (animationCurveRelationship.match(/X/)) {
curveNode.curves["x"] = animationCurve;
} else if (animationCurveRelationship.match(/Y/)) {
curveNode.curves['y'] = animationCurve;
} else if (animationCurveRelationship.match(/Z/)) {
curveNode.curves['z'] = animationCurve;
} else if (animationCurveRelationship.match(/d|DeformPercent/) && curveNodesMap.has(animationCurveId)) {
curveNode.curves['morph'] = animationCurve;
}
}
}
/**
* Prepares parsing the animation curves.
*/
private static _PrepareAnimationCurves(objects: FBXReaderNode): Map<number, IFBXAnimationRawCurveNode> {
const map = new Map<number, IFBXAnimationRawCurveNode>();
const animationCurveNodes = objects.nodes("AnimationCurveNode");
if (!animationCurveNodes.length) {
return map;
}
animationCurveNodes.forEach((cvn) => {
const attrName = cvn.prop(1, "string")!.replace("AnimCurveNode::", "");
if (attrName.match(/S|R|T|DeformPercent/) !== null) {
const id = cvn.prop(0, "number")!;
map.set(id, { id, attrName, curves: {} });
}
});
return map;
}
} | the_stack |
import { IStorage } from "../interfaces/IStorage";
import { DropErc721ContractSchema } from "../../schema/contracts/drop-erc721";
import { ContractMetadata } from "./contract-metadata";
import { DropERC1155, IERC20, IERC20__factory } from "contracts";
import { BigNumber, BigNumberish, constants, ethers } from "ethers";
import { isNativeToken } from "../../common/currency";
import { ContractWrapper } from "./contract-wrapper";
import { ClaimCondition, ClaimConditionInput } from "../../types";
import deepEqual from "fast-deep-equal";
import { ClaimEligibility } from "../../enums";
import { TransactionResult } from "../index";
import {
getClaimerProofs,
processClaimConditionInputs,
transformResultToClaimCondition,
updateExistingClaimConditions,
} from "../../common/claim-conditions";
import { includesErrorMessage } from "../../common";
import { isNode } from "../../common/utils";
/**
* Manages claim conditions for Edition Drop contracts
* @public
*/
export class DropErc1155ClaimConditions {
private contractWrapper;
private metadata;
private storage: IStorage;
constructor(
contractWrapper: ContractWrapper<DropERC1155>,
metadata: ContractMetadata<DropERC1155, typeof DropErc721ContractSchema>,
storage: IStorage,
) {
this.storage = storage;
this.contractWrapper = contractWrapper;
this.metadata = metadata;
}
/** ***************************************
* READ FUNCTIONS
*****************************************/
/**
* Get the currently active claim condition
*
* @returns the claim condition metadata
*/
public async getActive(tokenId: BigNumberish): Promise<ClaimCondition> {
const id =
await this.contractWrapper.readContract.getActiveClaimConditionId(
tokenId,
);
const mc = await this.contractWrapper.readContract.getClaimConditionById(
tokenId,
id,
);
const metadata = await this.metadata.get();
return await transformResultToClaimCondition(
mc,
0,
this.contractWrapper.getProvider(),
metadata.merkle,
this.storage,
);
}
/**
* Get all the claim conditions
*
* @returns the claim conditions metadata
*/
public async getAll(tokenId: BigNumberish): Promise<ClaimCondition[]> {
const claimCondition =
await this.contractWrapper.readContract.claimCondition(tokenId);
const startId = claimCondition.currentStartId.toNumber();
const count = claimCondition.count.toNumber();
const conditions = [];
for (let i = startId; i < startId + count; i++) {
conditions.push(
await this.contractWrapper.readContract.getClaimConditionById(
tokenId,
i,
),
);
}
const metadata = await this.metadata.get();
return Promise.all(
conditions.map((c) =>
transformResultToClaimCondition(
c,
0,
this.contractWrapper.getProvider(),
metadata.merkle,
this.storage,
),
),
);
}
/**
* Can Claim
*
* @remarks Check if a particular NFT can currently be claimed by a given user.
*
* @example
* ```javascript
* // Quantity of tokens to check claimability of
* const quantity = 1;
* const canClaim = await contract.canClaim(quantity);
* ```
*/
public async canClaim(
tokenId: BigNumberish,
quantity: BigNumberish,
addressToCheck?: string,
): Promise<boolean> {
// TODO switch to use verifyClaim
return (
(
await this.getClaimIneligibilityReasons(
tokenId,
quantity,
addressToCheck,
)
).length === 0
);
}
/**
* For any claim conditions that a particular wallet is violating,
* this function returns human-readable information about the
* breaks in the condition that can be used to inform the user.
*
* @param tokenId - the token id to check
* @param quantity - The desired quantity that would be claimed.
* @param addressToCheck - The wallet address, defaults to the connected wallet.
*
*/
public async getClaimIneligibilityReasons(
tokenId: BigNumberish,
quantity: BigNumberish,
addressToCheck?: string,
): Promise<ClaimEligibility[]> {
const reasons: ClaimEligibility[] = [];
let activeConditionIndex: BigNumber;
let claimCondition: ClaimCondition;
if (addressToCheck === undefined) {
try {
addressToCheck = await this.contractWrapper.getSignerAddress();
} catch (err) {
console.warn("failed to get signer address", err);
}
}
// if we have been unable to get a signer address, we can't check eligibility, so return a NoWallet error reason
if (!addressToCheck) {
return [ClaimEligibility.NoWallet];
}
try {
[activeConditionIndex, claimCondition] = await Promise.all([
this.contractWrapper.readContract.getActiveClaimConditionId(tokenId),
this.getActive(tokenId),
]);
} catch (err: any) {
if (
includesErrorMessage(err, "!CONDITION") ||
includesErrorMessage(err, "no active mint condition")
) {
reasons.push(ClaimEligibility.NoClaimConditionSet);
return reasons;
}
reasons.push(ClaimEligibility.Unknown);
return reasons;
}
if (claimCondition.availableSupply !== "unlimited") {
if (BigNumber.from(claimCondition.availableSupply).lt(quantity)) {
reasons.push(ClaimEligibility.NotEnoughSupply);
}
}
// check for merkle root inclusion
const merkleRootArray = ethers.utils.stripZeros(
claimCondition.merkleRootHash,
);
if (merkleRootArray.length > 0) {
const merkleLower = claimCondition.merkleRootHash.toString();
const metadata = await this.metadata.get();
const proofs = await getClaimerProofs(
addressToCheck,
merkleLower,
0,
metadata.merkle,
this.storage,
);
try {
const [validMerkleProof] =
await this.contractWrapper.readContract.verifyClaimMerkleProof(
activeConditionIndex,
addressToCheck,
tokenId,
quantity,
proofs.proof,
proofs.maxClaimable,
);
if (!validMerkleProof) {
reasons.push(ClaimEligibility.AddressNotAllowed);
return reasons;
}
} catch (e) {
reasons.push(ClaimEligibility.AddressNotAllowed);
return reasons;
}
}
// check for claim timestamp between claims
const [lastClaimedTimestamp, timestampForNextClaim] =
await this.contractWrapper.readContract.getClaimTimestamp(
tokenId,
activeConditionIndex,
addressToCheck,
);
const now = BigNumber.from(Date.now()).div(1000);
if (lastClaimedTimestamp.gt(0) && now.lt(timestampForNextClaim)) {
// contract will return MaxUint256 if user has already claimed and cannot claim again
if (timestampForNextClaim.eq(constants.MaxUint256)) {
reasons.push(ClaimEligibility.AlreadyClaimed);
} else {
reasons.push(ClaimEligibility.WaitBeforeNextClaimTransaction);
}
}
// if not within a browser conetext, check for wallet balance.
// In browser context, let the wallet do that job
if (claimCondition.price.gt(0) && isNode()) {
const totalPrice = claimCondition.price.mul(quantity);
const provider = this.contractWrapper.getProvider();
if (isNativeToken(claimCondition.currencyAddress)) {
const balance = await provider.getBalance(addressToCheck);
if (balance.lt(totalPrice)) {
reasons.push(ClaimEligibility.NotEnoughTokens);
}
} else {
const erc20 = new ContractWrapper<IERC20>(
provider,
claimCondition.currencyAddress,
IERC20__factory.abi,
{},
);
const balance = await erc20.readContract.balanceOf(addressToCheck);
if (balance.lt(totalPrice)) {
reasons.push(ClaimEligibility.NotEnoughTokens);
}
}
}
return reasons;
}
/** ***************************************
* WRITE FUNCTIONS
*****************************************/
/**
* Set claim conditions on a single NFT
*
* @remarks Sets the public mint conditions that need to be fulfilled by users to claim a particular NFT in this contract.
*
* @example
* ```javascript
* const presaleStartTime = new Date();
* const publicSaleStartTime = new Date(Date.now() + 60 * 60 * 24 * 1000);
* const claimConditions = [
* {
* startTime: presaleStartTime, // start the presale now
* maxQuantity: 2, // limit how many mints for this presale
* price: 0.01, // presale price
* snapshot: ['0x...', '0x...'], // limit minting to only certain addresses
* },
* {
* startTime: publicSaleStartTime, // 24h after presale, start public sale
* price: 0.08, // public sale price
* }
* ]);
*
* const tokenId = 0; // the id of the NFT to set claim conditions on
* await dropContract.claimConditions.set(tokenId, claimConditions);
* ```
*
* @param tokenId - The id of the NFT to set the claim conditions on
* @param claimConditionInputs - The claim conditions
* @param resetClaimEligibilityForAll - Whether to reset the state of who already claimed NFTs previously
*/
public async set(
tokenId: BigNumberish,
claimConditionInputs: ClaimConditionInput[],
resetClaimEligibilityForAll = false,
): Promise<TransactionResult> {
return this.setBatch(
[tokenId],
claimConditionInputs,
resetClaimEligibilityForAll,
);
}
/**
* Set claim conditions on multiple NFTs at once
*
* @remarks Sets the claim conditions that need to be fulfilled by users to claim the given NFTs in this contract.
*
* @example
* ```javascript
* const presaleStartTime = new Date();
* const publicSaleStartTime = new Date(Date.now() + 60 * 60 * 24 * 1000);
* const claimConditions = [
* {
* startTime: presaleStartTime, // start the presale now
* maxQuantity: 2, // limit how many mints for this presale
* price: 0.01, // presale price
* snapshot: ['0x...', '0x...'], // limit minting to only certain addresses
* },
* {
* startTime: publicSaleStartTime, // 24h after presale, start public sale
* price: 0.08, // public sale price
* }
* ]);
*
* const tokenIds = [0,1,2]; // the ids of the NFTs to set claim conditions on
* await dropContract.claimConditions.setBatch(tokenIds, claimConditions);
* ```
*
* @param tokenIds - the token ids to set the claim conditions on
* @param claimConditionInputs - The claim conditions
* @param resetClaimEligibilityForAll - Whether to reset the state of who already claimed NFTs previously
*/
public async setBatch(
tokenIds: BigNumberish[],
claimConditionInputs: ClaimConditionInput[],
resetClaimEligibilityForAll = false,
) {
// process inputs
const { snapshotInfos, sortedConditions } =
await processClaimConditionInputs(
claimConditionInputs,
0,
this.contractWrapper.getProvider(),
this.storage,
);
const merkleInfo: { [key: string]: string } = {};
snapshotInfos.forEach((s) => {
merkleInfo[s.merkleRoot] = s.snapshotUri;
});
const metadata = await this.metadata.get();
const encoded = [];
// keep the old merkle roots from other tokenIds
for (const key of Object.keys(metadata.merkle)) {
merkleInfo[key] = metadata.merkle[key];
}
// upload new merkle roots to snapshot URIs if updated
if (!deepEqual(metadata.merkle, merkleInfo)) {
const mergedMetadata = this.metadata.parseInputMetadata({
...metadata,
merkle: merkleInfo,
});
// using internal method to just upload, avoids one contract call
const contractURI = await this.metadata._parseAndUploadMetadata(
mergedMetadata,
);
encoded.push(
this.contractWrapper.readContract.interface.encodeFunctionData(
"setContractURI",
[contractURI],
),
);
}
tokenIds.forEach((tokenId) => {
encoded.push(
this.contractWrapper.readContract.interface.encodeFunctionData(
"setClaimConditions",
[tokenId, sortedConditions, resetClaimEligibilityForAll],
),
);
});
return {
receipt: await this.contractWrapper.multiCall(encoded),
};
}
/**
* Update a single claim condition with new data.
* @param tokenId - the token id to update
* @param index - the index of the claim condition to update, as given by the index from the result of `getAll()`
* @param claimConditionInput - the new data to update, previous data will be retained
*/
public async update(
tokenId: BigNumberish,
index: number,
claimConditionInput: ClaimConditionInput,
): Promise<TransactionResult> {
const existingConditions = await this.getAll(tokenId);
const newConditionInputs = await updateExistingClaimConditions(
index,
claimConditionInput,
existingConditions,
);
return await this.set(tokenId, newConditionInputs);
}
} | the_stack |
import * as d3 from "d3";
import {Component} from "../components/component";
import {Point} from "../core/interfaces";
import * as Dispatchers from "../dispatchers";
import * as Scales from "../scales";
import {TransformableScale} from "../scales/scale";
import * as Utils from "../utils";
import * as Interactions from "./";
import {Interaction} from "./interaction";
import { constrainedTranslation, constrainedZoom } from "./panZoomConstraints";
export type PanCallback = () => void;
export type ZoomCallback = () => void;
export type PanZoomUpdateCallback = () => void;
export type WheelFilter = (wheelEvent: WheelEvent) => boolean;
export class PanZoom extends Interaction {
/**
* The number of pixels occupied in a line.
*/
private static _PIXELS_PER_LINE = 120;
private _xScales: Utils.Set<TransformableScale<any, number>>;
private _yScales: Utils.Set<TransformableScale<any, number>>;
private _dragInteraction: Interactions.Drag;
private _mouseDispatcher: Dispatchers.Mouse;
private _touchDispatcher: Dispatchers.Touch;
private _wheelFilter: WheelFilter = (e: WheelEvent) => true;
private _touchIds: d3.Map<Point>;
private _wheelCallback = (p: Point, e: WheelEvent) => this._handleWheelEvent(p, e);
private _touchStartCallback = (ids: number[], idToPoint: Point[], e: TouchEvent) => this._handleTouchStart(ids, idToPoint, e);
private _touchMoveCallback = (ids: number[], idToPoint: Point[], e: TouchEvent) => this._handlePinch(ids, idToPoint, e);
private _touchEndCallback = (ids: number[], idToPoint: Point[], e: TouchEvent) => this._handleTouchEnd(ids, idToPoint, e);
private _touchCancelCallback = (ids: number[], idToPoint: Point[], e: TouchEvent) => this._handleTouchEnd(ids, idToPoint, e);
private _minDomainExtents: Utils.Map<TransformableScale<any, number>, any>;
private _maxDomainExtents: Utils.Map<TransformableScale<any, number>, any>;
private _minDomainValues: Utils.Map<TransformableScale<any, number>, any>;
private _maxDomainValues: Utils.Map<TransformableScale<any, number>, any>;
private _panEndCallbacks = new Utils.CallbackSet<PanCallback>();
private _zoomEndCallbacks = new Utils.CallbackSet<ZoomCallback>();
private _panZoomUpdateCallbacks = new Utils.CallbackSet<PanZoomUpdateCallback>();
/**
* A PanZoom Interaction updates the domains of an x-scale and/or a y-scale
* in response to the user panning or zooming.
*
* @constructor
* @param {TransformableScale} [xScale] The x-scale to update on panning/zooming.
* @param {TransformableScale} [yScale] The y-scale to update on panning/zooming.
*/
constructor(xScale?: TransformableScale<any, number>, yScale?: TransformableScale<any, number>) {
super();
this._xScales = new Utils.Set<TransformableScale<any, number>>();
this._yScales = new Utils.Set<TransformableScale<any, number>>();
this._dragInteraction = new Interactions.Drag();
this._setupDragInteraction();
this._touchIds = d3.map<Point>();
this._minDomainExtents = new Utils.Map<TransformableScale<any, number>, number>();
this._maxDomainExtents = new Utils.Map<TransformableScale<any, number>, number>();
this._minDomainValues = new Utils.Map<TransformableScale<any, number>, any>();
this._maxDomainValues = new Utils.Map<TransformableScale<any, number>, any>();
if (xScale != null) {
this.addXScale(xScale);
}
if (yScale != null) {
this.addYScale(yScale);
}
}
/**
* Get the backing drag interaction. Useful to customize the panzoom interaction.
* @returns {Drag}
*/
public dragInteraction(): Interactions.Drag {
return this._dragInteraction;
}
/**
* Get the current mouse wheel filter.
* @returns {WheelFilter}
*/
public wheelFilter(): WheelFilter;
/** Set the current mouse wheel filter. PanZoomInteraction will only zoom
* when the wheelFilter evaluates to true for the source wheel event. Use
* this to define custom filters (e.g. requires shift to be held down.)
*/
public wheelFilter(filter: WheelFilter): this;
public wheelFilter(filter?: WheelFilter) {
if (arguments.length === 0) {
return this._wheelFilter;
}
this._wheelFilter = filter;
return this;
}
/**
* Pans the chart by a specified amount
*
* @param {Plottable.Point} [translateAmount] The amount by which to translate the x and y scales.
*/
public pan(translateAmount: Point) {
this.xScales().forEach((xScale) => {
xScale.pan(this._constrainedTranslation(xScale, translateAmount.x));
});
this.yScales().forEach((yScale) => {
yScale.pan(this._constrainedTranslation(yScale, translateAmount.y));
});
this._panZoomUpdateCallbacks.callCallbacks();
}
/**
* Zooms the chart by a specified amount around a specific point
*
* @param {number} [zoomAmount] The percentage by which to zoom the x and y scale.
* A value of 0.9 zooms in by 10%. A value of 1.1 zooms out by 10%. A value of 1 has
* no effect.
* @param {Plottable.Point} [centerValue] The center in pixels around which to zoom.
* By default, `centerValue` is the center of the x and y range of each scale.
* @param {boolean} [constrained] Whether to respect the zoom extents and min/max
* values. Default true.
*/
public zoom(zoomAmount: number, centerValue?: Point, constrained = true) {
let centerX: number;
let centerY: number;
if (centerValue != null) {
centerX = centerValue.x;
centerY = centerValue.y;
if (constrained) {
this.xScales().forEach((xScale) => {
const constrained = this._constrainedZoom(xScale, zoomAmount, centerX);
centerX = constrained.centerPoint;
zoomAmount = constrained.zoomAmount;
});
this.yScales().forEach((yScale) => {
const constrained = this._constrainedZoom(yScale, zoomAmount, centerY);
centerY = constrained.centerPoint;
zoomAmount = constrained.zoomAmount;
});
}
}
this.xScales().forEach((xScale) => {
const range = xScale.range();
const xCenter = centerX == null
? (range[1] + range[0]) / 2
: centerX;
xScale.zoom(zoomAmount, xCenter);
});
this.yScales().forEach((yScale) => {
const range = yScale.range();
const yCenter = centerY == null
? (range[1] + range[0]) / 2
: centerY;
yScale.zoom(zoomAmount, yCenter);
});
this._panZoomUpdateCallbacks.callCallbacks();
return { zoomAmount, centerValue: { centerX, centerY } };
}
protected _anchor(component: Component) {
super._anchor(component);
this._dragInteraction.attachTo(component);
this._mouseDispatcher = Dispatchers.Mouse.getDispatcher(this._componentAttachedTo);
this._mouseDispatcher.onWheel(this._wheelCallback);
this._touchDispatcher = Dispatchers.Touch.getDispatcher(this._componentAttachedTo);
this._touchDispatcher.onTouchStart(this._touchStartCallback);
this._touchDispatcher.onTouchMove(this._touchMoveCallback);
this._touchDispatcher.onTouchEnd(this._touchEndCallback);
this._touchDispatcher.onTouchCancel(this._touchCancelCallback);
}
protected _unanchor() {
super._unanchor();
this._mouseDispatcher.offWheel(this._wheelCallback);
this._mouseDispatcher = null;
this._touchDispatcher.offTouchStart(this._touchStartCallback);
this._touchDispatcher.offTouchMove(this._touchMoveCallback);
this._touchDispatcher.offTouchEnd(this._touchEndCallback);
this._touchDispatcher.offTouchCancel(this._touchCancelCallback);
this._touchDispatcher = null;
this._dragInteraction.detach();
}
private _handleTouchStart(ids: number[], idToPoint: { [id: number]: Point; }, e: TouchEvent) {
for (let i = 0; i < ids.length && this._touchIds.size() < 2; i++) {
const id = ids[i];
this._touchIds.set(id.toString(), this._translateToComponentSpace(idToPoint[id]));
}
}
private _handlePinch(ids: number[], idToPoint: { [id: number]: Point; }, e: TouchEvent) {
if (this._touchIds.size() < 2) {
return;
}
const oldPoints = this._touchIds.values();
if (!this._isInsideComponent(this._translateToComponentSpace(oldPoints[0])) || !this._isInsideComponent(this._translateToComponentSpace(oldPoints[1]))) {
return;
}
const oldCornerDistance = PanZoom._pointDistance(oldPoints[0], oldPoints[1]);
if (oldCornerDistance === 0) {
return;
}
ids.forEach((id) => {
if (this._touchIds.has(id.toString())) {
this._touchIds.set(id.toString(), this._translateToComponentSpace(idToPoint[id]));
}
});
const points = this._touchIds.values();
const newCornerDistance = PanZoom._pointDistance(points[0], points[1]);
if (newCornerDistance === 0) {
return;
}
const initMagnifyAmount = oldCornerDistance / newCornerDistance;
const normalizedPointDiffs = points.map((point, i) => {
return {
x: (point.x - oldPoints[i].x) / initMagnifyAmount,
y: (point.y - oldPoints[i].y) / initMagnifyAmount,
};
});
const oldCenterPoint = PanZoom.centerPoint(oldPoints[0], oldPoints[1]);
const { centerValue, zoomAmount } = this.zoom(initMagnifyAmount, oldCenterPoint);
const { centerX, centerY } = centerValue;
const constrainedPoints = oldPoints.map((oldPoint, i) => {
return {
x: normalizedPointDiffs[i].x * zoomAmount + oldPoint.x,
y: normalizedPointDiffs[i].y * zoomAmount + oldPoint.y,
};
});
const translateAmount = {
x: centerX - ((constrainedPoints[0].x + constrainedPoints[1].x) / 2),
y: centerY - ((constrainedPoints[0].y + constrainedPoints[1].y) / 2),
};
this.pan(translateAmount);
}
public static centerPoint(point1: Point, point2: Point) {
const leftX = Math.min(point1.x, point2.x);
const rightX = Math.max(point1.x, point2.x);
const topY = Math.min(point1.y, point2.y);
const bottomY = Math.max(point1.y, point2.y);
return { x: (leftX + rightX) / 2, y: (bottomY + topY) / 2 };
}
private static _pointDistance(point1: Point, point2: Point) {
const leftX = Math.min(point1.x, point2.x);
const rightX = Math.max(point1.x, point2.x);
const topY = Math.min(point1.y, point2.y);
const bottomY = Math.max(point1.y, point2.y);
return Math.sqrt(Math.pow(rightX - leftX, 2) + Math.pow(bottomY - topY, 2));
}
private _handleTouchEnd(ids: number[], idToPoint: { [id: number]: Point; }, e: TouchEvent) {
ids.forEach((id) => {
this._touchIds.remove(id.toString());
});
if (this._touchIds.size() > 0) {
this._zoomEndCallbacks.callCallbacks();
}
}
private _handleWheelEvent(p: Point, e: WheelEvent) {
if (!this._wheelFilter(e)) {
return;
}
const translatedP = this._translateToComponentSpace(p);
if (this._isInsideComponent(translatedP)) {
e.preventDefault();
// in cases where only horizontal scroll is present, use that in lieu of nothing.
const deltaAmount = e.deltaY !== 0 ? e.deltaY : e.deltaX;
const deltaPixelAmount = deltaAmount * (e.deltaMode ? PanZoom._PIXELS_PER_LINE : 1);
const zoomAmount = Math.pow(2, deltaPixelAmount * .002);
this.zoom(zoomAmount, translatedP);
this._zoomEndCallbacks.callCallbacks();
}
}
private _constrainedZoom(scale: TransformableScale<any, number>, zoomAmount: number, centerPoint: number) {
return constrainedZoom(
scale,
zoomAmount,
centerPoint,
this.minDomainExtent(scale),
this.maxDomainExtent(scale),
this.minDomainValue(scale),
this.maxDomainValue(scale),
);
}
private _constrainedTranslation(scale: TransformableScale<any, number>, translation: number) {
return constrainedTranslation(scale, translation, this.minDomainValue(scale), this.maxDomainValue(scale));
}
private _setupDragInteraction() {
this._dragInteraction.constrainedToComponent(false);
let lastDragPoint: Point;
this._dragInteraction.onDragStart(() => lastDragPoint = null);
this._dragInteraction.onDrag((startPoint, endPoint) => {
if (this._touchIds.size() >= 2) {
return;
}
const translateAmount = {
x: (lastDragPoint == null ? startPoint.x : lastDragPoint.x) - endPoint.x,
y: (lastDragPoint == null ? startPoint.y : lastDragPoint.y) - endPoint.y,
};
this.pan(translateAmount);
lastDragPoint = endPoint;
});
this._dragInteraction.onDragEnd(() => this._panEndCallbacks.callCallbacks());
}
private _nonLinearScaleWithExtents(scale: TransformableScale<any, number>) {
return this.minDomainExtent(scale) != null && this.maxDomainExtent(scale) != null && !(scale instanceof Scales.Linear) && !(scale instanceof Scales.Time);
}
/**
* Gets the x scales for this PanZoom Interaction.
*/
public xScales(): TransformableScale<any, number>[];
/**
* Sets the x scales for this PanZoom Interaction.
*
* @returns {Interactions.PanZoom} The calling PanZoom Interaction.
*/
public xScales(xScales: TransformableScale<any, number>[]): this;
public xScales(xScales?: TransformableScale<any, number>[]): any {
if (xScales == null) {
const scales: TransformableScale<any, number>[] = [];
this._xScales.forEach((xScale) => {
scales.push(xScale);
});
return scales;
}
this._xScales = new Utils.Set<TransformableScale<any, number>>();
xScales.forEach((xScale) => {
this.addXScale(xScale);
});
return this;
}
/**
* Gets the y scales for this PanZoom Interaction.
*/
public yScales(): TransformableScale<any, number>[];
/**
* Sets the y scales for this PanZoom Interaction.
*
* @returns {Interactions.PanZoom} The calling PanZoom Interaction.
*/
public yScales(yScales: TransformableScale<any, number>[]): this;
public yScales(yScales?: TransformableScale<any, number>[]): any {
if (yScales == null) {
const scales: TransformableScale<any, number>[] = [];
this._yScales.forEach((yScale) => {
scales.push(yScale);
});
return scales;
}
this._yScales = new Utils.Set<TransformableScale<any, number>>();
yScales.forEach((yScale) => {
this.addYScale(yScale);
});
return this;
}
/**
* Adds an x scale to this PanZoom Interaction
*
* @param {TransformableScale} An x scale to add
* @returns {Interactions.PanZoom} The calling PanZoom Interaction.
*/
public addXScale(xScale: TransformableScale<any, number>) {
this._xScales.add(xScale);
return this;
}
/**
* Removes an x scale from this PanZoom Interaction
*
* @param {TransformableScale} An x scale to remove
* @returns {Interactions.PanZoom} The calling PanZoom Interaction.
*/
public removeXScale(xScale: TransformableScale<any, number>) {
this._xScales.delete(xScale);
this._minDomainExtents.delete(xScale);
this._maxDomainExtents.delete(xScale);
this._minDomainValues.delete(xScale);
this._maxDomainValues.delete(xScale);
return this;
}
/**
* Adds a y scale to this PanZoom Interaction
*
* @param {TransformableScale} A y scale to add
* @returns {Interactions.PanZoom} The calling PanZoom Interaction.
*/
public addYScale(yScale: TransformableScale<any, number>) {
this._yScales.add(yScale);
return this;
}
/**
* Removes a y scale from this PanZoom Interaction
*
* @param {TransformableScale} A y scale to remove
* @returns {Interactions.PanZoom} The calling PanZoom Interaction.
*/
public removeYScale(yScale: TransformableScale<any, number>) {
this._yScales.delete(yScale);
this._minDomainExtents.delete(yScale);
this._maxDomainExtents.delete(yScale);
this._minDomainValues.delete(yScale);
this._maxDomainValues.delete(yScale);
return this;
}
/**
* Gets the minimum domain extent for the scale, specifying the minimum
* allowable amount between the ends of the domain.
*
* Note that extents will mainly work on scales that work linearly like
* Linear Scale and Time Scale
*
* @param {TransformableScale} scale The scale to query
* @returns {number} The minimum numerical domain extent for the scale.
*/
public minDomainExtent(scale: TransformableScale<any, number>): number;
/**
* Sets the minimum domain extent for the scale, specifying the minimum
* allowable amount between the ends of the domain.
*
* Note that extents will mainly work on scales that work linearly like
* Linear Scale and Time Scale
*
* @param {TransformableScale} scale The scale to query
* @param {number} minDomainExtent The minimum numerical domain extent for
* the scale.
* @returns {Interactions.PanZoom} The calling PanZoom Interaction.
*/
public minDomainExtent(scale: TransformableScale<any, number>, minDomainExtent: number): this;
public minDomainExtent(scale: TransformableScale<any, number>, minDomainExtent?: number): number | this {
if (minDomainExtent == null) {
return this._minDomainExtents.get(scale);
}
if (minDomainExtent.valueOf() < 0) {
throw new Error("extent must be non-negative");
}
const maxExtentForScale = this.maxDomainExtent(scale);
if (maxExtentForScale != null && maxExtentForScale.valueOf() < minDomainExtent.valueOf()) {
throw new Error("minDomainExtent must be smaller than maxDomainExtent for the same Scale");
}
if (this._nonLinearScaleWithExtents(scale)) {
Utils.Window.warn("Panning and zooming with extents on a nonlinear scale may have unintended behavior.");
}
this._minDomainExtents.set(scale, minDomainExtent);
return this;
}
/**
* Gets the maximum domain extent for the scale, specifying the maximum
* allowable amount between the ends of the domain.
*
* Note that extents will mainly work on scales that work linearly like
* Linear Scale and Time Scale
*
* @param {TransformableScale} scale The scale to query
* @returns {number} The maximum numerical domain extent for the scale.
*/
public maxDomainExtent(scale: TransformableScale<any, number>): number;
/**
* Sets the maximum domain extent for the scale, specifying the maximum
* allowable amount between the ends of the domain.
*
* For example, if the scale's transformation domain is `[500, 600]` and the
* `maxDomainExtent` is set to `50`, then the user will only be able to zoom
* out to see an interval like `[500, 550]` or `[520, 570]`.
*
* Note that extents will mainly work on scales that work linearly like
* Linear Scale and Time Scale
*
* @param {TransformableScale} scale The scale to query
* @param {number} minDomainExtent The maximum numerical domain extent for
* the scale.
* @returns {Interactions.PanZoom} The calling PanZoom Interaction.
*/
public maxDomainExtent(scale: TransformableScale<any, number>, maxDomainExtent: number): this;
public maxDomainExtent(scale: TransformableScale<any, number>, maxDomainExtent?: number): number | this {
if (maxDomainExtent == null) {
return this._maxDomainExtents.get(scale);
}
if (maxDomainExtent.valueOf() <= 0) {
throw new Error("extent must be positive");
}
const minExtentForScale = this.minDomainExtent(scale);
if (minExtentForScale != null && maxDomainExtent.valueOf() < minExtentForScale.valueOf()) {
throw new Error("maxDomainExtent must be larger than minDomainExtent for the same Scale");
}
if (this._nonLinearScaleWithExtents(scale)) {
Utils.Window.warn("Panning and zooming with extents on a nonlinear scale may have unintended behavior.");
}
this._maxDomainExtents.set(scale, maxDomainExtent);
return this;
}
/**
* Gets the minimum domain value for the scale, constraining the pan/zoom
* interaction to a minimum value in the domain.
*
* Note that this differs from minDomainExtent/maxDomainExtent, in that
* those methods provide constraints such as showing at least 2 but no more
* than 5 values at a time.
*
* By contrast, minDomainValue/maxDomainValue set a boundary beyond which
* the user cannot pan/zoom.
*
* @param {TransformableScale} scale The scale to query
* @returns {number} The minimum domain value for the scale.
*/
public minDomainValue(scale: TransformableScale<any, number>): number;
/**
* Sets the minimum domain value for the scale, constraining the pan/zoom
* interaction to a minimum value in the domain.
*
* Note that this differs from minDomainExtent/maxDomainExtent, in that
* those methods provide constraints such as showing at least 2 but no more
* than 5 values at a time.
*
* By contrast, minDomainValue/maxDomainValue set a boundary beyond which
* the user cannot pan/zoom.
*
* @param {TransformableScale} scale The scale to query
* @param {number} minDomainExtent The minimum domain value for the scale.
* @returns {Interactions.PanZoom} The calling PanZoom Interaction.
*/
public minDomainValue(scale: TransformableScale<any, number>, minDomainValue: number): this;
public minDomainValue(scale: TransformableScale<any, number>, minDomainValue?: number): number | this {
if (minDomainValue == null) {
return this._minDomainValues.get(scale);
}
this._minDomainValues.set(scale, minDomainValue);
return this;
}
/**
* Gets the maximum domain value for the scale, constraining the pan/zoom
* interaction to a maximum value in the domain.
*
* Note that this differs from minDomainExtent/maxDomainExtent, in that
* those methods provide constraints such as showing at least 2 but no more
* than 5 values at a time.
*
* By contrast, minDomainValue/maxDomainValue set a boundary beyond which
* the user cannot pan/zoom.
*
* @param {TransformableScale} scale The scale to query
* @returns {number} The maximum domain value for the scale.
*/
public maxDomainValue(scale: TransformableScale<any, number>): number;
/**
* Sets the maximum domain value for the scale, constraining the pan/zoom
* interaction to a maximum value in the domain.
*
* Note that this differs from minDomainExtent/maxDomainExtent, in that
* those methods provide constraints such as showing at least 2 but no more
* than 5 values at a time.
*
* By contrast, minDomainValue/maxDomainValue set a boundary beyond which
* the user cannot pan/zoom.
*
* @param {TransformableScale} scale The scale to query
* @param {number} maxDomainExtent The maximum domain value for the scale.
* @returns {Interactions.PanZoom} The calling PanZoom Interaction.
*/
public maxDomainValue(scale: TransformableScale<any, number>, maxDomainValue: number): this;
public maxDomainValue(scale: TransformableScale<any, number>, maxDomainValue?: number): number | this {
if (maxDomainValue == null) {
return this._maxDomainValues.get(scale);
}
this._maxDomainValues.set(scale, maxDomainValue);
return this;
}
/**
* Uses the current domain of the scale to apply a minimum and maximum
* domain value for that scale.
*
* This constrains the pan/zoom interaction to show no more than the domain
* of the scale.
*/
public setMinMaxDomainValuesTo(scale: TransformableScale<any, number>) {
this._minDomainValues.delete(scale);
this._maxDomainValues.delete(scale);
const [ domainMin, domainMax ] = scale.getTransformationDomain();
this.minDomainValue(scale, domainMin);
this.maxDomainValue(scale, domainMax);
return this;
}
/**
* Adds a callback to be called when panning ends.
*
* @param {PanCallback} callback
* @returns {this} The calling PanZoom Interaction.
*/
public onPanEnd(callback: PanCallback) {
this._panEndCallbacks.add(callback);
return this;
}
/**
* Removes a callback that would be called when panning ends.
*
* @param {PanCallback} callback
* @returns {this} The calling PanZoom Interaction.
*/
public offPanEnd(callback: PanCallback) {
this._panEndCallbacks.delete(callback);
return this;
}
/**
* Adds a callback to be called when zooming ends.
*
* @param {ZoomCallback} callback
* @returns {this} The calling PanZoom Interaction.
*/
public onZoomEnd(callback: ZoomCallback) {
this._zoomEndCallbacks.add(callback);
return this;
}
/**
* Removes a callback that would be called when zooming ends.
*
* @param {ZoomCallback} callback
* @returns {this} The calling PanZoom Interaction.
*/
public offZoomEnd(callback: ZoomCallback) {
this._zoomEndCallbacks.delete(callback);
return this;
}
/**
* Adds a callback to be called when any pan or zoom update occurs. This is
* called on every frame, so be sure your callback is fast.
*
* @param {PanZoomUpdateCallback} callback
* @returns {this} The calling PanZoom Interaction.
*/
public onPanZoomUpdate(callback: PanZoomUpdateCallback) {
this._panZoomUpdateCallbacks.add(callback);
return this;
}
/**
* Removes a callback that would be called when any pan or zoom update occurs.
*
* @param {PanZoomUpdateCallback} callback
* @returns {this} The calling PanZoom Interaction.
*/
public offPanZoomUpdate(callback: PanZoomUpdateCallback) {
this._panZoomUpdateCallbacks.delete(callback);
return this;
}
} | the_stack |
* DescribeImageStat请求参数结构体
*/
export interface DescribeImageStatRequest {
/**
* 审核类型 1: 机器审核; 2: 人工审核
*/
AuditType: number
/**
* 查询条件
*/
Filters: Array<Filters>
}
/**
* 识别量统计
*/
export interface TrendCount {
/**
* 总调用量
注意:此字段可能返回 null,表示取不到有效值。
*/
TotalCount: number
/**
* 总调用时长
注意:此字段可能返回 null,表示取不到有效值。
*/
TotalHour: number
/**
* 通过量
注意:此字段可能返回 null,表示取不到有效值。
*/
PassCount: number
/**
* 通过时长
注意:此字段可能返回 null,表示取不到有效值。
*/
PassHour: number
/**
* 违规量
注意:此字段可能返回 null,表示取不到有效值。
*/
EvilCount: number
/**
* 违规时长
注意:此字段可能返回 null,表示取不到有效值。
*/
EvilHour: number
/**
* 疑似违规量
注意:此字段可能返回 null,表示取不到有效值。
*/
SuspectCount: number
/**
* 疑似违规时长
注意:此字段可能返回 null,表示取不到有效值。
*/
SuspectHour: number
/**
* 日期
注意:此字段可能返回 null,表示取不到有效值。
*/
Date: string
}
/**
* 坐标
*/
export interface Location {
/**
* 左上角横坐标
*/
X: number
/**
* 左上角纵坐标
*/
Y: number
/**
* 宽度
*/
Width: number
/**
* 高度
*/
Height: number
/**
* 检测框的旋转角度
*/
Rotate: number
}
/**
* 分类模型命中子标签结果
*/
export interface LabelDetailItem {
/**
* 序号
注意:此字段可能返回 null,表示取不到有效值。
*/
Id: number
/**
* 子标签名称
注意:此字段可能返回 null,表示取不到有效值。
*/
Name: string
/**
* 子标签分数
注意:此字段可能返回 null,表示取不到有效值。
*/
Score: number
}
/**
* ImageModeration返回参数结构体
*/
export interface ImageModerationResponse {
/**
* 数据是否属于恶意类型。
0:正常,1:可疑;
*/
HitFlag: number
/**
* 建议您拿到判断结果后的执行操作。
建议值,Block:建议屏蔽,Review:建议复审,Pass:建议通过
*/
Suggestion: string
/**
* 恶意标签,Normal:正常,Porn:色情,Abuse:谩骂,Ad:广告,Custom:自定义图片。
以及令人反感、不安全或不适宜的内容类型。
*/
Label: string
/**
* 子标签名称,如色情--性行为;当未命中子标签时,返回空字符串;
*/
SubLabel: string
/**
* 机器判断当前分类的置信度,取值范围:0.00~100.00。分数越高,表示越有可能属于当前分类。
(如:色情 99.99,则该样本属于色情的置信度非常高。)
*/
Score: number
/**
* 智能模型的识别结果,包括涉黄、广告等令人反感、不安全或不适宜的内容类型识别结果。
注意:此字段可能返回 null,表示取不到有效值。
*/
LabelResults: Array<LabelResult>
/**
* 物体检测模型的审核结果,包括实体、广告台标/二维码等物体坐标信息与内容审核信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
ObjectResults: Array<ObjectResult>
/**
* OCR识别后的文本识别结果,包括文本所处图片的OCR坐标信息以及图片文本的识别结果。
注意:此字段可能返回 null,表示取不到有效值。
*/
OcrResults: Array<OcrResult>
/**
* 基于图片风险库识别的结果。
风险库包括不安全黑库与正常白库的结果。
注意:此字段可能返回 null,表示取不到有效值。
*/
LibResults: Array<LibResult>
/**
* 请求参数中的DataId。
*/
DataId: string
/**
* 您在入参时所填入的Biztype参数。 -- 该字段暂未开放。
*/
BizType: string
/**
* 扩展字段,用于特定信息返回,不同客户/Biztype下返回信息不同。
注意:此字段可能返回 null,表示取不到有效值。
注意:此字段可能返回 null,表示取不到有效值。
*/
Extra: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ImageModeration请求参数结构体
*/
export interface ImageModerationRequest {
/**
* 该字段用于标识业务场景。您可以在内容安全控制台创建对应的ID,配置不同的内容审核策略,通过接口调用,默认不填为0,后端使用默认策略。 -- 该字段暂未开放。
*/
BizType?: string
/**
* 数据ID,可以由英文字母、数字、下划线、-、@#组成,不超过64个字符
*/
DataId?: string
/**
* 数据Base64编码,图片检测接口为图片文件内容,大小不能超过5M
*/
FileContent?: string
/**
* 图片资源访问链接,__与FileContent参数必须二选一输入__
*/
FileUrl?: string
/**
* 截帧频率,GIF图/长图检测专用,默认值为0,表示只会检测GIF图/长图的第一帧
*/
Interval?: number
/**
* GIF图/长图检测专用,代表均匀最大截帧数量,默认值为1(即只取GIF第一张,或长图不做切分处理(可能会造成处理超时))。
*/
MaxFrames?: number
/**
* 账号相关信息字段,填入后可识别违规风险账号。
*/
User?: User
/**
* 设备相关信息字段,填入后可识别违规风险设备。
*/
Device?: Device
}
/**
* DescribeImsList返回参数结构体
*/
export interface DescribeImsListResponse {
/**
* 返回列表数据----非必选,该参数暂未对外开放
注意:此字段可能返回 null,表示取不到有效值。
*/
ImsDetailSet?: Array<ImsDetail>
/**
* 总条数
*/
TotalCount?: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* OCR结果检测详情
*/
export interface OcrResult {
/**
* 场景识别结果
*/
Scene: string
/**
* 建议您拿到判断结果后的执行操作。
建议值,Block:建议屏蔽,Review:建议复审,Pass:建议通过
*/
Suggestion: string
/**
* 恶意标签,Normal:正常,Porn:色情,Abuse:谩骂,Ad:广告,Custom:自定义词库。
以及令人反感、不安全或不适宜的内容类型。
*/
Label: string
/**
* 子标签检测结果
*/
SubLabel: string
/**
* 该标签模型命中的分值
*/
Score: number
/**
* ocr结果详情
*/
Details: Array<OcrTextDetail>
/**
* ocr识别出的文本结果
*/
Text: string
}
/**
* User结果
*/
export interface User {
/**
* 业务用户ID 如填写,会根据账号历史恶意情况,判定消息有害结果,特别是有利于可疑恶意情况下的辅助判断。账号可以填写微信uin、QQ号、微信openid、QQopenid、字符串等。该字段和账号类别确定唯一账号。
*/
UserId?: string
/**
* 业务用户ID类型 "1-微信uin 2-QQ号 3-微信群uin 4-qq群号 5-微信openid 6-QQopenid 7-其它string"
*/
AccountType?: string
/**
* 用户昵称
*/
Nickname?: string
/**
* 性别 默认0 未知 1 男性 2 女性
*/
Gender?: number
/**
* 年龄 默认0 未知
*/
Age?: number
/**
* 用户等级,默认0 未知 1 低 2 中 3 高
*/
Level?: number
/**
* 手机号
*/
Phone?: string
/**
* 用户简介,长度不超过5000字
*/
Desc?: string
/**
* 用户头像图片链接
*/
HeadUrl?: string
}
/**
* 分类模型命中结果
*/
export interface LabelResult {
/**
* 场景识别结果
*/
Scene: string
/**
* 建议您拿到判断结果后的执行操作。
建议值,Block:建议屏蔽,Review:建议复审,Pass:建议通过
*/
Suggestion: string
/**
* 恶意标签,Normal:正常,Porn:色情,Abuse:谩骂,Ad:广告,Custom:自定义图片。
以及令人反感、不安全或不适宜的内容类型。
*/
Label: string
/**
* 子标签检测结果
注意:此字段可能返回 null,表示取不到有效值。
*/
SubLabel: string
/**
* 该标签模型命中的分值
*/
Score: number
/**
* 分类模型命中子标签结果
注意:此字段可能返回 null,表示取不到有效值。
*/
Details: Array<LabelDetailItem>
}
/**
* Device结果
*/
export interface Device {
/**
* 发表消息设备IP
*/
Ip?: string
/**
* Mac地址
*/
Mac?: string
/**
* 设备指纹Token
*/
TokenId?: string
/**
* 设备指纹ID
*/
DeviceId?: string
/**
* 设备序列号
*/
IMEI?: string
/**
* IOS设备,Identifier For Advertising(广告标识符)
*/
IDFA?: string
/**
* IOS设备,IDFV - Identifier For Vendor(应用开发商标识符)
*/
IDFV?: string
/**
* IP地址类型 0 代表ipv4 1 代表ipv6
*/
IpType?: number
}
/**
* 机器审核详情列表数据项
*/
export interface ImsDetail {
/**
* 文本内容
*/
Content: string
/**
* 数据方式, 0:我审,1:人审
*/
DataSource: number
/**
* 最后更新时间
*/
UpdateTime: string
/**
* ----非必选,该参数暂未对外开放
*/
EvilType: number
/**
* 机器审核时间
*/
ModerationTime: string
/**
* 最后更新人
*/
UpdateUser: string
/**
* 内容RequestId
*/
ContentId: string
/**
* 自主审核结果
*/
OperEvilType: number
}
/**
* 违规数据分布
*/
export interface EvilCount {
/**
* ----非必选,该参数功能暂未对外开放
*/
EvilType: string
/**
* 分布类型总量
*/
Count: number
}
/**
* 实体检测结果详情:实体、广告台标、二维码
*/
export interface ObjectResult {
/**
* 场景识别结果
*/
Scene: string
/**
* 建议您拿到判断结果后的执行操作。
建议值,Block:建议屏蔽,Review:建议复审,Pass:建议通过
*/
Suggestion: string
/**
* 恶意标签,Normal:正常,Porn:色情,Abuse:谩骂,Ad:广告,Custom:自定义图片。
以及令人反感、不安全或不适宜的内容类型。
*/
Label: string
/**
* 子标签检测结果
注意:此字段可能返回 null,表示取不到有效值。
*/
SubLabel: string
/**
* 该标签模型命中的分值
*/
Score: number
/**
* 实体名称
注意:此字段可能返回 null,表示取不到有效值。
*/
Names: Array<string>
/**
* 实体检测结果明细
注意:此字段可能返回 null,表示取不到有效值。
*/
Details: Array<ObjectDetail>
}
/**
* OCR文本结果详情
*/
export interface OcrTextDetail {
/**
* OCR文本内容
*/
Text: string
/**
* 恶意标签,Normal:正常,Porn:色情,Abuse:谩骂,Ad:广告,Custom:自定义词库。
以及令人反感、不安全或不适宜的内容类型。
*/
Label: string
/**
* 仅当Label为Custom自定义关键词时有效,表示自定义库id
*/
LibId: string
/**
* 仅当Label为Custom自定义关键词时有效,表示自定义库名称
*/
LibName: string
/**
* 该标签下命中的关键词
*/
Keywords: Array<string>
/**
* 该标签模型命中的分值
*/
Score: number
/**
* OCR位置
*/
Location: Location
/**
* OCR文本识别置信度
*/
Rate: number
}
/**
* 实体检测结果明细,当检测场景为实体、广告台标、二维码时表示模型检测目标框的标签名称、标签值、标签分数以及检测框的位置信息。
*/
export interface ObjectDetail {
/**
* 序号
*/
Id: number
/**
* 标签名称
*/
Name: string
/**
* 标签值,
当标签为二维码时,表示URL地址,如Name为QrCode时,Value为"http//abc.com/aaa"
*/
Value: string
/**
* 分数
*/
Score: number
/**
* 检测框坐标
*/
Location: Location
}
/**
* 描述键值对过滤器,用于条件过滤查询。例如过滤ID、名称、状态等
*/
export interface Filter {
/**
* 过滤键的名称。
*/
Name?: string
/**
* 一个或者多个过滤值。
*/
Values?: Array<string>
}
/**
* DescribeImageStat返回参数结构体
*/
export interface DescribeImageStatResponse {
/**
* 识别结果统计
*/
Overview?: Overview
/**
* 识别量统计
*/
TrendCount?: Array<TrendCount>
/**
* 违规数据分布
注意:此字段可能返回 null,表示取不到有效值。
*/
EvilCount?: Array<EvilCount>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeImsList请求参数结构体
*/
export interface DescribeImsListRequest {
/**
* 分页 页索引
*/
PageIndex: number
/**
* 分页条数
*/
PageSize: number
/**
* 过滤条件
*/
Filters?: Array<Filter>
}
/**
* 黑白库结果明细
*/
export interface LibResult {
/**
* 场景识别结果
*/
Scene: string
/**
* 建议您拿到判断结果后的执行操作。
建议值,Block:建议屏蔽,Review:建议复审,Pass:建议通过
*/
Suggestion: string
/**
* 恶意标签,Normal:正常,Porn:色情,Abuse:谩骂,Ad:广告,Custom:自定义词库。
以及令人反感、不安全或不适宜的内容类型。
*/
Label: string
/**
* 子标签检测结果
注意:此字段可能返回 null,表示取不到有效值。
*/
SubLabel: string
/**
* 该标签模型命中的分值
*/
Score: number
/**
* 黑白库结果明细
注意:此字段可能返回 null,表示取不到有效值。
*/
Details: Array<LibDetail>
}
/**
* 识别结果统计
*/
export interface Overview {
/**
* 总调用量
*/
TotalCount: number
/**
* 总调用时长
*/
TotalHour: number
/**
* 通过量
*/
PassCount: number
/**
* 通过时长
*/
PassHour: number
/**
* 违规量
*/
EvilCount: number
/**
* 违规时长
*/
EvilHour: number
/**
* 疑似违规量
*/
SuspectCount: number
/**
* 疑似违规时长
*/
SuspectHour: number
}
/**
* 自定义库/黑白库明细
*/
export interface LibDetail {
/**
* 序号
*/
Id: number
/**
* 仅当Label为Custom自定义关键词时有效,表示自定义库id
*/
LibId: string
/**
* 仅当Label为Custom自定义关键词时有效,表示自定义库名称
注意:此字段可能返回 null,表示取不到有效值。
*/
LibName: string
/**
* 图片ID
*/
ImageId: string
/**
* 恶意标签,Normal:正常,Porn:色情,Abuse:谩骂,Ad:广告,Custom:自定义词库。
以及其他令人反感、不安全或不适宜的内容类型。
*/
Label: string
/**
* 自定义标签
注意:此字段可能返回 null,表示取不到有效值。
*/
Tag: string
/**
* 命中的模型分值
*/
Score: number
}
/**
* 图片过滤条件
*/
export interface Filters {
/**
* 查询字段:
策略BizType
子账号SubUin
日期区间DateRange
*/
Name: string
/**
* 查询值
*/
Values: Array<string>
} | the_stack |
import { expect } from 'chai';
import { I80F48 } from '../src/fixednum';
import BN from 'bn.js';
import Big from 'big.js';
describe('fixednumTests', async () => {
describe('creating an I80F48', async () => {
// NOTE: The max representation Int is 170141183460469231731687303715884105727 <- ((2 ^ 48) / 2) - 1
// NOTE: The min representation Int is -170141183460469231731687303715884105728 <- ((2 ^ 48) / 2) * (-1)
it('should create the max representation number', async () => {
new I80F48(new BN('170141183460469231731687303715884105727'));
});
it('should create the min representation number', async () => {
new I80F48(new BN('-170141183460469231731687303715884105728'));
});
it('should create an arbitrary representation number', async () => {
new I80F48(new BN('170141183460'));
});
it('should fail creating a higher representation number than the max number', async () => {
expect(function () {
new I80F48(new BN('170141183460469231731687303715884105728'));
}).to.throw('Number out of range');
});
it('should fail creating a lower representation number than the min number', async () => {
expect(function () {
new I80F48(new BN('-170141183460469231731687303715884105729'));
}).to.throw('Number out of range');
});
});
describe('fromNumber', async () => {
it('should create the max value', async () => {
expect(I80F48.fromNumber(Number.MAX_SAFE_INTEGER).toNumber()).to.eq(
Number.MAX_SAFE_INTEGER,
);
});
it('should create the min value', async () => {
expect(I80F48.fromNumber(Number.MIN_SAFE_INTEGER).toNumber()).to.eq(
Number.MIN_SAFE_INTEGER,
);
});
it('fractions', async () => {
expect(I80F48.fromNumber(2.75).toNumber()).to.eq(
2.75,
);
expect(I80F48.fromNumber(-2.75).toNumber()).to.eq(
-2.75,
);
// lowest bit
expect(I80F48.fromNumber(Math.pow(2, -48)).getData().toNumber()).to.eq(
1
);
expect(I80F48.fromNumber(-Math.pow(2, -48)).getData().toNumber()).to.eq(
-1
);
// two lowest bits
expect(I80F48.fromNumber(Math.pow(2, -48) + Math.pow(2, -47)).getData().toNumber()).to.eq(
3
);
// rounded down
expect(I80F48.fromNumber(0.99 * (Math.pow(2, -48) + Math.pow(2, -47))).getData().toNumber()).to.eq(
2
);
expect(I80F48.fromNumber(-0.99 * (Math.pow(2, -48) + Math.pow(2, -47))).getData().toNumber()).to.eq(
-2
);
expect(I80F48.fromNumber(1.01 * (Math.pow(2, -48) + Math.pow(2, -47))).getData().toNumber()).to.eq(
3
);
expect(I80F48.fromNumber(0.99 * Math.pow(2, -48)).getData().toNumber()).to.eq(
0
);
});
});
describe('fromI64', async () => {
it('should create the max value', async () => {
expect(I80F48.fromI64(new BN(Number.MAX_SAFE_INTEGER)).toNumber()).to.eq(
Number.MAX_SAFE_INTEGER,
);
});
it('should create the min value', async () => {
expect(I80F48.fromI64(new BN(Number.MIN_SAFE_INTEGER)).toNumber()).to.eq(
Number.MIN_SAFE_INTEGER,
);
});
});
describe('fromString', async () => {
// NOTE: The max number of I80 = 604462909807314587353087 <- ((2 ^ 80) / 2) - 1
// NOTE: The max number of I80F48 = 604462909807314587353087.99999999999999644729 <- 604462909807314587353088 - (1 / (2 ^ 48))
// NOTE: The min number of I80F48 = I80 = -604462909807314587353088 <- (2 ^ 80) / 2
it('should create the max value', async () => {
const stepSize = new Big(1).div(new Big(2).pow(48));
const maxValue = new Big('604462909807314587353088').minus(stepSize);
expect(
I80F48.fromString(maxValue.toFixed()).getData().toString().toString(),
).to.equal('170141183460469231731687303715884105727');
});
it('should create the min value', async () => {
expect(
I80F48.fromString('-604462909807314587353088')
.getData()
.toString()
.toString(),
).to.equal('-170141183460469231731687303715884105728');
});
it('should create arbitrary values', async () => {
expect(I80F48.fromString('0').getData().toString()).to.equal('0');
expect(I80F48.fromString('1').getData().toString()).to.equal(
'281474976710656',
);
expect(I80F48.fromString('-1').getData().toString()).to.equal(
'-281474976710656',
);
expect(I80F48.fromString('1.25').getData().toString()).to.equal(
'351843720888320',
);
expect(I80F48.fromString('-1.25').getData().toString()).to.equal(
'-351843720888320',
);
});
it('should fail creating a (max number + 1)', async () => {
expect(function () {
I80F48.fromString('604462909807314587353088');
}).to.throw('Number out of range');
});
it('should fail creating a (min number - 1)', async () => {
expect(function () {
I80F48.fromString('-604462909807314587353089');
}).to.throw('Number out of range');
});
});
describe('toString', async () => {
it('should output the max value', async () => {
expect(
new I80F48(
new BN('170141183460469231731687303715884105727'),
).toString(),
).to.equal('604462909807314587353087.99999999999999644729');
});
it('should output the min value', async () => {
expect(
new I80F48(
new BN('-170141183460469231731687303715884105728'),
).toString(),
).to.equal('-604462909807314587353088');
});
it('should output the same string used to create itself', async () => {
const stepSize = new Big(1).div(new Big(2).pow(48));
const maxValue = new Big('604462909807314587353088').minus(stepSize);
expect(I80F48.fromString(maxValue.toFixed()).toString()).to.equal(
maxValue.toFixed(),
);
expect(
I80F48.fromString('-604462909807314587353088').toString(),
).to.equal('-604462909807314587353088');
expect(I80F48.fromString('1').toString()).to.equal('1');
expect(I80F48.fromString('-1').toString()).to.equal('-1');
expect(I80F48.fromString('1.25').toString()).to.equal('1.25');
expect(I80F48.fromString('-1.25').toString()).to.equal('-1.25');
});
});
describe('fromArray', async () => {
const maxValue = [
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
127,
];
const minValue = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128];
const zeroValue = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 0
const oneValue = [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 1
const oneNegValue = [
0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
]; // -1
const oneFracValue = [0, 0, 0, 0, 0, 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 1.25
const oneFracNegValue = [
0, 0, 0, 0, 0, 192, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
]; // 1.25
// NOTE: All array values taken from rust I80F48 fixed point type
it('should create the max value', async () => {
expect(
I80F48.fromArray(new Uint8Array(maxValue))
.getData()
.toString()
.toString(),
).to.equal('170141183460469231731687303715884105727');
});
it('should create the min value', async () => {
expect(
I80F48.fromArray(new Uint8Array(minValue))
.getData()
.toString()
.toString(),
).to.equal('-170141183460469231731687303715884105728');
});
it('should create arbitrary values', async () => {
expect(
I80F48.fromArray(new Uint8Array(zeroValue))
.getData()
.toString()
.toString(),
).to.equal('0');
expect(
I80F48.fromArray(new Uint8Array(oneValue))
.getData()
.toString()
.toString(),
).to.equal('281474976710656');
expect(
I80F48.fromArray(new Uint8Array(oneNegValue))
.getData()
.toString()
.toString(),
).to.equal('-281474976710656');
expect(
I80F48.fromArray(new Uint8Array(oneFracValue))
.getData()
.toString()
.toString(),
).to.equal('351843720888320');
expect(
I80F48.fromArray(new Uint8Array(oneFracNegValue))
.getData()
.toString()
.toString(),
).to.equal('-351843720888320');
});
it('should enforce the array length rule', async () => {
expect(function () {
I80F48.fromArray(new Uint8Array([1]));
}).to.throw('Uint8Array must be of length 16');
expect(function () {
I80F48.fromArray(
new Uint8Array([0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
);
}).to.throw('Uint8Array must be of length 16');
});
});
describe('toArray', async () => {
const maxValue = [
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
127,
];
const minValue = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128];
const zeroValue = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 0
const oneValue = [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 1
const oneNegValue = [
0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
]; // -1
const oneFracValue = [0, 0, 0, 0, 0, 64, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 1.25
const oneFracNegValue = [
0, 0, 0, 0, 0, 192, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
]; // 1.25
it('should output the max value', async () => {
new I80F48(new BN('170141183460469231731687303715884105727'))
.toArray()
.forEach((x: any, i: any) => {
expect(x).to.equal(maxValue[i]);
});
});
it('should output the min value', async () => {
new I80F48(new BN('-170141183460469231731687303715884105728'))
.toArray()
.forEach((x: any, i: any) => {
expect(x).to.equal(minValue[i]);
});
});
it('should output the same array used to create itself', async () => {
I80F48.fromArray(new Uint8Array(maxValue))
.toArray()
.forEach((x: any, i: any) => {
expect(x).to.equal(maxValue[i]);
});
I80F48.fromArray(new Uint8Array(minValue))
.toArray()
.forEach((x: any, i: any) => {
expect(x).to.equal(minValue[i]);
});
I80F48.fromArray(new Uint8Array(zeroValue))
.toArray()
.forEach((x: any, i: any) => {
expect(x).to.equal(zeroValue[i]);
});
I80F48.fromArray(new Uint8Array(oneValue))
.toArray()
.forEach((x: any, i: any) => {
expect(x).to.equal(oneValue[i]);
});
I80F48.fromArray(new Uint8Array(oneNegValue))
.toArray()
.forEach((x: any, i: any) => {
expect(x).to.equal(oneNegValue[i]);
});
I80F48.fromArray(new Uint8Array(oneFracValue))
.toArray()
.forEach((x: any, i: any) => {
expect(x).to.equal(oneFracValue[i]);
});
I80F48.fromArray(new Uint8Array(oneFracNegValue))
.toArray()
.forEach((x: any, i: any) => {
expect(x).to.equal(oneFracNegValue[i]);
});
});
it('toString and toArray should output identical values', async () => {
const stepSize = new Big(1).div(new Big(2).pow(48));
const maxStringValue = new Big('604462909807314587353088').minus(
stepSize,
);
expect(I80F48.fromArray(new Uint8Array(maxValue)).toString()).to.equal(
I80F48.fromString(maxStringValue.toFixed()).toString(),
);
});
});
describe('add', async () => {
it('604462909807314587353087 + 0.99999999999999644729 should be 604462909807314587353087.99999999999999644729', async () => {
expect(
I80F48.fromString('604462909807314587353087')
.add(I80F48.fromString('0.99999999999999644729'))
.toString(),
).to.equal('604462909807314587353087.99999999999999644729');
});
it('0 + 0 should be 0', async () => {
expect(
I80F48.fromString('0').add(I80F48.fromString('0')).toString(),
).to.equal('0');
});
it('1 + 1 should be 2', async () => {
expect(
I80F48.fromString('1').add(I80F48.fromString('1')).toString(),
).to.equal('2');
});
it('1 + (-1) should be 0', async () => {
expect(
I80F48.fromString('1').add(I80F48.fromString('-1')).toString(),
).to.equal('0');
});
it('1 + 1.25 should be 2.25', async () => {
expect(
I80F48.fromString('1').add(I80F48.fromString('1.25')).toString(),
).to.equal('2.25');
});
it('1.25 + 1.25 should be 2.5', async () => {
expect(
I80F48.fromString('1.25').add(I80F48.fromString('1.25')).toString(),
).to.equal('2.5');
});
it('604462909807314587353087 + 1 should throw', async () => {
expect(function () {
I80F48.fromString('604462909807314587353087').add(
I80F48.fromString('1'),
);
}).to.throw('Number out of range');
});
});
describe('subtract', async () => {
it('604462909807314587353087.99999999999999644729 - 0.99999999999999644729 should be 604462909807314587353087', async () => {
expect(
I80F48.fromString('604462909807314587353087.99999999999999644729')
.sub(I80F48.fromString('0.99999999999999644729'))
.toString(),
).to.equal('604462909807314587353087');
});
it('0 - 0 should be 0', async () => {
expect(
I80F48.fromString('0').sub(I80F48.fromString('0')).toString(),
).to.equal('0');
});
it('1 - 1 should be 0', async () => {
expect(
I80F48.fromString('1').sub(I80F48.fromString('1')).toString(),
).to.equal('0');
});
it('1 - (-1) should be 2', async () => {
expect(
I80F48.fromString('1').sub(I80F48.fromString('-1')).toString(),
).to.equal('2');
});
it('1 - 1.25 should be -0.25', async () => {
expect(
I80F48.fromString('1').sub(I80F48.fromString('1.25')).toString(),
).to.equal('-0.25');
});
it('-1.25 - 1.25 should be -2.5', async () => {
expect(
I80F48.fromString('-1.25').sub(I80F48.fromString('1.25')).toString(),
).to.equal('-2.5');
});
it('-604462909807314587353088 - 1 should throw', async () => {
expect(function () {
I80F48.fromString('-604462909807314587353088').sub(
I80F48.fromString('1'),
);
}).to.throw('Number out of range');
});
});
describe('multiply', async () => {
it('1 * 1 should be 1', async () => {
expect(
I80F48.fromString('1').mul(I80F48.fromString('1')).toString(),
).to.equal('1');
});
it('1 * (-1) should be -1', async () => {
expect(
I80F48.fromString('1').mul(I80F48.fromString('-1')).toString(),
).to.equal('-1');
});
it('(-1) * (-1) should be -1', async () => {
expect(
I80F48.fromString('-1').mul(I80F48.fromString('-1')).toString(),
).to.equal('1');
});
it('6 * 7 should be 42', async () => {
expect(
I80F48.fromString('6').mul(I80F48.fromString('7')).toString(),
).to.equal('42');
});
it('6 * (-7) should be -42', async () => {
expect(
I80F48.fromString('6').mul(I80F48.fromString('-7')).toString(),
).to.equal('-42');
});
it('(-6) * (-7) should be 42', async () => {
expect(
I80F48.fromString('-6').mul(I80F48.fromString('-7')).toString(),
).to.equal('42');
});
it('2 * 2.5 should be 5', async () => {
expect(
I80F48.fromString('2').mul(I80F48.fromString('2.5')).toString(),
).to.equal('5');
});
it('2 * (-2.5) should be -5', async () => {
expect(
I80F48.fromString('2').mul(I80F48.fromString('-2.5')).toString(),
).to.equal('-5');
});
it('(-2) * (-2.5) should be 5', async () => {
expect(
I80F48.fromString('-2').mul(I80F48.fromString('-2.5')).toString(),
).to.equal('5');
});
it('2.5 * 3.5 should be 8.75', async () => {
expect(
I80F48.fromString('2.5').mul(I80F48.fromString('3.5')).toString(),
).to.equal('8.75');
});
it('2.5 * (-3.5) should be -8.75', async () => {
expect(
I80F48.fromString('2.5').mul(I80F48.fromString('-3.5')).toString(),
).to.equal('-8.75');
});
it('(-2.5) * (-3.5) should be 8.75', async () => {
expect(
I80F48.fromString('-2.5').mul(I80F48.fromString('-3.5')).toString(),
).to.equal('8.75');
});
it('3.14 * 3.1444 should start with 9.873416', async () => {
expect(
I80F48.fromString('3.14').mul(I80F48.fromString('3.1444')).toString(),
).to.match(/^9.873416/i);
});
it('3.14 * (-3.1444) should start with -9.873416', async () => {
expect(
I80F48.fromString('3.14').mul(I80F48.fromString('-3.1444')).toString(),
).to.match(/^-9.873416/i);
});
it('(-3.14) * (-3.1444) should start with 9.873416', async () => {
expect(
I80F48.fromString('-3.14').mul(I80F48.fromString('-3.1444')).toString(),
).to.match(/^9.873416/i);
});
it('604462909807314587353087 * 2 should throw', async () => {
expect(function () {
I80F48.fromString('604462909807314587353087').mul(
I80F48.fromString('2'),
);
}).to.throw('Number out of range');
});
});
describe('divide', async () => {
it('1 / 1 should be 1', async () => {
expect(
I80F48.fromString('1').div(I80F48.fromString('1')).toString(),
).to.equal('1');
});
it('1 / (-1) should be -1', async () => {
expect(
I80F48.fromString('1').div(I80F48.fromString('-1')).toString(),
).to.equal('-1');
});
it('(-1) / (-1) should be -1', async () => {
expect(
I80F48.fromString('-1').div(I80F48.fromString('-1')).toString(),
).to.equal('1');
});
it('42 / 7 should be 6', async () => {
expect(
I80F48.fromString('42').div(I80F48.fromString('7')).toString(),
).to.equal('6');
});
it('42 / (-7) should be -6', async () => {
expect(
I80F48.fromString('42').div(I80F48.fromString('-7')).toString(),
).to.equal('-6');
});
it('335000022 / 106633819 should start with 3.1415926', async () => {
expect(
I80F48.fromString('335000022')
.div(I80F48.fromString('106633819'))
.toString(),
).to.match(/^3.1415926/i);
});
it('335000022 / (-106633819) should start with -3.1415926', async () => {
expect(
I80F48.fromString('335000022')
.div(I80F48.fromString('-106633819'))
.toString(),
).to.match(/^-3.1415926/i);
});
it('(-335000022) / (-106633819) should start with 3.1415926', async () => {
expect(
I80F48.fromString('-335000022')
.div(I80F48.fromString('-106633819'))
.toString(),
).to.match(/^3.1415926/i);
});
});
}); | the_stack |
import * as Diff from 'diff';
interface DiffPos {
left: number;
right: number;
isLastDiff: boolean;
}
export default (hole: string, exp: string, out: string, argv: string[]) => {
if (stringsEqual(exp, out, shouldIgnoreCase(hole))) return null;
// Show args? Exclude holes with one big argument like QR Decoder.
const isArgDiff = argv.length > 1 && argv.length == lines(exp).length;
const {rows, maxLineNum} = diffHTMLRows(hole, exp, out, argv, isArgDiff);
return <table>
{makeCols(isArgDiff, maxLineNum, argv)}
<tr>
{isArgDiff ? <th class="right">Args</th> : <th/>}
<th>Output</th>
{isArgDiff ? null : <th/>}
<th>Expected</th>
</tr>
{rows}
</table>;
};
function pushToDiff(diff: Diff.Change[], entry: Diff.Change, join: string) {
// Mutate the given diff by pushing `entry`
// If `entry` has the same type as the previous entry, then merge them together
const last = diff[diff.length - 1];
if (
last &&
((entry.removed && last.removed) ||
(entry.added && last.added) ||
(!entry.added && !last.added && !entry.removed && !last.removed))
) {
// The value keeps a trailing newline when join="\n"
last.value += entry.value + join;
last.count ??= 0;
last.count += entry.count ?? 0;
}
else {
diff.push(entry);
}
}
function diffWrapper(join: string, left: string[], right: string[], diffOpts: Diff.BaseOptions) {
// join = "\n" for line diff or "" for char diff
// pass in left,right = list of tokens;
// for char diff, this is a list of chars
// for line diff, this is a list of lines
// Wrapper for performance
// Include characters until the first difference, then include 1000 characters
// after that, and treat the rest as a single block
const d = firstDifference(left, right, diffOpts.ignoreCase ?? false);
const length = Math.min(1000, Math.max(left.length - d, right.length - d));
// Concatenate a newline on line diff because Diff.diffLines counts
// lines without trailing newlines as changed
const diff = (join === '' ? Diff.diffChars : Diff.diffLines)(
left.slice(d, d + length).join(join) + join,
right.slice(d, d + length).join(join) + join,
diffOpts,
);
const head = left.slice(0, d);
if (head.length > 0) {
const fst = diff[0];
if (fst && !fst.added && !fst.removed) {
fst.count ??= 0;
fst.count += head.length;
fst.value += head.join(join) + join;
}
else {
diff.unshift({
count: head.length,
value: head.join(join),
});
}
}
const leftTail = left.slice(d + length);
const ltString = leftTail.join(join);
const rightTail = right.slice(d + length);
const rtString = rightTail.join(join);
if (stringsEqual(ltString, rtString, diffOpts.ignoreCase ?? false)) {
pushToDiff(
diff,
{
count: leftTail.length,
value: ltString,
},
join,
);
}
else {
if (ltString !== '') {
pushToDiff(
diff,
{
added: undefined,
removed: true,
count: leftTail.length,
value: ltString,
},
join,
);
}
if (rtString !== '') {
pushToDiff(
diff,
{
added: true,
removed: undefined,
count: rightTail.length,
value: rtString,
},
join,
);
}
}
return diff;
}
function firstDifference(left: string[], right: string[], ignoreCase: boolean) {
for (let i=0; i<left.length || i<right.length; i++) {
if (!stringsEqual(left[i], right[i], ignoreCase)) {
return i;
}
}
return Math.min(left.length, right.length) + 1;
}
function makeCols(isArgDiff: boolean, maxLineNum: number, argv: string[]) {
const col = (width: number) => <col style={`width:${width}px`}/>;
const cols = [];
const numLength = String(maxLineNum).length + 1;
const charWidth = 11;
if (isArgDiff) {
const longestArgLength = Math.max(6, ...argv.map(arg => arg.length));
cols.push(col(Math.min(longestArgLength * charWidth, 350)));
}
else {
cols.push(col(numLength * charWidth));
}
cols.push(<col class="diff-col-text"/>);
if (!isArgDiff)
cols.push(col(numLength * charWidth));
cols.push(<col class="diff-col-text"/>);
return cols;
}
function diffHTMLRows(hole: string, exp: string, out: string, argv: string[], isArgDiff: boolean) {
const rows = [];
const pos = {
left: 1,
right: 1,
isLastDiff: false,
};
const changes = getLineChanges(hole, out, exp, isArgDiff);
let pendingChange = null;
for (let i = 0; i < changes.length; i++) {
const change = changes[i];
pos.isLastDiff = i === changes.length - 1;
if (change.added || change.removed) {
if (pendingChange === null) {
pendingChange = change;
}
else {
rows.push(...getDiffRow(hole, pendingChange, change, pos, argv, isArgDiff));
pendingChange = null;
}
}
else {
if (pendingChange) {
rows.push(...getDiffRow(hole, pendingChange, {value: ''}, pos, argv, isArgDiff));
pendingChange = null;
}
rows.push(...getDiffLines(hole, change, change, pos, argv, isArgDiff));
}
}
if (pendingChange) {
rows.push(...getDiffRow(hole, pendingChange, {value: ''}, pos, argv, isArgDiff));
}
return {
rows,
maxLineNum: Math.max(pos.left, pos.right),
};
}
function stringsEqual(a: string, b: string, ignoreCase: boolean) {
// https://stackoverflow.com/a/2140723/7481517
return (
a !== undefined &&
a !== null &&
0 ===
a.localeCompare(
b,
undefined,
ignoreCase
? {
sensitivity: 'accent',
}
: undefined,
)
);
}
function getLineChanges(hole: string, before: string, after: string, isArgDiff: boolean) {
if (isArgDiff) {
const out = [];
const splitBefore = lines(before);
const splitAfter = lines(after);
let currentUnchanged = [];
const ignoreCase = shouldIgnoreCase(hole);
for (let i=0; i<Math.max(splitBefore.length, splitAfter.length); i++) {
const a = splitBefore[i] ?? '';
const b = splitAfter[i] ?? '';
const linesEqual = stringsEqual(a, b, ignoreCase);
if (linesEqual) {
currentUnchanged.push(a);
}
else {
if (currentUnchanged.length > 0) {
out.push({
count: currentUnchanged.length,
value: currentUnchanged.join('\n') + '\n',
});
currentUnchanged = [];
}
for (const [k,v] of [['removed', a], ['added', b]]) {
if (v !== undefined) {
pushToDiff(
out,
{
count: 1,
[k]: true,
value: v + '\n',
},
'\n',
);
}
}
}
}
if (currentUnchanged.length > 0) {
out.push({
count: currentUnchanged.length,
value: currentUnchanged.join('\n') + '\n',
});
}
return out;
}
else {
return diffWrapper('\n', lines(before), lines(after), {
ignoreCase: shouldIgnoreCase(hole),
});
}
}
function getDiffRow(hole: string, change1: Diff.Change, change2: Diff.Change, pos: DiffPos, argv: string[], isArgDiff: boolean) {
change2.value ??= '';
change2.count ??= 0;
const left = change1.removed ? change1 : change2;
const right = change1.added ? change1 : change2;
return getDiffLines(hole, left, right, pos, argv, isArgDiff);
}
function getDiffLines(hole: string, left: Diff.Change, right: Diff.Change, pos: DiffPos, argv: string[], isArgDiff: boolean) {
const leftSplit = lines(left.value);
const rightSplit = lines(right.value);
if (!(pos.isLastDiff && hole === 'quine')) {
// ignore trailing newline
if (leftSplit[leftSplit.length - 1] === '') leftSplit.pop();
if (rightSplit[rightSplit.length - 1] === '') rightSplit.pop();
}
const diffOpts = {
ignoreCase: shouldIgnoreCase(hole),
};
const rows = [];
const numLines = Math.max(leftSplit.length, rightSplit.length);
const isUnchanged = !left.removed && !right.added;
// Skip the middle of any block of more than 7 unchanged lines, or 41 changed lines
const padding = isUnchanged ? 3 : 20;
const skipMiddle = numLines > 2 * padding + 1;
for (let i=0; i<numLines; i++) {
const row = <tr/>;
rows.push(row);
if (skipMiddle) {
// In the middle; skip the line
if (padding < i && i < numLines - padding) continue;
// At the start of the middle; add a line saying lines omitted
if (i === padding) {
row.append(<td class="diff-skip" colspan={isArgDiff ? 3 : 4}>
{`@@ ${numLines - 2 * padding} lines omitted @@`}
</td>);
continue;
}
}
const leftLine = leftSplit[i];
const rightLine = rightSplit[i];
const charDiff = diffWrapper(
'',
[...leftLine ?? ''],
[...rightLine ?? ''],
diffOpts,
);
// Subtract 1 because argv is 0-based and lines are 1-based.
if (isArgDiff)
row.append(<td class="right">{argv[i + pos.right - 1]}</td>);
if (leftLine !== undefined) {
if (!isArgDiff)
row.append(<td class="diff-left-num">{i + pos.left}</td>);
row.append(
renderCharDiff(
'diff-left' + (left.removed?' diff-removal':''),
charDiff,
false,
),
);
}
else {
row.append(<td/>, <td/>);
}
if (rightLine !== undefined) {
if (!isArgDiff)
row.append(<td class="diff-right-num">{i + pos.right}</td>);
row.append(
renderCharDiff(
'diff-right' + (right.added ? ' diff-addition' : ''),
charDiff,
true,
),
);
}
else {
row.append(<td/>, <td/>);
}
}
pos.left += left.count ?? 0;
pos.right += right.count ?? 0;
return rows;
}
function renderCharDiff(className: string, charDiff: Diff.Change[], isRight: boolean) {
const td = <td class={className}/>;
for (const change of charDiff)
if (change.added && isRight)
td.append(<span class="diff-char-addition">{change.value}</span>);
else if (change.removed && !isRight)
td.append(<span class="diff-char-removal">{change.value}</span>);
else if (!change.added && !change.removed)
td.append(change.value);
return td;
}
function shouldIgnoreCase(hole: string) {
return hole === 'css-colors';
}
function lines(s: string) {
return s.split(/\r?\n/);
} | the_stack |
import { NodeEditBehaviorScriptInstance, NodeEditBehaviorInstance } from '../../node-edit-behavior/node-edit-behavior';
import { MonacoEditorScriptMetaMods, MetaBlock } from '../monaco-editor/monaco-editor';
import { Polymer } from '../../../../../tools/definitions/polymer';
import { I18NKeys } from '../../../../_locales/i18n-keys';
import { I18NClass } from '../../../../js/shared';
declare const browserAPI: browserAPI;
namespace ScriptEditElement {
export const scriptEditProperties: {
item: CRM.ScriptNode;
} = {
item: {
type: Object,
value: {},
notify: true
}
} as any;
export class SCE implements I18NClass {
static is: string = 'script-edit';
static behaviors = [window.Polymer.NodeEditBehavior, window.Polymer.CodeEditBehavior];
static properties = scriptEditProperties;
private static _permissionDialogListeners: (() => void)[] = [];
static isTsEnabled(this: NodeEditBehaviorScriptInstance) {
return this.item.value && this.item.value.ts && this.item.value.ts.enabled;
}
static toggleBackgroundLibs(this: NodeEditBehaviorScriptInstance) {
this.async(() => {
const backgroundEnabled = this.$.paperLibrariesShowbackground.checked;
if (backgroundEnabled) {
this.$.paperLibrariesSelector.updateLibraries(this.item.value.backgroundLibraries as any,
this.newSettings as CRM.ScriptNode, 'background');
} else {
this.$.paperLibrariesSelector.updateLibraries(this.item.value.libraries as any,
this.newSettings as CRM.ScriptNode, 'main');
}
}, 0);
}
static getKeyBindingValue(binding: {
name: string;
defaultKey: string;
monacoKey: string;
storageKey: keyof CRM.KeyBindings;
}) {
return (window.app.settings &&
window.app.settings.editor.keyBindings[binding.storageKey]) ||
binding.defaultKey;
}
private static _toggleTypescriptButton(this: NodeEditBehaviorScriptInstance) {
const isEnabled = !!(this.$.editorTypescript.getAttribute('active') !== null);
if (isEnabled) {
this.$.editorTypescript.removeAttribute('active');
} else {
this.$.editorTypescript.setAttribute('active', 'active');
}
}
static jsLintGlobalsChange(this: NodeEditBehaviorScriptInstance) {
this.async(() => {
const jsLintGlobals = this.$.editorJSLintGlobalsInput.$$('input').value.split(',').map(val => val.trim());
browserAPI.storage.local.set({
jsLintGlobals
});
window.app.jsLintGlobals = jsLintGlobals;
}, 0);
}
static toggleTypescript(this: NodeEditBehaviorScriptInstance) {
const shouldBeEnabled = !(this.$.editorTypescript.getAttribute('active') !== null);
this._toggleTypescriptButton();
if (this.newSettings.value.ts) {
this.newSettings.value.ts.enabled = shouldBeEnabled;
} else {
this.newSettings.value.ts = {
enabled: shouldBeEnabled,
backgroundScript: {},
script: {}
};
}
this.getEditorInstance().setTypescript(shouldBeEnabled);
}
static openDocs(this: NodeEditBehaviorScriptInstance) {
const docsUrl = 'http://sanderronde.github.io/CustomRightClickMenu/documentation/classes/crm.crmapi.instance.html';
window.open(docsUrl, '_blank');
}
static async onKeyBindingKeyDown(this: NodeEditBehaviorScriptInstance, e: Polymer.PolymerKeyDownEvent) {
const input = window.app.util.findElementWithTagname(e, 'paper-input');
const index = ~~input.getAttribute('data-index');
this._createKeyBindingListener(input, (await this.getKeyBindings())[index]);
}
static clearTriggerAndNotifyMetaTags(this: NodeEditBehaviorScriptInstance, e: Polymer.ClickEvent) {
if (this.shadowRoot.querySelectorAll('.executionTrigger').length === 1) {
window.doc.messageToast.text = 'You need to have at least one trigger';
window.doc.messageToast.show();
return;
}
(this as NodeEditBehaviorInstance).clearTrigger(e);
};
private static _disableButtons(this: NodeEditBehaviorScriptInstance) {
this.$.dropdownMenu.disable();
};
private static _enableButtons(this: NodeEditBehaviorScriptInstance) {
this.$.dropdownMenu.enable();
};
private static _saveEditorContents(this: NodeEditBehaviorScriptInstance) {
if (this.editorMode === 'background') {
this.newSettings.value.backgroundScript = this.editorManager.getValue();
} else if (this.editorMode === 'main') {
this.newSettings.value.script = this.editorManager.getValue();
} else if (this.editorMode === 'options') {
try {
this.newSettings.value.options = JSON.parse(this.editorManager.getValue());
} catch(e) {
this.newSettings.value.options = this.editorManager.getValue();
}
}
}
private static _changeTab(this: NodeEditBehaviorScriptInstance, mode: 'main'|'background') {
if (mode !== this.editorMode) {
const isTs = this.item.value.ts && this.item.value.ts.enabled;
if (mode === 'main') {
if (this.editorMode === 'background') {
this.newSettings.value.backgroundScript = this.editorManager.getValue();
}
this.editorMode = 'main';
this._enableButtons();
this.editorManager.switchToModel('default', this.newSettings.value.script,
isTs ? this.editorManager.EditorMode.TS_META :
this.editorManager.EditorMode.JS_META);
} else if (mode === 'background') {
if (this.editorMode === 'main') {
this.newSettings.value.script = this.editorManager.getValue();
}
this.editorMode = 'background';
this._disableButtons();
this.editorManager.switchToModel('background', this.newSettings.value.backgroundScript || '',
isTs ? this.editorManager.EditorMode.TS_META :
this.editorManager.EditorMode.JS_META);
}
const element = window.scriptEdit.shadowRoot.querySelector(mode === 'main' ? '.mainEditorTab' : '.backgroundEditorTab');
Array.prototype.slice.apply(window.scriptEdit.shadowRoot.querySelectorAll('.editorTab')).forEach(
function(tab: HTMLElement) {
tab.classList.remove('active');
});
element.classList.add('active');
}
};
static switchBetweenScripts(this: NodeEditBehaviorScriptInstance, element: Polymer.PolymerElement) {
element.classList.remove('optionsEditorTab');
if (this.editorMode === 'options') {
try {
this.newSettings.value.options = JSON.parse(this.editorManager.getValue());
} catch(e) {
this.newSettings.value.options = this.editorManager.getValue();
}
}
this.hideCodeOptions();
this._initKeyBindings();
}
static changeTabEvent(this: NodeEditBehaviorScriptInstance, e: Polymer.ClickEvent) {
const element = window.app.util.findElementWithClassName(e, 'editorTab');
const isMain = element.classList.contains('mainEditorTab');
const isBackground = element.classList.contains('backgroundEditorTab');
const isLibraries = element.classList.contains('librariesTab');
const isOptions = element.classList.contains('optionsTab');
if (!isLibraries) {
this.$.codeTabContentContainer.classList.remove('showLibs');
}
if (isMain && this.editorMode !== 'main') {
this.switchBetweenScripts(element);
this._changeTab('main');
} else if (isBackground && this.editorMode !== 'background') {
this.switchBetweenScripts(element);
this._changeTab('background');
} else if (isOptions && this.editorMode !== 'options') {
if (this.editorMode === 'main') {
this.newSettings.value.script = this.editorManager.getValue();
} else if (this.editorMode === 'background') {
this.newSettings.value.backgroundScript = this.editorManager.getValue();
}
this.showCodeOptions();
this.editorMode = 'options';
} else if (isLibraries && this.editorMode !== 'libraries') {
this.$.codeTabContentContainer.classList.add('showLibs');
this.$.paperLibrariesSelector.updateLibraries(
this.newSettings.value.libraries as any, this.newSettings as CRM.ScriptNode,
'main');
this.editorMode = 'libraries';
}
Array.prototype.slice.apply(window.scriptEdit.shadowRoot.querySelectorAll('.editorTab')).forEach(
function(tab: HTMLElement) {
tab.classList.remove('active');
});
element.classList.add('active');
};
private static _getExportData(this: NodeEditBehaviorScriptInstance) {
const settings = {};
this.save(null, settings);
this.$.dropdownMenu.selected = 0;
return settings as CRM.ScriptNode;
};
static exportScriptAsCRM(this: NodeEditBehaviorScriptInstance) {
window.app.editCRM.exportSingleNode(this._getExportData(), 'CRM');
};
static exportScriptAsUserscript(this: NodeEditBehaviorScriptInstance) {
window.app.editCRM.exportSingleNode(this._getExportData(), 'Userscript');
};
static cancelChanges(this: NodeEditBehaviorScriptInstance) {
if (this.fullscreen) {
this.exitFullScreen();
}
window.setTimeout(() => {
this.finishEditing();
window.externalEditor.cancelOpenFiles();
this.editorManager.destroy();
this.fullscreenEditorManager &&
this.fullscreenEditorManager.destroy();
this.active = false;
}, this.fullscreen ? 500 : 0);
};
/**
* Gets the values of the metatag block
*/
private static _getMetaTagValues(this: NodeEditBehaviorScriptInstance) {
const typeHandler = this.editorManager.getModel('default').handlers[0] as MonacoEditorScriptMetaMods;
return typeHandler &&
typeHandler.getMetaBlock &&
typeHandler.getMetaBlock() &&
typeHandler.getMetaBlock().content;
};
static saveChanges(this: NodeEditBehaviorScriptInstance, resultStorage: Partial<CRM.ScriptNode>) {
resultStorage.value.metaTags = this._getMetaTagValues() || {};
resultStorage.value.launchMode = this.$.dropdownMenu.selected;
this._saveEditorContents();
this.finishEditing();
window.externalEditor.cancelOpenFiles();
this.editorManager.destroy();
this.fullscreenEditorManager &&
this.fullscreenEditorManager.destroy();
this.editorMode = 'main';
this._enableButtons();
this.active = false;
};
private static _onPermissionsDialogOpen(extensionWideEnabledPermissions: string[],
settingsStorage: Partial<CRM.ScriptNode>) {
let el, svg;
const showBotEls = Array.prototype.slice.apply(window.app.shadowRoot.querySelectorAll('.requestPermissionsShowBot'));
const newListeners: (() => void)[] = [];
showBotEls.forEach((showBotEl: HTMLElement) => {
this._permissionDialogListeners.forEach((listener) => {
showBotEl.removeEventListener('click', listener);
});
const listener = () => {
el = $(showBotEl).parent().parent().children('.requestPermissionsPermissionBotCont')[0] as HTMLElement & {
animation: Animation;
};
svg = $(showBotEl).find('.requestPermissionsSvg')[0];
if ((svg as any).__rotated) {
window.setTransform(svg, 'rotate(90deg)');
(svg as any).rotated = false;
} else {
window.setTransform(svg, 'rotate(270deg)');
(svg as any).rotated = true;
}
if (el.animation && el.animation.reverse) {
el.animation.reverse();
} else {
el.animation = el.animate([
{
height: '0'
}, {
height: el.scrollHeight + 'px'
}
], {
duration: 250,
easing: 'cubic-bezier(0.215, 0.610, 0.355, 1.000)',
fill: 'both'
});
}
};
newListeners.push(listener);
showBotEl.addEventListener('click', listener);
});
this._permissionDialogListeners = newListeners;
let permission: CRM.Permission;
const requestPermissionButtonElements = Array.prototype.slice.apply(window.app.shadowRoot.querySelectorAll('.requestPermissionButton'));
requestPermissionButtonElements.forEach((requestPermissionButton: HTMLPaperToggleButtonElement & {
__listener: Function;
}) => {
if (requestPermissionButton.__listener) {
requestPermissionButton.removeEventListener('click', requestPermissionButton.__listener as any);
}
const fn = () => {
permission = requestPermissionButton.previousElementSibling.previousElementSibling.textContent as CRM.Permission;
const slider = requestPermissionButton;
if (requestPermissionButton.checked) {
if (Array.prototype.slice.apply(extensionWideEnabledPermissions).indexOf(permission) === -1) {
if (!(browserAPI.permissions)) {
window.app.util.showToast(`Not asking for permission ${permission} as your browser does not support asking for permissions`);
return;
}
browserAPI.permissions.request({
permissions: [permission as _browser.permissions.Permission]
}).then((accepted) => {
if (!accepted) {
//The user didn't accept, don't pretend it's active when it's not, turn it off
slider.checked = false;
} else {
//Accepted, remove from to-request permissions if it's there
browserAPI.storage.local.get<CRM.StorageLocal>().then((e) => {
const permissionsToRequest = e.requestPermissions;
permissionsToRequest.splice(permissionsToRequest.indexOf(permission), 1);
browserAPI.storage.local.set({
requestPermissions: permissionsToRequest
});
});
//Add to script's permissions
settingsStorage.permissions = settingsStorage.permissions || [];
settingsStorage.permissions.push(permission);
}
});
} else {
//Add to script's permissions
settingsStorage.permissions = settingsStorage.permissions || [];
settingsStorage.permissions.push(permission);
}
} else {
//Remove from script's permissions
settingsStorage.permissions.splice(settingsStorage.permissions.indexOf(permission), 1);
}
};
requestPermissionButton.addEventListener('click', fn);
requestPermissionButton.__listener = fn;
});
}
static openPermissionsDialog(this: NodeEditBehaviorScriptInstance, item: Polymer.ClickEvent|CRM.ScriptNode) {
return new Promise(async (resolve) => {
let nodeItem: CRM.ScriptNode;
let settingsStorage: Partial<CRM.ScriptNode>;
if (!item || item.type === 'tap') {
//It's an event, ignore it
nodeItem = this.item;
settingsStorage = this.newSettings;
} else {
nodeItem = item as CRM.ScriptNode;
settingsStorage = item as CRM.ScriptNode;
}
//Prepare all permissions
const { permissions } = browserAPI.permissions ? await browserAPI.permissions.getAll() : {
permissions: []
};
if (!(browserAPI.permissions)) {
window.app.util.showToast('Not toggling for browser permissions as your browser does not support them');
}
if (!nodeItem.permissions) {
nodeItem.permissions = [];
}
const scriptPermissions = nodeItem.permissions;
const crmPermissions = window.app.templates.getScriptPermissions();
const askedPermissions = (nodeItem.nodeInfo &&
nodeItem.nodeInfo.permissions) || [];
const requiredActive: {
name: string;
toggled: boolean;
required: boolean;
description: string;
}[] = [];
const requiredInactive: {
name: string;
toggled: boolean;
required: boolean;
description: string;
}[] = [];
const nonRequiredActive: {
name: string;
toggled: boolean;
required: boolean;
description: string;
}[] = [];
const nonRequiredNonActive: {
name: string;
toggled: boolean;
required: boolean;
description: string;
}[] = [];
let isAsked;
let isActive;
let permissionObj;
crmPermissions.forEach(function(permission) {
isAsked = askedPermissions.indexOf(permission) > -1;
isActive = scriptPermissions.indexOf(permission as CRM.Permission) > -1;
permissionObj = {
name: permission,
toggled: isActive,
required: isAsked,
description: window.app.templates.getPermissionDescription(permission)
};
if (isAsked && isActive) {
requiredActive.push(permissionObj);
} else if (isAsked && !isActive) {
requiredInactive.push(permissionObj);
} else if (!isAsked && isActive) {
nonRequiredActive.push(permissionObj);
} else {
nonRequiredNonActive.push(permissionObj);
}
});
const permissionList = nonRequiredActive;
permissionList.push.apply(permissionList, requiredActive);
permissionList.push.apply(permissionList, requiredInactive);
permissionList.push.apply(permissionList, nonRequiredNonActive);
window.app.$.scriptPermissionsTemplate.items = permissionList;
window.app.shadowRoot.querySelector('.requestPermissionsScriptName').innerHTML = 'Managing permisions for script "' + nodeItem.name;
const scriptPermissionDialog = window.app.$.scriptPermissionDialog;
scriptPermissionDialog.addEventListener('iron-overlay-opened', () => {
this._onPermissionsDialogOpen(permissions, settingsStorage);
});
scriptPermissionDialog.addEventListener('iron-overlay-closed', () => {
resolve(null);
});
scriptPermissionDialog.open();
});
};
/**
* Reloads the editor completely (to apply new settings)
*/
static reloadEditor(this: NodeEditBehaviorScriptInstance) {
if (this.editorManager) {
if (this.editorMode === 'main') {
this.newSettings.value.script = this.editorManager.getValue();
} else if (this.editorMode === 'background') {
this.newSettings.value.backgroundScript = this.editorManager.getValue();
} else {
try {
this.newSettings.value.options = JSON.parse(this.editorManager.getValue());
} catch(e) {
this.newSettings.value.options = this.editorManager.getValue();
}
}
}
let value: string;
if (this.editorMode === 'main') {
value = this.newSettings.value.script;
} else if (this.editorMode === 'background') {
value = this.newSettings.value.backgroundScript;
} else {
if (typeof this.newSettings.value.options === 'string') {
value = this.newSettings.value.options;
} else {
value = JSON.stringify(this.newSettings.value.options);
}
}
if (this.fullscreen) {
this.fullscreenEditorManager.reset();
const editor = this.fullscreenEditorManager.editor;
if (!this.fullscreenEditorManager.isDiff(editor)) {
editor.setValue(value);
}
} else {
this.editorManager.reset();
const editor = this.editorManager.editor;
if (!this.editorManager.isDiff(editor)) {
editor.setValue(value);
}
}
};
private static _createKeyBindingListener(this: NodeEditBehaviorScriptInstance, element: HTMLPaperInputElement, keyBinding: {
name: string;
defaultKey: string;
monacoKey: string;
storageKey: keyof CRM.KeyBindings;
}) {
return async (event: KeyboardEvent) => {
event.preventDefault();
//Make sure it's not just one modifier key being pressed and nothing else
if (event.keyCode < 16 || event.keyCode > 18) {
//Make sure at least one modifier is being pressed
if (event.altKey || event.shiftKey || event.ctrlKey) {
const values = [];
if (event.ctrlKey) {
values.push('Ctrl');
}
if (event.altKey) {
values.push('Alt');
}
if (event.shiftKey) {
values.push('Shift');
}
values.push(String.fromCharCode(event.keyCode));
const value = element.value = values.join('-');
element.setAttribute('data-prev-value', value);
const keyBindings = await this.getKeyBindings();
window.app.settings.editor.keyBindings = window.app.settings.editor.keyBindings || {
goToDef: keyBindings[0].defaultKey,
rename: keyBindings[1].defaultKey
};
window.app.settings.editor.keyBindings[keyBinding.storageKey] = value;
this._initKeyBinding(keyBinding);
}
}
element.value = element.getAttribute('data-prev-value') || '';
return;
};
};
static getKeyBindingsSync(this: Polymer.ElementI18N): {
name: string;
defaultKey: string;
monacoKey: string;
storageKey: keyof CRM.KeyBindings;
}[] {
return [{
name: this.___(I18NKeys.options.editPages.code.goToDef),
defaultKey: 'Ctrl-F12',
monacoKey: 'editor.action.goToTypeDefinition',
storageKey: 'goToDef'
}, {
name: this.___(I18NKeys.options.editPages.code.rename),
defaultKey: 'Ctrl-F2',
monacoKey: 'editor.action.rename',
storageKey: 'rename'
}];
}
static async getKeyBindings(this: Polymer.ElementI18N): Promise<{
name: string;
defaultKey: string;
monacoKey: string;
storageKey: keyof CRM.KeyBindings;
}[]> {
return [{
name: await this.__async(I18NKeys.options.editPages.code.goToDef),
defaultKey: 'Ctrl-F12',
monacoKey: 'editor.action.goToTypeDefinition',
storageKey: 'goToDef'
}, {
name: await this.__async(I18NKeys.options.editPages.code.rename),
defaultKey: 'Ctrl-F2',
monacoKey: 'editor.action.rename',
storageKey: 'rename'
}];
}
private static _translateKeyCombination(this: NodeEditBehaviorScriptInstance, keys: string): number[] {
const monacoKeys: number[] = [];
for (const key of keys.split('-')) {
if (key === 'Ctrl') {
monacoKeys.push(monaco.KeyMod.CtrlCmd);
} else if (key === 'Alt') {
monacoKeys.push(monaco.KeyMod.Alt);
} else if (key === 'Shift') {
monacoKeys.push(monaco.KeyMod.Shift);
} else {
if (monaco.KeyCode[`KEY_${key.toUpperCase()}` as any]) {
monacoKeys.push(monaco.KeyCode[`KEY_${key.toUpperCase()}` as any] as any);
}
}
}
return monacoKeys;
}
private static _initKeyBinding(this: NodeEditBehaviorScriptInstance, keyBinding: {
name: string;
defaultKey: string;
monacoKey: string;
storageKey: "goToDef" | "rename";
}, key: string = keyBinding.defaultKey) {
const editor = this.editorManager.getEditorAsMonaco();
if (!this.editorManager.isTextarea(editor) && !this.editorManager.isDiff(editor)) {
const oldAction = editor.getAction(keyBinding.monacoKey) as monaco.editor.IEditorAction & {
_precondition: {
expr: {
key: string;
defaultValue: boolean;
}[];
}
}
editor.addAction({
id: keyBinding.monacoKey,
label: keyBinding.name,
run: () => {
oldAction.run();
},
keybindings: this._translateKeyCombination(key),
precondition: oldAction._precondition.expr.map((condition) => {
return condition.key;
}).join('&&')
});
}
}
/**
* Initializes the keybindings for the editor
*/
private static async _initKeyBindings(this: NodeEditBehaviorScriptInstance) {
const keyBindings = await this.getKeyBindings();
for (const keyBinding of keyBindings) {
this._initKeyBinding(keyBinding);
}
};
/**
* Triggered when the monaco editor has been loaded, fills it with the options and fullscreen element
*/
static async editorLoaded(this: NodeEditBehaviorScriptInstance) {
const editorManager = this.editorManager;
(editorManager.getTypeHandler() as any)[0].listen('metaChange', (_oldMetaTags: MetaBlock, newMetaTags: MetaBlock) => {
if (this.editorMode === 'main') {
this.newSettings.value.metaTags = JSON.parse(JSON.stringify(newMetaTags)).content;
}
});
this.$.mainEditorTab.classList.add('active');
this.$.backgroundEditorTab.classList.remove('active');
editorManager.editor.getDomNode().classList.remove('stylesheet-edit-codeMirror');
editorManager.editor.getDomNode().classList.add('script-edit-codeMirror');
editorManager.editor.getDomNode().classList.add('small');
if (this.fullscreen) {
this.$.editorFullScreen.children[0].innerHTML = '<path d="M10 32h6v6h4V28H10v4zm6-16h-6v4h10V10h-4v6zm12 22h4v-6h6v-4H28v10zm4-22v-6h-4v10h10v-4h-6z"/>';
}
await window.__.ready;
this._initKeyBindings();
};
onLangChanged(this: NodeEditBehaviorScriptInstance) {
this._initKeyBindings();
}
/**
* Loads the monaco editor
*/
private static async loadEditor(this: NodeEditBehaviorScriptInstance, content: string = this.item.value.script) {
const placeHolder = $(this.$.editor);
this.editorHeight = placeHolder.height();
this.editorWidth = placeHolder.width();
const keyBindings = await this.getKeyBindings();
!window.app.settings.editor && (window.app.settings.editor = {
theme: 'dark',
zoom: '100',
keyBindings: {
goToDef: keyBindings[0].defaultKey,
rename: keyBindings[1].defaultKey
},
cssUnderlineDisabled: false,
disabledMetaDataHighlight: false
});
const isTs = this.item.value.ts && this.item.value.ts.enabled;
const type = isTs ? this.$.editor.EditorMode.TS_META :
this.$.editor.EditorMode.JS_META;
this.editorManager = await this.$.editor.create(type, {
value: content,
language: isTs ? 'typescript' : 'javascript',
theme: window.app.settings.editor.theme === 'dark' ? 'vs-dark' : 'vs',
wordWrap: 'off',
fontSize: (~~window.app.settings.editor.zoom / 100) * 14,
folding: true
});
this.editorLoaded();
};
static init(this: NodeEditBehaviorScriptInstance) {
this._init();
this._CEBIinit();
this.$.dropdownMenu.init();
this.$.exportMenu.init();
this.$.exportMenu.$.dropdownSelected.innerText = 'EXPORT AS';
this.initDropdown();
this.selectorStateChange(0, this.newSettings.value.launchMode);
window.app.$.editorToolsRibbonContainer.classList.remove('editingStylesheet');
window.app.$.editorToolsRibbonContainer.classList.add('editingScript');
window.scriptEdit = this;
window.externalEditor.init();
if (window.app.storageLocal.recoverUnsavedData) {
browserAPI.storage.local.set({
editing: {
val: this.item.value.script,
id: this.item.id,
mode: this.editorMode,
crmType: window.app.crmTypes
}
});
this.savingInterval = window.setInterval(() => {
if (this.active && this.editorManager) {
//Save
const val = this.editorManager.getValue();
browserAPI.storage.local.set({
editing: {
val: val,
id: this.item.id,
mode: this.editorMode,
crmType: window.app.crmTypes
}
}).catch(() => {});
} else {
//Stop this interval
browserAPI.storage.local.set({
editing: false
});
window.clearInterval(this.savingInterval);
}
}, 5000);
}
this.active = true;
setTimeout(() => {
this.loadEditor();
}, 750);
}
}
ScriptEditElement
if (window.objectify) {
window.register(SCE);
} else {
window.addEventListener('RegisterReady', () => {
window.register(SCE);
});
}
}
export type ScriptEdit = Polymer.El<'script-edit', typeof ScriptEditElement.SCE &
typeof ScriptEditElement.scriptEditProperties>; | the_stack |
import { RotationType } from './RotationType';
import { EasingFunction, EasingFunctions } from '../Util/EasingFunctions';
import { ActionQueue } from './ActionQueue';
import { Repeat } from './Action/Repeat';
import { RepeatForever } from './Action/RepeatForever';
import { MoveBy } from './Action/MoveBy';
import { MoveTo } from './Action/MoveTo';
import { RotateTo } from './Action/RotateTo';
import { RotateBy } from './Action/RotateBy';
import { ScaleTo } from './Action/ScaleTo';
import { ScaleBy } from './Action/ScaleBy';
import { CallMethod } from './Action/CallMethod';
import { EaseTo } from './Action/EaseTo';
import { Blink } from './Action/Blink';
import { Fade } from './Action/Fade';
import { Delay } from './Action/Delay';
import { Die } from './Action/Die';
import { Follow } from './Action/Follow';
import { Meet } from './Action/Meet';
import { Vector } from '../Math/vector';
import { Entity } from '../EntityComponentSystem/Entity';
/**
* The fluent Action API allows you to perform "actions" on
* [[Actor|Actors]] such as following, moving, rotating, and
* more. You can implement your own actions by implementing
* the [[Action]] interface.
*/
export class ActionContext {
private _entity: Entity;
private _queue: ActionQueue;
constructor(entity: Entity) {
this._entity = entity;
this._queue = new ActionQueue(entity);
}
public getQueue(): ActionQueue {
return this._queue;
}
public update(elapsedMs: number) {
this._queue.update(elapsedMs);
}
/**
* Clears all queued actions from the Actor
*/
public clearActions(): void {
this._queue.clearActions();
}
/**
* This method will move an actor to the specified `x` and `y` position over the
* specified duration using a given [[EasingFunctions]] and return back the actor. This
* method is part of the actor 'Action' fluent API allowing action chaining.
* @param pos The x,y vector location to move the actor to
* @param duration The time it should take the actor to move to the new location in milliseconds
* @param easingFcn Use [[EasingFunctions]] or a custom function to use to calculate position, Default is [[EasingFunctions.Linear]]
*/
public easeTo(pos: Vector, duration: number, easingFcn?: EasingFunction): ActionContext
/**
* This method will move an actor to the specified `x` and `y` position over the
* specified duration using a given [[EasingFunctions]] and return back the actor. This
* method is part of the actor 'Action' fluent API allowing action chaining.
* @param x The x location to move the actor to
* @param y The y location to move the actor to
* @param duration The time it should take the actor to move to the new location in milliseconds
* @param easingFcn Use [[EasingFunctions]] or a custom function to use to calculate position, Default is [[EasingFunctions.Linear]]
*/
public easeTo(x: number, y: number, duration: number, easingFcn?: EasingFunction): ActionContext
public easeTo(...args: any[]): ActionContext {
let x = 0;
let y = 0;
let duration = 0;
let easingFcn = EasingFunctions.Linear;
if (args[0] instanceof Vector) {
x = args[0].x;
y = args[0].y;
duration = args[1];
easingFcn = args[2] ?? easingFcn;
} else {
x = args[0];
y = args[1];
duration = args[2];
easingFcn = args[3] ?? easingFcn;
}
this._queue.add(new EaseTo(this._entity, x, y, duration, easingFcn));
return this;
}
/**
* This method will move an actor to the specified x and y position at the
* speed specified (in pixels per second) and return back the actor. This
* method is part of the actor 'Action' fluent API allowing action chaining.
* @param pos The x,y vector location to move the actor to
* @param speed The speed in pixels per second to move
*/
public moveTo(pos: Vector, speed: number): ActionContext;
/**
* This method will move an actor to the specified x and y position at the
* speed specified (in pixels per second) and return back the actor. This
* method is part of the actor 'Action' fluent API allowing action chaining.
* @param x The x location to move the actor to
* @param y The y location to move the actor to
* @param speed The speed in pixels per second to move
*/
public moveTo(x: number, y: number, speed: number): ActionContext;
public moveTo(xOrPos: number | Vector, yOrSpeed: number, speedOrUndefined?: number | undefined): ActionContext {
let x = 0;
let y = 0;
let speed = 0;
if (xOrPos instanceof Vector) {
x = xOrPos.x;
y = xOrPos.y;
speed = yOrSpeed;
} else {
x = xOrPos;
y = yOrSpeed;
speed = speedOrUndefined;
}
this._queue.add(new MoveTo(this._entity, x, y, speed));
return this;
}
/**
* This method will move an actor by the specified x offset and y offset from its current position, at a certain speed.
* This method is part of the actor 'Action' fluent API allowing action chaining.
* @param xOffset The x offset to apply to this actor
* @param yOffset The y location to move the actor to
* @param speed The speed in pixels per second the actor should move
*/
public moveBy(offset: Vector, speed: number): ActionContext;
public moveBy(xOffset: number, yOffset: number, speed: number): ActionContext;
public moveBy(xOffsetOrVector: number | Vector, yOffsetOrSpeed: number, speedOrUndefined?: number | undefined): ActionContext {
let xOffset = 0;
let yOffset = 0;
let speed = 0;
if (xOffsetOrVector instanceof Vector) {
xOffset = xOffsetOrVector.x;
yOffset = xOffsetOrVector.y;
speed = yOffsetOrSpeed;
} else {
xOffset = xOffsetOrVector;
yOffset = yOffsetOrSpeed;
speed = speedOrUndefined;
}
this._queue.add(new MoveBy(this._entity, xOffset, yOffset, speed));
return this;
}
/**
* This method will rotate an actor to the specified angle at the speed
* specified (in radians per second) and return back the actor. This
* method is part of the actor 'Action' fluent API allowing action chaining.
* @param angleRadians The angle to rotate to in radians
* @param speed The angular velocity of the rotation specified in radians per second
* @param rotationType The [[RotationType]] to use for this rotation
*/
public rotateTo(angleRadians: number, speed: number, rotationType?: RotationType): ActionContext {
this._queue.add(new RotateTo(this._entity, angleRadians, speed, rotationType));
return this;
}
/**
* This method will rotate an actor by the specified angle offset, from it's current rotation given a certain speed
* in radians/sec and return back the actor. This method is part
* of the actor 'Action' fluent API allowing action chaining.
* @param angleRadiansOffset The angle to rotate to in radians relative to the current rotation
* @param speed The speed in radians/sec the actor should rotate at
* @param rotationType The [[RotationType]] to use for this rotation, default is shortest path
*/
public rotateBy(angleRadiansOffset: number, speed: number, rotationType?: RotationType): ActionContext {
this._queue.add(new RotateBy(this._entity, angleRadiansOffset, speed, rotationType));
return this;
}
/**
* This method will scale an actor to the specified size at the speed
* specified (in magnitude increase per second) and return back the
* actor. This method is part of the actor 'Action' fluent API allowing
* action chaining.
* @param size The scale to adjust the actor to over time
* @param speed The speed of scaling specified in magnitude increase per second
*/
public scaleTo(size: Vector, speed: Vector): ActionContext;
/**
* This method will scale an actor to the specified size at the speed
* specified (in magnitude increase per second) and return back the
* actor. This method is part of the actor 'Action' fluent API allowing
* action chaining.
* @param sizeX The scaling factor to apply on X axis
* @param sizeY The scaling factor to apply on Y axis
* @param speedX The speed of scaling specified in magnitude increase per second on X axis
* @param speedY The speed of scaling specified in magnitude increase per second on Y axis
*/
public scaleTo(sizeX: number, sizeY: number, speedX: number, speedY: number): ActionContext;
public scaleTo(sizeXOrVector: number | Vector,
sizeYOrSpeed: number | Vector,
speedXOrUndefined?: number | undefined,
speedYOrUndefined?: number | undefined): ActionContext {
let sizeX = 1;
let sizeY = 1;
let speedX = 0;
let speedY = 0;
if (sizeXOrVector instanceof Vector && sizeYOrSpeed instanceof Vector) {
sizeX = sizeXOrVector.x;
sizeY = sizeXOrVector.y;
speedX = sizeYOrSpeed.x;
speedY = sizeYOrSpeed.y;
}
if (typeof sizeXOrVector === 'number' && typeof sizeYOrSpeed === 'number') {
sizeX = sizeXOrVector;
sizeY = sizeYOrSpeed;
speedX = speedXOrUndefined;
speedY = speedYOrUndefined;
}
this._queue.add(new ScaleTo(this._entity, sizeX, sizeY, speedX, speedY));
return this;
}
/**
* This method will scale an actor by an amount relative to the current scale at a certain speed in scale units/sec
* and return back the actor. This method is part of the
* actor 'Action' fluent API allowing action chaining.
* @param offset The scaling factor to apply to the actor
* @param speed The speed to scale at in scale units/sec
*/
public scaleBy(offset: Vector, speed: number): ActionContext;
/**
* This method will scale an actor by an amount relative to the current scale at a certain speed in scale units/sec
* and return back the actor. This method is part of the
* actor 'Action' fluent API allowing action chaining.
* @param sizeOffsetX The scaling factor to apply on X axis
* @param sizeOffsetY The scaling factor to apply on Y axis
* @param speed The speed to scale at in scale units/sec
*/
public scaleBy(sizeOffsetX: number, sizeOffsetY: number, speed: number): ActionContext;
public scaleBy(sizeOffsetXOrVector: number | Vector, sizeOffsetYOrSpeed: number, speed?: number | undefined): ActionContext {
let sizeOffsetX = 1;
let sizeOffsetY = 1;
if (sizeOffsetXOrVector instanceof Vector) {
sizeOffsetX = sizeOffsetXOrVector.x;
sizeOffsetY = sizeOffsetXOrVector.y;
speed = sizeOffsetYOrSpeed;
}
if (typeof sizeOffsetXOrVector === 'number' && typeof sizeOffsetYOrSpeed === 'number') {
sizeOffsetX = sizeOffsetXOrVector;
sizeOffsetY = sizeOffsetYOrSpeed;
}
this._queue.add(new ScaleBy(this._entity, sizeOffsetX, sizeOffsetY, speed));
return this;
}
/**
* This method will cause an actor to blink (become visible and not
* visible). Optionally, you may specify the number of blinks. Specify the amount of time
* the actor should be visible per blink, and the amount of time not visible.
* This method is part of the actor 'Action' fluent API allowing action chaining.
* @param timeVisible The amount of time to stay visible per blink in milliseconds
* @param timeNotVisible The amount of time to stay not visible per blink in milliseconds
* @param numBlinks The number of times to blink
*/
public blink(timeVisible: number, timeNotVisible: number, numBlinks: number = 1): ActionContext {
this._queue.add(new Blink(this._entity, timeVisible, timeNotVisible, numBlinks));
return this;
}
/**
* This method will cause an actor's opacity to change from its current value
* to the provided value by a specified time (in milliseconds). This method is
* part of the actor 'Action' fluent API allowing action chaining.
* @param opacity The ending opacity
* @param time The time it should take to fade the actor (in milliseconds)
*/
public fade(opacity: number, time: number): ActionContext {
this._queue.add(new Fade(this._entity, opacity, time));
return this;
}
/**
* This method will delay the next action from executing for a certain
* amount of time (in milliseconds). This method is part of the actor
* 'Action' fluent API allowing action chaining.
* @param time The amount of time to delay the next action in the queue from executing in milliseconds
*/
public delay(time: number): ActionContext {
this._queue.add(new Delay(time));
return this;
}
/**
* This method will add an action to the queue that will remove the actor from the
* scene once it has completed its previous Any actions on the
* action queue after this action will not be executed.
*/
public die(): ActionContext {
this._queue.add(new Die(this._entity));
return this;
}
/**
* This method allows you to call an arbitrary method as the next action in the
* action queue. This is useful if you want to execute code in after a specific
* action, i.e An actor arrives at a destination after traversing a path
*/
public callMethod(method: () => any): ActionContext {
this._queue.add(new CallMethod(method));
return this;
}
/**
* This method will cause the actor to repeat all of the actions built in
* the `repeatBuilder` callback. If the number of repeats
* is not specified it will repeat forever. This method is part of
* the actor 'Action' fluent API allowing action chaining
*
* ```typescript
* // Move up in a zig-zag by repeated moveBy's
* actor.actions.repeat(repeatCtx => {
* repeatCtx.moveBy(10, 0, 10);
* repeatCtx.moveBy(0, 10, 10);
* }, 5);
* ```
*
* @param repeatBuilder The builder to specify the repeatable list of actions
* @param times The number of times to repeat all the previous actions in the action queue. If nothing is specified the actions
* will repeat forever
*/
public repeat(repeatBuilder: (repeatContext: ActionContext) => any, times?: number): ActionContext {
if (!times) {
this.repeatForever(repeatBuilder);
return this;
}
this._queue.add(new Repeat(this._entity, repeatBuilder, times));
return this;
}
/**
* This method will cause the actor to repeat all of the actions built in
* the `repeatBuilder` callback. If the number of repeats
* is not specified it will repeat forever. This method is part of
* the actor 'Action' fluent API allowing action chaining
*
* ```typescript
* // Move up in a zig-zag by repeated moveBy's
* actor.actions.repeat(repeatCtx => {
* repeatCtx.moveBy(10, 0, 10);
* repeatCtx.moveBy(0, 10, 10);
* }, 5);
* ```
*
* @param repeatBuilder The builder to specify the repeatable list of actions
*/
public repeatForever(repeatBuilder: (repeatContext: ActionContext) => any): ActionContext {
this._queue.add(new RepeatForever(this._entity, repeatBuilder));
return this;
}
/**
* This method will cause the entity to follow another at a specified distance
* @param entity The entity to follow
* @param followDistance The distance to maintain when following, if not specified the actor will follow at the current distance.
*/
public follow(entity: Entity, followDistance?: number): ActionContext {
if (followDistance === undefined) {
this._queue.add(new Follow(this._entity, entity));
} else {
this._queue.add(new Follow(this._entity, entity, followDistance));
}
return this;
}
/**
* This method will cause the entity to move towards another until they
* collide "meet" at a specified speed.
* @param entity The entity to meet
* @param speed The speed in pixels per second to move, if not specified it will match the speed of the other actor
*/
public meet(entity: Entity, speed?: number): ActionContext {
if (speed === undefined) {
this._queue.add(new Meet(this._entity, entity));
} else {
this._queue.add(new Meet(this._entity, entity, speed));
}
return this;
}
/**
* Returns a promise that resolves when the current action queue up to now
* is finished.
* @deprecated Use `toPromise()` will be removed in v0.26.0
*/
public asPromise(): Promise<void> {
return this.toPromise();
}
/**
* Returns a promise that resolves when the current action queue up to now
* is finished.
*/
public toPromise(): Promise<void> {
const temp = new Promise<void>((resolve) => {
this._queue.add(
new CallMethod(() => {
resolve();
})
);
});
return temp;
}
} | the_stack |
import Logger from '../Utils/Logger';
import SpeedChecker from '../Utils/networkSpeedChecker';
import LoaderStatus from '../Loaders/LoaderStatus';
import Errors from '../Errors/index';
import Events from '../Events/index';
import FetchStreamLoader from '../Loaders/FetchStreamLoader';
import MozChunkedLoader from '../Loaders/XHRMozChunkedLoader';
import MSStreamLoader from '../Loaders/XHRMsStreamLoader';
import RangeLoader from '../Loaders/XHRRangeLoader';
import WebSocketLoader from '../Loaders/WebSocketLoader';
import FragmentLoader from '../Loaders/FragmentLoader';
import RangeSeekHandler from '../Utils/range-seek-handler';
import ParamSeekHandler from '../Utils/param-seek-handler';
import {
RuntimeException,
IllegalStateException,
InvalidArgumentException
} from '../Utils/Exception';
import MediaConfig from '../Interfaces/MediaConfig';
import SeekRange from '../Interfaces/SeekRange';
import ErrorData from '../Interfaces/ErrorData';
import HJPlayerConfig from '../Interfaces/HJPlayerConfig';
import TSManifest from '../Interfaces/TSManifest';
import { TSExtraData } from '../Interfaces/TSExtraData';
class IOController {
/**
* 文件标签
*/
Tag: string
/**
* 媒体文件设置
*/
private _mediaConfig: MediaConfig
/**
* 用户设置
*/
private _config: HJPlayerConfig
/**
* 存储的buffer初始大小
*/
private _stashInitialSize: number
/**
* 缓冲池已用大小
*/
private _stashUsed: number
/**
* 存储的buffer尺寸
*/
private _stashSize: number
/**
* 是否允许 LoaderIO 建立缓冲池
*/
private _enableStash: boolean
/**
* 缓冲池的尺寸
*/
private _bufferSize: number
/**
* LoaderIO的缓冲池
*/
private _stashBuffer: ArrayBuffer
/**
* 缓冲池缓冲的Buffer数据流在媒体文件中的位置
*/
private _stashByteStart: number
/**
* 加载器实例
*/
private _loader:
| FetchStreamLoader
| MozChunkedLoader
| MSStreamLoader
| RangeLoader
| WebSocketLoader
| FragmentLoader
| null
// 加载媒体文件的加载器实例
/**
* 加载媒体文件的加载器定义类
*/
private _loaderClass:
| FetchStreamLoader
| MozChunkedLoader
| MSStreamLoader
| RangeLoader
| WebSocketLoader
| FragmentLoader
| any
/**
* 视频 seek 处理函数, 可根据后台服务自己去定义
*/
private _seekHandler: ParamSeekHandler | RangeSeekHandler | any
/**
* 媒体设置里的URL是否为 WebSocket 地址
*/
private _isWebSocketURL: boolean
/**
* 加载文件体积
*/
private _refTotalLength: number | null
/**
* 总体文件大小
*/
private _totalLength: number | null
/**
* 全部请求的标志
*/
private _fullRequestFlag: boolean
/**
* 请求的范围 from xxx, to xxx
*/
private _currentRange: SeekRange | null
/**
* HTTP 301/302跳转后的地址
*/
private _redirectedURL: string | null
/**
* 计算后的网速标准值
*/
private _speedNormalized: number | null
/**
* 网速标准表, 用于把 networkSpeedChecker 估算后得到的网速经计算后得到标准值 _speedNormalized
*/
private _speedNormalizeList: Array<number>
/**
* 是否过早的遇到 EOF
*/
private _isEarlyEofReconnecting: boolean
/**
* 是否暂停
*/
private _paused: boolean
/**
* 恢复下载时的续传点
*/
private _resumeFrom: number
// 恢复下载时的续传点
/**
* 数据透传到IOController的处理函数
*/
private _onDataArrival: Function | null
/**
* 当 seek 结束时上报的函数
*/
private _onSeeked: Function | null
/**
* 发生错误的处理函数
*/
private _onError: Function | null
/**
* 加载完成时透传的函数
*/
private _onComplete: Function | null
/**
* 遇到 HTTP 301/302 网址跳转时处理的函数
*/
private _onRedirect: Function | null
/**
* 当从 EarlyEof 恢复时透传的函数
*/
private _onRecoveredEarlyEof: Function | null
/**
* 当M3U8文档被解析之后向上提交
*/
private _onManifestParsed: Function | null
/**
* 额外的数据, 在flv.js中用于传输segment的索引值
*/
private _extraData: number | null;
/**
* hls 解析的Levels
*/
private _tsExtraData: TSExtraData | undefined
/**
* 网速检查器
*/
private _speedChecker: SpeedChecker
constructor(dataSource: MediaConfig, config: HJPlayerConfig, extraData: number) {
this.Tag = 'IOController';
this._config = config;
this._extraData = extraData;
this._stashInitialSize = 1024 * 384; // default initial size: 384KB
if(config.stashInitialSize !== undefined && config.stashInitialSize > 0) {
// apply from config
this._stashInitialSize = config.stashInitialSize * 1024;
}
this._stashUsed = 0;
this._stashSize = this._stashInitialSize;
this._bufferSize = 1024 * 1024 * 3; // initial size: 3MB
this._stashBuffer = new ArrayBuffer(this._bufferSize);
this._stashByteStart = 0;
this._enableStash = true;
if(config.enableStashBuffer === false) {
this._enableStash = false;
}
this._loader = null;
this._loaderClass = null;
this._seekHandler = null;
this._mediaConfig = dataSource;
this._isWebSocketURL = /wss?:\/\/(.+?)/.test(dataSource.url);
this._refTotalLength = dataSource.fileSize ? dataSource.fileSize : null;
this._totalLength = this._refTotalLength;
this._tsExtraData = undefined;
this._fullRequestFlag = false;
this._currentRange = null;
this._redirectedURL = null;
this._speedNormalized = 0;
this._speedChecker = new SpeedChecker();
this._speedNormalizeList = [64, 128, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096];
this._isEarlyEofReconnecting = false;
this._paused = false;
this._resumeFrom = 0;
this._onDataArrival = null;
this._onSeeked = null;
this._onError = null;
this._onComplete = null;
this._onRedirect = null;
this._onRecoveredEarlyEof = null;
this._onManifestParsed = null;
this._selectSeekHandler();
this._selectLoader();
this._createLoader();
}
destroy() {
if(this._loader!.isWorking()) {
this._loader!.abort();
}
this._loader!.destroy();
this._loader = null;
this._loaderClass = null;
delete this._mediaConfig;
delete this._stashBuffer;
this._stashByteStart = 0;
this._bufferSize = 0;
this._stashSize = 0;
this._stashUsed = 0;
this._currentRange = null;
delete this._speedChecker;
this._isEarlyEofReconnecting = false;
this._onDataArrival = null;
this._onSeeked = null;
this._onError = null;
this._onComplete = null;
this._onRedirect = null;
this._onRecoveredEarlyEof = null;
this._onManifestParsed = null;
this._extraData = null;
}
isWorking() {
return this._loader && this._loader.isWorking() && !this._paused;
}
isPaused() {
return this._paused;
}
get status() {
return this._loader!.status;
}
get extraData() {
return this._extraData;
}
set extraData(data) {
this._extraData = data;
}
// prototype: function onDataArrival(chunks: ArrayBuffer, byteStart: number): number
get onDataArrival() {
return this._onDataArrival;
}
set onDataArrival(callback) {
this._onDataArrival = callback;
}
get onSeeked() {
return this._onSeeked;
}
set onSeeked(callback) {
this._onSeeked = callback;
}
// prototype: function onError(type: number, info: {code: number, msg: string}): void
get onError() {
return this._onError;
}
set onError(callback) {
this._onError = callback;
}
get onComplete() {
return this._onComplete;
}
set onComplete(callback) {
this._onComplete = callback;
}
get onRedirect() {
return this._onRedirect;
}
set onRedirect(callback) {
this._onRedirect = callback;
}
get onRecoveredEarlyEof() {
return this._onRecoveredEarlyEof;
}
set onRecoveredEarlyEof(callback) {
this._onRecoveredEarlyEof = callback;
}
get onManifestParsed() {
return this._onManifestParsed;
}
set onManifestParsed(callback) {
this._onManifestParsed = callback;
}
get currentURL() {
return this._mediaConfig.url;
}
get hasRedirect() {
return this._redirectedURL != null || this._mediaConfig.redirectedURL !== undefined;
}
get currentRedirectedURL() {
return this._redirectedURL || this._mediaConfig.redirectedURL;
}
// in KB/s
get currentSpeed() {
if(this._loader instanceof RangeLoader) {
// SpeedSampler is inaccuracy if loader is RangeLoader
return this._loader.currentSpeed;
}
return this._speedChecker.lastSecondKBps;
}
get loaderType() {
return this._loader!.type;
}
_selectSeekHandler() {
const config = this._config;
if(config.seekType === 'range') {
this._seekHandler = new RangeSeekHandler(this._config.rangeLoadZeroStart);
} else if(config.seekType === 'param') {
const paramStart = config.seekParamStart || 'bstart';
const paramEnd = config.seekParamEnd || 'bend';
this._seekHandler = new ParamSeekHandler(paramStart, paramEnd);
} else if(config.seekType === 'custom') {
if(typeof config.CustomSeekHandler !== 'function') {
throw new InvalidArgumentException(
'Custom seekType specified in config but invalid CustomSeekHandler!'
);
}
this._seekHandler = new config.CustomSeekHandler();
} else {
throw new InvalidArgumentException(`Invalid seekType in config: ${config.seekType}`);
}
}
_selectLoader() {
if(this._mediaConfig.type === 'flv') {
if(this._config.customLoader != null) {
this._loaderClass = this._config.customLoader;
} else if(this._isWebSocketURL) {
this._loaderClass = WebSocketLoader;
} else if(FetchStreamLoader.isSupported()) {
this._loaderClass = FetchStreamLoader;
} else if(MozChunkedLoader.isSupported()) {
this._loaderClass = MozChunkedLoader;
} else if(RangeLoader.isSupported()) {
this._loaderClass = RangeLoader;
} else {
throw new RuntimeException(
"Your browser doesn't support xhr with arraybuffer responseType!"
);
}
} else if(this._mediaConfig.type === 'm3u8') {
this._loaderClass = FragmentLoader;
}
}
_createLoader() {
this._loader = new this._loaderClass(this._seekHandler, this._config);
this._bindLoaderEvents();
}
_bindLoaderEvents() {
if(!this._loader) return;
if(this._loader.needStashBuffer === false) {
this._enableStash = false;
}
this._loader.onContentLengthKnown = this._onContentLengthKnown.bind(this);
this._loader.onURLRedirect = this._onURLRedirect.bind(this);
this._loader.onDataArrival = this._onLoaderChunkArrival.bind(this);
this._loader.onComplete = this._onLoaderComplete.bind(this);
this._loader.onError = this._onLoaderError.bind(this);
if(this._mediaConfig.type === 'm3u8') {
this._loader.on(Events.MANIFEST_PARSED, (data: TSManifest) => {
this._onManifestParsed && this._onManifestParsed(data);
});
}
}
/**
* 从选择的点开始加载
* @param optionalFrom 开始加载的点
*/
open(optionalFrom?: number) {
this._currentRange = { from: 0, to: -1 };
if(optionalFrom) {
this._currentRange.from = optionalFrom;
}
this._speedChecker.reset();
if(!optionalFrom) {
this._fullRequestFlag = true;
}
this._loader && this._loader.startLoad(this._mediaConfig, { ...this._currentRange });
}
abort() {
this._loader!.abort();
if(this._paused) {
this._paused = false;
this._resumeFrom = 0;
}
}
pause() {
if(this.isWorking()) {
this._loader!.abort();
if(this._currentRange) {
if(this._stashUsed !== 0) {
this._resumeFrom = this._stashByteStart;
this._currentRange.to = this._stashByteStart - 1;
} else {
this._resumeFrom = this._currentRange.to + 1;
}
}
this._stashUsed = 0;
this._stashByteStart = 0;
this._paused = true;
}
}
resume() {
if(this._paused) {
this._paused = false;
const bytes = this._resumeFrom;
this._resumeFrom = 0;
this._internalSeek(bytes, true);
}
}
seek(bytes: number) {
this._paused = false;
this._stashUsed = 0;
this._stashByteStart = 0;
this._internalSeek(bytes, true);
}
/**
* hls流处理seek, 查找相应的ts文件, 然后下载
*/
tsSeek(milliseconds: number) {
this._loader instanceof FragmentLoader && this._loader.seek(milliseconds);
}
/**
* 加载下一个片段
*/
loadNextFrag() {
this._loader instanceof FragmentLoader && this._loader.loadNextFrag();
}
/**
* When seeking request is from media seeking, unconsumed stash data should be dropped
* However, stash data shouldn't be dropped if seeking requested from http reconnection
*
* @dropUnconsumed: Ignore and discard all unconsumed data in stash buffer
*/
_internalSeek(bytes: number, dropUnconsumed?: boolean) {
if(this._loader!.isWorking()) {
this._loader!.abort();
}
if(this._mediaConfig.type === 'flv') {
this._flushStashBuffer(dropUnconsumed);
// dispatch & flush stash buffer before seek
this._loader!.destroy();
this._loader = null;
const requestRange = { from: bytes, to: -1 };
this._currentRange = { from: requestRange.from, to: -1 };
this._stashSize = this._stashInitialSize;
this._createLoader();
this._loader!.startLoad(this._mediaConfig, requestRange);
} else {
if(this._loader instanceof FragmentLoader) {
this._loader.resume();
this._loader.loadNextFrag();
}
}
this._speedChecker.reset();
if(this._onSeeked) {
this._onSeeked();
}
}
/**
* 扩冲数据池
* @param expectedBytes 期望的数据池大小
*/
_expandBuffer(expectedBytes: number) {
let bufferNewSize = this._stashSize;
while(bufferNewSize + 1024 * 1024 * 1 < expectedBytes) {
bufferNewSize *= 2;
}
bufferNewSize += 1024 * 1024 * 1; // bufferSize = stashSize + 1MB
if(bufferNewSize === this._bufferSize) {
return;
}
const newBuffer = new ArrayBuffer(bufferNewSize);
if(this._stashUsed > 0) {
// copy existing data into new buffer
const stashOldArray = new Uint8Array(this._stashBuffer, 0, this._stashUsed);
const stashNewArray = new Uint8Array(newBuffer, 0, bufferNewSize);
stashNewArray.set(stashOldArray, 0);
}
this._stashBuffer = newBuffer;
this._bufferSize = bufferNewSize;
}
/**
* 标准化网速值, 使之等于标准1M, 2M, 4M 10M等带宽的网速最大值
* @param input speedChecker返回的网速值
*/
_normalizeSpeed(input: number) {
const list = this._speedNormalizeList;
const last = list.length - 1;
let mid = 0;
let lbound = 0;
let ubound = last;
if(input < list[0]) {
return list[0];
}
// binary search
while(lbound <= ubound) {
mid = lbound + Math.floor((ubound - lbound) / 2);
if(mid === last || (input >= list[mid] && input < list[mid + 1])) {
return list[mid];
} if(list[mid] < input) {
lbound = mid + 1;
} else {
ubound = mid - 1;
}
}
}
_adjustStashSize(normalized: number) {
let stashSizeKB = 0;
if(this._config.isLive) {
// live stream: always use single normalized speed for size of stashSizeKB
stashSizeKB = normalized;
} else {
if(normalized < 512) {
stashSizeKB = normalized;
} else if(normalized >= 512 && normalized <= 1024) {
stashSizeKB = Math.floor(normalized * 1.5);
} else {
stashSizeKB = normalized * 2;
}
}
if(stashSizeKB > 8192) {
stashSizeKB = 8192;
}
const bufferSize = stashSizeKB * 1024 + 1024 * 1024 * 1; // stashSize + 1MB
if(this._bufferSize < bufferSize) {
this._expandBuffer(bufferSize);
}
this._stashSize = stashSizeKB * 1024;
}
/**
* 向上发送数据块, 并返回已经解析处理的数据的长度
* @param chunks 发送的数据内容
* @param byteStart 数据内容在总的数据中的索引值
* @param extraData 额外的数据
*/
_dispatchChunks(chunks: ArrayBuffer, byteStart: number, extraData?: TSExtraData): number {
this._currentRange && (this._currentRange.to = byteStart + chunks.byteLength - 1);
if(this._onDataArrival) {
return this._onDataArrival(chunks, byteStart, extraData);
}
return 0;
}
/**
* 发生 301/302 地址跳转后的处理函数
* @param redirectedURL 跳转的地址
*/
_onURLRedirect(redirectedURL: string) {
this._redirectedURL = redirectedURL;
if(this._onRedirect) {
this._onRedirect(redirectedURL);
}
}
/**
* 当在response header 中获知请求文件大小后处理的函数
* @param contentLength 在请求头中获知文件的大小
*/
_onContentLengthKnown(contentLength: number) {
if(contentLength && this._fullRequestFlag) {
this._totalLength = contentLength;
this._fullRequestFlag = false;
}
}
/**
* 收到loader发送过来的数据块的处理函数
* @param chunk loader接受到的数据块
* @param byteStart 该数据块在已经收数据流里索引
* @param receivedLength 收到的长度
* @param extraData 额外数据
*/
_onLoaderChunkArrival(
chunk: ArrayBuffer,
byteStart: number,
receivedLength: number,
extraData?: TSExtraData
) {
if(!this._onDataArrival) {
throw new IllegalStateException(
'IOController: No existing consumer (onDataArrival) callback!'
);
}
if(this._paused) {
return;
}
// 当收到数据流时如果处于 EarlyEOF 状态中, 而取消该状态, 通知外部已恢复
if(this._isEarlyEofReconnecting) {
this._isEarlyEofReconnecting = false;
if(this._onRecoveredEarlyEof) {
this._onRecoveredEarlyEof();
}
}
this._speedChecker.addBytes(new Uint8Array(chunk).length);
this._tsExtraData = extraData;
// adjust stash buffer size according to network speed dynamically
const KBps = this._speedChecker.lastSecondKBps;
if(KBps !== 0) {
const normalized = this._normalizeSpeed(KBps);
if(this._speedNormalized !== normalized) {
this._speedNormalized = Number(normalized);
this._adjustStashSize(normalized as number);
}
}
if(this._mediaConfig.type === 'm3u8') {
this._dispatchChunks(chunk, this._stashByteStart, this._tsExtraData);
return;
}
if(!this._enableStash) {
// disable stash
if(this._stashUsed === 0) {
// dispatch chunk directly to consumer;
// check ret value (consumed bytes) and stash unconsumed to stashBuffer
const consumed = this._dispatchChunks(chunk, byteStart, extraData);
if(consumed < chunk.byteLength) {
// unconsumed data remain.
const remain = chunk.byteLength - consumed;
if(remain > this._bufferSize) {
this._expandBuffer(remain);
}
const stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
stashArray.set(new Uint8Array(chunk, consumed), 0);
this._stashUsed += remain;
this._stashByteStart = byteStart + consumed;
}
} else {
// else: Merge chunk into stashBuffer, and dispatch stashBuffer to consumer.
if(this._stashUsed + chunk.byteLength > this._bufferSize) {
this._expandBuffer(this._stashUsed + chunk.byteLength);
}
const stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
stashArray.set(new Uint8Array(chunk), this._stashUsed);
this._stashUsed += chunk.byteLength;
const consumed = this._dispatchChunks(
this._stashBuffer.slice(0, this._stashUsed),
this._stashByteStart,
extraData
);
if(consumed < this._stashUsed && consumed > 0) {
// unconsumed data remain
const remainArray = new Uint8Array(this._stashBuffer, consumed);
stashArray.set(remainArray, 0);
}
this._stashUsed -= consumed;
this._stashByteStart += consumed;
}
} else {
// enable stash
if(this._stashUsed === 0 && this._stashByteStart === 0) {
// seeked? or init chunk?
// This is the first chunk after seek action
this._stashByteStart = byteStart;
}
if(this._stashUsed + chunk.byteLength <= this._stashSize) {
// just stash
const stashArray = new Uint8Array(this._stashBuffer, 0, this._stashSize);
stashArray.set(new Uint8Array(chunk), this._stashUsed);
this._stashUsed += chunk.byteLength;
} else {
// stashUsed + chunkSize > stashSize, size limit exceeded
let stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
if(this._stashUsed > 0) {
// There're stash datas in buffer
// dispatch the whole stashBuffer, and stash remain data
// then append chunk to stashBuffer (stash)
const buffer = this._stashBuffer.slice(0, this._stashUsed);
const consumed = this._dispatchChunks(buffer, this._stashByteStart, extraData);
if(consumed < buffer.byteLength) {
if(consumed > 0) {
const remainArray = new Uint8Array(buffer, consumed);
stashArray.set(remainArray, 0);
this._stashUsed = remainArray.byteLength;
this._stashByteStart += consumed;
}
} else {
this._stashUsed = 0;
this._stashByteStart += consumed;
}
if(this._stashUsed + chunk.byteLength > this._bufferSize) {
this._expandBuffer(this._stashUsed + chunk.byteLength);
stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
}
stashArray.set(new Uint8Array(chunk), this._stashUsed);
this._stashUsed += chunk.byteLength;
} else {
// stash buffer empty, but chunkSize > stashSize (oh, holy shit)
// dispatch chunk directly and stash remain data
const consumed = this._dispatchChunks(chunk, byteStart, extraData);
if(consumed < chunk.byteLength) {
const remain = chunk.byteLength - consumed;
if(remain > this._bufferSize) {
this._expandBuffer(remain);
stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
}
stashArray.set(new Uint8Array(chunk, consumed), 0);
this._stashUsed += remain;
this._stashByteStart = byteStart + consumed;
}
}
}
}
}
/**
* 清空存储的buffer;
* @param dropUnconsumed 是否丢弃未处理的数据
*/
_flushStashBuffer(dropUnconsumed?: boolean) {
if(this._stashUsed > 0) {
const buffer = this._stashBuffer.slice(0, this._stashUsed);
const consumed = this._dispatchChunks(buffer, this._stashByteStart, this._tsExtraData);
const remain = buffer.byteLength - consumed;
if(consumed < buffer.byteLength) {
if(dropUnconsumed) {
Logger.warn(
this.Tag,
`${remain} bytes unconsumed data remain when flush buffer, dropped`
);
} else {
if(consumed > 0) {
const stashArray = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
const remainArray = new Uint8Array(buffer, consumed);
stashArray.set(remainArray, 0);
this._stashUsed = remainArray.byteLength;
this._stashByteStart += consumed;
}
return 0;
}
}
this._stashUsed = 0;
this._stashByteStart = 0;
return remain;
}
return 0;
}
_onLoaderComplete() {
// Force-flush stash buffer, and drop unconsumed data
this._flushStashBuffer(true);
if(this._onComplete) {
this._onComplete(this._extraData);
}
}
_onLoaderError(type: string, data: ErrorData) {
Logger.error(this.Tag, `Loader error, code = ${data.code}, msg = ${data.reason}`);
this._flushStashBuffer(false);
if(this._isEarlyEofReconnecting) {
// Auto-reconnect for EarlyEof failed, throw UnrecoverableEarlyEof error to upper-layer
this._isEarlyEofReconnecting = false;
type = Errors.UNRECOVERABLE_EARLY_EOF;
}
switch(type) {
case Errors.EARLY_EOF: {
if(!this._config.isLive) {
// Do internal http reconnect if not live stream
if(this._totalLength && this._currentRange) {
const nextFrom = this._currentRange.to + 1;
if(nextFrom < this._totalLength) {
Logger.warn(this.Tag, 'Connection lost, trying reconnect...');
this._isEarlyEofReconnecting = true;
this._internalSeek(nextFrom, false);
}
return;
}
// else: We don't know totalLength, throw UnrecoverableEarlyEof
}
// live stream: throw UnrecoverableEarlyEof error to upper-layer
type = Errors.UNRECOVERABLE_EARLY_EOF;
break;
}
case Errors.UNRECOVERABLE_EARLY_EOF:
case Errors.CONNECTING_TIMEOUT:
case Errors.HTTP_STATUS_CODE_INVALID:
case Errors.EXCEPTION:
break;
default:
break;
}
if(this._onError) {
this._onError(type, data);
} else {
throw new RuntimeException(`IOException: ${data.reason}`);
}
}
}
export default IOController; | the_stack |
import * as webdriver from 'selenium-webdriver';
import * as chrome from 'selenium-webdriver/chrome';
import * as edge from 'selenium-webdriver/edge';
import * as firefox from 'selenium-webdriver/firefox';
import {installOnDemand} from './install';
import {isHttpUrl} from './util';
/** Tachometer browser names. Often but not always equal to WebDriver's. */
export type BrowserName = 'chrome' | 'firefox' | 'safari' | 'edge' | 'ie';
/** Browsers we can drive. */
export const supportedBrowsers = new Set<BrowserName>([
'chrome',
'firefox',
'safari',
'edge',
'ie',
]);
type WebdriverModuleName = 'chromedriver' | 'geckodriver' | 'iedriver';
// Note that the edgedriver package doesn't work on recent versions of
// Windows 10, so users must manually install following Microsoft's
// documentation.
const browserWebdriverModules = new Map<BrowserName, WebdriverModuleName>([
['chrome', 'chromedriver'],
['firefox', 'geckodriver'],
['ie', 'iedriver'],
]);
/** Cases where Tachometer's browser name scheme does not equal WebDriver's. */
const webdriverBrowserNames = new Map<BrowserName, string>([
['edge', 'MicrosoftEdge'],
['ie', 'internet explorer'],
]);
/** Browsers that support headless mode. */
const headlessBrowsers = new Set<BrowserName>(['chrome', 'firefox']);
/** Browsers for which we can find the first contentful paint (FCP) time. */
export const fcpBrowsers = new Set<BrowserName>(['chrome']);
export interface BrowserConfig {
/** Name of the browser. */
name: BrowserName;
/** Whether to run in headless mode. */
headless: boolean;
/** A remote WebDriver server to launch the browser from. */
remoteUrl?: string;
/** Launch the browser window with these dimensions. */
windowSize: WindowSize;
/** Path to custom browser binary. */
binary?: string;
/** Additional binary arguments. */
addArguments?: string[];
/** WebDriver default binary arguments to omit. */
removeArguments?: string[];
/** CPU Throttling rate. (1 is no throttle, 2 is 2x slowdown, etc). */
cpuThrottlingRate?: number;
/** Advanced preferences usually set from the about:config page. */
preferences?: {[name: string]: string | number | boolean};
/** Trace browser performance logs configuration */
trace?: TraceConfig;
/** Path to profile directory to use instead of the default fresh one. */
profile?: string;
}
/**
* Configuration to turn on performance tracing
*/
export interface TraceConfig {
/**
* The tracing categories the browser should log
*/
categories: string[];
/**
* The directory to log performance traces to
*/
logDir: string;
}
export interface WindowSize {
width: number;
height: number;
}
/**
* Create a deterministic unique string key for the given BrowserConfig.
*/
export function browserSignature(config: BrowserConfig): string {
return JSON.stringify([
config.name,
config.headless,
config.remoteUrl ?? '',
config.windowSize.width,
config.windowSize.height,
config.binary ?? '',
config.addArguments ?? [],
config.removeArguments ?? [],
config.cpuThrottlingRate ?? 1,
config.preferences ?? {},
config.profile ?? '',
]);
}
type BrowserConfigWithoutWindowSize = Pick<
BrowserConfig,
Exclude<keyof BrowserConfig, 'windowSize'>
>;
/**
* Parse and validate a browser string specification. Examples:
*
* chrome
* chrome-headless
* chrome@<remote-selenium-server>
*/
export function parseBrowserConfigString(
str: string
): BrowserConfigWithoutWindowSize {
let remoteUrl;
const at = str.indexOf('@');
if (at !== -1) {
remoteUrl = str.substring(at + 1);
str = str.substring(0, at);
}
const headless = str.endsWith('-headless');
if (headless === true) {
str = str.replace(/-headless$/, '');
}
const name = str as BrowserName;
const config: BrowserConfigWithoutWindowSize = {name, headless};
if (remoteUrl !== undefined) {
config.remoteUrl = remoteUrl;
}
return config;
}
/**
* Throw if any property of the given BrowserConfig is invalid.
*/
export function validateBrowserConfig({
name,
headless,
remoteUrl,
windowSize,
}: BrowserConfig) {
if (!supportedBrowsers.has(name)) {
throw new Error(
`Browser ${name} is not supported, ` +
`only ${[...supportedBrowsers].join(', ')} are currently supported.`
);
}
if (headless === true && !headlessBrowsers.has(name)) {
throw new Error(`Browser ${name} does not support headless mode.`);
}
if (remoteUrl !== undefined && !isHttpUrl(remoteUrl)) {
throw new Error(`Invalid browser remote URL "${remoteUrl}".`);
}
if (windowSize.width < 0 || windowSize.height < 0) {
throw new Error(`Invalid window size, width and height must be >= 0.`);
}
}
/**
* Configure a WebDriver suitable for benchmarking the given browser.
*/
export async function makeDriver(
config: BrowserConfig
): Promise<webdriver.WebDriver> {
const browserName: BrowserName = config.name;
const webdriverModuleName = browserWebdriverModules.get(browserName);
if (webdriverModuleName != null) {
await installOnDemand(webdriverModuleName);
require(webdriverModuleName);
}
const builder = new webdriver.Builder();
const webdriverName = webdriverBrowserNames.get(config.name) || config.name;
builder.forBrowser(webdriverName);
builder.setChromeOptions(chromeOpts(config));
builder.setFirefoxOptions(firefoxOpts(config));
if (config.remoteUrl !== undefined) {
builder.usingServer(config.remoteUrl);
} else if (config.name === 'edge') {
// There appears to be bug where WebDriver doesn't automatically start or
// find an Edge service and throws "Cannot read property 'start' of null"
// so we need to start the service ourselves.
// See https://stackoverflow.com/questions/48577924.
builder.setEdgeService(new edge.ServiceBuilder());
}
const driver = await builder.build();
if (
config.name === 'safari' ||
config.name === 'edge' ||
config.name === 'ie'
) {
// Safari, Edge, and IE don't have flags we can use to launch with a given
// window size, but webdriver can resize the window after we've started
// up. Some versions of Safari have a bug where it is required to also
// provide an x/y position (see
// https://github.com/SeleniumHQ/selenium/issues/3796).
const rect =
config.name === 'safari'
? {...config.windowSize, x: 0, y: 0}
: config.windowSize;
await driver.manage().window().setRect(rect);
}
return driver;
}
function chromeOpts(config: BrowserConfig): chrome.Options {
const opts = new chrome.Options();
if (config.binary) {
opts.setChromeBinaryPath(config.binary);
}
if (config.headless === true) {
opts.addArguments('--headless');
}
if (config.addArguments) {
opts.addArguments(...config.addArguments);
}
if (config.removeArguments) {
opts.excludeSwitches(...config.removeArguments);
}
if (config.trace) {
const loggingPrefs = new webdriver.logging.Preferences();
loggingPrefs.setLevel('browser', webdriver.logging.Level.ALL);
loggingPrefs.setLevel('performance', webdriver.logging.Level.ALL);
opts.setLoggingPrefs(loggingPrefs);
opts.setPerfLoggingPrefs({
enableNetwork: true,
enablePage: true,
traceCategories: config.trace.categories.join(','),
});
}
const {width, height} = config.windowSize;
opts.addArguments(`--window-size=${width},${height}`);
if (config.profile) {
opts.addArguments(`user-data-dir=${config.profile}`);
}
return opts;
}
function firefoxOpts(config: BrowserConfig): firefox.Options {
const opts = new firefox.Options();
if (config.preferences) {
for (const [name, value] of Object.entries(config.preferences)) {
opts.setPreference(name, value);
}
}
if (config.binary) {
opts.setBinary(config.binary);
}
if (config.headless === true) {
opts.addArguments('-headless');
}
const {width, height} = config.windowSize;
opts.addArguments(`-width=${width}`);
opts.addArguments(`-height=${height}`);
if (config.addArguments) {
opts.addArguments(...config.addArguments);
}
if (config.profile) {
// Note there is also a `-profile` flag for Firefox that could be set with
// `addArguments`, but using that causes Selenium to timeout trying to
// connect to the browser process. This `setProfile` method creates a
// temporary copy of the profile.
opts.setProfile(config.profile);
}
return opts;
}
/**
* Open a new tab and switch to it. Assumes that the driver is on a page that
* hasn't replaced `window.open` (e.g. the initial blank tab that we always
* switch back to after running a benchmark).
*/
export async function openAndSwitchToNewTab(
driver: webdriver.WebDriver,
config: BrowserConfig
): Promise<void> {
// Chrome and Firefox add new tabs to the end of the handle list, but Safari
// adds them to the beginning. Just look for the new one instead of making
// any assumptions about this order.
const tabsBefore = await driver.getAllWindowHandles();
if (tabsBefore.length !== 1) {
throw new Error(`Expected only 1 open tab, got ${tabsBefore.length}`);
}
// "noopener=yes" prevents the new window from being able to access the
// first window. We set that here because in Chrome (and perhaps other
// browsers) we see a very significant improvement in the reliability of
// measurements, in particular it appears to eliminate interference between
// code across runs. It is likely this flag increases process isolation in a
// way that prevents code caching across tabs.
await driver.executeScript('window.open("", "", "noopener=yes");');
// Firefox (and maybe other browsers) won't always report the new tab ID
// immediately, so we'll need to poll for it.
const maxRetries = 20;
const retrySleepMs = 250;
let retries = 0;
let newTabId;
while (true) {
const tabsAfter = await driver.getAllWindowHandles();
const newTabs = tabsAfter.filter((tab) => tab !== tabsBefore[0]);
if (newTabs.length === 1) {
newTabId = newTabs[0];
break;
}
retries++;
if (newTabs.length > 1 || retries > maxRetries) {
throw new Error(`Expected to create 1 new tab, got ${newTabs.length}`);
}
await new Promise((resolve) => setTimeout(resolve, retrySleepMs));
}
await driver.switchTo().window(newTabId);
if (config.name === 'ie' || config.name === 'safari') {
// For IE and Safari (with rel=noopener) we get a new window instead of a
// new tab, so we need to resize every time.
const rect =
config.name === 'safari'
? {...config.windowSize, x: 0, y: 0}
: config.windowSize;
await driver.manage().window().setRect(rect);
}
type WithSendDevToolsCommand = {
sendDevToolsCommand?: (command: string, config: unknown) => Promise<void>;
};
const driverWithSendDevToolsCommand = driver as WithSendDevToolsCommand;
if (
driverWithSendDevToolsCommand.sendDevToolsCommand &&
config.cpuThrottlingRate !== undefined
) {
// Enables CPU throttling to emulate slow CPUs.
await driverWithSendDevToolsCommand.sendDevToolsCommand(
'Emulation.setCPUThrottlingRate',
{rate: config.cpuThrottlingRate}
);
}
} | the_stack |
import { DateAggregation, Entity } from '../types';
export const MockAggregatedDailyCosts: DateAggregation[] = [
{
date: '2020-08-07',
amount: 3500,
},
{
date: '2020-08-06',
amount: 2500,
},
{
date: '2020-08-05',
amount: 1400,
},
{
date: '2020-08-04',
amount: 3800,
},
{
date: '2020-08-09',
amount: 1900,
},
{
date: '2020-08-08',
amount: 2400,
},
{
date: '2020-08-03',
amount: 4000,
},
{
date: '2020-08-02',
amount: 3700,
},
{
date: '2020-08-01',
amount: 2500,
},
{
date: '2020-08-18',
amount: 4300,
},
{
date: '2020-08-17',
amount: 1500,
},
{
date: '2020-08-16',
amount: 3600,
},
{
date: '2020-08-15',
amount: 2200,
},
{
date: '2020-08-19',
amount: 3900,
},
{
date: '2020-08-10',
amount: 4100,
},
{
date: '2020-08-14',
amount: 3600,
},
{
date: '2020-08-13',
amount: 2900,
},
{
date: '2020-08-12',
amount: 2700,
},
{
date: '2020-08-11',
amount: 5100,
},
{
date: '2020-09-19',
amount: 1200,
},
{
date: '2020-09-18',
amount: 6500,
},
{
date: '2020-09-17',
amount: 2500,
},
{
date: '2020-09-16',
amount: 1400,
},
{
date: '2020-09-11',
amount: 2300,
},
{
date: '2020-09-10',
amount: 1900,
},
{
date: '2020-09-15',
amount: 3100,
},
{
date: '2020-09-14',
amount: 4500,
},
{
date: '2020-09-13',
amount: 3300,
},
{
date: '2020-09-12',
amount: 2800,
},
{
date: '2020-09-29',
amount: 2600,
},
{
date: '2020-09-28',
amount: 4100,
},
{
date: '2020-09-27',
amount: 3800,
},
{
date: '2020-09-22',
amount: 3700,
},
{
date: '2020-09-21',
amount: 2700,
},
{
date: '2020-09-20',
amount: 2200,
},
{
date: '2020-09-26',
amount: 3300,
},
{
date: '2020-09-25',
amount: 4000,
},
{
date: '2020-09-24',
amount: 3800,
},
{
date: '2020-09-23',
amount: 4100,
},
{
date: '2020-08-29',
amount: 4400,
},
{
date: '2020-08-28',
amount: 5000,
},
{
date: '2020-08-27',
amount: 4900,
},
{
date: '2020-08-26',
amount: 4100,
},
{
date: '2020-08-21',
amount: 3700,
},
{
date: '2020-08-20',
amount: 2200,
},
{
date: '2020-08-25',
amount: 1700,
},
{
date: '2020-08-24',
amount: 2100,
},
{
date: '2020-08-23',
amount: 3100,
},
{
date: '2020-08-22',
amount: 1500,
},
{
date: '2020-09-08',
amount: 2900,
},
{
date: '2020-09-07',
amount: 4100,
},
{
date: '2020-09-06',
amount: 3600,
},
{
date: '2020-09-05',
amount: 3300,
},
{
date: '2020-09-09',
amount: 2800,
},
{
date: '2020-08-31',
amount: 3400,
},
{
date: '2020-08-30',
amount: 4300,
},
{
date: '2020-09-04',
amount: 6100,
},
{
date: '2020-09-03',
amount: 2500,
},
{
date: '2020-09-02',
amount: 4900,
},
{
date: '2020-09-01',
amount: 6100,
},
{
date: '2020-09-30',
amount: 5500,
},
];
export const MockBigQueryInsights: Entity = {
id: 'bigQuery',
aggregation: [10_000, 30_000],
change: {
ratio: 3,
amount: 20_000,
},
entities: {
dataset: [
{
id: 'dataset-a',
aggregation: [5_000, 10_000],
change: {
ratio: 1,
amount: 5_000,
},
entities: {},
},
{
id: 'dataset-b',
aggregation: [5_000, 10_000],
change: {
ratio: 1,
amount: 5_000,
},
entities: {},
},
{
id: 'dataset-c',
aggregation: [0, 10_000],
change: {
amount: 10_000,
},
entities: {},
},
],
},
};
export const MockCloudDataflowInsights: Entity = {
id: 'cloudDataflow',
aggregation: [100_000, 158_000],
change: {
ratio: 0.58,
amount: 58_000,
},
entities: {
pipeline: [
{
id: null,
aggregation: [10_000, 12_000],
change: {
ratio: 0.2,
amount: 2_000,
},
entities: {
SKU: [
{
id: 'Mock SKU A',
aggregation: [3_000, 4_000],
change: {
ratio: 0.333333,
amount: 1_000,
},
entities: {},
},
{
id: 'Mock SKU B',
aggregation: [7_000, 8_000],
change: {
ratio: 0.14285714,
amount: 1_000,
},
entities: {},
},
],
},
},
{
id: 'pipeline-a',
aggregation: [60_000, 70_000],
change: {
ratio: 0.16666666666666666,
amount: 10_000,
},
entities: {
SKU: [
{
id: 'Mock SKU A',
aggregation: [20_000, 15_000],
change: {
ratio: -0.25,
amount: -5_000,
},
entities: {},
},
{
id: 'Mock SKU B',
aggregation: [30_000, 35_000],
change: {
ratio: -0.16666666666666666,
amount: -5_000,
},
entities: {},
},
{
id: 'Mock SKU C',
aggregation: [10_000, 20_000],
change: {
ratio: 1,
amount: 10_000,
},
entities: {},
},
],
},
},
{
id: 'pipeline-b',
aggregation: [12_000, 8_000],
change: {
ratio: -0.33333,
amount: -4_000,
},
entities: {
SKU: [
{
id: 'Mock SKU A',
aggregation: [4_000, 4_000],
change: {
ratio: 0,
amount: 0,
},
entities: {},
},
{
id: 'Mock SKU B',
aggregation: [8_000, 4_000],
change: {
ratio: -0.5,
amount: -4_000,
},
entities: {},
},
],
},
},
{
id: 'pipeline-c',
aggregation: [0, 10_000],
change: {
amount: 10_000,
},
entities: {},
},
],
},
};
export const MockCloudStorageInsights: Entity = {
id: 'cloudStorage',
aggregation: [45_000, 45_000],
change: {
ratio: 0,
amount: 0,
},
entities: {
bucket: [
{
id: 'bucket-a',
aggregation: [15_000, 20_000],
change: {
ratio: 0.333,
amount: 5_000,
},
entities: {
SKU: [
{
id: 'Mock SKU A',
aggregation: [10_000, 11_000],
change: {
ratio: 0.1,
amount: 1_000,
},
entities: {},
},
{
id: 'Mock SKU B',
aggregation: [2_000, 5_000],
change: {
ratio: 1.5,
amount: 3_000,
},
entities: {},
},
{
id: 'Mock SKU C',
aggregation: [3_000, 4_000],
change: {
ratio: 0.3333,
amount: 1_000,
},
entities: {},
},
],
},
},
{
id: 'bucket-b',
aggregation: [30_000, 25_000],
change: {
ratio: -0.16666,
amount: -5_000,
},
entities: {
SKU: [
{
id: 'Mock SKU A',
aggregation: [12_000, 13_000],
change: {
ratio: 0.08333333333333333,
amount: 1_000,
},
entities: {},
},
{
id: 'Mock SKU B',
aggregation: [16_000, 12_000],
change: {
ratio: -0.25,
amount: -4_000,
},
entities: {},
},
{
id: 'Mock SKU C',
aggregation: [2_000, 0],
change: {
amount: -2000,
},
entities: {},
},
],
},
},
{
id: 'bucket-c',
aggregation: [0, 0],
change: {
amount: 0,
},
entities: {},
},
],
},
};
export const MockComputeEngineInsights: Entity = {
id: 'computeEngine',
aggregation: [80_000, 90_000],
change: {
ratio: 0.125,
amount: 10_000,
},
entities: {
service: [
{
id: 'service-a',
aggregation: [20_000, 10_000],
change: {
ratio: -0.5,
amount: -10_000,
},
entities: {
SKU: [
{
id: 'Mock SKU A',
aggregation: [4_000, 2_000],
change: {
ratio: -0.5,
amount: -2_000,
},
entities: {},
},
{
id: 'Mock SKU B',
aggregation: [7_000, 6_000],
change: {
ratio: -0.14285714285714285,
amount: -1_000,
},
entities: {},
},
{
id: 'Mock SKU C',
aggregation: [9_000, 2_000],
change: {
ratio: -0.7777777777777778,
amount: -7000,
},
entities: {},
},
],
deployment: [
{
id: 'Compute Engine',
aggregation: [7_000, 6_000],
change: {
ratio: -0.5,
amount: -2_000,
},
entities: {},
},
{
id: 'Kubernetes',
aggregation: [4_000, 2_000],
change: {
ratio: -0.14285714285714285,
amount: -1_000,
},
entities: {},
},
],
},
},
{
id: 'service-b',
aggregation: [10_000, 20_000],
change: {
ratio: 1,
amount: 10_000,
},
entities: {
SKU: [
{
id: 'Mock SKU A',
aggregation: [1_000, 2_000],
change: {
ratio: 1,
amount: 1_000,
},
entities: {},
},
{
id: 'Mock SKU B',
aggregation: [4_000, 8_000],
change: {
ratio: 1,
amount: 4_000,
},
entities: {},
},
{
id: 'Mock SKU C',
aggregation: [5_000, 10_000],
change: {
ratio: 1,
amount: 5_000,
},
entities: {},
},
],
deployment: [
{
id: 'Compute Engine',
aggregation: [7_000, 6_000],
change: {
ratio: -0.5,
amount: -2_000,
},
entities: {},
},
{
id: 'Kubernetes',
aggregation: [4_000, 2_000],
change: {
ratio: -0.14285714285714285,
amount: -1_000,
},
entities: {},
},
],
},
},
{
id: 'service-c',
aggregation: [0, 10_000],
change: {
amount: 10_000,
},
entities: {},
},
],
},
};
export const MockEventsInsights: Entity = {
id: 'events',
aggregation: [20_000, 10_000],
change: {
ratio: -0.5,
amount: -10_000,
},
entities: {
event: [
{
id: 'event-a',
aggregation: [15_000, 7_000],
change: {
ratio: -0.53333333333,
amount: -8_000,
},
entities: {
product: [
{
id: 'Mock Product A',
aggregation: [5_000, 2_000],
change: {
ratio: -0.6,
amount: -3_000,
},
entities: {},
},
{
id: 'Mock Product B',
aggregation: [7_000, 2_500],
change: {
ratio: -0.64285714285,
amount: -4_500,
},
entities: {},
},
{
id: 'Mock Product C',
aggregation: [3_000, 2_500],
change: {
ratio: -0.16666666666,
amount: -500,
},
entities: {},
},
],
},
},
{
id: 'event-b',
aggregation: [5_000, 3_000],
change: {
ratio: -0.4,
amount: -2_000,
},
entities: {
product: [
{
id: 'Mock Product A',
aggregation: [2_000, 1_000],
change: {
ratio: -0.5,
amount: -1_000,
},
entities: {},
},
{
id: 'Mock Product B',
aggregation: [1_000, 1_500],
change: {
ratio: 0.5,
amount: 500,
},
entities: {},
},
{
id: 'Mock Product C',
aggregation: [2_000, 500],
change: {
ratio: -0.75,
amount: -1_500,
},
entities: {},
},
],
},
},
],
},
}; | the_stack |
import { BufferGeometry, Float32BufferAttribute, Vector3 } from 'three'
import * as BufferGeometryUtils from '../utils/BufferGeometryUtils'
const cb = new Vector3(),
ab = new Vector3()
function pushIfUnique<TItem>(array: TItem[], object: TItem): void {
if (array.indexOf(object) === -1) array.push(object)
}
function removeFromArray<TItem>(array: TItem[], object: TItem): void {
const k = array.indexOf(object)
if (k > -1) array.splice(k, 1)
}
class Vertex {
public position: Vector3
private id: number
public faces: Triangle[]
public neighbors: Vertex[]
public collapseCost: number
public collapseNeighbor: null | Vertex
public minCost: number = 0
public totalCost: number = 0
public costCount: number = 0
constructor(v: Vector3, id: number) {
this.position = v
this.id = id // old index id
this.faces = [] // faces vertex is connected
this.neighbors = [] // neighbouring vertices aka "adjacentVertices"
// these will be computed in computeEdgeCostAtVertex()
this.collapseCost = 0 // cost of collapsing this vertex, the less the better. aka objdist
this.collapseNeighbor = null // best candinate for collapsing
}
public addUniqueNeighbor(vertex: Vertex): void {
pushIfUnique(this.neighbors, vertex)
}
public removeIfNonNeighbor(n: Vertex): void {
const neighbors = this.neighbors
const faces = this.faces
const offset = neighbors.indexOf(n)
if (offset === -1) return
for (let i = 0; i < faces.length; i++) {
if (faces[i].hasVertex(n)) return
}
neighbors.splice(offset, 1)
}
}
// we use a triangle class to represent structure of face slightly differently
class Triangle {
private a: number
private b: number
private c: Number
public v1: Vertex
public v2: Vertex
public v3: Vertex
public normal = new Vector3()
constructor(v1: Vertex, v2: Vertex, v3: Vertex, a: number, b: number, c: number) {
this.a = a
this.b = b
this.c = c
this.v1 = v1
this.v2 = v2
this.v3 = v3
this.computeNormal()
v1.faces.push(this)
v1.addUniqueNeighbor(v2)
v1.addUniqueNeighbor(v3)
v2.faces.push(this)
v2.addUniqueNeighbor(v1)
v2.addUniqueNeighbor(v3)
v3.faces.push(this)
v3.addUniqueNeighbor(v1)
v3.addUniqueNeighbor(v2)
}
private computeNormal(): void {
const vA = this.v1.position
const vB = this.v2.position
const vC = this.v3.position
cb.subVectors(vC, vB)
ab.subVectors(vA, vB)
cb.cross(ab).normalize()
this.normal.copy(cb)
}
public hasVertex(v: Vertex): boolean {
return v === this.v1 || v === this.v2 || v === this.v3
}
public replaceVertex(oldv: Vertex, newv: Vertex): void {
if (oldv === this.v1) this.v1 = newv
else if (oldv === this.v2) this.v2 = newv
else if (oldv === this.v3) this.v3 = newv
removeFromArray(oldv.faces, this)
newv.faces.push(this)
oldv.removeIfNonNeighbor(this.v1)
this.v1.removeIfNonNeighbor(oldv)
oldv.removeIfNonNeighbor(this.v2)
this.v2.removeIfNonNeighbor(oldv)
oldv.removeIfNonNeighbor(this.v3)
this.v3.removeIfNonNeighbor(oldv)
this.v1.addUniqueNeighbor(this.v2)
this.v1.addUniqueNeighbor(this.v3)
this.v2.addUniqueNeighbor(this.v1)
this.v2.addUniqueNeighbor(this.v3)
this.v3.addUniqueNeighbor(this.v1)
this.v3.addUniqueNeighbor(this.v2)
this.computeNormal()
}
}
/**
* Simplification Geometry Modifier
* - based on code and technique
* - by Stan Melax in 1998
* - Progressive Mesh type Polygon Reduction Algorithm
* - http://www.melax.com/polychop/
*/
class SimplifyModifier {
constructor() {}
private computeEdgeCollapseCost = (u: Vertex, v: Vertex): number => {
// if we collapse edge uv by moving u to v then how
// much different will the model change, i.e. the "error".
const edgelength = v.position.distanceTo(u.position)
let curvature = 0
const sideFaces = []
let i,
il = u.faces.length,
face,
sideFace
// find the "sides" triangles that are on the edge uv
for (i = 0; i < il; i++) {
face = u.faces[i]
if (face.hasVertex(v)) {
sideFaces.push(face)
}
}
// use the triangle facing most away from the sides
// to determine our curvature term
for (i = 0; i < il; i++) {
let minCurvature = 1
face = u.faces[i]
for (let j = 0; j < sideFaces.length; j++) {
sideFace = sideFaces[j]
// use dot product of face normals.
const dotProd = face.normal.dot(sideFace.normal)
minCurvature = Math.min(minCurvature, (1.001 - dotProd) / 2)
}
curvature = Math.max(curvature, minCurvature)
}
// crude approach in attempt to preserve borders
// though it seems not to be totally correct
const borders = 0
if (sideFaces.length < 2) {
// we add some arbitrary cost for borders,
// borders += 10;
curvature = 1
}
const amt = edgelength * curvature + borders
return amt
}
private removeVertex(v: Vertex, vertices: Vertex[]): void {
console.assert(v.faces.length === 0)
while (v.neighbors.length) {
const n = v.neighbors.pop() as Vertex
removeFromArray(n.neighbors, v)
}
removeFromArray(vertices, v)
}
private computeEdgeCostAtVertex = (v: Vertex): void => {
// compute the edge collapse cost for all edges that start
// from vertex v. Since we are only interested in reducing
// the object by selecting the min cost edge at each step, we
// only cache the cost of the least cost edge at this vertex
// (in member variable collapse) as well as the value of the
// cost (in member variable collapseCost).
if (v.neighbors.length === 0) {
// collapse if no neighbors.
v.collapseNeighbor = null
v.collapseCost = -0.01
return
}
v.collapseCost = 100000
v.collapseNeighbor = null
// search all neighboring edges for "least cost" edge
for (let i = 0; i < v.neighbors.length; i++) {
const collapseCost = this.computeEdgeCollapseCost(v, v.neighbors[i])
if (!v.collapseNeighbor) {
v.collapseNeighbor = v.neighbors[i]
v.collapseCost = collapseCost
v.minCost = collapseCost
v.totalCost = 0
v.costCount = 0
}
v.costCount++
v.totalCost += collapseCost
if (collapseCost < v.minCost) {
v.collapseNeighbor = v.neighbors[i]
v.minCost = collapseCost
}
}
// we average the cost of collapsing at this vertex
v.collapseCost = v.totalCost / v.costCount
// v.collapseCost = v.minCost;
}
private removeFace = (f: Triangle, faces: Triangle[]): void => {
removeFromArray(faces, f)
if (f.v1) removeFromArray(f.v1.faces, f)
if (f.v2) removeFromArray(f.v2.faces, f)
if (f.v3) removeFromArray(f.v3.faces, f)
// TODO optimize this!
const vs = [f.v1, f.v2, f.v3]
let v1, v2
for (let i = 0; i < 3; i++) {
v1 = vs[i]
v2 = vs[(i + 1) % 3]
if (!v1 || !v2) continue
v1.removeIfNonNeighbor(v2)
v2.removeIfNonNeighbor(v1)
}
}
private collapse = (vertices: Vertex[], faces: Triangle[], u: Vertex, v: Vertex): void => {
// u and v are pointers to vertices of an edge
// Collapse the edge uv by moving vertex u onto v
if (!v) {
// u is a vertex all by itself so just delete it..
this.removeVertex(u, vertices)
return
}
let i
const tmpVertices = []
for (i = 0; i < u.neighbors.length; i++) {
tmpVertices.push(u.neighbors[i])
}
// delete triangles on edge uv:
for (i = u.faces.length - 1; i >= 0; i--) {
if (u.faces[i].hasVertex(v)) {
this.removeFace(u.faces[i], faces)
}
}
// update remaining triangles to have v instead of u
for (i = u.faces.length - 1; i >= 0; i--) {
u.faces[i].replaceVertex(u, v)
}
this.removeVertex(u, vertices)
// recompute the edge collapse costs in neighborhood
for (i = 0; i < tmpVertices.length; i++) {
this.computeEdgeCostAtVertex(tmpVertices[i])
}
}
private minimumCostEdge = (vertices: Vertex[]): Vertex => {
// O(n * n) approach. TODO optimize this
let least = vertices[0]
for (let i = 0; i < vertices.length; i++) {
if (vertices[i].collapseCost < least.collapseCost) {
least = vertices[i]
}
}
return least
}
public modify = (geometry: BufferGeometry, count: number): BufferGeometry => {
geometry = geometry.clone()
const attributes = geometry.attributes
// this modifier can only process indexed and non-indexed geomtries with a position attribute
for (let name in attributes) {
if (name !== 'position') geometry.deleteAttribute(name)
}
geometry = BufferGeometryUtils.mergeVertices(geometry)
//
// put data of original geometry in different data structures
//
const vertices = []
const faces = []
// add vertices
const positionAttribute = geometry.getAttribute('position')
for (let i = 0; i < positionAttribute.count; i++) {
const v = new Vector3().fromBufferAttribute(positionAttribute, i)
const vertex = new Vertex(v, i)
vertices.push(vertex)
}
// add faces
const geomIndex = geometry.getIndex()
if (geomIndex !== null) {
for (let i = 0; i < geomIndex.count; i += 3) {
const a = geomIndex.getX(i)
const b = geomIndex.getX(i + 1)
const c = geomIndex.getX(i + 2)
const triangle = new Triangle(vertices[a], vertices[b], vertices[c], a, b, c)
faces.push(triangle)
}
} else {
for (let i = 0; i < positionAttribute.count; i += 3) {
const a = i
const b = i + 1
const c = i + 2
const triangle = new Triangle(vertices[a], vertices[b], vertices[c], a, b, c)
faces.push(triangle)
}
}
// compute all edge collapse costs
for (let i = 0, il = vertices.length; i < il; i++) {
this.computeEdgeCostAtVertex(vertices[i])
}
let nextVertex
let z = count
while (z--) {
nextVertex = this.minimumCostEdge(vertices)
if (!nextVertex) {
console.log('THREE.SimplifyModifier: No next vertex')
break
} else {
this.collapse(vertices, faces, nextVertex, nextVertex.collapseNeighbor as Vertex)
}
}
//
const simplifiedGeometry = new BufferGeometry()
const position = []
let index = []
//
for (let i = 0; i < vertices.length; i++) {
const vertex = vertices[i].position
position.push(vertex.x, vertex.y, vertex.z)
}
//
for (let i = 0; i < faces.length; i++) {
const face = faces[i]
const a = vertices.indexOf(face.v1)
const b = vertices.indexOf(face.v2)
const c = vertices.indexOf(face.v3)
index.push(a, b, c)
}
//
simplifiedGeometry.setAttribute('position', new Float32BufferAttribute(position, 3))
simplifiedGeometry.setIndex(index)
return simplifiedGeometry
}
}
export { SimplifyModifier } | the_stack |
import { AfterContentInit, ContentChildren, Directive, ElementRef, EventEmitter, HostBinding,
Input, OnDestroy, Output, QueryList, Renderer2, Self, HostListener, OnInit } from '@angular/core';
import { cssClasses as listCssClasses } from '@material/list';
import { MDCMenuFoundation, MDCMenuAdapter, cssClasses, strings, DefaultFocusState } from '@material/menu';
import { MdcMenuSurfaceDirective } from '../menu-surface/mdc.menu-surface.directive';
import { MdcListDirective, MdcListFunction } from '../list/mdc.list.directive';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
/**
* Data send by the <code>pick</code> event of <code>MdcMenuDirective</code>.
*/
export interface MdcMenuSelection {
/**
* The <code>value</code> of the selected menu item (<code>MdcListItemDirective</code>).
*/
value: any,
/**
* The index of the selected menu item (<code>MdcListItemDirective</code>).
*/
index: number
}
// attributes on list-items that we maintain ourselves, so should be ignored
// in the adapter:
const ANGULAR_ITEM_ATTRIBUTES = [
strings.ARIA_CHECKED_ATTR, strings.ARIA_DISABLED_ATTR
];
// classes on list-items that we maintain ourselves, so should be ignored
// in the adapter:
const ANGULAR_ITEM_CLASSES = [
listCssClasses.LIST_ITEM_DISABLED_CLASS, cssClasses.MENU_SELECTED_LIST_ITEM
];
export enum FocusOnOpen {first = 0, last = 1, root = -1};
let nextId = 1;
/**
* Directive for a spec aligned material design Menu.
* This directive should wrap an `mdcList`. The `mdcList` contains the menu items (and possible separators).
*
* An `mdcMenu` element will also match with the selector of the menu surface directive, documented
* <a href="/components/menu-surface#mdcMenuSurface">here: mdcMenuSurface</a>. The
* <a href="/components/menu-surface#mdcMenuAnchor">mdcMenuAnchor API</a> is documented on the same page.
*
* # Accessibility
*
* * For `role` and `aria-*` attributes on the list, see documentation for `mdcList`.
* * The best way to open the menu by user interaction is to use the `mdcMenuTrigger` directive
* on the interaction element (e.g. button). This takes care of following ARIA recommended practices
* for focusing the correct element, and maintaining proper `aria-*` and `role` attributes on the
* interaction element, menu, and list.
* * When opening the `mdcMenuSurface` programmatic, the program is responsible for all of this.
* (including focusing an element of the menu or the menu itself).
* * The `mdcList` will be made focusable by setting a `"tabindex"="-1"` attribute.
* * The `mdcList` will get an `aria-orientation=vertical` attribute.
* * The `mdcList` will get an `aria-hidden=true` attribute when the menu surface is closed.
*/
@Directive({
selector: '[mdcMenu],[mdcSelectMenu]',
exportAs: 'mdcMenu'
})
export class MdcMenuDirective implements AfterContentInit, OnInit, OnDestroy {
private onDestroy$: Subject<any> = new Subject();
private onListChange$: Subject<any> = new Subject();
/** @internal */
@Output() readonly itemsChanged: EventEmitter<void> = new EventEmitter();
/** @internal */
@Output() readonly itemValuesChanged: EventEmitter<void> = new EventEmitter();
/** @internal */
@HostBinding('class.mdc-menu') readonly _cls = true;
private _id: string | null = null;
private cachedId: string | null = null;
private _function = MdcListFunction.menu;
private _lastList: MdcListDirective | null= null;
/**
* Event emitted when the user selects a value. The passed object contains a value
* (set to the <code>value</code> of the selected list item), and an index
* (set to the index of the selected list item).
*/
@Output() readonly pick: EventEmitter<MdcMenuSelection> = new EventEmitter();
/** @internal */
@ContentChildren(MdcListDirective) _listQuery?: QueryList<MdcListDirective>;
private mdcAdapter: MDCMenuAdapter = {
addClassToElementAtIndex: (index, className) => {
// ignore classes we maintain ourselves
if (!ANGULAR_ITEM_CLASSES.find(c => c === className)) {
const elm = this._list?.getItem(index)?._elm.nativeElement;
if (elm)
this.rndr.addClass(elm, className);
}
},
removeClassFromElementAtIndex: (index, className) => {
// ignore classes we maintain ourselves
if (!ANGULAR_ITEM_CLASSES.find(c => c === className)) {
const elm = this._list?.getItem(index)?._elm.nativeElement;
if (elm)
this.rndr.addClass(elm, className);
}
},
addAttributeToElementAtIndex: (index, attr, value) => {
// ignore attributes we maintain ourselves
if (!ANGULAR_ITEM_ATTRIBUTES.find(a => a === attr)) {
const elm = this._list?.getItem(index)?._elm.nativeElement;
if (elm)
this.rndr.setAttribute(elm, attr, value);
}
},
removeAttributeFromElementAtIndex: (index, attr) => {
// ignore attributes we maintain ourselves
if (!ANGULAR_ITEM_ATTRIBUTES.find(a => a === attr)) {
const elm = this._list?.getItem(index)?._elm.nativeElement;
if (elm)
this.rndr.removeAttribute(elm, attr);
}
},
elementContainsClass: (element, className) => element.classList.contains(className),
closeSurface: (skipRestoreFocus) => {
if (skipRestoreFocus)
this.surface.closeWithoutFocusRestore();
else
this.surface.open = false;
},
getElementIndex: (element) => this._list?._items!.toArray().findIndex(i => i._elm.nativeElement === element),
notifySelected: (evtData) => {
this.pick.emit({index: evtData.index, value: this._list._items!.toArray()[evtData.index].value});
},
getMenuItemCount: () => this._list?._items!.length || 0,
focusItemAtIndex: (index) => this._list.getItem(index)?._elm.nativeElement.focus(),
focusListRoot: () => this._list?._elm.nativeElement.focus(),
getSelectedSiblingOfItemAtIndex: () => -1, // menuSelectionGroup not yet supported
isSelectableItemAtIndex: () => false // menuSelectionGroup not yet supported
};
private foundation: MDCMenuFoundation | null = null;
constructor(public _elm: ElementRef, private rndr: Renderer2, @Self() private surface: MdcMenuSurfaceDirective) {
}
ngOnInit() {
// Force setter to be called in case id was not specified.
this.id = this.id;
}
ngAfterContentInit() {
this._lastList = this._listQuery!.first;
this._listQuery!.changes.subscribe(() => {
if (this._lastList !== this._listQuery!.first) {
this.onListChange$.next();
this._lastList?._setFunction(MdcListFunction.plain);
this._lastList = this._listQuery!.first;
this.destroyFoundation();
if (this._lastList)
this.initAll();
}
});
this.surface.afterOpened.pipe(takeUntil(this.onDestroy$)).subscribe(() => {
this.foundation?.handleMenuSurfaceOpened();
// reset default focus state for programmatic opening of menu;
// interactive opening sets the default when the open is triggered
// (see openAndFocus)
this.foundation?.setDefaultFocusState(DefaultFocusState.NONE);
});
this.surface.openChange.pipe(takeUntil(this.onDestroy$)).subscribe(() => {
if (this._list)
this._list._hidden = !this.surface.open;
});
if (this._lastList)
this.initAll();
}
ngOnDestroy() {
this.onListChange$.next(); this.onListChange$.complete();
this.onDestroy$.next(); this.onDestroy$.complete();
this.destroyFoundation();
}
private initAll() {
Promise.resolve().then(() => this._lastList!._setFunction(this._function));
this.initFoundation();
this.subscribeItemActions();
this._lastList?.itemsChanged.pipe(takeUntil(this.onListChange$)).subscribe(() => this.itemsChanged.emit());
this._lastList?.itemValuesChanged.pipe(takeUntil(this.onListChange$)).subscribe(() => this.itemValuesChanged.emit());
}
private initFoundation() {
this.foundation = new MDCMenuFoundation(this.mdcAdapter);
this.foundation.init();
// suitable for programmatic opening, program can focus whatever element it wants:
this.foundation.setDefaultFocusState(DefaultFocusState.NONE);
if (this._list)
this._list._hidden = !this.surface.open;
}
private destroyFoundation() {
if (this.foundation) {
this.foundation.destroy();
this.foundation = null;
}
}
private subscribeItemActions() {
this._lastList?.itemAction.pipe(takeUntil(this.onListChange$)).subscribe(data => {
this.foundation?.handleItemAction(this._list.getItem(data.index)!._elm.nativeElement);
});
}
/** @docs-private */
@HostBinding()
@Input() get id() {
return this._id;
}
set id(value: string | null) {
this._id = value || this._newId();
}
/** @internal */
_newId(): string {
this.cachedId = this.cachedId || `mdc-menu-${nextId++}`;
return this.cachedId;
}
/** @docs-private */
get open() {
return this.surface.open;
}
/** @docs-private */
openAndFocus(focus: FocusOnOpen) {
switch (focus) {
case FocusOnOpen.first:
this.foundation?.setDefaultFocusState(DefaultFocusState.FIRST_ITEM);
break;
case FocusOnOpen.last:
this.foundation?.setDefaultFocusState(DefaultFocusState.LAST_ITEM);
break;
case FocusOnOpen.root:
default:
this.foundation?.setDefaultFocusState(DefaultFocusState.LIST_ROOT);
}
this.surface.open = true;
}
/** @internal */
doClose() {
this.surface.open = false;
}
/** @internal */
set _listFunction(val: MdcListFunction) {
this._function = val;
if (this._lastList) // otherwise this will happen in ngAfterContentInit
this._list._setFunction(val);
}
/** @internal */
get _list(): MdcListDirective {
return this._listQuery!.first;
}
/** @internal */
@HostListener('keydown', ['$event']) _onKeydown(event: KeyboardEvent) {
this.foundation?.handleKeydown(event);
}
}
/**
*
* # Accessibility
*
* * `Enter`, `Space`, and `Down Arrow` keys open the menu and place focus on the first item.
* * `Up Arrow` opens the menu and places focus on the last item
* * Click/Touch events set focus to the mdcList root element
*
* * Attribute `role=button` will be set if the element is not already a button element.
* * Attribute `aria-haspopup=menu` will be set if an `mdcMenu` is attached.
* * Attribute `aria-expanded` will be set while the attached menu is open
* * Attribute `aria-controls` will be set to the id of the attached menu. (And a unique id will be generated,
* if none was set on the menu).
* * `Enter`, `Space`, and `Down-Arrow` will open the menu with the first menu item focused.
* * `Up-Arrow` will open the menu with the last menu item focused.
* * Mouse/Touch events will open the menu with the list root element focused. The list root element
* will handle keyboard navigation once it receives focus.
*/
@Directive({
selector: '[mdcMenuTrigger]',
})
export class MdcMenuTriggerDirective {
/** @internal */
@HostBinding('attr.role') _role: string | null = 'button';
private _mdcMenuTrigger: MdcMenuDirective | null = null;
private down = {
enter: false,
space: false
}
constructor(elm: ElementRef) {
if (elm.nativeElement.nodeName.toUpperCase() === 'BUTTON')
this._role = null;
}
/** @internal */
@HostListener('click') onClick() {
if (this.down.enter || this.down.space)
this._mdcMenuTrigger?.openAndFocus(FocusOnOpen.first);
else
this._mdcMenuTrigger?.openAndFocus(FocusOnOpen.root);
}
/** @internal */
@HostListener('keydown', ['$event']) onKeydown(event: KeyboardEvent) {
this.setDown(event, true);
const {key, keyCode} = event;
if (key === 'ArrowUp' || keyCode === 38)
this._mdcMenuTrigger?.openAndFocus(FocusOnOpen.last);
else if (key === 'ArrowDown' || keyCode === 40)
this._mdcMenuTrigger?.openAndFocus(FocusOnOpen.first);
}
/** @internal */
@HostListener('keyup', ['$event']) onKeyup(event: KeyboardEvent) {
this.setDown(event, false);
}
/** @internal */
@HostBinding('attr.aria-haspopup') get _hasPopup() {
return this._mdcMenuTrigger ? 'menu' : null;
}
/** @internal */
@HostBinding('attr.aria-expanded') get _expanded() {
return this._mdcMenuTrigger?.open ? 'true' : null;
}
/** @internal */
@HostBinding('attr.aria-controls') get _ariaControls() {
return this._mdcMenuTrigger?.id;
}
@Input() get mdcMenuTrigger() {
return this._mdcMenuTrigger;
}
set mdcMenuTrigger(value: MdcMenuDirective | null) {
if (value && value.openAndFocus)
this._mdcMenuTrigger = value;
else
this._mdcMenuTrigger = null;
}
private setDown(event: KeyboardEvent, isDown: boolean) {
const {key, keyCode} = event;
if (key === 'Enter' || keyCode === 13)
this.down.enter = isDown;
else if (key === 'Space' || keyCode === 32)
this.down.space = isDown;
}
}
export const MENU_DIRECTIVES = [
MdcMenuDirective, MdcMenuTriggerDirective
]; | the_stack |
import { setup } from '../../../../../../test/setup'
import request from 'supertest'
import { INestApplication, CACHE_MANAGER } from '@nestjs/common'
import {
NationalRegistryService,
NationalRegistryUser,
} from '../../../nationalRegistry'
import { Flight } from '../../flight.model'
let app: INestApplication
let cacheManager: CacheManager
let nationalRegistryService: NationalRegistryService
const user: NationalRegistryUser = {
nationalId: '1234567890',
firstName: 'Jón',
gender: 'kk',
lastName: 'Jónsson',
middleName: 'Gunnar',
address: 'Bessastaðir 1',
postalcode: 900,
city: 'Vestmannaeyjar',
}
beforeAll(async () => {
app = await setup()
cacheManager = app.get<CacheManager>(CACHE_MANAGER)
cacheManager.ttl = () => Promise.resolve('')
nationalRegistryService = app.get<NationalRegistryService>(
NationalRegistryService,
)
jest
.spyOn(nationalRegistryService, 'getUser')
.mockImplementation(() => Promise.resolve(user))
// 2020-08-18T14:26:22.018Z
Date.now = jest.fn(() => 1597760782018)
})
describe('Create Flight', () => {
it(`POST /api/public/discounts/:discountCode/flights should create a flight`, async () => {
const spy = jest
.spyOn(cacheManager, 'get')
.mockImplementation(() =>
Promise.resolve({ nationalId: user.nationalId }),
)
const response = await request(app.getHttpServer())
.post('/api/public/discounts/12345678/flights')
.set('Authorization', 'Bearer ernir')
.send({
bookingDate: '2020-08-17T12:35:50.971Z',
flightLegs: [
{
origin: 'REK',
destination: 'AEY',
originalPrice: 50000,
discountPrice: 30000,
date: '2021-03-12T12:35:50.971Z',
},
{
origin: 'AEY',
destination: 'REK',
originalPrice: 100000,
discountPrice: 60000,
date: '2021-03-15T12:35:50.971Z',
},
],
})
.expect(201)
expect(response.body).toEqual({
id: expect.any(String),
nationalId: '123456xxx0',
bookingDate: '2020-08-17T12:35:50.971Z',
flightLegs: [
{
id: expect.any(String),
date: '2021-03-12T12:35:50.971Z',
origin: 'REK',
destination: 'AEY',
discountPrice: 30000,
originalPrice: 50000,
},
{
id: expect.any(String),
date: '2021-03-15T12:35:50.971Z',
origin: 'AEY',
destination: 'REK',
discountPrice: 60000,
originalPrice: 100000,
},
],
})
spy.mockRestore()
})
it('POST /api/public/discounts/:discountCode/flights should return bad request when flightLegs are omitted', async () => {
await request(app.getHttpServer())
.post('/api/public/discounts/12345678/flights')
.set('Authorization', 'Bearer ernir')
.send({
nationalId: user.nationalId,
bookingDate: '2020-08-17T12:35:50.971Z',
})
.expect(400)
})
})
describe('ConnectionDiscountCodes generation', () => {
it('Should not create a discount code for Reykjavík-Gjögur flight', async () => {
// Create discount without flights in the system
let createDiscount = await request(app.getHttpServer())
.post('/api/private/users/1234567890/discounts')
.set('Authorization', 'Bearer norlandair')
.send({
nationalId: user.nationalId,
})
.expect(201)
const discountCode = createDiscount.body.discountCode
await request(app.getHttpServer())
.post(`/api/public/discounts/${discountCode}/flights`)
.set('Authorization', 'Bearer norlandair')
.send({
bookingDate: '2020-08-10T14:26:22.018Z',
flightLegs: [
{
origin: 'REK',
destination: 'GJG',
originalPrice: 50000,
discountPrice: 30000,
date: '2020-08-17T14:26:22',
},
],
})
.expect(201)
// Re-create discounts with a flight in the system
createDiscount = await request(app.getHttpServer())
.post('/api/private/users/1234567890/discounts')
.set('Authorization', 'Bearer norlandair')
.send({
nationalId: user.nationalId,
})
.expect(201)
expect(createDiscount.body.connectionDiscountCodes.length).toBe(0)
})
})
describe('Reykjavik -> Akureyri connecting flight validations', () => {
let cacheSpy: jest.SpyInstance<Promise<any>, any[]>
let flightId = ''
beforeEach(async () => {
cacheSpy = jest.spyOn(cacheManager, 'get').mockImplementation(() =>
Promise.resolve({
nationalId: user.nationalId,
connectionDiscountCodes: [
{
code: 'ABCDEFGH',
flightId,
validUntil: '2020-08-19T14:26:22',
},
],
}),
)
const response = await request(app.getHttpServer())
.post('/api/public/discounts/12345678/flights')
.set('Authorization', 'Bearer norlandair')
.send({
bookingDate: '2020-08-10T14:26:22.018Z',
flightLegs: [
{
origin: 'REK',
destination: 'AEY',
originalPrice: 50000,
discountPrice: 30000,
date: '2020-08-17T14:26:22', // 24 hours before Date.now jest
},
],
})
flightId = response.body.id
expect(response.status).toBe(201)
})
it('Akureyri->Grímsey 24 hours after allowed', async () => {
await request(app.getHttpServer())
.post('/api/public/discounts/ABCDEFGH/isValidConnectionFlight')
.set('Authorization', 'Bearer norlandair')
.send({
flightLegs: [
{
origin: 'AEY',
destination: 'GRY',
date: '2020-08-18T14:26:22',
},
],
})
.expect(200)
cacheSpy.mockRestore()
})
it('Grímsey->Vopnafjörður 24 hours after not allowed (must touch Akureyri)', async () => {
const connectionRes = await request(app.getHttpServer())
.post('/api/public/discounts/ABCDEFGH/isValidConnectionFlight')
.set('Authorization', 'Bearer norlandair')
.send({
flightLegs: [
{
origin: 'GRY',
destination: 'VPN',
date: '2020-08-18T14:26:22',
},
],
})
.expect(403)
expect(
connectionRes.body.message.includes('User does not meet the requirement'),
).toBe(true)
cacheSpy.mockRestore()
})
it('Akureyri->Reykjavík not allowed as a connecting flight', async () => {
const connectionRes = await request(app.getHttpServer())
.post('/api/public/discounts/ABCDEFGH/isValidConnectionFlight')
.set('Authorization', 'Bearer norlandair')
.send({
flightLegs: [
{
origin: 'AEY',
destination: 'RKV',
date: '2020-08-18T14:26:22',
},
],
})
.expect(403)
expect(connectionRes.body.message).toEqual(
'A flightleg contains invalid flight code/s [AEY, RKV]. Allowed flight codes: [AEY,VPN,GRY,THO]',
)
cacheSpy.mockRestore()
})
it('Akureyri->Grímsey 72 hours after not allowed (validUntil expired)', async () => {
const connectionRes = await request(app.getHttpServer())
.post('/api/public/discounts/ABCDEFGH/isValidConnectionFlight')
.set('Authorization', 'Bearer norlandair')
.send({
flightLegs: [
{
origin: 'AEY',
destination: 'GRY',
date: '2020-08-20T14:26:22',
},
],
})
.expect(403)
expect(
connectionRes.body.message.includes('User does not meet the requirement'),
).toBe(true)
cacheSpy.mockRestore()
})
it('Akureyri -> Grímsey 24 hours before not allowed', async () => {
const connectionRes = await request(app.getHttpServer())
.post('/api/public/discounts/ABCDEFGH/isValidConnectionFlight')
.set('Authorization', 'Bearer norlandair')
.send({
flightLegs: [
{
origin: 'AEY',
destination: 'GRY',
date: '2020-08-16T14:26:22',
},
],
})
.expect(403)
expect(
connectionRes.body.message.includes('User does not meet the requirement'),
).toBe(true)
cacheSpy.mockRestore()
})
it('AEY -> GRY -> GRY -> AEY, not allowed since there is no return trip to RKV', async () => {
const connectionRes = await request(app.getHttpServer())
.post('/api/public/discounts/ABCDEFGH/isValidConnectionFlight')
.set('Authorization', 'Bearer norlandair')
.send({
flightLegs: [
{
origin: 'AEY',
destination: 'GRY',
date: '2020-08-16T14:26:22',
},
{
origin: 'GRY',
destination: 'AEY',
date: '2020-08-16T16:26:22',
},
],
})
.expect(403)
expect(
connectionRes.body.message.includes('User does not meet the requirement'),
).toBe(true)
cacheSpy.mockRestore()
})
it('Correct flight, wrong discount code should result in error', async () => {
const connectionRes = await request(app.getHttpServer())
.post('/api/public/discounts/HIJKLMNO/isValidConnectionFlight')
.set('Authorization', 'Bearer norlandair')
.send({
flightLegs: [
{
origin: 'AEY',
destination: 'GRY',
date: '2020-08-18T14:26:22',
},
],
})
.expect(403)
expect(connectionRes.body.message).toEqual(
'The provided discount code is either not intended for connecting flights or is expired',
)
cacheSpy.mockRestore()
})
})
describe('Reykjavik -> Akureyri -> Akureyri -> Reykjavík connecting flight validations', () => {
let cacheSpy: jest.SpyInstance<Promise<any>, any[]>
let flightId = ''
beforeEach(async () => {
cacheSpy = jest.spyOn(cacheManager, 'get').mockImplementation(() =>
Promise.resolve({
nationalId: user.nationalId,
connectionDiscountCodes: [
{
code: 'ABCDEFGH',
flightId,
validUntil: '2020-08-19T14:26:22',
},
],
}),
)
const response = await request(app.getHttpServer())
.post('/api/public/discounts/12345678/flights')
.set('Authorization', 'Bearer norlandair')
.send({
bookingDate: '2020-08-10T14:26:22.018Z',
flightLegs: [
{
origin: 'RKV',
destination: 'AEY',
originalPrice: 50000,
discountPrice: 30000,
date: '2020-08-14T14:26:22',
},
{
origin: 'AEY',
destination: 'RKV',
originalPrice: 50000,
discountPrice: 30000,
date: '2020-08-17T14:26:22', // 24 hours before Date.now jest
},
],
})
flightId = response.body.id
expect(response.status).toBe(201)
})
it('Akureyri -> Grímsey -> Grímsey -> Akureyri', async () => {
await request(app.getHttpServer())
.post('/api/public/discounts/ABCDEFGH/isValidConnectionFlight')
.set('Authorization', 'Bearer norlandair')
.send({
flightLegs: [
{
origin: 'AEY',
destination: 'GRY',
date: '2020-08-15T14:26:22',
},
{
origin: 'GRY',
destination: 'AEY',
date: '2020-08-16T14:26:22',
},
],
})
.expect(200)
cacheSpy.mockRestore()
})
it('AEY->GRY->GRY->AEY, one flightLeg has wrong date', async () => {
const connectionRes = await request(app.getHttpServer())
.post('/api/public/discounts/ABCDEFGH/isValidConnectionFlight')
.set('Authorization', 'Bearer norlandair')
.send({
flightLegs: [
{
origin: 'AEY',
destination: 'GRY',
date: '2020-08-15T14:26:22',
},
{
origin: 'GRY',
destination: 'AEY',
date: '2020-08-20T14:26:22',
},
],
})
.expect(403)
expect(
connectionRes.body.message.includes(
'Must be 48 hours or less between flight and connectingflight',
),
).toBe(true)
cacheSpy.mockRestore()
})
it('Akureyri -> Raufarhöfn -> Raufarhöfn -> Akureyri not allowed (Raufarhöfn not an allowed airport)', async () => {
const connectionRes = await request(app.getHttpServer())
.post('/api/public/discounts/ABCDEFGH/isValidConnectionFlight')
.set('Authorization', 'Bearer norlandair')
.send({
flightLegs: [
{
origin: 'AEY',
destination: 'RHN',
date: '2020-08-15T14:26:22',
},
{
origin: 'RHN',
destination: 'AEY',
date: '2020-08-16T14:26:22',
},
],
})
.expect(403)
expect(connectionRes.body.message).toBe(
'A flightleg contains invalid flight code/s [AEY, RHN]. Allowed flight codes: [AEY,VPN,GRY,THO]',
)
cacheSpy.mockRestore()
})
})
describe('Delete Flight', () => {
it(`DELETE /api/public/flights/:flightId should delete a flight`, async () => {
const spy = jest
.spyOn(cacheManager, 'get')
.mockImplementation(() =>
Promise.resolve({ nationalId: user.nationalId }),
)
const createRes = await request(app.getHttpServer())
.post('/api/public/discounts/12345678/flights')
.set('Authorization', 'Bearer icelandair')
.send({
bookingDate: '2020-08-17T12:35:50.971Z',
flightLegs: [
{
origin: 'REK',
destination: 'AEY',
originalPrice: 50000,
discountPrice: 30000,
date: '2021-03-12T12:35:50.971Z',
},
{
origin: 'AEY',
destination: 'REK',
originalPrice: 100000,
discountPrice: 60000,
date: '2021-03-15T12:35:50.971Z',
},
],
})
.expect(201)
spy.mockRestore()
await request(app.getHttpServer())
.delete(`/api/public/flights/${createRes.body.id}`)
.set('Authorization', 'Bearer icelandair')
.expect(204)
const getRes = await request(app.getHttpServer())
.get(`/api/private/flights`)
.expect(200)
expect(getRes.body.length).toBe(0)
})
it(`DELETE /api/public/flights/:flightId should validate flightId`, async () => {
await request(app.getHttpServer())
.delete('/api/public/flights/this-is-not-uuid')
.set('Authorization', 'Bearer ernir')
.expect(400)
})
it(`DELETE /api/public/flights/:flightId should return not found if flight does not exist`, async () => {
await request(app.getHttpServer())
.delete('/api/public/flights/dfac526d-5dc0-4748-b858-3d9cd2ae45be')
.set('Authorization', 'Bearer ernir')
.expect(404)
})
it(`DELETE /api/public/flights/:flightId/flightLegs/:flightLegId should delete a flightLeg`, async () => {
// Arrange
const spy = jest
.spyOn(cacheManager, 'get')
.mockImplementation(() =>
Promise.resolve({ nationalId: user.nationalId }),
)
const createRes = await request(app.getHttpServer())
.post('/api/public/discounts/12345678/flights')
.set('Authorization', 'Bearer icelandair')
.send({
bookingDate: '2020-08-17T12:35:50.971Z',
flightLegs: [
{
origin: 'REK',
destination: 'AEY',
originalPrice: 50000,
discountPrice: 30000,
date: '2021-03-12T12:35:50.971Z',
},
{
origin: 'AEY',
destination: 'REK',
originalPrice: 100000,
discountPrice: 60000,
date: '2021-03-15T12:35:50.971Z',
},
],
})
.expect(201)
spy.mockRestore()
expect(createRes.body.flightLegs.length).toBe(2)
// Act
await request(app.getHttpServer())
.delete(
`/api/public/flights/${createRes.body.id}/flightLegs/${createRes.body.flightLegs[0].id}`,
)
.set('Authorization', 'Bearer icelandair')
.expect(204)
// Assert
const getRes = await request(app.getHttpServer()).get(
`/api/private/flights`,
)
expect(
getRes.body.find((flight: Flight) => flight.id === createRes.body.id)
.flightLegs.length,
).toBe(1)
})
}) | the_stack |
import {
AfterViewInit,
ChangeDetectorRef,
Directive,
ElementRef,
HostBinding,
HostListener,
Inject,
Input,
OnDestroy,
Optional,
Renderer2,
Self,
} from '@angular/core';
import {
AbstractControl,
FormControlName,
NgControl,
NgModel
} from '@angular/forms';
import { Subscription } from 'rxjs';
import { IgxInputGroupBase } from '../../input-group/input-group.common';
const nativeValidationAttributes = [
'required',
'pattern',
'minlength',
'maxlength',
'min',
'max',
'step',
];
export enum IgxInputState {
INITIAL,
VALID,
INVALID,
}
/**
* The `igxInput` directive creates single- or multiline text elements, covering common scenarios when dealing with form inputs.
*
* @igxModule IgxInputGroupModule
*
* @igxParent Data Entry & Display
*
* @igxTheme igx-input-group-theme
*
* @igxKeywords input, input group, form, field, validation
*
* @igxGroup presentation
*
* @example
* ```html
* <input-group>
* <label for="address">Address</label>
* <input igxInput name="address" type="text" [(ngModel)]="customer.address">
* </input-group>
* ```
*/
@Directive({
selector: '[igxInput]',
exportAs: 'igxInput',
})
export class IgxInputDirective implements AfterViewInit, OnDestroy {
private static ngAcceptInputType_required: boolean | '';
private static ngAcceptInputType_disabled: boolean | '';
/**
* Sets/gets whether the `"igx-input-group__input"` class is added to the host element.
* Default value is `false`.
*
* @example
* ```typescript
* this.igxInput.isInput = true;
* ```
*
* @example
* ```typescript
* let isCLassAdded = this.igxInput.isInput;
* ```
*/
@HostBinding('class.igx-input-group__input')
public isInput = false;
/**
* Sets/gets whether the `"class.igx-input-group__textarea"` class is added to the host element.
* Default value is `false`.
*
* @example
* ```typescript
* this.igxInput.isTextArea = true;
* ```
*
* @example
* ```typescript
* let isCLassAdded = this.igxInput.isTextArea;
* ```
*/
@HostBinding('class.igx-input-group__textarea')
public isTextArea = false;
private _valid = IgxInputState.INITIAL;
private _statusChanges$: Subscription;
private _fileNames: string;
private _disabled = false;
constructor(
public inputGroup: IgxInputGroupBase,
@Optional() @Self() @Inject(NgModel) protected ngModel: NgModel,
@Optional()
@Self()
@Inject(FormControlName)
protected formControl: FormControlName,
protected element: ElementRef<HTMLInputElement>,
protected cdr: ChangeDetectorRef,
protected renderer: Renderer2
) { }
private get ngControl(): NgControl {
return this.ngModel ? this.ngModel : this.formControl;
}
/**
* Sets the `value` property.
*
* @example
* ```html
* <input-group>
* <input igxInput #igxInput [value]="'IgxInput Value'">
* </input-group>
* ```
*/
@Input()
public set value(value: any) {
this.nativeElement.value = value ?? '';
this.updateValidityState();
}
/**
* Gets the `value` property.
*
* @example
* ```typescript
* @ViewChild('igxInput', {read: IgxInputDirective})
* public igxInput: IgxInputDirective;
* let inputValue = this.igxInput.value;
* ```
*/
public get value() {
return this.nativeElement.value;
}
/**
* Sets the `disabled` property.
*
* @example
* ```html
* <input-group>
* <input igxInput #igxInput [disabled]="true">
* </input-group>
* ```
*/
@Input()
@HostBinding('disabled')
public set disabled(value: boolean) {
this._disabled = this.inputGroup.disabled = !!((value as any === '') || value);
if (this.focused && this._disabled) {
// Browser focus may not fire in good time and mess with change detection, adjust here in advance:
this.inputGroup.isFocused = false;
}
}
/**
* Gets the `disabled` property
*
* @example
* ```typescript
* @ViewChild('igxInput', {read: IgxInputDirective})
* public igxInput: IgxInputDirective;
* let isDisabled = this.igxInput.disabled;
* ```
*/
public get disabled() {
return this._disabled;
}
/**
* Sets the `required` property.
*
* @example
* ```html
* <input-group>
* <input igxInput #igxInput required>
* </input-group>
* ```
*/
@Input()
public set required(value: boolean) {
this.nativeElement.required = this.inputGroup.isRequired = (value as any === '') || value;
}
/**
* Gets whether the igxInput is required.
*
* @example
* ```typescript
* let isRequired = this.igxInput.required;
* ```
*/
public get required() {
let validation;
if (this.ngControl && (this.ngControl.control.validator || this.ngControl.control.asyncValidator)) {
validation = this.ngControl.control.validator({} as AbstractControl);
}
return validation && validation.required || this.nativeElement.hasAttribute('required');
}
/**
* @hidden
* @internal
*/
@HostListener('focus')
public onFocus() {
this.inputGroup.isFocused = true;
}
/**
* @param event The event to invoke the handler
*
* @hidden
* @internal
*/
@HostListener('blur')
public onBlur() {
this.inputGroup.isFocused = false;
this.updateValidityState();
}
/** @hidden @internal */
@HostListener('input')
public onInput() {
this.checkNativeValidity();
}
/** @hidden @internal */
@HostListener('change', ['$event'])
public change(event: Event) {
if (this.type === 'file') {
const fileList: FileList | null = (event.target as HTMLInputElement)
.files;
const fileArray: File[] = [];
if (fileList) {
for (const file of Array.from(fileList)) {
fileArray.push(file);
}
}
this._fileNames = (fileArray || []).map((f: File) => f.name).join(', ');
if (this.required && fileList?.length > 0) {
this._valid = IgxInputState.INITIAL;
}
}
}
/** @hidden @internal */
public get fileNames() {
return this._fileNames;
}
/** @hidden @internal */
public clear() {
this.nativeElement.value = null;
this._fileNames = '';
}
/** @hidden @internal */
public ngAfterViewInit() {
this.inputGroup.hasPlaceholder = this.nativeElement.hasAttribute(
'placeholder'
);
if (this.ngControl && this.ngControl.disabled !== null) {
this.disabled = this.ngControl.disabled;
}
this.inputGroup.disabled =
this.inputGroup.disabled ||
this.nativeElement.hasAttribute('disabled');
this.inputGroup.isRequired = this.nativeElement.hasAttribute(
'required'
);
// Make sure we do not invalidate the input on init
if (!this.ngControl) {
this._valid = IgxInputState.INITIAL;
}
// Also check the control's validators for required
if (this.required && !this.inputGroup.isRequired) {
this.inputGroup.isRequired = this.required;
}
this.renderer.setAttribute(this.nativeElement, 'aria-required', this.required.toString());
const elTag = this.nativeElement.tagName.toLowerCase();
if (elTag === 'textarea') {
this.isTextArea = true;
} else {
this.isInput = true;
}
if (this.ngControl) {
this._statusChanges$ = this.ngControl.statusChanges.subscribe(
this.onStatusChanged.bind(this)
);
}
this.cdr.detectChanges();
}
/** @hidden @internal */
public ngOnDestroy() {
if (this._statusChanges$) {
this._statusChanges$.unsubscribe();
}
}
/**
* Sets a focus on the igxInput.
*
* @example
* ```typescript
* this.igxInput.focus();
* ```
*/
public focus() {
this.nativeElement.focus();
}
/**
* Gets the `nativeElement` of the igxInput.
*
* @example
* ```typescript
* let igxInputNativeElement = this.igxInput.nativeElement;
* ```
*/
public get nativeElement() {
return this.element.nativeElement;
}
/** @hidden @internal */
protected onStatusChanged() {
// Enable/Disable control based on ngControl #7086
if (this.disabled !== this.ngControl.disabled) {
this.disabled = this.ngControl.disabled;
}
this.updateValidityState();
}
/**
* @hidden
* @internal
*/
protected updateValidityState() {
if (this.ngControl) {
if (this.ngControl.control.validator || this.ngControl.control.asyncValidator) {
// Run the validation with empty object to check if required is enabled.
const error = this.ngControl.control.validator({} as AbstractControl);
this.inputGroup.isRequired = error && error.required;
if (!this.disabled && (this.ngControl.control.touched || this.ngControl.control.dirty)) {
// the control is not disabled and is touched or dirty
this._valid = this.ngControl.invalid ?
IgxInputState.INVALID : this.focused ? IgxInputState.VALID :
IgxInputState.INITIAL;
} else {
// if control is untouched, pristine, or disabled its state is initial. This is when user did not interact
// with the input or when form/control is reset
this._valid = IgxInputState.INITIAL;
}
} else {
// If validator is dynamically cleared, reset label's required class(asterisk) and IgxInputState #10010
this._valid = IgxInputState.INITIAL;
this.inputGroup.isRequired = false;
}
this.renderer.setAttribute(this.nativeElement, 'aria-required', this.required.toString());
const ariaInvalid = this.valid === IgxInputState.INVALID;
this.renderer.setAttribute(this.nativeElement, 'aria-invalid', ariaInvalid.toString());
} else {
this.checkNativeValidity();
}
}
/**
* Gets whether the igxInput has a placeholder.
*
* @example
* ```typescript
* let hasPlaceholder = this.igxInput.hasPlaceholder;
* ```
*/
public get hasPlaceholder() {
return this.nativeElement.hasAttribute('placeholder');
}
/**
* Gets the placeholder element of the igxInput.
*
* @example
* ```typescript
* let igxInputPlaceholder = this.igxInput.placeholder;
* ```
*/
public get placeholder() {
return this.nativeElement.placeholder;
}
/**
* @returns An indicator of whether the input has validator attributes or not
*
* @hidden
* @internal
*/
private _hasValidators(): boolean {
for (const nativeValidationAttribute of nativeValidationAttributes) {
if (this.nativeElement.hasAttribute(nativeValidationAttribute)) {
return true;
}
}
return false;
}
/**
* Gets whether the igxInput is focused.
*
* @example
* ```typescript
* let isFocused = this.igxInput.focused;
* ```
*/
public get focused() {
return this.inputGroup.isFocused;
}
/**
* Gets the state of the igxInput.
*
* @example
* ```typescript
* let igxInputState = this.igxInput.valid;
* ```
*/
public get valid(): IgxInputState {
return this._valid;
}
/**
* Sets the state of the igxInput.
*
* @example
* ```typescript
* this.igxInput.valid = IgxInputState.INVALID;
* ```
*/
public set valid(value: IgxInputState) {
this._valid = value;
}
/**
* Gets whether the igxInput is valid.
*
* @example
* ```typescript
* let valid = this.igxInput.isValid;
* ```
*/
public get isValid(): boolean {
return this.valid !== IgxInputState.INVALID;
}
/**
* A function to assign a native validity property of an input.
* This should be used when there's no ngControl
*
* @hidden
* @internal
*/
private checkNativeValidity() {
if (!this.disabled && this._hasValidators()) {
this._valid = this.nativeElement.checkValidity() ?
this.focused ? IgxInputState.VALID : IgxInputState.INITIAL :
IgxInputState.INVALID;
}
}
/**
* Returns the input type.
*
* @hidden
* @internal
*/
public get type() {
return this.nativeElement.type;
}
} | the_stack |
import { Observable, of, forkJoin } from 'rxjs';
import { DataEntityType } from '../lib/api/entity/data-entity.base';
import { RelationshipRepository } from '../lib/api/repository/relationship-repository';
import { Repository } from '../lib/api/repository/repository';
import { DataQuery } from '../lib/data_access/data-query';
import { DataOptions, defaultDataOptions } from '../lib/data_access/data.options';
import { Paris } from '../lib/paris';
import { mergeMap } from 'rxjs/operators';
import { CreateTodoListApiCall } from './mock/create-new-list.api-call';
import { Tag } from './mock/tag.value-object';
import { TodoList } from './mock/todo-list.entity';
import { TodoListItemsRelationship } from './mock/todo-list.relationships';
import { TodoStatus } from './mock/todo-status.entity';
import { Todo } from './mock/todo.entity';
import { UpdateTodoApiCall } from './mock/update-todo.api-call';
import { DataSet } from "../lib/data_access/dataset";
import { DataStoreService } from '../lib/data_access/data-store.service';
import { TodoType } from './mock/todo-type.entity';
import { RequestMethod } from '../lib/data_access/http.service';
import { EntityModelBase } from '../lib/config/entity-model.base';
describe('Paris main', () => {
let paris: Paris;
describe('Get repository', () => {
let repo: Repository<Todo>;
beforeEach(() => {
paris = new Paris();
repo = paris.getRepository(Todo);
});
it('should create a ToDo repository', () => {
expect(repo).toBeDefined();
});
it('should return a Repository from getRepository', () => {
expect(repo).toBeInstanceOf(Repository);
});
it('should return a repository for a ValueObject', () => {
expect(paris.getRepository(Tag)).toBeDefined();
});
it.skip("should return null if entity doesn't exist", () => { });
});
describe('Get Todo item by ID', () => {
let repo: Repository<Todo>, item$: Observable<Todo>;
beforeEach(() => {
paris = new Paris();
repo = paris.getRepository(Todo);
jest.spyOn(paris.dataStore.httpService, 'request');
jest.spyOn(repo, 'getItemById');
jest.spyOn(paris.dataStore, 'request');
item$ = paris.getItemById(Todo, 1);
});
it('should call Repository.getItemById with correct default params', () => {
expect(repo.getItemById).toHaveBeenCalledWith(1, defaultDataOptions, undefined);
});
it('should call Http.request with correct default params', () => {
expect(paris.dataStore.httpService.request).toHaveBeenCalledWith(
'GET',
'/todo/1',
{"customHeaders": {"keyForRegularTodoItem": "valueForRegularTodoItem"}},
{ timeout: 20000 }
);
});
it('should call Repository.getItemById with correct params', () => {
paris.getItemById(Todo, 1, null, { test: 1 });
expect(repo.getItemById).toHaveBeenCalledWith(1, defaultDataOptions, { test: 1 });
});
it('should call Http.request with correct params', () => {
paris.getItemById(Todo, 1, null, { test: 1});
expect(paris.dataStore.httpService.request).toHaveBeenCalledWith(
'GET',
'/todo/1',
{ customHeaders: {'keyForRegularTodoItem': 'valueForRegularTodoItem'}, params: { test: 1 }},
{ timeout: 20000 }
);
});
it('should return an Observable from paris.getItemById', () => {
expect(item$).toBeInstanceOf(Observable);
});
it.skip('should throw error if getItem is not supported', () => { });
it('should call datastore.request', () => {
expect(paris.dataStore.request).toHaveBeenCalled();
});
});
describe('getModelBaseConfig', () => {
beforeEach(() => {
paris = new Paris();
});
it('should return the entityConfig for Todo', () => {
expect(paris.getModelBaseConfig(Todo)).toBe((<DataEntityType>Todo).entityConfig);
});
it('should return the valueObjectConfig for a ValueObject', () => {
expect(paris.getModelBaseConfig(Tag)).toBe((<DataEntityType>Tag).valueObjectConfig);
});
});
describe('query', () => {
let repo: Repository<Todo>;
const next = 'https://localhost:666/api/todo?p=2';
const todoMockData = {
items: [
{
id: 1,
text: 'First',
type: 0
},
{
id: 2,
text: 'Second',
type: 1
},
{
id: 3,
text: 'Third',
type: 1
}
],
next: next,
count: 3
};
const typesMockData = {
count: 2,
items: [
{
id: 0,
name: 'Human'
},
{
id: 1,
name: 'Machine-Generated'
}
]
};
beforeEach(<T extends EntityModelBase<number>>() => {
// @ts-ignore
const mockDataFetch:(method: RequestMethod, endpoint: string) => Observable<DataSet<T>> = (method:string, url: string) => of<DataSet<T>>(<DataSet<T>>(/types/.test(url) ? typesMockData : todoMockData));
// @ts-ignore
DataStoreService.prototype.get = jest.fn<Observable<DataSet<T>>, [RequestMethod, string]>(mockDataFetch);
// @ts-ignore
DataStoreService.prototype.request = jest.fn<Observable<DataSet<T>>, [RequestMethod, string]>(mockDataFetch);
});
afterEach(() => {
jest.restoreAllMocks();
});
beforeEach(() => {
paris = new Paris();
repo = paris.getRepository(Todo);
jest.spyOn(repo, 'query');
});
it('should call Repository.query with correct default params', () => {
paris.query(Todo);
expect(repo.query).toHaveBeenCalledWith(undefined, defaultDataOptions);
});
it('should call Repository.query with correct params', () => {
const query: DataQuery = { where: { a: 1 } },
dataOptions: DataOptions = { allowCache: false };
paris.query(Todo, query, dataOptions);
expect(repo.query).toHaveBeenCalledWith(query, dataOptions);
});
it('should return an Observable from paris.query', () => {
expect(paris.query(Todo)).toBeInstanceOf(Observable);
});
it("should throw error if repo doesn't exist", () => {
expect(() => paris.query(<any>String)).toThrow();
});
it("should have a 'next' property in the DataSet", done => {
paris.query(Todo).subscribe((dataSet: DataSet<Todo>) => {
expect(dataSet.next).toEqual(next);
done();
});
});
it('should have a submodel', done => {
paris.query(Todo).subscribe(({ items }: DataSet<Todo>) => {
expect(items[0].type).toBeInstanceOf(TodoType);
done();
});
});
it('should point submodels to the same model when using loadAll', done => {
paris.query(Todo).subscribe(({ items }: DataSet<Todo>) => {
expect(items[1].type).toBe(items[2].type);
done();
});
});
});
describe('apiCall', () => {
let jestGetApiCallCacheSpy: jest.SpyInstance<Observable<Paris>>;
let jestMakeApiCallSpy: jest.SpyInstance<Observable<any>>;
beforeEach(() => {
paris = new Paris();
jest.spyOn(paris.dataStore.httpService, 'request');
jestGetApiCallCacheSpy = jest.spyOn(paris, 'getApiCallCache' as any);
jestMakeApiCallSpy = jest.spyOn(paris, 'makeApiCall' as any);
});
describe('cache behaviour', () => {
function callTwoDifferentApiCalls() {
return forkJoin(paris.apiCall(CreateTodoListApiCall), paris.apiCall(UpdateTodoApiCall));
}
const testObj = {};
beforeEach(done => {
jestMakeApiCallSpy.mockReturnValue(of(testObj));
callTwoDifferentApiCalls().subscribe(_ => done());
});
it('should retreive data from cache', done => {
callTwoDifferentApiCalls().subscribe(val => {
expect(val[0]).toBe(testObj);
expect(jestMakeApiCallSpy).toHaveBeenCalledTimes(2);//expecting no additional calls to 'makeApiCall'
done();
})
});
it('should clear a specific ApiCall cache', done => {
paris.clearApiCallCache(CreateTodoListApiCall);
callTwoDifferentApiCalls().subscribe(_ => {
expect(jestMakeApiCallSpy).toHaveBeenCalledTimes(3);//expecting exactly one additional call to 'makeApiCall'
done();
})
});
it('should clear all ApiCalls cache', done => {
paris.clearApiCallCache();
callTwoDifferentApiCalls().subscribe(_ => {
expect(jestMakeApiCallSpy).toHaveBeenCalledTimes(4);//expecting exactly two additional calls to 'makeApiCall'
done();
})
});
});
it('should get data from cache if available and configured to', () => {
jestGetApiCallCacheSpy.mockRestore();
const fakeCache = { get: jest.fn(() => of(null)) };
paris['getApiCallCache'] = jest.fn(() => fakeCache) as any;
paris.apiCall(CreateTodoListApiCall);
expect((<any>paris).makeApiCall).not.toHaveBeenCalled();
expect(paris.dataStore.httpService.request).not.toHaveBeenCalled();
expect(fakeCache.get).toHaveBeenCalled();
});
it('should not get data from cache if allowCache is false', () => {
paris.apiCall(CreateTodoListApiCall, undefined, { allowCache: false });
expect((<any>paris).getApiCallCache).not.toHaveBeenCalled();
});
it('should be able to serialize complex objects with circular dependencies', done => {
jestMakeApiCallSpy.mockReturnValue(of(new Paris));
const todoItem = paris.createItem(Todo, {
id: 1,
text: 'myTodo',
time: new Date(),
tags: [],
status: { name: 'Open' },
});
todoItem
.pipe(mergeMap(todoItem => paris.apiCall(UpdateTodoApiCall, todoItem)))
.subscribe(() => {
done();
});
});
it('should always add newer data to cache if cache exists', () => { });
it('should not cache null/undefined values', () => { });
it('should call makeApiCall with correct params', () => { });
it('should call makeApiCall with correct default params', () => { });
it('should emit from error$ if encountered an error', () => { });
it('should call modelArray if repo exists data is array', () => { });
it('should call createItem if repo exists and data is not an array', () => { });
it("should call DataTransformersService.parse if repo doesn't exist and data type is defined", () => { });
it('should call parse if defined', () => { });
it('should return an Observable', () => { });
it('should throw an error if no endpoint is configured', () => { });
it('should throw an error if no endpoint is configured', () => { });
it.skip('should call datastore.request', () => {
expect(paris.dataStore.request).toHaveBeenCalled();
});
it('should call makeApiCall with the right custom headers which are given by a callback', () => {
paris.apiCall(CreateTodoListApiCall, "test", { allowCache: false });
expect((<any>paris).makeApiCall).toHaveBeenCalledWith(
{"cache": true, "customHeaders": jasmine.any(Function), "endpoint": "create_new_list", "method": "POST", "name": "Create a new Todo list"},
'POST',
{"customHeaders": {"testHeader": "testValue"}, "data": "test"},
undefined,
null
);
});
it('should call makeApiCall with the right custom headers which are given directly', () => {
const createToDoListApiCall = Object.assign({}, CreateTodoListApiCall, {config: Object.assign({}, (<any>CreateTodoListApiCall).config, {'customHeaders': {'directTestHeader': 'directTestValue'}})});
paris.apiCall(createToDoListApiCall, undefined, { allowCache: false });
expect((<any>paris).makeApiCall).toHaveBeenCalled();
expect((<any>paris).makeApiCall).toHaveBeenCalledWith(
{"cache": true, "customHeaders": {"directTestHeader": "directTestValue"}, "endpoint": "create_new_list", "method": "POST", "name": "Create a new Todo list"},
'POST',
{"customHeaders": {"directTestHeader": "directTestValue"}},
undefined,
null
);
});
it('should call Http.request with correct default params', () => { });
it('should call Http.request with correct params', () => { });
it('should pass the timeout property as part of the options if it exists', () => {
const timeout = 123456;
const createToDoListApiCall = {
...CreateTodoListApiCall,
config: {
...(<any>CreateTodoListApiCall).config,
timeout
}
};
paris.apiCall(<any>createToDoListApiCall, undefined, { allowCache: false });
const [, , , , requestOptions] = (<any>paris).makeApiCall.mock.calls[0];
expect(requestOptions.timeout).toBe(timeout);
});
});
describe('callQuery', () => {
let jestGetApiCallCacheSpy: jest.SpyInstance<Observable<Paris>>;
let jestMakeApiCallSpy: jest.SpyInstance<Observable<any>>;
beforeEach(() => {
paris = new Paris();
jest.spyOn(paris.dataStore.httpService, 'request');
jestGetApiCallCacheSpy = jest.spyOn(paris, 'getApiCallCache' as any);
jestMakeApiCallSpy = jest.spyOn(paris, 'makeApiCall' as any);
});
it('should call makeApiCall with correct params', () => { });
it('should call makeApiCall with correct default params', () => { });
it('should call rawDataToDataSet with correct params', () => { });
it('should emit from error$ if encountered an error', () => { });
it('should return an Observable', () => { });
it.skip('should call datastore.request', () => {
expect(paris.dataStore.request).toHaveBeenCalled();
});
it('should call Http.request with correct default params', () => { });
it('should call Http.request with correct params', () => { });
it('should pass the timeout property as part of the options if it exists', () => {
const timeout = 123456;
const createToDoListApiCall = {
...CreateTodoListApiCall,
config: {
...(<any>CreateTodoListApiCall).config,
timeout
}
};
paris.callQuery(<any>createToDoListApiCall, createToDoListApiCall.config);
const [, , , , requestOptions] = (<any>paris).makeApiCall.mock.calls[0];
expect(requestOptions.timeout).toBe(timeout);
});
});
describe('createItem', () => {
let createItem$: Observable<Todo>;
beforeEach(() => {
paris = new Paris();
createItem$ = paris.createItem<Todo>(Todo, { id: 1, text: 'test' });
});
it('should return an Observable', () => {
expect(createItem$).toBeInstanceOf(Observable);
});
it('should create a Todo item', done => {
createItem$.subscribe(todo => {
expect(todo).toBeInstanceOf(Todo);
done();
});
});
});
describe('queryForItem', () => {
beforeEach(() => {
paris = new Paris();
});
it('should call RelationshipRepository.queryForItem with correct params', () => { });
it('should call RelationshipRepository.queryForItem with correct default params', () => { });
it("should throw error if repo doesn't exist", () => {
expect(() => paris.queryForItem(TodoList, new Todo({ id: 1 }))).toThrow();
});
it('should return an Observable', () => { });
});
describe('getRelatedItem', () => {
beforeEach(() => {
paris = new Paris();
});
it('should call RelationshipRepository.getRelatedItem with correct params', () => { });
it('should call RelationshipRepository.getRelatedItem with correct default params', () => { });
it("should throw error if the relationship repository doesn't exist", () => {
expect(() => paris.getRelatedItem(TodoList, new Todo({ id: 1 }))).toThrow();
});
it("should throw an error if the relationship doesn't support OneToMany", () => {
expect(() =>
paris.getRelatedItem(TodoListItemsRelationship, new TodoList({ id: 1 }))
).toThrow();
});
it('should return an Observable', () => {
expect(
paris.queryForItem(TodoListItemsRelationship, new TodoList({ id: 1 }))
).toBeInstanceOf(Observable);
});
});
describe('getValue', () => {
beforeEach(() => {
paris = new Paris();
});
it("should return null if repo doesn't exist", () => {
class SomeClass { }
expect(paris.getValue(SomeClass, 1)).toBe(null);
});
it("should return null if repo doesn't have defined values", () => {
expect(paris.getValue(TodoStatus, 9)).toBe(null);
});
it("should call valueId if it's a function (predicate)", () => {
expect(paris.getValue(TodoStatus, status => /done/i.test(status.name)).name).toBe(
'Done'
);
});
it('should call getValueById if valueId is not a function', () => {
expect(paris.getValue(TodoStatus, 1).name).toBe('Open');
});
it('should return the correct type', () => {
expect(paris.getValue(TodoStatus, 1)).toBeInstanceOf(TodoStatus);
});
});
describe('getRelationshipRepository', () => {
beforeEach(() => {
paris = new Paris();
});
it('should create a RelationshipRepository', () => {
expect(paris.getRelationshipRepository(TodoListItemsRelationship)).toBeDefined();
});
it('should return a RelationshipRepository', () => {
expect(paris.getRelationshipRepository(TodoListItemsRelationship)).toBeInstanceOf(
RelationshipRepository
);
});
});
}); | the_stack |
import { expect } from 'chai'
import { AssertFalse, AssertTrue, Has, IsExact } from 'conditional-type-checks'
import fc from 'fast-check'
import { AnythingMatcher } from '../../src/matchers/Anything'
import { createPlugin, SmartEqRule } from '../../src/plugins'
import { buildSmartEqResult, ExpectedEqual, loadSmartEqRules, smartEq } from '../../src/validators/smartEq'
import { arbitraries } from '../arbitraries'
import { clearModuleCache } from '../common'
describe('smartEq', () => {
it('compares primitive values', () => {
expect(smartEq(1, 1)).to.be.deep.eq({ result: 'success' })
expect(smartEq('abc', 'abc')).to.be.deep.eq({ result: 'success' })
expect(smartEq(true, true)).to.be.deep.eq({ result: 'success' })
expect(smartEq(1, 2)).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq('abc', ' def')).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq(true, false)).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq(undefined, null)).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
})
it('given two primitives, smartEq(a, b) succeeds only if a === b', () => {
fc.assert(
fc.property(
arbitraries.primitive,
arbitraries.primitive,
(a, b) => (a === b) === (smartEq(a, b).result === 'success'),
),
)
})
it('compares objects', () => {
expect(smartEq({}, {})).to.be.deep.eq({ result: 'success' })
expect(smartEq({ abc: true }, { abc: true })).to.be.deep.eq({ result: 'success' })
expect(smartEq({ a: { b: 1 } }, { a: { b: 1 } })).to.be.deep.eq({ result: 'success' })
expect(smartEq({}, { abc: true })).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq({ abc: true }, { abc: 'true' })).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq({ a: { b: 1, c: 1 } }, { a: { b: 1 } })).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
})
it('compares primitive values against matchers', () => {
expect(smartEq(1, AnythingMatcher.make())).to.be.deep.eq({ result: 'success' })
expect(smartEq('abc', AnythingMatcher.make())).to.be.deep.eq({ result: 'success' })
})
it('compares object values against matchers', () => {
expect(smartEq({}, { abc: AnythingMatcher.make() })).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq({ complex: { abc: 'ced' } }, { complex: AnythingMatcher.make() })).to.be.deep.eq({
result: 'success',
})
expect(smartEq({ complex: undefined }, { complex: AnythingMatcher.make() })).to.be.deep.eq({ result: 'success' })
expect(smartEq({}, { complex: AnythingMatcher.make() })).to.be.deep.eq({
result: 'error',
reason: 'value mismatch',
})
})
it('compares undefined', () => {
expect(smartEq(undefined, {})).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq(undefined, null)).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq(undefined, 0)).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq(undefined, '')).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq(undefined, undefined)).to.be.deep.eq({ result: 'success' })
})
it('compares null', () => {
expect(smartEq(null, {})).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq(null, undefined)).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq(null, 0)).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq(null, '')).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq(null, null)).to.be.deep.eq({ result: 'success' })
})
it('compares arrays', () => {
expect(smartEq([], {})).to.be.deep.eq({ result: 'error', reason: 'prototype mismatch' })
expect(smartEq([1, 2, 3], [1, 2])).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq([1, 2], [1, 2, 3])).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq([1, 2, 3], [1, 2, 3])).to.be.deep.eq({ result: 'success' })
})
it('compares iterables', () => {
function makeIterable(values: any[]): IterableIterator<any> {
return new Set(values).entries()
}
expect(smartEq(makeIterable([1, 2, 3]), makeIterable([1, 2, 3]))).to.be.deep.eq({ result: 'success' })
expect(smartEq(makeIterable([1, 2, 3]), makeIterable([1, 2]))).to.be.deep.eq({
result: 'error',
reason: 'value mismatch',
})
expect(smartEq(makeIterable([]), {})).to.be.deep.eq({ result: 'error', reason: 'prototype mismatch' })
})
it('compares objects with digits', () => {
expect(smartEq({ 0: '1', 1: '2' }, { 0: '1', 1: '2' })).to.be.deep.eq({ result: 'success' })
})
it('compares prototypes', () => {
class Test {
constructor(public readonly property: boolean) {}
}
expect(smartEq(new Test(true), { property: true })).to.be.deep.eq({ result: 'error', reason: 'prototype mismatch' })
})
it('compares dates', () => {
expect(smartEq(new Date(1, 2, 3), new Date(1, 2, 3))).to.be.deep.eq({ result: 'success' })
expect(smartEq(new Date(1, 2, 3), new Date(1, 2, 4))).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq(new Date(1, 2, 3), undefined)).to.be.deep.eq({ result: 'error', reason: 'prototype mismatch' })
})
it('given two dates, smartEq(a, b) succeeds only if their unix timestamps equal', () => {
fc.assert(
fc.property(fc.date(), fc.date(), (a, b) => {
return (smartEq(a, b).result === 'success') === (a.getTime() === b.getTime())
}),
{ examples: [[new Date(0), new Date(0)]] },
)
})
it('compares sets', () => {
expect(smartEq(new Set([1, 2, 3]), new Set([1, 2, 3]))).to.be.deep.eq({ result: 'success' })
expect(smartEq(new Set([1, 2, 3]), new Set([1, 2, 4]))).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq(new Set([1, 2, 3]), undefined)).to.be.deep.eq({ result: 'error', reason: 'prototype mismatch' })
})
it('compares maps', () => {
expect(
smartEq(new Map(Object.entries({ a: '1', b: 2, c: 3 })), new Map(Object.entries({ a: '1', b: 2, c: 3 }))),
).to.be.deep.eq({
result: 'success',
})
expect(
smartEq(new Map(Object.entries({ a: '1', b: 2, c: 3 })), new Map(Object.entries({ a: '1', b: 2, d: 3 }))),
).to.be.deep.eq({
result: 'error',
reason: 'value mismatch',
})
expect(
smartEq(new Map(Object.entries({ a: '1', b: 2, c: 3 })), new Map(Object.entries({ a: '1', b: 2, c: 6 }))),
).to.be.deep.eq({
result: 'error',
reason: 'value mismatch',
})
expect(
smartEq(
new Map(Object.entries({ a: '1', b: 2, c: 3 })),
new Map(Object.entries({ a: '1', b: 2, c: AnythingMatcher.make() })),
),
).to.be.deep.eq({
result: 'success',
})
expect(smartEq(new Map(Object.entries({ a: '1', b: 2, c: 3 })), undefined)).to.be.deep.eq({
result: 'error',
reason: 'prototype mismatch',
})
})
it('compares symbols', () => {
expect(smartEq(Symbol('abc'), Symbol('abc'))).to.be.deep.eq({ result: 'success' })
expect(smartEq(Symbol('abc'), Symbol('abd'))).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq(Symbol('abc'), 'abc')).to.be.deep.eq({ result: 'error', reason: 'prototype mismatch' })
})
it('compares edge cases', () => {
expect(smartEq(NaN, NaN)).to.be.deep.eq({ result: 'success' })
expect(smartEq(-0, +0)).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
})
it('compares recursive objects #1', () => {
interface Node {
prev?: Node
next?: Node
value: any
}
const node = (value: any): Node => ({ value })
const list = (...values: any[]) =>
values.map(node).map((node, index, nodes) => {
node.prev = nodes[index - 1]
node.next = nodes[index + 1]
return node
})[0]
const a = list(1, 2, 3)
const b = list(1, 2, 3)
const c = list(4, 5)
expect(smartEq(a, b)).to.be.deep.eq({ result: 'success' })
expect(smartEq(a, c)).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
})
it('compares recursive objects #2', () => {
const a: any = { v: 1 }
a.foo = a
const b: any = { v: 2, foo: { v: 2, foo: { v: 2 } } }
b.foo.foo.foo = b
expect(smartEq(a, b)).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
})
it('compares recursive objects #3 (nasty counter)', () => {
let _value = 0
const nastyCounter = {
// Don't do this in your projects.
get value() {
return _value++
},
}
expect(smartEq(nastyCounter, nastyCounter)).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
})
it('does not crash on infinite object', () => {
type MagicBean = { readonly grow: string; next: MagicBean | null }
const makeMagicBean = (): MagicBean => ({
get grow() {
this.next = { ...this }
return 'ok'
},
next: null,
})
const magicBean = makeMagicBean()
expect(smartEq(magicBean, magicBean)).to.be.deep.eq({ result: 'error', reason: 'object possibly infinite' })
expect(smartEq(magicBean, makeMagicBean())).to.be.deep.eq({ result: 'error', reason: 'object possibly infinite' })
})
describe('non-strict', () => {
it('doesnt compare prototypes', () => {
class Test {
constructor(public readonly property: boolean) {}
}
expect(smartEq(new Test(true), { property: true }, false)).to.be.deep.eq({ result: 'success' })
})
it('doesnt compare prototypes with nested objects', () => {
class Test {
constructor(public readonly property: boolean) {}
}
expect(smartEq({ nested: new Test(true) }, { nested: { property: true } }, false)).to.be.deep.eq({
result: 'success',
})
})
})
type SmartEqType = typeof smartEq
type LoadSmartEqRulesType = typeof loadSmartEqRules
describe('plugin', () => {
let smartEq: SmartEqType
let loadSmartEqRules: LoadSmartEqRulesType
beforeEach(function () {
this.timeout(5_000)
clearModuleCache()
;({ smartEq, loadSmartEqRules } = require('../../src/validators/smartEq'))
})
afterEach(clearModuleCache)
it('adds new smartEq rules', () => {
const breakMathEqRule = (a: any, e: any) => {
if (a === 2 && e === 2) {
return buildSmartEqResult(false)
}
}
loadSmartEqRules([breakMathEqRule])
expect(smartEq(2, 2)).to.be.deep.eq({ result: 'error', reason: 'value mismatch' })
expect(smartEq(3, 3)).to.be.deep.eq({ result: 'success' })
})
it('clears cache correctly', () => {
expect(smartEq(2, 2)).to.be.deep.eq({ result: 'success' })
})
})
/**
* Based on Jest's property tests
* @see https://github.com/facebook/jest/blob/e0b33b74b5afd738edc183858b5c34053cfc26dd/packages/expect/src/__tests__/matchers-toEqual.property.test.ts
*/
describe('properties', () => {
const equals = <T>(a: T, b: T) => smartEq(a, b).result === 'success'
it('should be reflexive', () => {
fc.assert(
fc.property(fc.dedup(arbitraries.anything, 2), ([a, b]) => equals(a, b)),
{},
)
})
it('should be symmetric', () => {
fc.assert(
fc.property(
arbitraries.anything,
arbitraries.anything,
(a, b) =>
// Given: a and b values
// Assert: We expect `expect(a).toEqual(b)`
// to be equivalent to `expect(b).toEqual(a)`
equals(a, b) === equals(b, a),
),
{
examples: [
[0, 5e-324],
// eslint-disable-next-line no-new-wrappers
[new Set([false, true]), new Set([new Boolean(true), new Boolean(true)])],
],
},
)
})
})
})
// #region type-level tests
type _ActualTypes = [
ExpectedEqual<number>,
ExpectedEqual<string>,
ExpectedEqual<undefined>,
ExpectedEqual<1 | 2 | 3>,
ExpectedEqual<Fruit>,
ExpectedEqual<Banana>,
]
type _ExpectedTypes = [number, string, undefined, 1 | 2 | 3, Fruit, Banana]
type _EveryTypeCanBeEqualToItself = AssertTrue<IsExact<_ActualTypes, _ExpectedTypes>>
interface TestPlugin {
smartEqRules: {
applesToOranges: SmartEqRule<Apple | Orange, Apple | Orange>
potatoToFruit: SmartEqRule<Potato, Fruit>
ruleThatCouldPossiblyBreakEverything: SmartEqRule<any, any>
anotherNastyRule: SmartEqRule<unknown, unknown>
}
}
type TestPluginRules = createPlugin.SmartEqRulesOf<TestPlugin>
type _NastyRulesAreFilteredOut = AssertTrue<IsExact<keyof TestPluginRules, 'applesToOranges' | 'potatoToFruit'>>
declare module '../../src/validators/smartEq' {
export interface SmartEqRules extends TestPluginRules {}
}
type _ApplesCanBeComparedToOranges = AssertTrue<IsExact<ExpectedEqual<Apple>, Apple | Orange>>
type _OrangesCanBeComparedToApples = AssertTrue<IsExact<ExpectedEqual<Orange>, Apple | Orange>>
type _PotatoCanBeComparedWithFruit = AssertTrue<IsExact<ExpectedEqual<Potato>, Potato | Fruit>>
type _ButAFruitCannotBeComparedWithPotato = AssertFalse<Has<ExpectedEqual<Fruit>, Potato>>
class Apple {
// private property forces nominal typing
#brand!: never
}
class Banana {
#brand!: never
}
class Orange {
#brand!: never
}
class Potato {
#brand!: never
}
type Fruit = Apple | Banana | Orange
// #endregion type-level tests | the_stack |
import React from "react"
import { fmap } from "../Functor"
import { Internals } from "../Internals"
import { List } from "../List"
import { Just, Maybe } from "../Maybe"
import { add } from "../Num"
const { Nothing } = Internals
// CONSTRUCTORS
test ("Just", () => {
expect (Just (3) .value) .toEqual (3)
expect (Just (3) .isJust) .toEqual (true)
expect (Just (3) .isNothing) .toEqual (false)
})
test ("Nothing", () => {
expect (Nothing .isJust) .toEqual (false)
expect (Nothing .isNothing) .toEqual (true)
})
test ("Maybe", () => {
expect (Maybe (3)) .toEqual (Just (3))
expect (Maybe (undefined)) .toEqual (Nothing)
expect (Maybe (null)) .toEqual (Nothing)
})
// MAYBE FUNCTIONS (PART 1)
test ("isJust", () => {
expect (Maybe.isJust (Maybe (3)))
.toBeTruthy ()
expect (Maybe.isJust (Maybe (null)))
.toBeFalsy ()
})
test ("isNothing", () => {
expect (Maybe.isNothing (Maybe (3)))
.toBeFalsy ()
expect (Maybe.isNothing (Maybe (null)))
.toBeTruthy ()
})
test ("fromJust", () => {
expect (Maybe.fromJust (Maybe (3) as Just<number>))
.toEqual (3)
expect (() => Maybe.fromJust (Maybe (null) as Just<null>))
.toThrow ()
})
test ("fromMaybe", () => {
expect (Maybe.fromMaybe (0) (Maybe (3)))
.toEqual (3)
expect (Maybe.fromMaybe (0) (Maybe (null) as Maybe<number>))
.toEqual (0)
})
test ("fromMaybe_", () => {
expect (Maybe.fromMaybe_ (() => 0) (Maybe (3)))
.toEqual (3)
expect (Maybe.fromMaybe_ (() => 0) (Maybe (null) as Maybe<number>))
.toEqual (0)
})
// APPLICATIVE
test ("pure", () => {
expect (Maybe.pure (2)) .toEqual (Just (2))
})
test ("ap", () => {
expect (Maybe.ap (Just ((x: number) => x * 2)) (Just (3)))
.toEqual (Just (6))
expect (Maybe.ap (Just ((x: number) => x * 2)) (Nothing))
.toEqual (Nothing)
expect (Maybe.ap (Nothing) (Just (3)))
.toEqual (Nothing)
expect (Maybe.ap (Nothing) (Nothing))
.toEqual (Nothing)
})
// ALTERNATIVE
test ("alt", () => {
expect (Maybe.alt (Just (3)) (Just (2)))
.toEqual (Just (3))
expect (Maybe.alt (Just (3)) (Nothing))
.toEqual (Just (3))
expect (Maybe.alt (Nothing) (Just (2)))
.toEqual (Just (2))
expect (Maybe.alt (Nothing) (Nothing))
.toEqual (Nothing)
})
test ("alt_", () => {
expect (Maybe.alt_ (Just (3)) (() => Just (2)))
.toEqual (Just (3))
expect (Maybe.alt_ (Just (3)) (() => Nothing))
.toEqual (Just (3))
expect (Maybe.alt_ (Nothing) (() => Just (2)))
.toEqual (Just (2))
expect (Maybe.alt_ (Nothing) (() => Nothing))
.toEqual (Nothing)
})
test ("altF", () => {
expect (Maybe.altF (Just (2)) (Just (3)))
.toEqual (Just (3))
expect (Maybe.altF (Nothing) (Just (3)))
.toEqual (Just (3))
expect (Maybe.altF (Just (2)) (Nothing))
.toEqual (Just (2))
expect (Maybe.altF (Nothing) (Nothing))
.toEqual (Nothing)
})
test ("altF_", () => {
expect (Maybe.altF_ (() => Just (2)) (Just (3)))
.toEqual (Just (3))
expect (Maybe.altF_ (() => Nothing) (Just (3)))
.toEqual (Just (3))
expect (Maybe.altF_ (() => Just (2)) (Nothing))
.toEqual (Just (2))
expect (Maybe.altF_ (() => Nothing) (Nothing))
.toEqual (Nothing)
})
test ("empty", () => {
expect (Maybe.empty) .toEqual (Nothing)
})
test ("guard", () => {
expect (Maybe.guard (true))
.toEqual (Just (undefined))
expect (Maybe.guard (false))
.toEqual (Nothing)
})
// MONAD
test ("bind", () => {
expect (Maybe.bind (Maybe (3))
(x => Just (x * 2)))
.toEqual (Just (6))
expect (Maybe.bind (Maybe (null) as Maybe<number>)
(x => Just (x * 2)))
.toEqual (Nothing)
})
test ("bindF", () => {
expect (Maybe.bindF ((x: number) => Just (x * 2))
(Maybe (3)))
.toEqual (Just (6))
expect (Maybe.bindF ((x: number) => Just (x * 2))
(Maybe (null) as Maybe<number>))
.toEqual (Nothing)
})
test ("then", () => {
expect (Maybe.then (Just (3)) (Just (2)))
.toEqual (Just (2))
expect (Maybe.then (Nothing) (Maybe.Just (2)))
.toEqual (Nothing)
expect (Maybe.then (Just (3)) (Nothing))
.toEqual (Nothing)
expect (Maybe.then (Nothing) (Nothing))
.toEqual (Nothing)
})
test ("kleisli", () => {
expect (Maybe.kleisli ((x: number) => x > 5 ? Nothing : Just (x))
(x => x < 0 ? Nothing : Just (x))
(2))
.toEqual (Just (2))
expect (Maybe.kleisli ((x: number) => x > 5 ? Nothing : Just (x))
(x => x < 0 ? Nothing : Just (x))
(6))
.toEqual (Nothing)
expect (Maybe.kleisli ((x: number) => x > 5 ? Nothing : Just (x))
(x => x < 0 ? Nothing : Just (x))
(-1))
.toEqual (Nothing)
})
test ("join", () => {
expect (Maybe.join (Just (Just (3))))
.toEqual (Just (3))
expect (Maybe.join (Just (Nothing)))
.toEqual (Nothing)
expect (Maybe.join (Nothing))
.toEqual (Nothing)
})
test ("mapM", () => {
expect (
Maybe.mapM ((x: number) => x === 2 ? Nothing : Just (x + 1))
(List.empty)
)
.toEqual (Just (List.empty))
expect (
Maybe.mapM ((x: number) => x === 2 ? Nothing : Just (x + 1))
(List (1, 3))
)
.toEqual (Just (List (2, 4)))
expect (
Maybe.mapM ((x: number) => x === 2 ? Nothing : Just (x + 1))
(List (1, 2, 3))
)
.toEqual (Nothing)
})
test ("liftM2", () => {
expect (Maybe.liftM2 ((x: number) => (y: number) => x + y) (Just (1)) (Just (2)))
.toEqual (Just (3))
expect (Maybe.liftM2 ((x: number) => (y: number) => x + y) (Nothing) (Just (2)))
.toEqual (Nothing)
expect (Maybe.liftM2 ((x: number) => (y: number) => x + y) (Just (1)) (Nothing))
.toEqual (Nothing)
expect (Maybe.liftM2 ((x: number) => (y: number) => x + y) (Nothing) (Nothing))
.toEqual (Nothing)
})
test ("liftM3", () => {
expect (
Maybe.liftM3 ((x: number) => (y: number) => (z: number) => x + y + z)
(Just (1))
(Just (2))
(Just (3))
)
.toEqual (Just (6))
expect (
Maybe.liftM3 ((x: number) => (y: number) => (z: number) => x + y + z)
(Nothing)
(Just (2))
(Just (3))
)
.toEqual (Nothing)
expect (
Maybe.liftM3 ((x: number) => (y: number) => (z: number) => x + y + z)
(Just (1))
(Nothing)
(Just (3))
)
.toEqual (Nothing)
expect (
Maybe.liftM3 ((x: number) => (y: number) => (z: number) => x + y + z)
(Just (1))
(Just (2))
(Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM3 ((x: number) => (y: number) => (z: number) => x + y + z)
(Just (1))
(Nothing)
(Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM3 ((x: number) => (y: number) => (z: number) => x + y + z)
(Nothing)
(Just (2))
(Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM3 ((x: number) => (y: number) => (z: number) => x + y + z)
(Nothing)
(Nothing)
(Just (3))
)
.toEqual (Nothing)
expect (
Maybe.liftM3 ((x: number) => (y: number) => (z: number) => x + y + z)
(Nothing)
(Nothing)
(Nothing)
)
.toEqual (Nothing)
})
test ("liftM4", () => {
expect (
Maybe.liftM4 ((x: number) => (y: number) => (z: number) => (a: number) => x + y + z + a)
(Just (1)) (Just (2)) (Just (3)) (Just (4))
)
.toEqual (Just (10))
expect (
Maybe.liftM4 ((x: number) => (y: number) => (z: number) => (a: number) => x + y + z + a)
(Nothing) (Just (2)) (Just (3)) (Just (4))
)
.toEqual (Nothing)
expect (
Maybe.liftM4 ((x: number) => (y: number) => (z: number) => (a: number) => x + y + z + a)
(Just (1)) (Nothing) (Just (3)) (Just (4))
)
.toEqual (Nothing)
expect (
Maybe.liftM4 ((x: number) => (y: number) => (z: number) => (a: number) => x + y + z + a)
(Just (1)) (Just (2)) (Nothing) (Just (4))
)
.toEqual (Nothing)
expect (
Maybe.liftM4 ((x: number) => (y: number) => (z: number) => (a: number) => x + y + z + a)
(Just (1)) (Just (2)) (Just (3)) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM4 ((x: number) => (y: number) => (z: number) => (a: number) => x + y + z + a)
(Just (1)) (Just (2)) (Nothing) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM4 ((x: number) => (y: number) => (z: number) => (a: number) => x + y + z + a)
(Just (1)) (Nothing) (Just (3)) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM4 ((x: number) => (y: number) => (z: number) => (a: number) => x + y + z + a)
(Just (1)) (Nothing) (Nothing) (Just (4))
)
.toEqual (Nothing)
expect (
Maybe.liftM4 ((x: number) => (y: number) => (z: number) => (a: number) => x + y + z + a)
(Nothing) (Just (2)) (Just (3)) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM4 ((x: number) => (y: number) => (z: number) => (a: number) => x + y + z + a)
(Nothing) (Just (2)) (Nothing) (Just (4))
)
.toEqual (Nothing)
expect (
Maybe.liftM4 ((x: number) => (y: number) => (z: number) => (a: number) => x + y + z + a)
(Nothing) (Nothing) (Just (3)) (Just (4))
)
.toEqual (Nothing)
expect (
Maybe.liftM4 ((x: number) => (y: number) => (z: number) => (a: number) => x + y + z + a)
(Just (1)) (Nothing) (Nothing) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM4 ((x: number) => (y: number) => (z: number) => (a: number) => x + y + z + a)
(Nothing) (Just (2)) (Nothing) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM4 ((x: number) => (y: number) => (z: number) => (a: number) => x + y + z + a)
(Nothing) (Nothing) (Just (3)) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM4 ((x: number) => (y: number) => (z: number) => (a: number) => x + y + z + a)
(Nothing) (Nothing) (Nothing) (Just (4))
)
.toEqual (Nothing)
expect (
Maybe.liftM4 ((x: number) => (y: number) => (z: number) => (a: number) => x + y + z + a)
(Nothing) (Nothing) (Nothing) (Nothing)
)
.toEqual (Nothing)
})
test ("liftM5", () => {
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Just (1)) (Just (2)) (Just (3)) (Just (4)) (Just (5))
)
.toEqual (Just (15))
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Nothing) (Just (2)) (Just (3)) (Just (4)) (Just (5))
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Just (1)) (Nothing) (Just (3)) (Just (4)) (Just (5))
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Just (1)) (Just (2)) (Nothing) (Just (4)) (Just (5))
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Just (1)) (Just (2)) (Just (3)) (Nothing) (Just (5))
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Just (1)) (Just (2)) (Just (3)) (Just (4)) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Just (1)) (Just (2)) (Just (3)) (Nothing) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Just (1)) (Just (2)) (Nothing) (Just (4)) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Just (1)) (Nothing) (Just (3)) (Just (4)) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Nothing) (Just (2)) (Just (3)) (Just (4)) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Just (1)) (Just (2)) (Nothing) (Nothing) (Just (5))
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Just (1)) (Nothing) (Just (3)) (Nothing) (Just (5))
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Nothing) (Just (2)) (Just (3)) (Nothing) (Just (5))
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Just (1)) (Nothing) (Nothing) (Just (4)) (Just (5))
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Nothing) (Just (2)) (Nothing) (Just (4)) (Just (5))
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Nothing) (Nothing) (Nothing) (Just (4)) (Just (5))
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Nothing) (Nothing) (Just (3)) (Nothing) (Just (5))
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Nothing) (Nothing) (Just (3)) (Just (4)) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Just (1)) (Nothing) (Nothing) (Nothing) (Just (5))
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Just (1)) (Nothing) (Nothing) (Just (4)) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Just (1)) (Just (2)) (Nothing) (Nothing) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Just (1)) (Nothing) (Just (3)) (Nothing) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Nothing) (Just (2)) (Just (3)) (Nothing) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Nothing) (Just (2)) (Nothing) (Nothing) (Just (5))
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Just (1)) (Nothing) (Nothing) (Nothing) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Nothing) (Just (2)) (Nothing) (Nothing) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Nothing) (Nothing) (Just (3)) (Nothing) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Nothing) (Nothing) (Nothing) (Just (4)) (Nothing)
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Nothing) (Nothing) (Nothing) (Nothing) (Just (5))
)
.toEqual (Nothing)
expect (
Maybe.liftM5 ((x: number) => (y: number) => (z: number) => (a: number) => (b: number) =>
x + y + z + a + b)
(Nothing) (Nothing) (Nothing) (Nothing) (Nothing)
)
.toEqual (Nothing)
})
// FOLDABLE
test ("foldr", () => {
expect (Maybe.foldr ((x: number) => (acc: number) => x * 2 + acc) (2) (Just (3)))
.toEqual (8)
expect (Maybe.foldr ((x: number) => (acc: number) => x * 2 + acc) (2) (Nothing))
.toEqual (2)
})
test ("foldl", () => {
expect (Maybe.foldl ((acc: number) => (x: number) => x * 2 + acc) (2) (Just (3)))
.toEqual (8)
expect (Maybe.foldl ((acc: number) => (x: number) => x * 2 + acc) (2) (Nothing))
.toEqual (2)
})
test ("toList", () => {
expect (Maybe.toList (Just (3)))
.toEqual (List (3))
expect (Maybe.toList (Nothing))
.toEqual (List ())
})
test ("fnull", () => {
expect (Maybe.fnull (Just (3)))
.toEqual (false)
expect (Maybe.fnull (Nothing))
.toEqual (true)
})
test ("flength", () => {
expect (Maybe.flength (Just (3)))
.toEqual (1)
expect (Maybe.flength (Nothing))
.toEqual (0)
})
test ("elem", () => {
expect (Maybe.elem (3) (Nothing))
.toBeFalsy ()
expect (Maybe.elem (3) (Just (2)))
.toBeFalsy ()
expect (Maybe.elem (3) (Just (3)))
.toBeTruthy ()
})
test ("elemF", () => {
expect (Maybe.elemF (Nothing) (3))
.toBeFalsy ()
expect (Maybe.elemF (Just (2)) (3))
.toBeFalsy ()
expect (Maybe.elemF (Just (3)) (3))
.toBeTruthy ()
})
test ("sum", () => {
expect (Maybe.sum (Just (3)))
.toEqual (3)
expect (Maybe.sum (Nothing))
.toEqual (0)
})
test ("product", () => {
expect (Maybe.product (Just (3)))
.toEqual (3)
expect (Maybe.product (Nothing))
.toEqual (1)
})
test ("concat", () => {
expect (Maybe.concat (Just (List (1, 2, 3))))
.toEqual (List (1, 2, 3))
expect (Maybe.concat (Nothing))
.toEqual (List ())
})
test ("concatMap", () => {
expect (Maybe.concatMap ((e: number) => List (e, e)) (Just (3)))
.toEqual (List (3, 3))
expect (Maybe.concatMap ((e: number) => List (e, e)) (Nothing))
.toEqual (List ())
})
test ("and", () => {
expect (Maybe.and (Just (true)))
.toEqual (true)
expect (Maybe.and (Just (false)))
.toEqual (false)
expect (Maybe.and (Nothing))
.toEqual (true)
})
test ("or", () => {
expect (Maybe.or (Just (true)))
.toEqual (true)
expect (Maybe.or (Just (false)))
.toEqual (false)
expect (Maybe.or (Nothing))
.toEqual (false)
})
test ("any", () => {
expect (Maybe.any ((e: number) => e > 3) (Just (5)))
.toEqual (true)
expect (Maybe.any ((e: number) => e > 3) (Just (3)))
.toEqual (false)
expect (Maybe.any ((e: number) => e > 3) (Nothing))
.toEqual (false)
})
test ("all", () => {
expect (Maybe.all ((e: number) => e > 3) (Just (5)))
.toEqual (true)
expect (Maybe.all ((e: number) => e > 3) (Just (3)))
.toEqual (false)
expect (Maybe.all ((e: number) => e > 3) (Nothing))
.toEqual (true)
})
test ("notElem", () => {
expect (Maybe.notElem (3) (Nothing))
.toBeTruthy ()
expect (Maybe.notElem (3) (Just (2)))
.toBeTruthy ()
expect (Maybe.notElem (3) (Just (3)))
.toBeFalsy ()
})
test ("find", () => {
expect (Maybe.find ((e: number) => e > 3) (Just (5)))
.toEqual (Just (5))
expect (Maybe.find ((e: number) => e > 3) (Just (3)))
.toEqual (Nothing)
expect (Maybe.find ((e: number) => e > 3) (Nothing))
.toEqual (Nothing)
})
// ORD
test ("gt", () => {
expect (Maybe.gt (Just (1)) (Just (2)))
.toBeTruthy ()
expect (Maybe.gt (Just (1)) (Just (1)))
.toBeFalsy ()
expect (Maybe.gt (Just (1)) (Nothing))
.toBeFalsy ()
expect (Maybe.gt (Nothing) (Just (2)))
.toBeFalsy ()
expect (Maybe.gt (Nothing) (Nothing))
.toBeFalsy ()
})
test ("lt", () => {
expect (Maybe.lt (Just (3)) (Just (2)))
.toBeTruthy ()
expect (Maybe.lt (Just (1)) (Just (1)))
.toBeFalsy ()
expect (Maybe.lt (Just (3)) (Nothing))
.toBeFalsy ()
expect (Maybe.lt (Nothing) (Just (2)))
.toBeFalsy ()
expect (Maybe.lt (Nothing) (Nothing))
.toBeFalsy ()
})
test ("gte", () => {
expect (Maybe.gte (Just (1)) (Just (2)))
.toBeTruthy ()
expect (Maybe.gte (Just (2)) (Just (2)))
.toBeTruthy ()
expect (Maybe.gte (Just (2)) (Just (1)))
.toBeFalsy ()
expect (Maybe.gte (Just (1)) (Nothing))
.toBeFalsy ()
expect (Maybe.gte (Just (2)) (Nothing))
.toBeFalsy ()
expect (Maybe.gte (Nothing) (Just (2)))
.toBeFalsy ()
expect (Maybe.gte (Nothing) (Nothing))
.toBeFalsy ()
})
test ("lte", () => {
expect (Maybe.lte (Just (3)) (Just (2)))
.toBeTruthy ()
expect (Maybe.lte (Just (2)) (Just (2)))
.toBeTruthy ()
expect (Maybe.lte (Just (2)) (Just (3)))
.toBeFalsy ()
expect (Maybe.lte (Just (3)) (Nothing))
.toBeFalsy ()
expect (Maybe.lte (Just (2)) (Nothing))
.toBeFalsy ()
expect (Maybe.lte (Nothing) (Just (2)))
.toBeFalsy ()
expect (Maybe.lte (Nothing) (Nothing))
.toBeFalsy ()
})
// SEMIGROUP
// test('mappend', () => {
// expect(Just (List(3)).mappend(Just (List(2))))
// .toEqual(Just (List(3, 2)))
// expect(Just (List(3)).mappend(Nothing))
// .toEqual(Just (List(3)))
// expect(Nothing.mappend(Just (List(2))))
// .toEqual(Nothing)
// expect(Nothing.mappend(Nothing))
// .toEqual(Nothing)
// })
// MAYBE FUNCTIONS (PART 2)
test ("maybe", () => {
expect (Maybe.maybe (0) ((x: number) => x * 2) (Just (3)))
.toEqual (6)
expect (Maybe.maybe (0) ((x: number) => x * 2) (Nothing))
.toEqual (0)
})
test ("listToMaybe", () => {
expect (Maybe.listToMaybe (List (3)))
.toEqual (Just (3))
expect (Maybe.listToMaybe (List ()))
.toEqual (Nothing)
})
test ("maybeToList", () => {
expect (Maybe.maybeToList (Just (3)))
.toEqual (List (3))
expect (Maybe.maybeToList (Nothing))
.toEqual (List ())
})
test ("catMaybes", () => {
expect (Maybe.catMaybes (List<Maybe<number>> (Just (3), Just (2), Nothing, Just (1))))
.toEqual (List (3, 2, 1))
})
test ("mapMaybe", () => {
expect (Maybe.mapMaybe (Maybe.ensure ((x: number) => x > 2)) (List (1, 2, 3, 4, 5)))
.toEqual (List (3, 4, 5))
})
// CUSTOM MAYBE FUNCTIONS
test ("isMaybe", () => {
expect (Maybe.isMaybe (4)) .toEqual (false)
expect (Maybe.isMaybe (Just (4))) .toEqual (true)
expect (Maybe.isMaybe (Nothing)) .toEqual (true)
})
test ("normalize", () => {
expect (Maybe.normalize (4)) .toEqual (Just (4))
expect (Maybe.normalize (Just (4))) .toEqual (Just (4))
expect (Maybe.normalize (Nothing)) .toEqual (Nothing)
expect (Maybe.normalize (undefined)) .toEqual (Nothing)
expect (Maybe.normalize (null)) .toEqual (Nothing)
})
test ("ensure", () => {
expect (Maybe.ensure ((x: number) => x > 2) (3))
.toEqual (Just (3))
expect (Maybe.ensure ((x: number) => x > 3) (3))
.toEqual (Nothing)
})
test ("imapMaybe", () => {
expect (Maybe.imapMaybe (i => (e: number) => fmap (add (i))
(Maybe.ensure ((x: number) => x > 2) (e)))
(List (1, 2, 3, 4, 5)))
.toEqual (List (5, 7, 9))
})
test ("maybeToNullable", () => {
const element = React.createElement ("div")
expect (Maybe.maybeToNullable (Nothing)) .toEqual (null)
expect (Maybe.maybeToNullable (Just (element))) .toEqual (element)
})
test ("maybeToUndefined", () => {
const element = React.createElement ("div")
expect (Maybe.maybeToUndefined (Nothing)) .toEqual (undefined)
expect (Maybe.maybeToUndefined (Just (element))) .toEqual (element)
})
test ("maybe_", () => {
expect (Maybe.maybe_ (() => 0) ((x: number) => x * 2) (Just (3)))
.toEqual (6)
expect (Maybe.maybe_ (() => 0) ((x: number) => x * 2) (Nothing))
.toEqual (0)
})
test ("joinMaybeList", () => {
expect (Maybe.joinMaybeList (Just (List (1, 2, 3))))
.toEqual (List (1, 2, 3))
expect (Maybe.joinMaybeList (Nothing))
.toEqual (List ())
})
test ("guardReplace", () => {
expect (Maybe.guardReplace (true) (3))
.toEqual (Just (3))
expect (Maybe.guardReplace (false) (3))
.toEqual (Nothing)
})
test ("orN", () => {
expect (Maybe.orN (true)) .toEqual (true)
expect (Maybe.orN (false)) .toEqual (false)
expect (Maybe.orN (undefined)) .toEqual (false)
}) | the_stack |
import { hex2RGB } from '../utils';
import { buildStyle, buildEmptyStyle } from '../utils/helpers';
import { Style } from 'windicss/utils/style';
import { patterns, allowAttr } from '../utils/filetypes';
import { generateCompletions } from '../utils/completions';
import { languages, Range, Position, CompletionItem, SnippetString, CompletionItemKind } from 'vscode';
import type Extension from './index';
import type { DocumentSelector } from 'vscode';
import type { Processor } from 'windicss/lib';
import type { Completion } from '../interfaces';
export default class Completions {
processor: Processor;
extension: Extension;
separator: string;
completions: Completion;
constructor(extension: Extension, processor: Processor) {
this.processor = processor;
this.extension = extension;
this.separator = processor.config('separator', ':') as string;
this.completions = generateCompletions(processor, this.extension.colors, true, processor.config('prefix', '') as string);
this.extension.attrs = this.completions.attr.static;
}
// register suggestions in class = ... | className = ... | @apply ... | sm = ... | hover = ...
registerUtilities(ext: DocumentSelector, type: string, pattern?: RegExp, enableUtility = true, enableVariant = true, enableDynamic = true, enableBracket = true, enableEmmet = false) {
return languages.registerCompletionItemProvider(
ext,
{
provideCompletionItems: (document, position) => {
const text = document.getText(new Range(new Position(0, 0), position));
if ((!pattern || text.match(pattern) === null) && text.match(patterns[type]) === null) {
const key = text.match(/\S+(?=\s*=\s*["']?[^"']*$)/)?.[0];
if ((!key) || !(allowAttr(type) && this.extension.isAttrVariant(key))) return [];
}
let completions: CompletionItem[] = [];
if (enableUtility && text.endsWith('/')) {
const utility = text.match(/[\w-:!<@]+(?=\/$)/);
if (!utility) return [];
return Object.keys(this.processor.theme('opacity', {}) as string[]).map((opacity, index) => {
const item = new CompletionItem(opacity, CompletionItemKind.Unit);
item.detail = utility[0];
item.sortText = '1-' + index.toString().padStart(8, '0');
return item;
});
}
if (enableUtility) {
completions = completions.concat(
this.completions.static.map((classItem, index) => {
const item = new CompletionItem(classItem, CompletionItemKind.Constant);
item.sortText = '1-' + index.toString().padStart(8, '0');
return item;
})
);
}
if (enableVariant) {
completions = completions.concat(
Object.keys(this.extension.variants).map((variant, index) => {
const item = new CompletionItem(variant + this.separator, CompletionItemKind.Module);
item.detail = variant;
item.sortText = '2-' + index.toString().padStart(8, '0');
// register suggestion after select variant
item.command = {
command: 'editor.action.triggerSuggest',
title: variant,
};
return item;
})
).concat(
this.completions.color.map(({ label, doc }, index) => {
const color = new CompletionItem(label, CompletionItemKind.Color);
color.sortText = '0-' + index.toString().padStart(8, '0');
color.documentation = doc;
return color;
})
);
}
if (enableBracket) {
completions = completions.concat(
this.completions.bracket.map((label, index) => {
const item = new CompletionItem(label, CompletionItemKind.Struct);
item.sortText = '3-' + index.toString().padStart(8, '0');
return item;
})
);
}
if (enableDynamic) {
completions = completions.concat(
this.completions.dynamic.map(({ label, pos }, index) => {
const item = new CompletionItem(label, CompletionItemKind.Variable);
item.sortText = '4-' + index.toString().padStart(8, '0');
return item;
})
);
}
return completions;
},
resolveCompletionItem: (item) => {
switch (item.kind) {
case CompletionItemKind.Constant:
item.documentation = buildStyle(this.processor.interpret(item.label).styleSheet);
break;
case CompletionItemKind.Module:
item.documentation = this.buildVariantDoc(item.detail);
item.detail = undefined;
break;
case CompletionItemKind.Struct:
item.documentation = buildStyle(this.processor.interpret(item.label).styleSheet);
item.insertText = new SnippetString(`${item.label.replace('-[', '-[${1:').slice(0, -1)}}]`);
break;
case CompletionItemKind.Variable:
this.generateDynamicInfo(item, false);
break;
case CompletionItemKind.Color:
const color = (item.documentation || 'currentColor') as string;
item.documentation = ['transparent', 'currentColor'].includes(color) ? color : `rgb(${hex2RGB(color)?.join(', ')})`;
item.detail = this.processor.interpret(item.label).styleSheet.build();
break;
case CompletionItemKind.Unit:
item.documentation = item.detail ? buildStyle(this.processor.interpret(`${item.detail}/${item.label}`).styleSheet) : undefined;
item.detail = undefined;
break;
}
return item;
},
},
'"',
'\'',
'/',
':',
'!',
'(',
' ',
...(enableEmmet ? [ '.' ] : []),
);
}
// register suggestion for bg, text, sm, hover ...
registerAttrKeys(ext: DocumentSelector, enableUtility = true, enableVariant = true) {
return languages.registerCompletionItemProvider(
ext,
{
provideCompletionItems: (document, position) => {
const text = document.getText(new Range(new Position(0, 0), position));
if (text.match(/(<\w+\s*)[^>]*$/) !== null) {
if (!text.match(/\S+(?=\s*=\s*["']?[^"']*$)/) || text.match(/<\w+\s+$/)) {
let completions: CompletionItem[] = [];
const prefix = this.processor.config('attributify.prefix');
const disable = this.processor.config('attributify.disable') as string[] | undefined;
let prevKey = undefined;
if (text.endsWith(':')) {
prevKey = document.getText(document.getWordRangeAtPosition(new Position(position.line, position.character-1), /[^:\s]+/));
}
if (!prevKey || (prevKey && (prevKey in this.extension.variants || this.extension.isAttrVariant(prevKey)))) {
if (enableUtility) {
completions = completions.concat(
Object.keys(this.completions.attr.static).map(label => attrKey(prefix && !text.endsWith(':') ? prefix + label : label, CompletionItemKind.Field, 0))
);
}
if (enableVariant) {
const variants = disable ? Object.keys(this.extension.variants).filter(i => !disable.includes(i)) : Object.keys(this.extension.variants);
completions = completions.concat(variants.map(label => attrKey(prefix && !text.endsWith(':') ? prefix + label : label, CompletionItemKind.Module, 1)));
}
}
return completions;
}
}
return [];
},
resolveCompletionItem: item => {
switch (item.kind) {
case CompletionItemKind.Field:
item.documentation = this.buildAttrDoc(item.label);
break;
case CompletionItemKind.Module:
item.documentation = this.buildVariantDoc(item.label, true);
break;
}
return item;
},
},
':',
);
}
registerAttrValues(ext: DocumentSelector, enableUtility = true, enableVariant = true, enableDynamic = true, enableBracket = true) {
return languages.registerCompletionItemProvider(
ext,
{
provideCompletionItems: (document, position) => {
const text = document.getText(new Range(new Position(0, 0), position));
if (text.match(/(<\w+\s*)[^>]*$/) !== null) {
const key = this.extension.isAttrUtility(text.match(/\S+(?=\s*=\s*["']?[^"']*$)/)?.[0]);
if (!key) return [];
let completions: CompletionItem[] = [];
if (enableUtility && text.endsWith('/')) {
const utility = text.match(/[\w-:!<@]+(?=\/$)/);
if (!utility) return [];
return Object.keys(this.processor.theme('opacity', {}) as string[]).map((opacity, index) => {
const item = new CompletionItem(opacity, CompletionItemKind.Unit);
item.detail = [key, utility[0]].join('____');
item.sortText = '1-' + index.toString().padStart(8, '0');
return item;
});
}
if (enableUtility) {
completions = completions.concat(
this.completions.attr.static[key].map((label, index) => {
const item = new CompletionItem(label, CompletionItemKind.Constant);
item.detail = key;
item.sortText = '1-' + index.toString().padStart(8, '0');
return item;
})
).concat(
key in this.completions.attr.color ? this.completions.attr.color[key].map(({ label, doc }, index) => {
const color = new CompletionItem(label, CompletionItemKind.Color);
color.sortText = '0-' + index.toString().padStart(8, '0');
color.detail = key;
color.documentation = doc;
return color;
}) : []
);
}
if (enableVariant) {
completions = completions.concat(
Object.keys(this.extension.variants).map((variant, index) => {
const item = new CompletionItem(variant + this.separator, CompletionItemKind.Module);
item.detail = key + ',' + variant;
item.sortText = '2-' + index.toString().padStart(8, '0');
item.command = {
command: 'editor.action.triggerSuggest',
title: variant,
};
return item;
})
);
}
if (enableBracket && key in this.completions.attr.bracket) {
completions = completions.concat(
this.completions.attr.bracket[key].map((label, index) => {
const item = new CompletionItem(label, CompletionItemKind.Struct);
item.detail = key;
item.sortText = '3-' + index.toString().padStart(8, '0');
return item;
})
);
}
if (enableDynamic && key in this.completions.attr.dynamic) {
completions = completions.concat(
this.completions.attr.dynamic[key].map(({ label, pos }, index) => {
const item = new CompletionItem(label, CompletionItemKind.Variable);
item.detail = key;
item.sortText = '4-' + index.toString().padStart(8, '0');
return item;
})
);
}
return completions;
}
},
resolveCompletionItem: item => {
switch (item.kind) {
case CompletionItemKind.Constant:
item.documentation = buildStyle(this.processor.attributify({ [item.detail ?? ''] : [ item.label ] }).styleSheet);
item.detail = undefined;
break;
case CompletionItemKind.Module:
const [attr, variant] = item.detail?.split(',') || [];
item.documentation = this.buildAttrDoc(attr, variant, this.separator);
item.detail = undefined;
break;
case CompletionItemKind.Struct:
item.documentation = buildStyle(this.processor.attributify({ [item.detail ?? ''] : [ item.label ] }).styleSheet);
item.insertText = new SnippetString(`${item.label.replace('[', '[${1:').slice(0, -1)}}]`);
item.detail = undefined;
break;
case CompletionItemKind.Variable:
this.generateDynamicInfo(item, true);
break;
case CompletionItemKind.Color:
const color = (item.documentation || 'currentColor') as string;
item.documentation = ['transparent', 'currentColor'].includes(color) ? color : `rgb(${hex2RGB(color)?.join(', ')})`;
item.detail = this.processor.attributify({ [item.detail ?? ''] : [ item.label ] }).styleSheet.build();
break;
case CompletionItemKind.Unit:
const [ key, utility ] = item.detail?.split('____') || [];
item.documentation = buildStyle(this.processor.attributify({ [key] : [ `${utility}/${item.label}` ] }).styleSheet);
item.detail = undefined;
break;
}
return item;
},
},
'"',
'\'',
':',
'/',
' ',
);
}
generateDynamicInfo(item: CompletionItem, attributify = false) {
const match = item.label.match(/{\w+}$/);
if (!match) return;
switch (match[0]) {
case '{int}':
this.setDynamicInfo(item, 'int', '99', attributify);
break;
case '{float}':
this.setDynamicInfo(item, 'float', '5.21', attributify);
break;
case '{fraction}':
this.setDynamicInfo(item, 'fraction', '13/14', attributify);
break;
case '{time}':
this.setDynamicInfo(item, 'time', '1.25s', attributify);
break;
case '{size}':
this.setDynamicInfo(item, 'size', '25px', attributify);
break;
case '{string}':
this.setDynamicInfo(item, 'string', 'i-love-u', attributify);
break;
case '{nxl}':
this.setDynamicInfo(item, 'nxl', '9xl', attributify);
break;
case '{var}':
this.setDynamicInfo(item, 'var', 'forever-and-ever', attributify);
break;
}
}
setDynamicInfo(item: CompletionItem, type: string, example: string, attributify = false) {
const regex = new RegExp(`{${type}}$`);
item.documentation = buildStyle(attributify? this.processor.attributify({ [item.detail ?? ''] : [ item.label.replace(regex, example) ] }).styleSheet : this.processor.interpret(item.label.replace(regex, example)).styleSheet);
item.detail = `type.${type}(${example})`;
item.insertText = new SnippetString(item.label.replace(regex, `\${1:${example}}`));
}
buildAttrDoc(attr: string, variant?: string, separator?: string) {
let style;
if (variant) {
style = this.extension.variants[variant]();
style.selector = `[${this.processor?.e(attr)}~="${variant}${separator}&"]`;
} else {
style = new Style(`[${this.processor?.e(attr)}~="&"]`);
}
return buildEmptyStyle(style);
}
buildVariantDoc(variant?: string, attributify = false) {
if (!variant) return '';
const style = this.extension.variants[variant]();
if (attributify) {
style.selector = `[${this.processor?.e(variant)}~="&"]`;
} else {
style.selector = '&';
}
return buildEmptyStyle(style);
}
}
function attrKey(label: string, kind: CompletionItemKind, order: number) {
const item = new CompletionItem(label, kind);
item.sortText = `${order}-` + label;
item.insertText = new SnippetString(`${label}="$1"`);
item.command = {
command: 'editor.action.triggerSuggest',
title: label,
};
return item;
} | the_stack |
// This file implements the foundationdb binding API tester fuzzer backend
// described here:
//
// https://github.com/apple/foundationdb/blob/master/bindings/bindingtester/spec/bindingApiTester.md
// This script should not be invoked directly. Instead checkout foundationdb
// and invoke the binding tester from there, pointing it at this script.
import * as fdb from '../lib'
import {
Transaction, Database, Directory, DirectoryLayer, Subspace,
tuple, TupleItem,
keySelector,
StreamingMode, MutationType,
util,
TransactionOptionCode,
} from '../lib'
// TODO: Expose these in lib
import {packPrefixedVersionstamp} from '../lib/versionstamp'
import { concat2, startsWith } from '../lib/util'
import {DirectoryError} from '../lib/directory'
import assert = require('assert')
import nodeUtil = require('util')
import * as chalk from 'chalk'
import fs = require('fs')
import { Transformer } from '../lib/transformer'
let verbose = false
// The string keys are all buffers, encoded as hex.
// This is shared between all threads.
const transactions: {[k: string]: Transaction} = {}
// 'RESULT_NOT_PRESENT' -> 'ResultNotPresent'
const toUpperCamelCase = (str: string) => (
str.toLowerCase().replace(/(^\w|_\w)/g, x => x[x.length-1].toUpperCase())
)
const toStr = (val: any): string => (
(typeof val === 'object' && val.data) ? toStr(val.data)
: Buffer.isBuffer(val) ? val.toString('ascii')
: nodeUtil.inspect(val)
)
const tupleStrict: Transformer<TupleItem | TupleItem[], TupleItem[]> = {
...tuple,
name: 'tuple strict',
unpack: val => tuple.unpack(val, true),
}
const colors = [chalk.blueBright, chalk.red, chalk.cyan, chalk.greenBright, chalk.grey]
const makeMachine = (db: Database, initialName: Buffer) => {
type StackItem = {instrId: number, data: any}
const stack: StackItem[] = []
let tnName = initialName
let instrId = 0
let lastVersion: Buffer = Buffer.alloc(8) // null / empty last version.
const threadColor = colors.pop()!
colors.unshift(threadColor)
// Directory stuff
const dirList: (Subspace<any, any, any, any> | Directory<any, any, any, any> | fdb.DirectoryLayer | null)[] = [fdb.directory]
let dirIdx = 0
let dirErrIdx = 0
const tnNameKey = () => tnName.toString('hex')
const catchFdbErr = (e: Error) => {
if (e instanceof fdb.FDBError) {
// This encoding is silly. Also note that these errors are normal & part of the test.
if (verbose) console.log(chalk.red('output error'), instrId, e)
return fdb.tuple.pack([Buffer.from('ERROR'), Buffer.from(e.code.toString())])
} else throw e
}
const unwrapNull = <T>(val: T | null | undefined) => val === undefined ? Buffer.from('RESULT_NOT_PRESENT') : val
const wrapP = <T>(p: T | Promise<T>) => (p instanceof Promise) ? p.then(unwrapNull, catchFdbErr) : unwrapNull(p)
const popValue = async () => {
assert(stack.length, 'popValue when stack is empty')
if (verbose) {
console.log(chalk.green('pop value'), stack[stack.length-1].instrId, 'value:', stack[stack.length-1].data)
}
return stack.pop()!.data
}
const chk = async <T>(pred: (item: any) => boolean, typeLabel: string): Promise<T> => {
const {instrId} = stack[stack.length-1]
let val = await popValue()
assert(pred(val), `${threadColor('Unexpected type')} of ${nodeUtil.inspect(val, false, undefined, true)} inserted at ${instrId} - espected ${typeLabel}`)
return val as any as T // :(
}
const popStr = () => chk<string>(val => typeof val === 'string', 'string')
const popBool = () => chk<boolean>(val => val === 0 || val === 1, 'bool').then(x => !!x)
const popInt = () => chk<number | bigint>(val => Number.isInteger(val) || typeof val === 'bigint', 'int')
const popSmallInt = () => chk<number>(val => Number.isInteger(val), 'int')
const popBuffer = () => chk<Buffer>(Buffer.isBuffer, 'buf')
const popStrBuf = () => chk<string | Buffer>(val => typeof val === 'string' || Buffer.isBuffer(val), 'buf|str')
const popNullableBuf = () => chk<Buffer | null>(val => val == null || Buffer.isBuffer(val), 'buf|null')
const popSelector = async () => {
const key = await popBuffer()
const orEqual = await popBool()
const offset = await popInt()
return keySelector(key, orEqual, Number(offset))
}
const popNValues = async () => {
const n = await popInt()
const result = []
for (let i = 0; i < n; i++) result.push(await popValue())
return result
}
const pushValue = (data: any) => {
if (verbose) console.log(chalk.green('push value'), instrId, 'value:', data)
stack.push({instrId, data})
}
const pushArrItems = (data: any[]) => {
for (let i = 0; i < data.length; i++) pushValue(data[i])
}
const pushTupleItem = (data: TupleItem) => {
pushValue(data)
if (verbose) console.log(chalk.green('(encodes to)'), tuple.pack(data))
}
const pushLiteral = (data: string) => {
if (verbose) console.log(chalk.green('(literal:'), data, chalk.green(')'))
pushValue(Buffer.from(data, 'ascii'))
}
const maybePush = (data: Promise<any> | any) => {
if (data) pushValue(wrapP(data))
}
// const orNone = (val: Buffer | null) => val == null ? 'RESULT_NOT_PRESENT' : val
const bufBeginsWith = (buf: Buffer, prefix: Buffer) => (
prefix.length <= buf.length && buf.compare(prefix, 0, prefix.length, 0, prefix.length) === 0
)
// Directory helpers
const getCurrentDirectory = (): Directory => {
const val = dirList[dirIdx] as Directory
assert(val instanceof Directory)
return val
}
const getCurrentSubspace = (): Subspace => {
const val = dirList[dirIdx] as Directory | Subspace
assert(val instanceof Directory || val instanceof Subspace)
return val.getSubspace()
}
const getCurrentDirectoryOrLayer = (): Directory | DirectoryLayer => {
const val = dirList[dirIdx] as Directory | DirectoryLayer
assert(val instanceof Directory || val instanceof DirectoryLayer)
return val
}
// const errOrNull = async <T>(fn: (() => Promise<T>)): Promise<T | null> => {
// try {
// const val = fn()
// return val
// } catch (e) {
// return null
// }
// }
const errOrNull = async <T>(promiseOrFn: Promise<T> | (() => Promise<T>)): Promise<T | null> => {
try {
return await (typeof promiseOrFn === 'function' ? promiseOrFn() : promiseOrFn)
} catch (e) {
return null
}
}
const operations: {[op: string]: (operand: Database | Transaction, ...args: TupleItem[]) => any} = {
// Stack operations
PUSH(_, data: any) { pushValue(data) },
POP() { stack.pop() },
DUP() { stack.push(stack[stack.length-1]) },
EMPTY_STACK() { stack.length = 0 },
async SWAP() {
// TODO: Should this wait for the promises in question to resolve?
const depth = Number(await popInt())
assert(depth < stack.length)
const a = stack[stack.length - depth - 1]
const b = stack[stack.length - 1]
stack[stack.length - depth - 1] = b
stack[stack.length - 1] = a
},
async SUB() {
const a = await popInt()
const b = await popInt()
pushValue(BigInt(a) - BigInt(b))
},
async CONCAT() {
const a = await popStrBuf() // both strings or both bytes.
const b = await popStrBuf()
assert(typeof a === typeof b, 'concat type mismatch')
if (typeof a === 'string') pushValue(a + b)
else pushValue(Buffer.concat([a as Buffer, b as Buffer]))
},
async LOG_STACK() {
const prefix = await popBuffer()
let i = 0
while (i < stack.length) {
await db.doTransaction(async tn => {
for (let k = 0; k < 100 && i < stack.length; k++) {
const {instrId, data} = stack[i]
let packedData = fdb.tuple.pack([
await wrapP<TupleItem>(data)
])
if (packedData.length > 40000) packedData = packedData.slice(0, 40000)
// TODO: Would be way better here to use a tuple transaction.
tn.set(Buffer.concat([prefix, fdb.tuple.pack([i, instrId])]), packedData)
i++
}
})
}
stack.length = 0
},
// Transactions
NEW_TRANSACTION() {
// We're setting the trannsaction identifier so if you turn on tracing at
// the bottom of the file, we'll be able to track individual transactions.
// This is helpful for debugging write conflicts, and things like that.
const opts: fdb.TransactionOptions = {
debug_transaction_identifier: `${instrId}`,
log_transaction: true,
}
transactions[tnNameKey()] = db.rawCreateTransaction(instrId > 430 ? undefined : opts)
;(transactions[tnNameKey()] as any)._instrId = instrId
},
async USE_TRANSACTION() {
tnName = await popBuffer()
if (verbose) console.log('using tn', tnName)
if (transactions[tnNameKey()] == null) transactions[tnNameKey()] = db.rawCreateTransaction()
// transactions[tnNameKey()].setOption(fdb.TransactionOptionCode.TransactionLoggingEnable, Buffer.from('x '+instrId))
},
async ON_ERROR(tn) {
const code = Number(await popInt())
pushValue(wrapP((<Transaction>tn).rawOnError(code)))
},
// Transaction read functions
// async get(oper) {
// const key = await popBuffer()
// pushValue(await wrapP(oper.get(key)))
// },
async GET(oper) {
const key = await popBuffer()
pushValue(wrapP(oper.get(key)))
},
async GET_KEY(oper) {
const keySel = await popSelector()
const prefix = await popBuffer()
const result = ((await oper.getKey(keySel)) || Buffer.from([])) as Buffer
// if (verbose) {
// console.log('get_key prefix', nodeUtil.inspect(prefix.toString('ascii')), result!.compare(prefix))
// console.log('get_key result', nodeUtil.inspect(result!.toString('ascii')), result!.compare(prefix))
// }
if (result!.equals(Buffer.from('RESULT_NOT_PRESENT'))) return result // Gross.
// result starts with prefix.
if (bufBeginsWith(result!, prefix)) pushValue(result)
else if (result!.compare(prefix) < 0) pushValue(prefix) // RESULT < PREFIX
else pushValue(util.strInc(prefix)) // RESULT > PREFIX
},
async GET_RANGE(oper) {
const beginKey = await popBuffer()
const endKey = await popBuffer()
const limit = Number(await popInt())
const reverse = await popBool()
const streamingMode = await popInt() as StreamingMode
// console.log('get range', instrId, beginKey, endKey, limit, reverse, 'mode', streamingMode, oper)
const results = await oper.getRangeAll(
keySelector.from(beginKey), keySelector.from(endKey),
{streamingMode, limit, reverse}
)
// console.log('get range result', results)
pushTupleItem(tuple.pack(Array.prototype.concat.apply([], results)))
},
async GET_RANGE_STARTS_WITH(oper) {
const prefix = await popBuffer()
const limit = Number(await popInt())
const reverse = await popBool()
const streamingMode = await popInt() as StreamingMode
const results = await oper.getRangeAllStartsWith(prefix, {streamingMode, limit, reverse})
pushValue(tuple.pack(Array.prototype.concat.apply([], results)))
},
async GET_RANGE_SELECTOR(oper) {
const beginSel = await popSelector()
const endSel = await popSelector()
const limit = Number(await popInt())
const reverse = await popBool()
const streamingMode = await popInt() as StreamingMode
const prefix = await popBuffer()
const results = (await oper.getRangeAll(beginSel, endSel, {streamingMode, limit, reverse}))
.filter(([k]) => bufBeginsWith(k as Buffer, prefix))
pushValue(tuple.pack(Array.prototype.concat.apply([], results)))
},
async GET_READ_VERSION(oper) {
try {
lastVersion = await (<Transaction>oper).getReadVersion()
pushLiteral("GOT_READ_VERSION")
} catch (e) {
pushValue(catchFdbErr(e))
}
},
async GET_VERSIONSTAMP(oper) {
pushValue(wrapP((<Transaction>oper).getVersionstamp().promise))
},
// Transaction set operations
async SET(oper) {
const key = await popStrBuf()
const val = await popStrBuf()
if (verbose) {
console.log('SET', key, val)
// const key2 = tuple.unpack(key as Buffer, true).map(v => Buffer.isBuffer(v) ? v.toString() : v)
// if (key2[1] !== 'workspace') console.error('SET', key2, val)
}
maybePush(oper.set(key, val))
},
SET_READ_VERSION(oper) {
;(<Transaction>oper).setReadVersion(lastVersion)
},
async CLEAR(oper) {
maybePush(oper.clear(await popStrBuf()))
},
async CLEAR_RANGE(oper) {
maybePush(oper.clearRange(await popStrBuf(), await popStrBuf()))
},
async CLEAR_RANGE_STARTS_WITH(oper) {
maybePush(oper.clearRangeStartsWith(await popStrBuf()))
},
async ATOMIC_OP(oper) {
const codeStr = toUpperCamelCase(await popStr()) as keyof typeof MutationType
const code: MutationType = MutationType[codeStr]
assert(code, 'Could not find atomic codestr ' + codeStr)
maybePush(oper.atomicOp(code, await popStrBuf(), await popStrBuf()))
},
async READ_CONFLICT_RANGE(oper) {
;(<Transaction>oper).addReadConflictRange(await popStrBuf(), await popStrBuf())
pushLiteral("SET_CONFLICT_RANGE")
},
async WRITE_CONFLICT_RANGE(oper) {
;(<Transaction>oper).addWriteConflictRange(await popStrBuf(), await popStrBuf())
pushLiteral("SET_CONFLICT_RANGE")
},
async READ_CONFLICT_KEY(oper) {
;(<Transaction>oper).addReadConflictKey(await popStrBuf())
pushLiteral("SET_CONFLICT_KEY")
},
async WRITE_CONFLICT_KEY(oper) {
;(<Transaction>oper).addWriteConflictKey(await popStrBuf())
pushLiteral("SET_CONFLICT_KEY")
},
DISABLE_WRITE_CONFLICT(oper) {
;(<Transaction>oper).setOption(TransactionOptionCode.NextWriteNoWriteConflictRange)
},
COMMIT(oper) {
const i = instrId
pushValue(wrapP((<Transaction>oper).rawCommit()))
},
RESET(oper) {(<Transaction>oper).rawReset()},
CANCEL(oper) {(<Transaction>oper).rawCancel()},
GET_COMMITTED_VERSION(oper) {
lastVersion = (<Transaction>oper).getCommittedVersion()
pushLiteral('GOT_COMMITTED_VERSION')
},
async GET_APPROXIMATE_SIZE(oper) {
await (<Transaction>oper).getApproximateSize()
pushLiteral('GOT_APPROXIMATE_SIZE')
},
async WAIT_FUTURE() {
const f = stack[stack.length-1]!.data
await f
},
// Tuple operations
async TUPLE_PACK() {
pushValue(tuple.pack(await popNValues()))
// pushValue(shittyBake(tuple.pack(await popNValues())))
},
async TUPLE_PACK_WITH_VERSIONSTAMP() {
const prefix = await popBuffer()
// console.log('prefix', prefix.toString('hex'), prefix.length)
try {
const value = tuple.packUnboundVersionstamp(await popNValues())
// console.log('a', value)
// console.log('_', value.data.toString('hex'), value.data.length)
// console.log('b', packPrefixedVersionStamp(prefix, value, true).toString('hex'))
pushLiteral('OK')
// pushValue(Buffer.concat([]))
// pushValue(Buffer.concat([prefix, (value as UnboundStamp).data, ]))
// const pack = packVersionStamp({data: Buffer.concat([prefix, value.data]), value.stampPos + prefix.length, true, false)
const pack = packPrefixedVersionstamp(prefix, value, true)
// console.log('packed', pack.toString('hex'))
pushValue(pack)
} catch (e) {
// console.log('c', e)
// TODO: Add userspace error codes to these.
if (e.message === 'No incomplete versionstamp included in tuple pack with versionstamp') {
pushLiteral('ERROR: NONE')
} else if (e.message === 'Tuples may only contain 1 unset versionstamp') {
pushLiteral('ERROR: MULTIPLE')
} else throw e
}
},
async TUPLE_UNPACK() {
const packed = await popBuffer()
for (const item of tuple.unpack(packed, true)) {
// const pack = tuple.pack([item])
// pushValue(isPackUnbound(pack) ? null : pack)
pushValue(tuple.pack([item]))
}
},
async TUPLE_RANGE() {
const {begin, end} = tuple.range(await popNValues())
pushValue(begin)
pushValue(end)
},
async TUPLE_SORT() {
// Look I'll be honest. I could put a compare function into the tuple
// type, but it doesn't do anything you can't trivially do yourself.
const items = (await popNValues())
.map(buf => tuple.unpack(buf as Buffer, true))
.sort((a: TupleItem[], b: TupleItem[]) => tuple.pack(a).compare(tuple.pack(b)))
for (const item of items) pushValue(tuple.pack(item))
},
async ENCODE_FLOAT() {
const buf = await popBuffer()
// Note the byte representation of nan isn't stable, so even though we can
// use DataView to read the "right" nan value here and avoid
// canonicalization, we still can't use it because v8 might change the
// representation of the passed nan value under the hood. More:
// https://github.com/nodejs/node/issues/32697
const value = buf.readFloatBE(0)
pushTupleItem(isNaN(value) ? {type: 'float', value, rawEncoding:buf} : {type: 'float', value})
},
async ENCODE_DOUBLE() {
const buf = await popBuffer()
const value = buf.readDoubleBE(0)
if (verbose) console.log('bt encode_double', buf, value, buf.byteOffset)
pushTupleItem(isNaN(value) ? {type: 'double', value, rawEncoding:buf} : {type: 'double', value})
},
async DECODE_FLOAT() {
// These are both super gross. Not sure what to do about that.
const val = await popValue() as {type: 'float', value: number, rawEncoding: Buffer}
assert(typeof val === 'object' && val.type === 'float')
const dv = new DataView(new ArrayBuffer(4))
dv.setFloat32(0, val.value, false)
// console.log('bt decode_float', val, Buffer.from(dv.buffer))
pushValue(Buffer.from(dv.buffer))
// const buf = Buffer.alloc(4)
// buf.writeFloatBE(val.value, 0)
// pushValue(buf)
// pushValue(val.rawEncoding)
},
async DECODE_DOUBLE() {
const val = await popValue() as {type: 'double', value: number, rawEncoding: Buffer}
assert(val.type === 'double', 'val is ' + nodeUtil.inspect(val))
const dv = new DataView(new ArrayBuffer(8))
dv.setFloat64(0, val.value, false)
pushValue(Buffer.from(dv.buffer))
// console.log('bt decode_double', val, Buffer.from(dv.buffer))
// const buf = Buffer.alloc(8)
// buf.writeDoubleBE(val.value, 0)
// pushValue(buf)
// pushValue(val.rawEncoding)
},
// Thread Operations
async START_THREAD() {
// Note we don't wait here - this is run concurrently.
const prefix = await popBuffer()
runFromPrefix(db, prefix)
},
async WAIT_EMPTY() {
const prefix = await popBuffer()
await db.doTransaction(async tn => {
const nextKey = (await tn.getKey(keySelector.firstGreaterOrEqual(prefix))) as Buffer
if (nextKey && bufBeginsWith(nextKey, prefix)) {
throw new fdb.FDBError('wait_empty', 1020)
}
}).catch(catchFdbErr)
pushLiteral('WAITED_FOR_EMPTY')
},
// TODO: Invoke mocha here
UNIT_TESTS() {},
// **** Directory stuff ****
async DIRECTORY_CREATE_SUBSPACE() {
const path = (await popNValues()) as string[]
const rawPrefix = await popStrBuf()
if (verbose) console.log('path', path, 'rawprefix', rawPrefix)
const subspace = new Subspace(rawPrefix).withKeyEncoding(tupleStrict).at(path)
dirList.push(subspace)
},
async DIRECTORY_CREATE_LAYER() {
const index1 = await popSmallInt()
const index2 = await popSmallInt()
const allowManualPrefixes = await popBool()
const nodeSubspace = dirList[index1] as Subspace | null
const contentSubspace = dirList[index2] as Subspace | null
if (verbose) console.log('dcl', index1, index2, allowManualPrefixes)
dirList.push(
(nodeSubspace == null || contentSubspace == null) ? null
: new fdb.DirectoryLayer({
nodeSubspace,
contentSubspace,
allowManualPrefixes,
})
)
},
async DIRECTORY_CREATE_OR_OPEN(oper) {
const path = (await popNValues()) as string[]
const layer = await popNullableBuf()
const dir = await getCurrentDirectoryOrLayer().createOrOpen(oper, path, layer || undefined)
dirList.push(dir)
},
async DIRECTORY_CREATE(oper) {
const path = (await popNValues()) as string[]
const layer = await popNullableBuf()
const prefix = (await popValue()) as Buffer | null || undefined
if (verbose) console.log('path', path, layer, prefix)
// console.log(dirList[dirIdx])
const dir = await getCurrentDirectoryOrLayer().create(oper, path, layer || undefined, prefix)
dirList.push(dir)
},
async DIRECTORY_OPEN(oper) {
const path = (await popNValues()) as string[]
const layer = await popNullableBuf()
const parent = getCurrentDirectoryOrLayer()
const dir = await parent.open(oper, path, layer || undefined)
if (verbose) console.log('push new directory', dir.getPath(), 'at index', dirList.length, 'p', parent.getPath(), parent.constructor.name, path)
dirList.push(dir)
},
async DIRECTORY_CHANGE() {
dirIdx = await popSmallInt()
if (dirList[dirIdx] == null) dirIdx = dirErrIdx
const result = dirList[dirIdx]
if (verbose) console.log('Changed directory index to', dirIdx, result == null ? 'null' : result.constructor.name)
},
async DIRECTORY_SET_ERROR_INDEX() {
dirErrIdx = await popSmallInt()
if (verbose) console.log('Changed directory error index to', dirErrIdx)
},
async DIRECTORY_MOVE(oper) {
const oldPath = (await popNValues()) as string[]
const newPath = (await popNValues()) as string[]
if (verbose) console.log('move', oldPath, newPath)
dirList.push(await getCurrentDirectoryOrLayer().move(oper, oldPath, newPath))
},
async DIRECTORY_MOVE_TO(oper) {
const dir = await getCurrentDirectoryOrLayer()
const newAbsPath = (await popNValues()) as string[]
// There's no moveTo method to call in DirectoryLayer - but this is what it would do if there were.
if (dir instanceof DirectoryLayer) throw new DirectoryError('The root directory cannot be moved.')
// console.log('move_to', dirIdx, dirList[dirIdx])
// console.log('move to', newAbsPath)
dirList.push(await getCurrentDirectory().moveTo(oper, newAbsPath))
},
async DIRECTORY_REMOVE(oper) {
const count = await popSmallInt() // either 0 or 1
const path = count === 1
? (await popNValues()) as string[]
: undefined
await getCurrentDirectoryOrLayer().remove(oper, path)
},
async DIRECTORY_REMOVE_IF_EXISTS(oper) {
const count = await popSmallInt() // either 0 or 1
const path = count === 1
? (await popNValues()) as string[]
: undefined
await getCurrentDirectoryOrLayer().removeIfExists(oper, path)
},
async DIRECTORY_LIST(oper) {
const count = await popSmallInt() // either 0 or 1
const path = count === 1
? (await popNValues()) as string[]
: undefined
const children = tuple.pack(await getCurrentDirectoryOrLayer().listAll(oper, path))
pushValue(children)
},
async DIRECTORY_EXISTS(oper) {
const count = await popSmallInt() // either 0 or 1
const path = count === 0
? undefined
: (await popNValues()) as string[]
pushValue(await getCurrentDirectoryOrLayer().exists(oper, path) ? 1 : 0)
},
async DIRECTORY_PACK_KEY() {
const keyTuple = await popNValues()
pushValue(getCurrentSubspace().withKeyEncoding(tupleStrict).packKey(keyTuple))
},
async DIRECTORY_UNPACK_KEY() {
const key = await popBuffer()
const tup = getCurrentSubspace().withKeyEncoding(tupleStrict).unpackKey(key)
if (verbose) console.log('unpack key', key, tup)
pushArrItems(tup)
},
async DIRECTORY_RANGE() {
const keyTuple = await popNValues()
const {begin, end} = getCurrentSubspace().withKeyEncoding(tupleStrict).packRange(keyTuple)
pushValue(begin); pushValue(end)
},
async DIRECTORY_CONTAINS() {
const key = await popStrBuf()
pushValue(getCurrentSubspace().contains(key) ? 1 : 0)
},
async DIRECTORY_OPEN_SUBSPACE() {
const childPrefix = await popNValues()
dirList.push(getCurrentSubspace().withKeyEncoding(tupleStrict).at(childPrefix))
},
async DIRECTORY_LOG_SUBSPACE(oper) {
const prefix = await popBuffer()
await oper.set(concat2(prefix, tuple.pack(dirIdx)), getCurrentSubspace().prefix)
},
async DIRECTORY_LOG_DIRECTORY(oper) {
const dir = await getCurrentDirectoryOrLayer()
const prefix = await popBuffer()
const logSubspace = new Subspace(prefix)
.withKeyEncoding(tupleStrict)
.withValueEncoding(tupleStrict)
.at(dirIdx)
let exists = await dir.exists(oper)
if (verbose) console.log('type', dir.constructor.name)
let children = exists ? await dir.listAll(oper) : []
let layer = dir instanceof Directory ? dir.getLayerRaw() : Buffer.alloc(0)
const scopedOper = (oper instanceof Database) ? oper.at(logSubspace) : oper.at(logSubspace) // lolscript.
await scopedOper.set('path', dir.getPath())
await scopedOper.set('layer', layer)
await scopedOper.set('exists', exists ? 1 : 0)
await scopedOper.set('children', children)
if (verbose) console.log('path', dir.getPath(), 'layer', layer, 'exists', exists, 'children', children)
},
async DIRECTORY_STRIP_PREFIX() {
const byteArray = await popBuffer()
if (verbose) console.log('strip prefix', dirList[dirIdx])
const prefix = getCurrentSubspace().prefix
if (!startsWith(byteArray, prefix)) {
throw Error('String does not start with raw prefix')
} else {
pushValue(byteArray.slice(prefix.length))
}
},
}
return {
async run(instrBuf: Buffer, log?: fs.WriteStream) {
const instruction = fdb.tuple.unpack(instrBuf, true)
let [opcode, ...oper] = instruction as [string, TupleItem[]]
// const txnOps = [
// 'NEW_TRANSACTION',
// 'USE_TRANSACTION',
// 'ON_ERROR',
// 'COMMIT',
// 'CANCEL',
// 'RESET',
// ]
// if (verbose || (instrId > 25000 && instrId < 28523 && txnOps.includes(opcode))) {
if (verbose) {
if (oper.length) console.log(chalk.magenta(opcode as string), instrId, threadColor(initialName.toString('ascii')), oper, instrBuf.toString('hex'))
else console.log(chalk.magenta(opcode as string), instrId, threadColor(initialName.toString('ascii')))
}
if (log) log.write(`${opcode} ${instrId} ${stack.length}\n`)
let operand: Transaction | Database = transactions[tnNameKey()]
if (opcode.endsWith('_SNAPSHOT')) {
opcode = opcode.slice(0, -'_SNAPSHOT'.length)
operand = (operand as Transaction).snapshot()
} else if (opcode.endsWith('_DATABASE')) {
opcode = opcode.slice(0, -'_DATABASE'.length)
operand = db
}
// verbose = (instrId > 27234-10) && (instrId < 27234+10)
// verbose = (instrId > 12700 && instrId < 12710) || (instrId > 12770 && instrId < 12788)
try {
await operations[opcode](operand, ...oper)
} catch (e) {
if (verbose) console.log('Exception:', e.message)
if (opcode.startsWith('DIRECTORY_')) {
// For some reason we absorb all errors here rather than just
// directory errors. This is probably a bug in the fuzzer, but eh. See
// seed 3079719521.
// if (!(e instanceof DirectoryError)) throw e
if (([
'DIRECTORY_CREATE_SUBSPACE',
'DIRECTORY_CREATE_LAYER',
'DIRECTORY_CREATE_OR_OPEN',
'DIRECTORY_CREATE',
'DIRECTORY_OPEN',
'DIRECTORY_MOVE',
'DIRECTORY_MOVE_TO',
'DIRECTORY_OPEN_SUBSPACE'
]).includes(opcode)) {
dirList.push(null)
}
pushLiteral('DIRECTORY_ERROR')
} else {
const err = catchFdbErr(e)
pushValue(err)
}
}
if (verbose) {
console.log(chalk.yellow('STATE'), instrId, threadColor(initialName.toString('ascii')), tnName.toString('ascii'), lastVersion)
console.log(`stack length ${stack.length}:`)
if (stack.length >= 1) console.log(' Stack top:', stack[stack.length-1].instrId, stack[stack.length-1].data)
if (stack.length >= 2) console.log(' stack t-1:', stack[stack.length-2].instrId, stack[stack.length-2].data)
}
instrId++
}
}
}
const threads = new Set<Promise<void>>()
let instructionsRun = 0
const run = async (db: Database, prefix: Buffer, log?: fs.WriteStream) => {
const machine = makeMachine(db, prefix)
const {begin, end} = fdb.tuple.range([prefix])
const instructions = await db.getRangeAll(begin, end)
if (verbose) console.log(`Executing ${instructions.length} instructions from ${prefix.toString()}`)
for (const [key, value] of instructions) {
// console.log(key, value)
await machine.run(value as Buffer, log)
// TODO: consider inserting tiny sleeps to increase concurrency.
}
instructionsRun += instructions.length
// console.log(`Thread ${prefix.toString()} complete`)
}
async function runFromPrefix(db: Database, prefix: Buffer, log?: fs.WriteStream) {
const thread = run(db, prefix, log)
threads.add(thread)
await thread
threads.delete(thread)
}
if (require.main === module) (async () => {
process.on('unhandledRejection', (err: any) => {
console.log(chalk.redBright('✖'), 'Unhandled error in binding tester:\n', err.message, 'code', err.code, err.stack)
throw err
})
const prefixStr = process.argv[2]
const requestedAPIVersion = +process.argv[3]
const clusterFile = process.argv[4]
// const log = fs.createWriteStream('nodetester.log')
const log = undefined
fdb.setAPIVersion(requestedAPIVersion)
fdb.configNetwork({
// trace_enable: 'trace',
trace_log_group: 'debug',
// trace_format: 'json',
// external_client_library: '~/3rdparty/foundationdb/lib/libfdb_c.dylib-debug',
})
const db = fdb.open(clusterFile)
runFromPrefix(db, Buffer.from(prefixStr, 'ascii'), log)
// Wait until all 'threads' are finished.
while (threads.size) {
await Promise.all(Array.from(threads))
}
console.log(`${chalk.greenBright('✔')} Node binding tester complete. ${instructionsRun} commands executed`)
// And wait for other threads! Logging won't work for concurrent runs.
// if (log) log.end()
})() | the_stack |
module formFor {
/**
* This service can be used to configure default behavior for all instances of formFor within a project.
* Note that it is a service accessible to during the run loop and not a provider accessible during config.
*/
export class FormForConfiguration {
public autoGenerateLabels:boolean = false;
public autoTrimValues:boolean = false;
public defaultDebounceDuration:number = 500;
public defaultSubmitComplete:(formData:any) => void = angular.noop;
public defaultSubmitError:(error:any) => void = angular.noop;
public defaultValidationFailed:(error:any) => void = angular.noop;
public defaultSelectEmptyOptionValue:any = undefined;
public helpIcon:string = null;
public labelClass:string = null;
public requiredLabel:string = null;
private validationFailedForCustomMessage_:string = "Failed custom validation";
private validationFailedForEmailTypeMessage_:string = "Invalid email format";
private validationFailedForIncrementMessage_:string = "Value must be in increments of {{num}}";
private validationFailedForIntegerTypeMessage_:string = "Must be an integer";
private validationFailedForMaxCollectionSizeMessage_:string = "Must be fewer than {{num}} items";
private validationFailedForMaximumMessage_:string = "Must be no more than {{num}}";
private validationFailedForMaxLengthMessage_:string = "Must be fewer than {{num}} characters";
private validationFailedForMinimumMessage_:string = "Must be at least {{num}}";
private validationFailedForMinCollectionSizeMessage_:string = "Must at least {{num}} items";
private validationFailedForMinLengthMessage_:string = "Must be at least {{num}} characters";
private validationFailedForNegativeTypeMessage_:string = "Must be negative";
private validationFailedForNonNegativeTypeMessage_:string = "Must be non-negative";
private validationFailedForNumericTypeMessage_:string = "Must be numeric";
private validationFailedForPatternMessage_:string = "Invalid format";
private validationFailedForPositiveTypeMessage_:string = "Must be positive";
private validationFailedForRequiredMessage_:string = "Required field";
// Public methods ////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Use this method to disable auto-generated labels for formFor input fields.
*/
public disableAutoLabels():void {
this.autoGenerateLabels = false;
}
/**
* Use this method to enable auto-generated labels for formFor input fields.
* Labels will be generated based on attribute-name for fields without a label attribute present.
* Radio fields are an exception to this rule.
* Their names are generated from their values.
*/
public enableAutoLabels():void {
this.autoGenerateLabels = true;
}
/**
* Disable auto-trim.
*/
public disableAutoTrimValues():void {
this.autoTrimValues = false;
}
/**
* Auto-trim leading and trailing whitespace from values before syncing back to the formData object.
*/
public enableAutoTrimValues():void {
this.autoTrimValues = true;
}
/**
* Returns the appropriate error message for the validation failure type.
*/
public getFailedValidationMessage(failureType:ValidationFailureType):string {
switch (failureType) {
case ValidationFailureType.CUSTOM:
return this.validationFailedForCustomMessage_;
case ValidationFailureType.COLLECTION_MAX_SIZE:
return this.validationFailedForMaxCollectionSizeMessage_;
case ValidationFailureType.COLLECTION_MIN_SIZE:
return this.validationFailedForMinCollectionSizeMessage_;
case ValidationFailureType.INCREMENT:
return this.validationFailedForIncrementMessage_;
case ValidationFailureType.MINIMUM:
return this.validationFailedForMinimumMessage_;
case ValidationFailureType.MAX_LENGTH:
return this.validationFailedForMaxLengthMessage_;
case ValidationFailureType.MAXIMUM:
return this.validationFailedForMaximumMessage_;
case ValidationFailureType.MIN_LENGTH:
return this.validationFailedForMinLengthMessage_;
case ValidationFailureType.PATTERN:
return this.validationFailedForPatternMessage_;
case ValidationFailureType.REQUIRED:
return this.validationFailedForRequiredMessage_;
case ValidationFailureType.TYPE_EMAIL:
return this.validationFailedForEmailTypeMessage_;
case ValidationFailureType.TYPE_INTEGER:
return this.validationFailedForIntegerTypeMessage_;
case ValidationFailureType.TYPE_NEGATIVE:
return this.validationFailedForNegativeTypeMessage_;
case ValidationFailureType.TYPE_NON_NEGATIVE:
return this.validationFailedForNonNegativeTypeMessage_;
case ValidationFailureType.TYPE_NUMERIC:
return this.validationFailedForNumericTypeMessage_;
case ValidationFailureType.TYPE_POSITIVE:
return this.validationFailedForPositiveTypeMessage_;
}
}
/**
* Sets the default debounce interval (in ms) for all textField inputs.
* This setting can be overridden on a per-input basis (see textField).
* Defaults to 500ms.
* To disable debounce (update only on blur) pass false.
*/
public setDefaultDebounceDuration(value:number):void {
this.defaultDebounceDuration = value;
}
/**
* Sets the default submit-complete behavior for all formFor directives.
* This setting can be overridden on a per-form basis (see formFor).
*
* Default handler function accepting a data parameter representing the server-response returned by the submitted form.
* This function should accept a single parameter, the response data from the form-submit method.
*/
public setDefaultSubmitComplete(value:(formData:any) => void):void {
this.defaultSubmitComplete = value;
}
/**
* Sets the default submit-error behavior for all formFor directives.
* This setting can be overridden on a per-form basis (see formFor).
* @memberof FormForConfiguration
* @param {Function} method Default handler function accepting an error parameter representing the data passed to the rejected submit promise.
* This function should accept a single parameter, the error returned by the form-submit method.
*/
public setDefaultSubmitError(value:(error:any) => void):void {
this.defaultSubmitError = value;
}
/**
* Sets the default validation-failed behavior for all formFor directives.
* This setting can be overridden on a per-form basis (see formFor).
* @memberof FormForConfiguration
* @param {Function} method Default function invoked when local form validation fails.
*/
public setDefaultValidationFailed(value:(error:any) => void):void {
this.defaultValidationFailed = value;
}
/**
* Sets the default value of empty option for selectField inputs.
* Defaults to undefined.
*/
public setDefaultSelectEmptyOptionValue(value:number):void {
this.defaultSelectEmptyOptionValue = value;
}
/**
* Sets the class(es) to be used as the help icon in supported templates.
* Each template specifies its own default help icon that can be overridden with this method.
* @memberof FormForConfiguration
* @param {string} class(es) for the desired icon, multiple classes are space separated
*/
public setHelpIcon(value:string):void {
this.helpIcon = value;
}
/**
* Global class-name for field <label>s.
*/
public setLabelClass(value:string):void {
this.labelClass = value;
}
/**
* Sets a default label to be displayed beside each text and select input for required attributes only.
*/
public setRequiredLabel(value:string):void {
this.requiredLabel = value;
}
/**
* Override the default error message for failed custom validations.
* This setting applies to all instances of formFor unless otherwise overridden on a per-rule basis.
*/
public setValidationFailedForCustomMessage(value:string):void {
this.validationFailedForCustomMessage_ = value;
}
/**
* Override the default error message for failed numeric increment validations.
* This setting applies to all instances of formFor unless otherwise overridden on a per-rule basis.
*/
public setValidationFailedForIncrementMessage(value:string):void {
this.validationFailedForIncrementMessage_ = value;
}
/**
* Override the default error message for failed max collection size validations.
* This setting applies to all instances of formFor unless otherwise overridden on a per-rule basis.
*/
public setValidationFailedForMaxCollectionSizeMessage(value:string):void {
this.validationFailedForMaxCollectionSizeMessage_ = value;
}
/**
* Override the default error message for failed maximum validations.
* This setting applies to all instances of formFor unless otherwise overridden on a per-rule basis.
*/
public setValidationFailedForMaximumMessage(value:string):void {
this.validationFailedForMaximumMessage_= value;
}
/**
* Override the default error message for failed maxlength validations.
* This setting applies to all instances of formFor unless otherwise overridden on a per-rule basis.
*/
public setValidationFailedForMaxLengthMessage(value:string):void {
this.validationFailedForMaxLengthMessage_ = value;
}
/**
* Override the default error message for failed min collection size validations.
* This setting applies to all instances of formFor unless otherwise overridden on a per-rule basis.
*/
public setValidationFailedForMinCollectionSizeMessage(value:string):void {
this.validationFailedForMaxCollectionSizeMessage_ = value;
}
/**
* Override the default error message for failed minimum validations.
* This setting applies to all instances of formFor unless otherwise overridden on a per-rule basis.
*/
public setValidationFailedForMinimumMessage(value:string):void {
this.validationFailedForMinimumMessage_= value;
}
/**
* Override the default error message for failed minlength validations.
* This setting applies to all instances of formFor unless otherwise overridden on a per-rule basis.
*/
public setValidationFailedForMinLengthMessage(value:string):void {
this.validationFailedForMinLengthMessage_ = value;
}
/**
* Override the default error message for failed pattern validations.
* This setting applies to all instances of formFor unless otherwise overridden on a per-rule basis.
*/
public setValidationFailedForPatternMessage(value:string):void {
this.validationFailedForPatternMessage_ = value;
}
/**
* Override the default error message for failed required validations.
* This setting applies to all instances of formFor unless otherwise overridden on a per-rule basis.
*/
public setValidationFailedForRequiredMessage(value:string):void {
this.validationFailedForRequiredMessage_ = value;
}
/**
* Override the default error message for failed type = 'email' validations.
* This setting applies to all instances of formFor unless otherwise overridden on a per-rule basis.
*/
public setValidationFailedForEmailTypeMessage(value:string):void {
this.validationFailedForEmailTypeMessage_ = value;
}
/**
* Override the default error message for failed type = 'integer' validations.
* This setting applies to all instances of formFor unless otherwise overridden on a per-rule basis.
*/
public setValidationFailedForIntegerTypeMessage(value:string):void {
this.validationFailedForIntegerTypeMessage_ = value;
}
/**
* Override the default error message for failed type = 'negative' validations.
* This setting applies to all instances of formFor unless otherwise overridden on a per-rule basis.
*/
public setValidationFailedForNegativeTypeMessage(value:string):void {
this.validationFailedForNegativeTypeMessage_ = value;
}
/**
* Override the default error message for failed type = 'nonNegative' validations.
* This setting applies to all instances of formFor unless otherwise overridden on a per-rule basis.
*/
public setValidationFailedForNonNegativeTypeMessage(value:string):void {
this.validationFailedForNonNegativeTypeMessage_ = value;
}
/**
* Override the default error message for failed type = 'numeric' validations.
* This setting applies to all instances of formFor unless otherwise overridden on a per-rule basis.
*/
public setValidationFailedForNumericTypeMessage(value:string):void {
this.validationFailedForNumericTypeMessage_ = value;
}
/**
* Override the default error message for failed type = 'positive' validations.
* This setting applies to all instances of formFor unless otherwise overridden on a per-rule basis.
*/
public setValidationFailedForPositiveTypeMessage(value:string):void {
this.validationFailedForPositiveTypeMessage_ = value;
}
};
angular.module('formFor').service('FormForConfiguration', () => new FormForConfiguration());
}; | the_stack |
// tslint:disable-next-line: no-require-imports
import performanceNow = require("performance-now");
import { Language, Lexer, ParseSettings, TypeScriptUtils } from "../..";
import { Parser, ParserUtils, ParseState, ParseStateCheckpoint, ParseStateUtils } from "../../powerquery-parser/parser";
export interface BenchmarkState extends ParseState {
readonly baseParser: Parser;
readonly functionTimestamps: Map<number, FunctionTimestamp>;
functionTimestampCounter: number;
}
export interface FunctionTimestamp {
readonly id: number;
readonly fnName: string;
readonly lineNumberStart: number;
readonly lineCodeUnitStart: number;
readonly codeUnitStart: number;
lineNumberEnd: number | undefined;
lineCodeUnitEnd: number | undefined;
codeUnitEnd: number | undefined;
readonly timeStart: number;
timeEnd: number | undefined;
timeDuration: number | undefined;
}
export const BenchmarkParser: Parser = {
applyState: (state: ParseState, update: ParseState) => {
const mutableState: TypeScriptUtils.StripReadonly<BenchmarkState> = state as BenchmarkState;
ParseStateUtils.applyState(mutableState, update);
mutableState.functionTimestamps = (update as BenchmarkState).functionTimestamps;
mutableState.functionTimestampCounter = (update as BenchmarkState).functionTimestampCounter;
},
copyState: (state: ParseState) => {
const benchmarkState: BenchmarkState = state as BenchmarkState;
return {
...ParseStateUtils.copyState(state),
baseParser: benchmarkState.baseParser,
functionTimestampCounter: benchmarkState.functionTimestampCounter,
functionTimestamps: new Map(
[
...benchmarkState.functionTimestamps.entries(),
].map(([counter, functionTimestamp]: [number, FunctionTimestamp]) => [
counter,
{ ...functionTimestamp },
]),
),
};
},
createCheckpoint: (state: ParseState) => ParserUtils.createCheckpoint(state),
restoreCheckpoint: (state: ParseState, checkpoint: ParseStateCheckpoint) =>
ParserUtils.restoreCheckpoint(state, checkpoint),
// 12.1.6 Identifiers
readIdentifier: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readIdentifier),
readGeneralizedIdentifier: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readGeneralizedIdentifier),
readKeyword: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readKeyword),
// 12.2.1 Documents
readDocument: (state: ParseState, parser: Parser) => {
const readDocumentLambda: () => Language.Ast.TDocument = () =>
(state as BenchmarkState).baseParser.readDocument(state, parser) as Language.Ast.TDocument;
return traceFunction(state, parser, readDocumentLambda);
},
// 12.2.2 Section Documents
readSectionDocument: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readSectionDocument),
readSectionMembers: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readSectionMembers),
readSectionMember: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readSectionMember),
// 12.2.3.1 Expressions
readNullCoalescingExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readNullCoalescingExpression),
readExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readExpression),
// 12.2.3.2 Logical expressions
readLogicalExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readLogicalExpression),
// 12.2.3.3 Is expression
readIsExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readIsExpression),
readNullablePrimitiveType: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readNullablePrimitiveType),
// 12.2.3.4 As expression
readAsExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readAsExpression),
// 12.2.3.5 Equality expression
readEqualityExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readEqualityExpression),
// 12.2.3.6 Relational expression
readRelationalExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readRelationalExpression),
// 12.2.3.7 Arithmetic expressions
readArithmeticExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readArithmeticExpression),
// 12.2.3.8 Metadata expression
readMetadataExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readMetadataExpression),
// 12.2.3.9 Unary expression
readUnaryExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readUnaryExpression),
// 12.2.3.10 Primary expression
readPrimaryExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readPrimaryExpression),
readRecursivePrimaryExpression: (state: ParseState, parser: Parser, head) => {
const readRecursivePrimaryExpressionLambda: () => Language.Ast.RecursivePrimaryExpression = () =>
(state as BenchmarkState).baseParser.readRecursivePrimaryExpression(state, parser, head);
return traceFunction(state, parser, readRecursivePrimaryExpressionLambda);
},
// 12.2.3.11 Literal expression
readLiteralExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readLiteralExpression),
// 12.2.3.12 Identifier expression
readIdentifierExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readIdentifierExpression),
// 12.2.3.14 Parenthesized expression
readParenthesizedExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readParenthesizedExpression),
// 12.2.3.15 Not-implemented expression
readNotImplementedExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readNotImplementedExpression),
// 12.2.3.16 Invoke expression
readInvokeExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readInvokeExpression),
// 12.2.3.17 List expression
readListExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readListExpression),
readListItem: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readListItem),
// 12.2.3.18 Record expression
readRecordExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readRecordExpression),
// 12.2.3.19 Item access expression
readItemAccessExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readItemAccessExpression),
// 12.2.3.20 Field access expression
readFieldSelection: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readFieldSelection),
readFieldProjection: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readFieldProjection),
readFieldSelector: (state: ParseState, parser: Parser, allowOptional: boolean) => {
const readFieldSelectorLambda: () => Language.Ast.FieldSelector = () =>
(state as BenchmarkState).baseParser.readFieldSelector(state, parser, allowOptional);
return traceFunction(state, parser, readFieldSelectorLambda);
},
// 12.2.3.21 Function expression
readFunctionExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readFunctionExpression),
readParameterList: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readParameterList),
readAsType: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readAsType),
// 12.2.3.22 Each expression
readEachExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readEachExpression),
// 12.2.3.23 Let expression
readLetExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readLetExpression),
// 12.2.3.24 If expression
readIfExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readIfExpression),
// 12.2.3.25 Type expression
readTypeExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readTypeExpression),
readType: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readType),
readPrimaryType: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readPrimaryType),
readRecordType: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readRecordType),
readTableType: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readTableType),
readFieldSpecificationList: (state: ParseState, parser: Parser, allowOpenMarker: boolean, testPostCommaError) => {
const readFieldSpecificationListLambda: () => Language.Ast.FieldSpecificationList = () =>
(state as BenchmarkState).baseParser.readFieldSpecificationList(
state,
parser,
allowOpenMarker,
testPostCommaError,
);
return traceFunction(state, parser, readFieldSpecificationListLambda);
},
readListType: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readListType),
readFunctionType: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readFunctionType),
readParameterSpecificationList: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readParameterSpecificationList),
readNullableType: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readNullableType),
// 12.2.3.26 Error raising expression
readErrorRaisingExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readErrorRaisingExpression),
// 12.2.3.27 Error handling expression
readErrorHandlingExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readErrorHandlingExpression),
// 12.2.4 Literal Attributes
readRecordLiteral: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readRecordLiteral),
readFieldNamePairedAnyLiterals: (
state: ParseState,
parser: Parser,
onePairRequired: boolean,
testPostCommaError,
) => {
const readFieldNamePairedAnyLiteralsLambda: () => Language.Ast.ICsvArray<
Language.Ast.GeneralizedIdentifierPairedAnyLiteral
> = () =>
(state as BenchmarkState).baseParser.readFieldNamePairedAnyLiterals(
state,
parser,
onePairRequired,
testPostCommaError,
);
return traceFunction(state, parser, readFieldNamePairedAnyLiteralsLambda);
},
readListLiteral: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readListLiteral),
readAnyLiteral: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readAnyLiteral),
readPrimitiveType: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readPrimitiveType),
// key-value pairs
readIdentifierPairedExpressions: (
state: ParseState,
parser: Parser,
onePairRequired: boolean,
testPostCommaError,
) => {
const readFieldSpecificationListLambda: () => Language.Ast.ICsvArray<
Language.Ast.IdentifierPairedExpression
> = () =>
(state as BenchmarkState).baseParser.readIdentifierPairedExpressions(
state,
parser,
onePairRequired,
testPostCommaError,
);
return traceFunction(state, parser, readFieldSpecificationListLambda);
},
readIdentifierPairedExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readIdentifierPairedExpression),
readGeneralizedIdentifierPairedExpressions: (
state: ParseState,
parser: Parser,
onePairRequired: boolean,
testPostCommaError,
) => {
const readFieldSpecificationListLambda: () => Language.Ast.ICsvArray<
Language.Ast.GeneralizedIdentifierPairedExpression
> = () =>
(state as BenchmarkState).baseParser.readGeneralizedIdentifierPairedExpressions(
state,
parser,
onePairRequired,
testPostCommaError,
);
return traceFunction(state, parser, readFieldSpecificationListLambda);
},
readGeneralizedIdentifierPairedExpression: (state: ParseState, parser: Parser) =>
traceFunction(state, parser, (state as BenchmarkState).baseParser.readGeneralizedIdentifierPairedExpression),
};
export function createBenchmarkState(
parseSettings: ParseSettings,
lexerSnapshot: Lexer.LexerSnapshot,
baseParser: Parser,
): BenchmarkState {
return {
...ParseStateUtils.createState(lexerSnapshot, {
maybeCancellationToken: parseSettings.maybeCancellationToken,
}),
baseParser,
functionTimestamps: new Map(),
functionTimestampCounter: 0,
};
}
function traceFunction<T>(
benchmarkState: ParseState,
benchmarkParser: Parser,
tracedFn: (state: ParseState, parser: Parser) => T,
): T {
const fnCallId: number = functionEntry(benchmarkState, tracedFn);
const result: T = tracedFn(benchmarkState, benchmarkParser);
functionExit(benchmarkState, fnCallId);
return result;
}
function functionEntry<T>(state: ParseState, fn: (state: ParseState, parser: Parser) => T): number {
const tokenPosition: Language.Token.TokenPosition = state.maybeCurrentToken!.positionStart;
const benchmarkState: BenchmarkState = state as BenchmarkState;
const id: number = benchmarkState.functionTimestampCounter;
benchmarkState.functionTimestampCounter += 1;
const functionTimestamp: FunctionTimestamp = {
id,
fnName: fn.name,
lineNumberStart: tokenPosition.lineNumber,
lineCodeUnitStart: tokenPosition.lineCodeUnit,
codeUnitStart: tokenPosition.codeUnit,
lineNumberEnd: undefined,
lineCodeUnitEnd: undefined,
codeUnitEnd: undefined,
timeStart: performanceNow(),
timeEnd: undefined,
timeDuration: undefined,
};
benchmarkState.functionTimestamps.set(id, functionTimestamp);
return id;
}
function functionExit(state: ParseState, id: number): void {
const tokenPosition: Language.Token.TokenPosition = state.maybeCurrentToken!.positionStart;
const fnTimestamp: FunctionTimestamp = (state as BenchmarkState).functionTimestamps.get(id)!;
const finish: number = performanceNow();
const duration: number = finish - fnTimestamp.timeStart;
fnTimestamp.timeEnd = finish;
fnTimestamp.timeDuration = duration;
fnTimestamp.lineNumberEnd = tokenPosition.lineNumber;
fnTimestamp.lineCodeUnitEnd = tokenPosition.lineCodeUnit;
fnTimestamp.codeUnitEnd = tokenPosition.codeUnit;
} | the_stack |
import * as tf from '@tensorflow/tfjs';
import * as socketProxy from 'socket.io-client';
import * as uuid from 'uuid/v4';
// tslint:disable-next-line:max-line-length
import {AsyncTfModel, ClientHyperparams, DEFAULT_CLIENT_HYPERPARAMS, deserializeVar, DownloadMsg, Events, FederatedCompileConfig, SerializedVariable, serializeVars, UploadCallback, UploadMsg, VersionCallback} from './common';
// tslint:disable-next-line:max-line-length
import {FederatedClientModel, FederatedClientTfModel, isFederatedClientModel} from './models';
// tslint:disable-next-line:no-angle-bracket-type-assertion no-any
const socketio = (<any>socketProxy).default || socketProxy;
const CONNECTION_TIMEOUT = 10 * 1000;
const UPLOAD_TIMEOUT = 5 * 1000;
const COOKIE_NAME = 'federated-learner-uuid';
const YEAR_IN_MS = 365 * 24 * 60 * 60 * 1000;
type CounterObj = {
[key: string]: number
};
type SocketCallback = () => SocketIOClient.Socket;
export type FederatedClientConfig = {
modelCompileConfig?: FederatedCompileConfig,
hyperparams?: ClientHyperparams,
verbose?: boolean,
clientId?: string,
sendMetrics?: boolean
};
/**
* Federated Learning Client library.
*
* Example usage with a tf.Model:
* ```js
* const model = await tf.loadModel('a-model.json');
* const client = new Client('http://server.com', model);
* await client.setup();
* await client.federatedUpdate(data.X, data.y);
* ```
* The server->client synchronisation happens transparently whenever the server
* broadcasts weights.
* The client->server syncs happen periodically after enough `federatedUpdate`
* calls occur.
*/
export class Client {
private msg: DownloadMsg;
private model: FederatedClientModel;
private socket: SocketIOClient.Socket;
private versionCallbacks: VersionCallback[];
private uploadCallbacks: UploadCallback[];
private x: tf.Tensor;
private y: tf.Tensor;
private versionUpdateCounts: CounterObj;
private server: string|SocketCallback;
private verbose: boolean;
private sendMetrics: boolean;
hyperparams: ClientHyperparams;
clientId: string;
/**
* Construct a client API for federated learning that will push and pull
* `model` updates from the server.
* @param model - model to use with federated learning
*/
constructor(
server: string|SocketCallback, model: FederatedClientModel|AsyncTfModel,
config?: FederatedClientConfig) {
this.server = server;
if (isFederatedClientModel(model)) {
this.model = model;
} else {
const compileConfig = (config || {}).modelCompileConfig || {};
this.model = new FederatedClientTfModel(model, compileConfig);
}
this.uploadCallbacks = [];
this.versionCallbacks = [(v1, v2) => {
this.log(`Updated model: ${v1} -> ${v2}`);
}];
this.versionUpdateCounts = {};
this.verbose = (config || {}).verbose;
this.sendMetrics = (config || {}).sendMetrics;
if ((config || {}).clientId) {
this.clientId = config.clientId;
} else if (getCookie(COOKIE_NAME)) {
this.clientId = getCookie(COOKIE_NAME);
} else {
this.clientId = uuid();
setCookie(COOKIE_NAME, this.clientId);
}
this.hyperparams = (config || {}).hyperparams || {};
}
/**
* @return The version of the model we're currently training
*/
public modelVersion(): string {
return this.msg == null ? 'unsynced' : this.msg.model.version;
}
/**
* Register a new callback to be invoked whenever the server updates the model
* version.
*
* @param callback function to be called (w/ old and new version IDs)
*/
onNewVersion(callback: VersionCallback) {
this.versionCallbacks.push(callback);
}
/**
* Register a new callback to be invoked whenever the client uploads a new set
* of weights.
*
* @param callback function to be called (w/ client's upload msg)
*/
onUpload(callback: UploadCallback) {
this.uploadCallbacks.push(callback);
}
/**
* Connect to a server, synchronise the variables to their initial values
* @param serverURL: The URL of the server
* @return A promise that resolves when the connection has been established
* and variables set to their inital values.
*/
public async setup(): Promise<void> {
await this.time('Initial model setup', async () => {
await this.model.setup();
});
this.x = tf.tensor([], [0].concat(this.model.inputShape));
this.y = tf.tensor([], [0].concat(this.model.outputShape));
await this.time('Download weights from server', async () => {
this.msg = await this.connectTo(this.server);
});
this.setVars(this.msg.model.vars);
const newVersion = this.modelVersion();
this.versionUpdateCounts[newVersion] = 0;
this.versionCallbacks.forEach(cb => cb(null, newVersion));
this.socket.on(Events.Download, (msg: DownloadMsg) => {
const oldVersion = this.modelVersion();
const newVersion = msg.model.version;
this.msg = msg;
this.setVars(msg.model.vars);
this.versionUpdateCounts[newVersion] = 0;
this.versionCallbacks.forEach(cb => cb(oldVersion, newVersion));
});
}
/**
* Disconnect from the server.
*/
public dispose(): void {
this.socket.disconnect();
this.log('Disconnected');
}
/**
* Train the model on the given examples, upload new weights to the server,
* then revert back to the original weights (so subsequent updates are
* relative to the same model).
*
* Note: this method will save copies of `x` and `y` when there
* are too few examples and only train/upload after reaching a
* configurable threshold (disposing of the copies afterwards).
*
* @param x Training inputs
* @param y Training labels
*/
public async federatedUpdate(x: tf.Tensor, y: tf.Tensor): Promise<void> {
// incorporate examples into our stored `x` and `y`
const xNew = addRows(this.x, x, this.model.inputShape);
const yNew = addRows(this.y, y, this.model.outputShape);
tf.dispose([this.x, this.y]);
this.x = xNew;
this.y = yNew;
// repeatedly, for as many iterations as we have batches of examples:
const examplesPerUpdate = this.hyperparam('examplesPerUpdate');
while (this.x.shape[0] >= examplesPerUpdate) {
// save original ID (in case it changes during training/serialization)
const modelVersion = this.modelVersion();
// grab the right number of examples
const xTrain = sliceWithEmptyTensors(this.x, 0, examplesPerUpdate);
const yTrain = sliceWithEmptyTensors(this.y, 0, examplesPerUpdate);
const fitConfig = {
epochs: this.hyperparam('epochs'),
batchSize: this.hyperparam('batchSize'),
learningRate: this.hyperparam('learningRate')
};
// optionally compute evaluation metrics for them
let metrics = null;
if (this.sendMetrics) {
metrics = this.model.evaluate(xTrain, yTrain);
}
// fit the model for the specified # of steps
await this.time('Fit model', async () => {
try {
await this.model.fit(xTrain, yTrain, fitConfig);
} catch (err) {
console.error(err);
throw err;
}
});
// serialize, possibly adding noise
const stdDev = this.hyperparam('weightNoiseStddev');
let newVars: SerializedVariable[];
if (stdDev) {
const newTensors = tf.tidy(() => {
return this.model.getVars().map(v => {
return v.add(tf.randomNormal(v.shape, 0, stdDev));
});
});
newVars = await serializeVars(newTensors);
tf.dispose(newTensors);
} else {
newVars = await serializeVars(this.model.getVars());
}
// revert our model back to its original weights
this.setVars(this.msg.model.vars);
// upload the updates to the server
const uploadMsg: UploadMsg = {
model: {version: modelVersion, vars: newVars},
clientId: this.clientId,
};
if (this.sendMetrics) {
uploadMsg.metrics = metrics;
}
await this.time('Upload weights to server', async () => {
await this.uploadVars(uploadMsg);
});
this.uploadCallbacks.forEach(cb => cb(uploadMsg));
this.versionUpdateCounts[modelVersion] += 1;
// dispose of the examples we saw
// TODO: consider storing some examples longer-term and reusing them for
// updates for multiple versions, if session is long-lived.
tf.dispose([xTrain, yTrain]);
const xRest = sliceWithEmptyTensors(this.x, examplesPerUpdate);
const yRest = sliceWithEmptyTensors(this.y, examplesPerUpdate);
tf.dispose([this.x, this.y]);
this.x = xRest;
this.y = yRest;
}
}
public evaluate(x: tf.Tensor, y: tf.Tensor): number[] {
return this.model.evaluate(x, y);
}
public predict(x: tf.Tensor): tf.Tensor {
return this.model.predict(x);
}
public get inputShape(): number[] {
return this.model.inputShape;
}
public get outputShape(): number[] {
return this.model.outputShape;
}
public numUpdates(): number {
let numTotal = 0;
Object.keys(this.versionUpdateCounts).forEach(k => {
numTotal += this.versionUpdateCounts[k];
});
return numTotal;
}
public numVersions(): number {
return Object.keys(this.versionUpdateCounts).length;
}
public numExamples(): number {
return this.x.shape[0];
}
private hyperparam(key: 'batchSize'|'learningRate'|'epochs'|
'examplesPerUpdate'|'weightNoiseStddev'): number {
return (
this.hyperparams[key] || this.msg.hyperparams[key] ||
DEFAULT_CLIENT_HYPERPARAMS[key]);
}
public numExamplesPerUpdate(): number {
return this.hyperparam('examplesPerUpdate');
}
public numExamplesRemaining(): number {
return this.numExamplesPerUpdate() - this.numExamples();
}
/**
* Upload the current values of the tracked variables to the server
* @return A promise that resolves when the server has recieved the variables
*/
private async uploadVars(msg: UploadMsg): Promise<{}> {
const prom = new Promise((resolve, reject) => {
const rejectTimer =
setTimeout(() => reject(`uploadVars timed out`), UPLOAD_TIMEOUT);
this.socket.emit(Events.Upload, msg, () => {
clearTimeout(rejectTimer);
resolve();
});
});
return prom;
}
protected setVars(newVars: SerializedVariable[]) {
tf.tidy(() => {
this.model.setVars(newVars.map(v => deserializeVar(v)));
});
}
private async connectTo(server: string|SocketCallback): Promise<DownloadMsg> {
if (typeof server === 'string') {
this.socket = socketio(server);
} else {
this.socket = server();
}
return fromEvent<DownloadMsg>(
this.socket, Events.Download, CONNECTION_TIMEOUT);
}
// tslint:disable-next-line:no-any
private log(...args: any[]) {
if (this.verbose) {
console.log('Federated Client:', ...args);
}
}
private async time(msg: string, action: () => Promise<void>) {
const t1 = new Date().getTime();
await action();
const t2 = new Date().getTime();
this.log(`${msg} took ${t2 - t1}ms`);
}
}
async function fromEvent<T>(
emitter: SocketIOClient.Socket, eventName: string,
timeout: number): Promise<T> {
return new Promise((resolve, reject) => {
const rejectTimer = setTimeout(
() => reject(`${eventName} event timed out`), timeout);
const listener = (evtArgs: T) => {
emitter.removeListener(eventName, listener);
clearTimeout(rejectTimer);
resolve(evtArgs);
};
emitter.on(eventName, listener);
}) as Promise<T>;
}
// TODO: remove once tfjs >= 0.12.5 is released
function concatWithEmptyTensors(a: tf.Tensor, b: tf.Tensor) {
if (a.shape[0] === 0) {
return b.clone();
} else if (b.shape[0] === 0) {
return a.clone();
} else {
return a.concat(b);
}
}
function sliceWithEmptyTensors(a: tf.Tensor, begin: number, size?: number) {
if (begin >= a.shape[0]) {
return tf.tensor([], [0].concat(a.shape.slice(1)));
} else {
return a.slice(begin, size);
}
}
function addRows(existing: tf.Tensor, newEls: tf.Tensor, unitShape: number[]) {
if (tf.util.arraysEqual(newEls.shape, unitShape)) {
return tf.tidy(
() => concatWithEmptyTensors(existing, tf.expandDims(newEls)));
} else { // batch dimension
tf.util.assertShapesMatch(newEls.shape.slice(1), unitShape);
return tf.tidy(() => concatWithEmptyTensors(existing, newEls));
}
}
function getCookie(name: string) {
if (typeof document === 'undefined') {
return null;
}
const v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return v ? v[2] : null;
}
function setCookie(name: string, value: string) {
if (typeof document === 'undefined') {
return;
}
const d = new Date();
d.setTime(d.getTime() + YEAR_IN_MS);
document.cookie = name + '=' + value + ';path=/;expires=' + d.toUTCString();
} | the_stack |
module WinJSTests {
"use strict";
var utilities = WinJS.Utilities;
var _element: HTMLDivElement;
var oldHasWinRT;
var oldRenderSelection;
var ItemContainer = <typeof WinJS.UI.PrivateItemContainer> WinJS.UI.ItemContainer;
function eventOnElement(element) {
var rect = element.getBoundingClientRect();
// Simulate clicking the middle of the element
return {
target: element,
clientX: (rect.left + rect.right) / 2,
clientY: (rect.top + rect.bottom) / 2,
defaultPrevented: false,
preventDefault: function () {
this.defaultPrevented = true;
}
};
}
function click(control, eventObject) {
var target = eventObject.target,
elementCoords;
if (typeof eventObject.button !== "number") {
eventObject.button = WinJS.UI._LEFT_MSPOINTER_BUTTON;
}
target.scrollIntoView(false);
elementCoords = eventOnElement(target);
eventObject.clientX = elementCoords.clientX;
eventObject.clientY = elementCoords.clientY;
eventObject.preventDefault = function () { };
control._onPointerDown(eventObject);
control._onPointerUp(eventObject);
control._onClick();
}
function createEvent(element, key, shiftKey = false, ctrlKey = false) {
return {
keyCode: key,
shiftKey: shiftKey,
ctrlKey: ctrlKey,
target: element,
stopPropagation: function () { },
preventDefault: function () { }
};
}
function verifySelectionVisual(element, selected) {
var parts = element.querySelectorAll(WinJS.Utilities._selectionPartsSelector);
if (selected) {
LiveUnit.Assert.isTrue(utilities.hasClass(element, WinJS.UI._selectedClass));
LiveUnit.Assert.areEqual(4, parts.length, "The control's container should have 4 selection parts");
} else {
LiveUnit.Assert.isFalse(utilities.hasClass(element, WinJS.UI._selectedClass));
LiveUnit.Assert.areEqual(0, parts.length, "The control's container should not have selection parts");
}
}
export class ItemContainerTests {
// This is the setup function that will be called at the beginning of each test function.
setUp() {
LiveUnit.LoggingCore.logComment("In setup");
var newNode = document.createElement("div");
newNode.id = "host";
document.body.appendChild(newNode);
_element = newNode;
oldHasWinRT = WinJS.Utilities.hasWinRT;
oldRenderSelection = WinJS.UI._ItemEventsHandler.renderSelection;
WinJS.Utilities._setHasWinRT(false);
}
tearDown() {
LiveUnit.LoggingCore.logComment("In tearDown");
if (_element) {
WinJS.Utilities.disposeSubTree(_element);
document.body.removeChild(_element);
_element = null;
}
WinJS.Utilities._setHasWinRT(oldHasWinRT);
WinJS.UI._ItemEventsHandler.renderSelection = oldRenderSelection;
}
testElementProperty(complete) {
var element = document.getElementById("host");
var control = new ItemContainer(element);
LiveUnit.Assert.areEqual(WinJS.Utilities._uniqueID(element), WinJS.Utilities._uniqueID(control.element), "Invalid element returned by the control's element property");
complete();
}
testDraggableProperty(complete) {
if (utilities.isPhone) {
complete();
return;
}
var element = document.getElementById("host");
var control = new ItemContainer(element);
LiveUnit.Assert.isFalse(control.draggable, "The control should not be draggable by default");
LiveUnit.Assert.isNull(element.getAttribute("draggable"));
control.draggable = true;
var itemBox = element.querySelector(".win-itembox");
LiveUnit.Assert.areEqual("true", itemBox.getAttribute("draggable"));
complete();
}
testSelectedProperty(complete) {
var element = document.getElementById("host");
var control = new ItemContainer(element);
LiveUnit.Assert.isFalse(control.selected, "The control should not be selected by default");
LiveUnit.Assert.isFalse(utilities.hasClass(element, WinJS.UI._selectedClass));
control.selected = true;
LiveUnit.Assert.isTrue(control.selected, "The control's selected property setter is not working");
verifySelectionVisual(element, true);
complete();
}
testSelectionDisabledProperty(complete) {
var element = document.getElementById("host");
var control = new ItemContainer(element);
LiveUnit.Assert.isFalse(control.selectionDisabled, "The default selectionDisabled should be false");
LiveUnit.Assert.areEqual(control._selectionMode, WinJS.UI.SelectionMode.single);
control.selectionDisabled = true;
LiveUnit.Assert.isTrue(control.selectionDisabled);
LiveUnit.Assert.areEqual(control._selectionMode, WinJS.UI.SelectionMode.none);
complete();
}
testTapBehaviorProperty(complete) {
var element = document.getElementById("host");
var control = new ItemContainer(element);
LiveUnit.Assert.areEqual(WinJS.UI.TapBehavior.invokeOnly, control.tapBehavior, "The control's tabBehavior property should default to invokeOnly");
complete();
}
testInvokedEvent(complete) {
var element = document.getElementById("host");
var control = new ItemContainer(element);
var listener1Called = false;
var listener2Called = false;
control.addEventListener("invoked", function (ev) {
listener1Called = true;
LiveUnit.Assert.areEqual(WinJS.Utilities._uniqueID(element), WinJS.Utilities._uniqueID(ev.target));
});
control.oninvoked = function (ev) {
listener2Called = true;
LiveUnit.Assert.areEqual(WinJS.Utilities._uniqueID(element), WinJS.Utilities._uniqueID(<HTMLElement>ev.target));
};
click(control, { target: element });
LiveUnit.Assert.isTrue(listener1Called);
LiveUnit.Assert.isTrue(listener2Called);
complete();
}
testInvokedEventWithTabBehaviorNone(complete) {
var element = document.getElementById("host");
var control = new ItemContainer(element);
control.tapBehavior = WinJS.UI.TapBehavior.none;
control.addEventListener("invoked", function (ev) {
LiveUnit.Assert.fail("invoked event should not be called when tabBehavior is none");
});
click(control, { target: element });
WinJS.Utilities._setImmediate(complete);
}
testSelectionChangingEventCalled(complete) {
var invoked = false;
var element = document.getElementById("host");
function selectionChanging(ev) {
invoked = true;
LiveUnit.Assert.areEqual(WinJS.Utilities._uniqueID(element), WinJS.Utilities._uniqueID(ev.target));
}
var control = new ItemContainer(element, { onselectionchanging: selectionChanging });
LiveUnit.Assert.isFalse(invoked);
control._onKeyDown(createEvent(element, utilities.Key.space));
LiveUnit.Assert.isTrue(invoked, "Selectionchanging event should have been called");
complete();
}
testSelectionChangingEventPrevented(complete) {
var element = document.getElementById("host");
function selectionChanging(ev) {
ev.preventDefault();
}
var control = new ItemContainer(element, { onselectionchanging: selectionChanging });
control.onselectionchanged = function () {
LiveUnit.Assert.fail("Selectionchanged should not be called because it was prevented on selectionchanging");
};
control._onKeyDown(createEvent(element, utilities.Key.space));
complete();
}
testSelectionChangedEventCalled(complete) {
var invoked = false;
var element = document.getElementById("host");
function selectionChanged(ev) {
invoked = true;
LiveUnit.Assert.areEqual(WinJS.Utilities._uniqueID(element), WinJS.Utilities._uniqueID(ev.target));
}
var control = new ItemContainer(element, { onselectionchanged: selectionChanged });
LiveUnit.Assert.isFalse(invoked);
control._onKeyDown(createEvent(element, utilities.Key.space));
LiveUnit.Assert.isTrue(invoked, "Selectionchanged event should have been called");
complete();
}
testKeyboardFocusBlur(complete) {
var element = document.getElementById("host");
var control = new ItemContainer(element);
WinJS.UI._keyboardSeenLast = false;
LiveUnit.Assert.areEqual(0, element.querySelectorAll("." + WinJS.UI._itemFocusOutlineClass).length);
control._onFocusIn();
LiveUnit.Assert.areEqual(0, element.querySelectorAll("." + WinJS.UI._itemFocusOutlineClass).length);
WinJS.UI._keyboardSeenLast = true;
control._onFocusIn();
LiveUnit.Assert.areEqual(1, element.querySelectorAll("." + WinJS.UI._itemFocusOutlineClass).length);
WinJS.UI._keyboardSeenLast = null;
control._onFocusOut();
LiveUnit.Assert.areEqual(0, element.querySelectorAll("." + WinJS.UI._itemFocusOutlineClass).length);
complete();
}
testTabIndex(complete) {
var element = document.getElementById("host");
var control = new ItemContainer(element);
LiveUnit.Assert.areEqual("0", element.getAttribute("tabindex"), "The control should set tabindex to 0 if a tabindex was not provided");
var element2 = document.createElement("div");
document.body.appendChild(element2);
element2.setAttribute("tabindex", "3");
var control2 = new ItemContainer(element2);
LiveUnit.Assert.areEqual("3", element2.getAttribute("tabindex"), "The control should not set tabindex if one was provided");
element2.parentNode.removeChild(element2);
complete();
}
testItemEventsHandlerIntegration(complete) {
var element = document.getElementById("host");
var control = new ItemContainer(element);
var handler = control._itemEventsHandler;
var site = handler._site;
LiveUnit.Assert.isNotNull(handler);
LiveUnit.Assert.areEqual(site.containerFromElement(null), element);
LiveUnit.Assert.areEqual(site.indexForItemElement(null), 1);
LiveUnit.Assert.areEqual(site.itemBoxAtIndex(0), control._itemBox);
LiveUnit.Assert.areEqual(site.itemAtIndex(0), element);
LiveUnit.Assert.areEqual(site.containerAtIndex(0), element);
LiveUnit.Assert.areEqual(site.selectionMode, WinJS.UI.SelectionMode.single);
LiveUnit.Assert.areEqual(site.tapBehavior, WinJS.UI.TapBehavior.invokeOnly);
control.tapBehavior = WinJS.UI.TapBehavior.toggleSelect;
LiveUnit.Assert.areEqual(site.tapBehavior, WinJS.UI.TapBehavior.toggleSelect);
LiveUnit.Assert.isFalse(site.draggable);
LiveUnit.Assert.isTrue(site.skipPreventDefaultOnPointerDown);
if (!utilities.isPhone) {
control.draggable = true;
LiveUnit.Assert.isTrue(site.draggable);
}
LiveUnit.Assert.isFalse(site.selection.selected);
control.selected = true;
LiveUnit.Assert.isTrue(site.selection.selected);
LiveUnit.Assert.isNull(site.customFootprintParent);
complete();
}
testDispose(complete) {
var element = document.getElementById("host");
var child = document.createElement("div");
WinJS.Utilities.addClass(child, "win-disposable");
element.appendChild(child);
var childDisposed = false;
child.winControl = {
dispose: function () {
childDisposed = true;
}
};
var control = new ItemContainer(element);
LiveUnit.Assert.isFalse(!!control._disposed);
LiveUnit.Assert.isFalse(childDisposed);
control.dispose();
LiveUnit.Assert.isTrue(control._disposed);
LiveUnit.Assert.isTrue(childDisposed);
complete();
}
testForceLayout(complete) {
var element = document.getElementById("host");
var control = new ItemContainer(element);
LiveUnit.Assert.isFalse(utilities.hasClass(element, "win-rtl"));
element.style.direction = "rtl";
control.forceLayout();
LiveUnit.Assert.isTrue(utilities.hasClass(element, "win-rtl"));
complete();
}
testSetupInternalTree(complete) {
var element = document.getElementById("host");
var child1 = document.createElement("div");
child1.className = "child1";
var child2 = document.createElement("div2");
child2.className = "child2";
element.appendChild(child1);
element.appendChild(child2);
var control = new ItemContainer(element);
LiveUnit.Assert.isTrue(element, ItemContainer._ClassName.itemContainer);
LiveUnit.Assert.isTrue(utilities.hasClass(element, WinJS.UI._containerClass));
// The main element should now have two children (the itembox + the captureProxy)
LiveUnit.Assert.areEqual(2, element.children.length);
var itemBox = <HTMLElement>element.children[0];
LiveUnit.Assert.isTrue(utilities.hasClass(itemBox, WinJS.UI._itemBoxClass));
LiveUnit.Assert.areEqual(1, itemBox.children.length);
var itemElement = <HTMLElement>itemBox.children[0];
LiveUnit.Assert.isTrue(itemElement, WinJS.UI._itemClass);
LiveUnit.Assert.areEqual(2, itemElement.children.length);
LiveUnit.Assert.isTrue(utilities.hasClass(<HTMLElement>itemElement.children[0], "child1"));
LiveUnit.Assert.isTrue(utilities.hasClass(<HTMLElement>itemElement.children[1], "child2"));
complete();
}
testSpaceBarSelection(complete) {
var element = document.getElementById("host");
element.textContent = "my item";
var control = new ItemContainer(element);
LiveUnit.Assert.isFalse(control.selected);
control._onKeyDown(createEvent(element, utilities.Key.space));
LiveUnit.Assert.isTrue(control.selected);
control._onKeyDown(createEvent(element, utilities.Key.space));
LiveUnit.Assert.isFalse(control.selected)
complete();
}
testToggleSelect(complete) {
var element = document.getElementById("host");
element.textContent = "my item";
var control = new ItemContainer(element);
control.tapBehavior = WinJS.UI.TapBehavior.toggleSelect;
LiveUnit.Assert.isFalse(control.selected);
click(control, { target: element });
verifySelectionVisual(element, true);
LiveUnit.Assert.isTrue(control.selected);
click(control, { target: element });
verifySelectionVisual(element, false);
complete();
}
testSetAriaRole(complete) {
var control1 = new ItemContainer(document.getElementById("host"));
LiveUnit.Assert.areEqual(control1.element.getAttribute("role"), "option", "By default selection/tap is enabled, so the default role should be option");
var element2 = document.createElement("div");
document.body.appendChild(element2);
var control2 = new ItemContainer(element2, {
tapBehavior: WinJS.UI.TapBehavior.none
});
LiveUnit.Assert.areEqual(control2.element.getAttribute("role"), "option", "By default selection is enabled, so the default role should be option");
element2.parentNode.removeChild(element2);
var element3 = document.createElement("div");
document.body.appendChild(element3);
var control3 = new ItemContainer(element3, {
selectionDisabled: true
});
LiveUnit.Assert.areEqual(control3.element.getAttribute("role"), "option", "By default tap is enabled, so the default role should be option");
element3.parentNode.removeChild(element3);
var element4 = document.createElement("div");
document.body.appendChild(element4);
var control4 = new ItemContainer(element4, {
selectionDisabled: true,
tapBehavior: WinJS.UI.TapBehavior.none
});
LiveUnit.Assert.areEqual(control4.element.getAttribute("role"), "listitem", "Selection and Tap are disabled, the default role should be listitem");
element4.parentNode.removeChild(element4);
var elementWithRole = document.createElement("div");
elementWithRole.setAttribute("role", "listbox");
document.body.appendChild(elementWithRole);
var control5 = new ItemContainer(elementWithRole);
LiveUnit.Assert.areEqual(control5.element.getAttribute("role"), "listbox", "A role was already specified. The control should not change it");
elementWithRole.parentNode.removeChild(elementWithRole);
var element6 = document.createElement("div");
document.body.appendChild(element6);
var control6 = new ItemContainer(element6);
LiveUnit.Assert.areEqual(control6.element.getAttribute("role"), "option", "By default selection/tap is enabled, so the default role should be option");
control6.tapBehavior = WinJS.UI.TapBehavior.none;
LiveUnit.Assert.areEqual(control6.element.getAttribute("role"), "option", "By default selection is enabled, so the default role should be option");
control6.selectionDisabled = true;
LiveUnit.Assert.areEqual(control6.element.getAttribute("role"), "listitem", "Selection is disabled and TapBehavior is none, the default role should be listitem");
element6.parentNode.removeChild(element6);
complete();
}
testUIASelect(complete) {
function blockSelection(eventObject) {
eventObject.preventDefault();
}
function test() {
var prevSelection;
function verifySelection(expectedSelection) {
prevSelection = expectedSelection;
LiveUnit.Assert.areEqual(expectedSelection, itemContainer.selected, "ItemContainer should be selected");
LiveUnit.Assert.areEqual(expectedSelection, WinJS.Utilities.hasClass(itemContainer.element, WinJS.UI._selectedClass), "ItemContainer selected class is in the wrong state");
LiveUnit.Assert.areEqual(expectedSelection, itemContainer.element.getAttribute("aria-selected") === "true", "ItemContainer aria-selected is incorrect");
}
var itemContainer = new ItemContainer(document.getElementById("host"));
return WinJS.Promise.timeout().then(function () {
// Simulate UIA SelectionItem.Select changes
verifySelection(false);
itemContainer.element.setAttribute("aria-selected", "false");
return WinJS.Promise.timeout();
}).then(function () {
verifySelection(false);
itemContainer.element.setAttribute("aria-selected", "true");
return WinJS.Promise.timeout();
}).then(function () {
verifySelection(true);
itemContainer.element.setAttribute("aria-selected", "false");
return WinJS.Promise.timeout();
}).then(function () {
verifySelection(false);
itemContainer.selected = true;
return WinJS.Promise.timeout();
}).then(function () {
// Simulate UIA SelectionItem.Select with blocked selection
itemContainer.addEventListener("selectionchanging", blockSelection, false);
itemContainer.element.setAttribute("aria-selected", "false");
return WinJS.Promise.timeout();
}).then(function () {
verifySelection(true);
itemContainer.removeEventListener("selectionchanging", blockSelection, false);
itemContainer.selected = false;
return WinJS.Promise.timeout();
}).then(function () {
// Simulate UIA SelectionItem.Select on item with selectionDisabled = true
itemContainer.selectionDisabled = true;
itemContainer.element.setAttribute("aria-selected", "true");
return WinJS.Promise.timeout();
}).then(function () {
verifySelection(false);
});
}
test().done(complete);
}
};
}
LiveUnit.registerTestClass("WinJSTests.ItemContainerTests"); | the_stack |
import { ChainStore } from "./chain";
import { EmbedChainInfos } from "../config";
import {
AmplitudeApiKey,
EthereumEndpoint,
FiatCurrencies,
} from "../config.ui";
import {
AccountStore,
ChainSuggestStore,
CoinGeckoPriceStore,
CosmosAccount,
CosmosQueries,
CosmwasmAccount,
CosmwasmQueries,
getKeplrFromWindow,
IBCChannelStore,
IBCCurrencyRegsitrar,
InteractionStore,
KeyRingStore,
LedgerInitStore,
PermissionStore,
QueriesStore,
SecretAccount,
SecretQueries,
SignInteractionStore,
TokensStore,
WalletStatus,
} from "@keplr-wallet/stores";
import {
KeplrETCQueries,
GravityBridgeCurrencyRegsitrar,
} from "@keplr-wallet/stores-etc";
import { ExtensionKVStore } from "@keplr-wallet/common";
import {
ContentScriptEnv,
ContentScriptGuards,
ExtensionRouter,
InExtensionMessageRequester,
} from "@keplr-wallet/router-extension";
import { APP_PORT } from "@keplr-wallet/router";
import { ChainInfoWithEmbed } from "@keplr-wallet/background";
import { FiatCurrency } from "@keplr-wallet/types";
import { UIConfigStore } from "./ui-config";
import { FeeType } from "@keplr-wallet/hooks";
import { AnalyticsStore, NoopAnalyticsClient } from "@keplr-wallet/analytics";
import Amplitude from "amplitude-js";
import { ChainIdHelper } from "@keplr-wallet/cosmos";
export class RootStore {
public readonly uiConfigStore: UIConfigStore;
public readonly chainStore: ChainStore;
public readonly keyRingStore: KeyRingStore;
public readonly ibcChannelStore: IBCChannelStore;
protected readonly interactionStore: InteractionStore;
public readonly permissionStore: PermissionStore;
public readonly signInteractionStore: SignInteractionStore;
public readonly ledgerInitStore: LedgerInitStore;
public readonly chainSuggestStore: ChainSuggestStore;
public readonly queriesStore: QueriesStore<
[CosmosQueries, CosmwasmQueries, SecretQueries, KeplrETCQueries]
>;
public readonly accountStore: AccountStore<
[CosmosAccount, CosmwasmAccount, SecretAccount]
>;
public readonly priceStore: CoinGeckoPriceStore;
public readonly tokensStore: TokensStore<ChainInfoWithEmbed>;
protected readonly ibcCurrencyRegistrar: IBCCurrencyRegsitrar<ChainInfoWithEmbed>;
protected readonly gravityBridgeCurrencyRegistrar: GravityBridgeCurrencyRegsitrar<ChainInfoWithEmbed>;
public readonly analyticsStore: AnalyticsStore<
{
chainId?: string;
chainName?: string;
toChainId?: string;
toChainName?: string;
registerType?: "seed" | "google" | "ledger" | "qr";
feeType?: FeeType | undefined;
isIbc?: boolean;
rpc?: string;
rest?: string;
},
{
registerType?: "seed" | "google" | "ledger" | "qr";
accountType?: "mnemonic" | "privateKey" | "ledger";
currency?: string;
language?: string;
}
>;
constructor() {
this.uiConfigStore = new UIConfigStore(
new ExtensionKVStore("store_ui_config")
);
const router = new ExtensionRouter(ContentScriptEnv.produceEnv);
router.addGuard(ContentScriptGuards.checkMessageIsInternal);
// Order is important.
this.interactionStore = new InteractionStore(
router,
new InExtensionMessageRequester()
);
this.chainStore = new ChainStore(
EmbedChainInfos,
new InExtensionMessageRequester()
);
this.keyRingStore = new KeyRingStore(
{
dispatchEvent: (type: string) => {
window.dispatchEvent(new Event(type));
},
},
"scrypt",
this.chainStore,
new InExtensionMessageRequester(),
this.interactionStore
);
this.ibcChannelStore = new IBCChannelStore(
new ExtensionKVStore("store_ibc_channel")
);
this.permissionStore = new PermissionStore(
this.interactionStore,
new InExtensionMessageRequester()
);
this.signInteractionStore = new SignInteractionStore(this.interactionStore);
this.ledgerInitStore = new LedgerInitStore(
this.interactionStore,
new InExtensionMessageRequester()
);
this.chainSuggestStore = new ChainSuggestStore(this.interactionStore);
this.queriesStore = new QueriesStore(
new ExtensionKVStore("store_queries"),
this.chainStore,
CosmosQueries.use(),
CosmwasmQueries.use(),
SecretQueries.use({
apiGetter: getKeplrFromWindow,
}),
KeplrETCQueries.use({
ethereumURL: EthereumEndpoint,
})
);
this.accountStore = new AccountStore(
window,
this.chainStore,
() => {
return {
suggestChain: false,
autoInit: true,
getKeplr: getKeplrFromWindow,
};
},
CosmosAccount.use({
queriesStore: this.queriesStore,
msgOptsCreator: (chainId) => {
// In certik, change the msg type of the MsgSend to "bank/MsgSend"
if (chainId.startsWith("shentu-")) {
return {
send: {
native: {
type: "bank/MsgSend",
},
},
};
}
// In akash or sifchain, increase the default gas for sending
if (
chainId.startsWith("akashnet-") ||
chainId.startsWith("sifchain")
) {
return {
send: {
native: {
gas: 120000,
},
},
};
}
if (chainId.startsWith("secret-")) {
return {
send: {
native: {
gas: 20000,
},
},
withdrawRewards: {
gas: 25000,
},
};
}
// For terra related chains
if (
chainId.startsWith("bombay-") ||
chainId.startsWith("columbus-")
) {
return {
send: {
native: {
type: "bank/MsgSend",
},
},
};
}
if (chainId.startsWith("evmos_")) {
return {
send: {
native: {
gas: 140000,
},
},
withdrawRewards: {
gas: 200000,
},
};
}
if (chainId.startsWith("osmosis")) {
return {
send: {
native: {
gas: 100000,
},
},
withdrawRewards: {
gas: 300000,
},
};
}
if (chainId.startsWith("stargaze-")) {
return {
send: {
native: {
gas: 100000,
},
},
withdrawRewards: {
gas: 200000,
},
};
}
},
}),
CosmwasmAccount.use({
queriesStore: this.queriesStore,
}),
SecretAccount.use({
queriesStore: this.queriesStore,
msgOptsCreator: (chainId) => {
if (chainId.startsWith("secret-")) {
return {
send: {
secret20: {
gas: 50000,
},
},
createSecret20ViewingKey: {
gas: 50000,
},
};
}
},
})
);
if (!window.location.href.includes("#/unlock")) {
// Start init for registered chains so that users can see account address more quickly.
for (const chainInfo of this.chainStore.chainInfos) {
const account = this.accountStore.getAccount(chainInfo.chainId);
// Because {autoInit: true} is given as the default option above,
// initialization for the account starts at this time just by using getAccount().
// However, run safe check on current status and init if status is not inited.
if (account.walletStatus === WalletStatus.NotInit) {
account.init();
}
}
} else {
// When the unlock request sent from external webpage,
// it will open the extension popup below the uri "/unlock".
// But, in this case, if the prefetching option is true, it will redirect
// the page to the "/unlock" with **interactionInternal=true**
// because prefetching will request the unlock from the internal.
// To prevent this problem, just check the first uri is "#/unlcok" and
// if it is "#/unlock", don't use the prefetching option.
}
this.priceStore = new CoinGeckoPriceStore(
new ExtensionKVStore("store_prices"),
FiatCurrencies.reduce<{
[vsCurrency: string]: FiatCurrency;
}>((obj, fiat) => {
obj[fiat.currency] = fiat;
return obj;
}, {}),
"usd"
);
this.tokensStore = new TokensStore(
window,
this.chainStore,
new InExtensionMessageRequester(),
this.interactionStore
);
this.ibcCurrencyRegistrar = new IBCCurrencyRegsitrar<ChainInfoWithEmbed>(
new ExtensionKVStore("store_ibc_curreny_registrar"),
24 * 3600 * 1000,
this.chainStore,
this.accountStore,
this.queriesStore,
this.queriesStore
);
this.gravityBridgeCurrencyRegistrar = new GravityBridgeCurrencyRegsitrar<ChainInfoWithEmbed>(
new ExtensionKVStore("store_gravity_bridge_currency_registrar"),
this.chainStore,
this.queriesStore
);
this.analyticsStore = new AnalyticsStore(
(() => {
if (!AmplitudeApiKey) {
return new NoopAnalyticsClient();
} else {
const amplitudeClient = Amplitude.getInstance();
amplitudeClient.init(AmplitudeApiKey, undefined, {
saveEvents: true,
platform: "Extension",
});
return amplitudeClient;
}
})(),
{
logEvent: (eventName, eventProperties) => {
if (eventProperties?.chainId || eventProperties?.toChainId) {
eventProperties = {
...eventProperties,
};
if (eventProperties.chainId) {
eventProperties.chainId = ChainIdHelper.parse(
eventProperties.chainId
).identifier;
}
if (eventProperties.toChainId) {
eventProperties.toChainId = ChainIdHelper.parse(
eventProperties.toChainId
).identifier;
}
}
return {
eventName,
eventProperties,
};
},
}
);
router.listen(APP_PORT);
}
}
export function createRootStore() {
return new RootStore();
} | the_stack |
import {toQueryPath} from '../binding';
export interface Expression<T> {
/**
* @return true if the given object is a literal expression.
*/
isConstant(): boolean;
/**
* @return true if the given object is a path expression.
*/
isPath(): boolean;
}
export interface ExpressionAccessor {
setExpression(expression: Expression<any>);
}
/**
* Refers to a property of an object.
*/
export interface Path<T> extends Expression<T> {
/**
* @return string representation of this expression.
*/
toString(): string;
/**
* @return the value of this path if it is bound to an data object (see {@link BeanBinding}.
*/
getValue(): any;
/**
* Sets a new value for the given path.
*
* @param newValue
*/
setValue(value: any);
/**
* @return name to use for forFormElement elements to uniquely identity this path. This current corresponds
* to toString, will later be extended to include resource$ identifiers to support complex forFormElement with
* multiple editors (TODO).
*/
toFormName(): string;
/**
* Underlying resource holding the values.
*
* @returns {any}
*/
getResource(): any;
/**
* Pointer of this path from the resource.
*/
getSourcePointer(): String;
/**
* @returns {string} path used for sorting and filtering (excludes any 'relationships' and 'attributes' in the path)
*/
toQueryPath(): string;
}
export const OPERATION_EQ = 'EQ';
export const OPERATION_NEQ = 'NEQ';
export const OPERATION_LIKE = 'LIKE';
export const OPERATION_GT = 'GT';
export const OPERATION_LT = 'LT';
export const OPERATION_GE = 'GE';
export const OPERATION_LE = 'LE';
/**
* Base implementation for a {@link Expression} providing a EQ and NEQ operation.
*/
export class SimpleExpression<T> implements Expression<T> {
public eq(right: T): BooleanExpression {
return new BooleanOperation(OPERATION_EQ, this, ExpressionFactory.toLiteral(right));
}
public neq(right: T): BooleanExpression {
return new BooleanOperation(OPERATION_NEQ, this, ExpressionFactory.toLiteral(right));
}
isConstant(): boolean {
return false;
}
isPath(): boolean {
return false;
}
}
/**
* Base implementation for a {@link Expression} providing equals and compare operations.
*/
export abstract class ComparableExpression<T> extends SimpleExpression<T> {
public lt(right: T): BooleanExpression {
return new BooleanOperation(OPERATION_LT.toString(), this, ExpressionFactory.toLiteral(right));
}
public le(right: T): BooleanExpression {
return new BooleanOperation(OPERATION_LE.toString(), this, ExpressionFactory.toLiteral(right));
}
public gt(right: T): BooleanExpression {
return new BooleanOperation(OPERATION_GT.toString(), this, ExpressionFactory.toLiteral(right));
}
public ge(right: T): BooleanExpression {
return new BooleanOperation(OPERATION_GE.toString(), this, ExpressionFactory.toLiteral(right));
}
}
/**
* Base implementation for {@link Expression} bound to a string.
*/
export abstract class StringExpression extends ComparableExpression<string> {
public like(right: string): BooleanExpression {
return new BooleanOperation(OPERATION_LIKE.toString(), this, new StringConstant(right));
}
}
/**
* Base implementation for {@link Expression} bound to a number.
*/
export abstract class NumberExpression extends ComparableExpression<number> {
}
/**
* Base implementation for {@link Expression} bound to a boolean.
*/
export abstract class BooleanExpression extends ComparableExpression<boolean> {
}
/**
* Represents a boolean operation comparing two expressions with the provided operation.
*/
export class BooleanOperation extends BooleanExpression {
public operation: string;
public expressions: Expression<any>[];
public constructor(operation: string, left: Expression<any>, right: Expression<any>) {
super();
this.operation = operation;
this.expressions = [left, right];
}
}
/**
* Helper methods to create expressions.
*/
export class ExpressionFactory {
public static toBeanPath<T>(object: any, attributeNames: Array<string>): BeanPath<any> {
let path: BeanPath<any> = new BeanBinding(object);
for (const attributeName of attributeNames) {
path = new BeanPath(path, attributeName);
}
return path;
}
public static toLiteral<T>(value: any): Constant<T> {
if (typeof value === 'string') {
return new StringConstant(value as string) as Constant<any>;
}
else if (typeof value === 'number') {
return new NumberConstant(value as number) as Constant<any>;
}
else if (typeof value === 'boolean') {
return new BooleanConstant(value as boolean) as Constant<any>;
}
else {
throw Error('unknown type for value ' + value);
}
}
static concat(parent: Expression<any>, value1: string) {
const value0 = parent != null ? parent.toString() : null;
if (value0) {
if (parent instanceof MapPath || parent instanceof ArrayPath) {
return value0 + '[' + value1 + ']';
} else {
return value0 + '.' + value1;
}
}
if (value1) {
return value1;
}
return null;
}
}
/**
* Represents a constant expression.
*/
export interface Constant<T> extends Expression<T> {
value: T;
}
export class BooleanConstant extends BooleanExpression implements Constant<boolean> {
value: boolean;
constructor(value: boolean) {
super();
this.value = value;
}
isConstant(): boolean {
return true;
}
toString(): string {
return this.value.toString();
}
}
function toSourcePointerInternal(path: string, resource: any) {
if (resource !== null) {
return '/data/' + path.replace(new RegExp('\\.', 'g'), '/');
}
else {
throw new Error('resource not available for ' + path.toString());
}
}
function toFormNameInternal(path: Path<any>, resource: any) {
if (resource !== null) {
return '//' + resource.type + '//' + resource.id + '//' + path.toString();
}
else {
throw new Error('resource not available for ' + path.toString());
}
}
export class NumberConstant extends NumberExpression implements Constant<number> {
value: number;
constructor(literal: number) {
super();
this.value = literal;
}
isConstant(): boolean {
return true;
}
toString(): string {
return this.value.toString();
}
}
export class StringConstant extends StringExpression implements Constant<string> {
value: string;
constructor(value: string) {
super();
this.value = value;
}
isConstant(): boolean {
return true;
}
toString(): string {
return this.value;
}
}
/**
* Represents a path accessing a object property.
*/
export class BeanPath<T> extends SimpleExpression<T> implements Path<T> {
constructor(public parentPath: BeanPath<any>, private property?: string) {
super();
}
protected add<P extends Path<any>>(path: P): P {
return path;
}
protected createString(property: string): StringPath {
return this.add(new StringPath(this, property));
}
protected createBoolean(property: string): BooleanPath {
return this.add(new BooleanPath(this, property));
}
protected createNumber(property: string): NumberPath {
return this.add(new NumberPath(this, property));
}
toString(): string {
if (this.parentPath) {
if (this.parentPath !== null) {
return ExpressionFactory.concat(this.parentPath, this.property);
}
}
return this.property;
}
isPath(): boolean {
return true;
}
getValue() {
return doGetValue(this.parentPath, this.property);
}
setValue(newValue) {
return doSetValue(this.parentPath, this.property, newValue);
}
getResource() {
return this.parentPath.getResource();
}
toFormName(): string {
return toFormNameInternal(this, this.parentPath.getResource());
}
getSourcePointer(): string {
return toSourcePointerInternal(this.toString(), this.parentPath.getResource());
}
toQueryPath(): string {
return toQueryPath(this.toString());
}
}
/**
* Represents a path accessing a string property.
*/
export class StringPath extends StringExpression implements Path<string> {
private parent: BeanPath<any>;
private property: string;
constructor(parent: BeanPath<any>, property: string) {
super();
this.parent = parent;
this.property = property;
}
toString(): string {
return ExpressionFactory.concat(this.parent, this.property);
}
isPath(): boolean {
return true;
}
getValue() {
return doGetValue(this.parent, this.property);
}
setValue(newValue) {
return doSetValue(this.parent, this.property, newValue);
}
toFormName(): string {
return toFormNameInternal(this, this.parent.getResource());
}
getResource() {
return this.parent.getResource();
}
getSourcePointer(): string {
return toSourcePointerInternal(this.toString(), this.parent.getResource());
}
toQueryPath(): string {
return toQueryPath(this.toString());
}
}
export class ArrayPath<Q extends Expression<T>, T> extends SimpleExpression<Array<T>> implements Path<Array<T>> {
constructor(private parent: BeanPath<any>, private property: string, private _referenceType: new (...args: any[]) => Q) {
super();
}
public getElement(index: number): Q {
return new this._referenceType(this, index);
}
toString(): string {
return ExpressionFactory.concat(this.parent, this.property);
}
isPath(): boolean {
return true;
}
isConstant(): boolean {
return false;
}
getValue() {
return doGetValue(this.parent, this.property);
}
setValue(newValue) {
return doSetValue(this.parent, this.property, newValue);
}
toFormName(): string {
return toFormNameInternal(this as Path<any>, this.parent.getResource());
}
getResource() {
return this.parent.getResource();
}
getSourcePointer(): string {
return toSourcePointerInternal(this.toString(), this.parent.getResource());
}
toQueryPath(): string {
return toQueryPath(this.toString());
}
}
export class MapPath<Q extends Expression<T>, T> extends SimpleExpression<Array<T>> implements Path<Array<T>> {
constructor(private parent: BeanPath<any>, private property: string, private _referenceType: new (...args: any[]) => Q) {
super();
}
public getElement(key: any): Q {
return new this._referenceType(this, key);
}
toString(): string {
return ExpressionFactory.concat(this.parent, this.property);
}
isPath(): boolean {
return true;
}
isConstant(): boolean {
return false;
}
getValue() {
return doGetValue(this.parent, this.property);
}
setValue(newValue) {
return doSetValue(this.parent, this.property, newValue);
}
toFormName(): string {
return toFormNameInternal(this as Path<any>, this.parent.getResource());
}
getResource() {
return this.parent.getResource();
}
getSourcePointer(): string {
return toSourcePointerInternal(this.toString(), this.parent.getResource());
}
toQueryPath(): string {
return toQueryPath(this.toString());
}
}
function doGetValue(parent: Path<any>, property: string) {
const parentValue = parent.getValue();
// consider to eliminate this case, root between binding and path
if (!property) {
return parentValue;
}
if (parentValue != null) {
return parentValue[property];
}
else {
return null;
}
}
function doSetValue(parent: Path<any>, property: string, newValue) {
const parentValue = parent.getValue();
if (parentValue === null) {
throw new Error(); // TODO setup map in parent
}
if (!property) {
return new Error();
}
parentValue[property] = newValue;
}
/**
* Represents a path accessing a number property.
*/
export class NumberPath extends NumberExpression implements Path<number> {
private parent: BeanPath<any>;
private property: string;
constructor(parent: BeanPath<any>, property: string) {
super();
this.parent = parent;
this.property = property;
}
toString(): string {
return ExpressionFactory.concat(this.parent, this.property);
}
isPath(): boolean {
return true;
}
getValue() {
return doGetValue(this.parent, this.property);
}
setValue(newValue) {
return doSetValue(this.parent, this.property, newValue);
}
toFormName(): string {
return toFormNameInternal(this, this.parent.getResource());
}
getResource() {
return this.parent.getResource();
}
getSourcePointer(): string {
return toSourcePointerInternal(this.toString(), this.parent.getResource());
}
toQueryPath(): string {
return toQueryPath(this.toString());
}
}
/**
* Represents a path accessing a boolean property.
*/
export class BooleanPath extends BooleanExpression implements Path<boolean> {
private parent: BeanPath<any>;
private property: string;
constructor(parent: BeanPath<any>, property: string) {
super();
this.parent = parent;
this.property = property;
}
toString(): string {
return ExpressionFactory.concat(this.parent, this.property);
}
isPath(): boolean {
return true;
}
getValue() {
return doGetValue(this.parent, this.property);
}
setValue(newValue) {
return doSetValue(this.parent, this.property, newValue);
}
toFormName(): string {
return toFormNameInternal(this, this.parent.getResource());
}
getResource() {
return this.parent.getResource();
}
getSourcePointer(): string {
return toSourcePointerInternal(this.toString(), this.parent.getResource());
}
toQueryPath(): string {
return toQueryPath(this.toString());
}
}
/**
* Represents a direct refresh to object. Sits at the root of an expression chain.
*/
export class BeanBinding extends BeanPath<any> {
constructor(public bean: any) {
super(null, null);
}
toString(): string {
return null;
}
getValue() {
return this.bean;
}
setValue(value: any) {
this.bean = value;
}
getResource() {
return this.bean;
}
} | the_stack |
import * as React from 'react';
import classNames from 'classnames';
export interface PickerProps {
prefixCls:string;
className?:string;
style?:any;
selectedValue?:[];
defaultSelectedValue?:[];
onScrollChange?:(value:any) => void;
onValueChange?:(value:any) => void;
children:React.ReactNode;
noAnimate?:boolean;
disabled:boolean;
indicatorStyle?:React.CSSProperties;
itemStyle?:React.CSSProperties;
}
const Item: React.FunctionComponent<ItemProps> = () => null;
export interface ItemProps {
className?: string;
value?: any;
};
class Picker extends React.Component<PickerProps,any> {
static Item=Item;
static defaultProps = {
prefixCls: 'Yep-picker',
disabled:false,
};
scrollHandlers = (() => {
let scrollY = -1;
let lastY = 0;
let startY = 0;
let scrollDisabled = false;
let isMoving = false;
const setTransform = (nodeStyle:any, value:any) => {
nodeStyle.transform = value;
nodeStyle.WebkitTransform = value;
};
const setTransition = (nodeStyle:any, value:any) => {
nodeStyle.transition = value;
nodeStyle.WebkitTransition = value;
};
const scrollTo = (_x:number, y:number, time = 0.3) => {
if (scrollY !== y) {
scrollY = y;
if (time) {
setTransition(this.contentRef.style, `cubic-bezier(0,0,0.2,1.15) ${time}s`);
}
setTransform(this.contentRef.style, `translate3d(0,${-y}px,0)`);
setTimeout(() => {
this.scrollingComplete();
if (this.contentRef) {
setTransition(this.contentRef.style, '');
}
}, +time * 1000);
}
};
//速度计
const Velocity = ((minInterval = 30, maxInterval = 100) => {
let _time = 0;
let _y = 0;
let _velocity = 0;
const recorder = {
record: (y:number) => {
const now = +new Date();
_velocity = (y - _y) / (now - _time);
if (now - _time >= minInterval) {
_velocity = now - _time <= maxInterval ? _velocity : 0;
_y = y;
_time = now;
}
},
getVelocity: (y:number) => {
if (y !== _y) {
recorder.record(y);
}
return _velocity;
},
};
return recorder;
})();
const onStart = (y:number) => {
if (scrollDisabled) {
return;
}
isMoving = true;
startY = y;
lastY = scrollY;
};
const onMove = (y:number) => {
if (scrollDisabled || !isMoving) {
return;
}
scrollY = lastY - y + startY;
Velocity.record(y);
this.onScrollChange();
setTransform(this.contentRef.style, `translate3d(0,${-scrollY}px,0)`);
};
const onFinish = () => {
isMoving = false;
let targetY = scrollY;
const height = (React.Children.count(this.props.children) - 1) * this.itemHeight;
let time = 0.3;
//const velocity = Velocity.getVelocity(targetY) * 4;
//if (velocity) {
//targetY = velocity * 40 + targetY;
//time = Math.abs(velocity) * .1;
//}
if (targetY % this.itemHeight !== 0) {
targetY = Math.round(targetY / this.itemHeight) * this.itemHeight;
}
if (targetY < 0) {
targetY = 0;
} else if (targetY > height) {
targetY = height;
}
scrollTo(0, targetY, time < 0.3 ? 0.3 : time);
this.onScrollChange();
};
return {
touchstart: (evt:any) => onStart(evt.touches[0].screenY),
mousedown: (evt:any) => onStart(evt.screenY),
touchmove: (evt:any) => {
evt.preventDefault();
onMove(evt.touches[0].screenY);
},
mousemove: (evt:any) => {
evt.preventDefault();
onMove(evt.screenY);
},
touchend: () => onFinish(),
touchcancel: () => onFinish(),
mouseup: () => onFinish(),
getValue: () => {
return scrollY;
},
scrollTo: scrollTo,
setDisabled: (disabled:boolean) => {
scrollDisabled = disabled;
},
};
})();
constructor(props:PickerProps) {
super(props);
this.createRootRef = this.createRootRef.bind(this);
this.createMaskRef = this.createMaskRef.bind(this);
this.createIndicatorRef = this.createIndicatorRef.bind(this);
this.createContentRef = this.createContentRef.bind(this);
this.passiveSupported = this.passiveSupported.bind(this);
this.onScrollChange = this.onScrollChange.bind(this);
this.scrollingComplete = this.scrollingComplete.bind(this);
this.fireValueChange = this.fireValueChange.bind(this);
this.scrollTo = this.scrollTo.bind(this);
this.scrollToWithoutAnimation = this.scrollToWithoutAnimation.bind(this);
this.select = this.select.bind(this);
this.selectByIndex = this.selectByIndex.bind(this);
this.doScrollingComplete = this.doScrollingComplete.bind(this);
this.computeChildIndex = this.computeChildIndex.bind(this);
let selectedValueState;
const {selectedValue, defaultSelectedValue} = props;
if (selectedValue !== undefined) {
selectedValueState = selectedValue;
} else if (defaultSelectedValue !== undefined) {
selectedValueState = defaultSelectedValue;
} else {
const children = React.Children.toArray(this.props.children);
// @ts-ignore
selectedValueState = children && children[0] && children[0].props.value;
}
this.state = {
selectedValue: selectedValueState,
};
}
itemHeight:number;
scrollValue:number;
rootRef:HTMLDivElement;
contentRef:HTMLDivElement;
maskRef:HTMLDivElement;
indicatorRef:HTMLDivElement;
createRootRef(el:HTMLDivElement) {
this.rootRef = el;
}
createMaskRef(el:HTMLDivElement) {
this.maskRef = el;
}
createIndicatorRef(el:HTMLDivElement) {
this.indicatorRef = el;
}
createContentRef(el:HTMLDivElement) {
this.contentRef = el;
}
passiveSupported() {
let passiveSupported = false;
try {
const options = Object.defineProperty({}, 'passive', {
get: () => {
passiveSupported = true;
},
});
window.addEventListener('test', () => {}, options);
} catch (err) {}
return passiveSupported;
}
onScrollChange() {
const {children, onScrollChange } = this.props;
const top = this.scrollHandlers.getValue();
if (top >= 0) {
const index = this.computeChildIndex(top, this.itemHeight, React.Children.count(children));
if (this.scrollValue !== index) {
this.scrollValue = index;
// @ts-ignore
const child = children[index];
if (child && onScrollChange) {
onScrollChange(child.props.value);
} else if (!child && console.warn) {
console.warn('child not found', children, index);
}
}
}
}
fireValueChange(selectedValue:any) {
if (selectedValue !== this.state.selectedValue) {
if (!('selectedValue' in this.props)) {
this.setState({
selectedValue,
});
}
if (this.props.onValueChange) {
this.props.onValueChange(selectedValue);
}
}
}
scrollingComplete() {
const top = this.scrollHandlers.getValue();
if (top >= 0) {
this.doScrollingComplete(top, this.itemHeight, this.fireValueChange);
}
}
scrollTo(top:number) {
this.scrollHandlers.scrollTo(0, top);
}
scrollToWithoutAnimation(top:number) {
this.scrollHandlers.scrollTo(0, top, 0);
}
componentDidMount() {
const {rootRef, maskRef, indicatorRef, contentRef} = this;
const rootHeight = rootRef.getBoundingClientRect().height;
const itemHeight = (this.itemHeight = indicatorRef.getBoundingClientRect().height);
let itemNum = Math.floor(rootHeight / itemHeight);
if (itemNum % 2 === 0) {
itemNum--;
}
itemNum--;
itemNum /= 2;
contentRef.style.padding = `${itemHeight * itemNum}px 0`;
indicatorRef.style.top = `${itemHeight * itemNum}px`;
maskRef.style.backgroundSize = `100% ${itemHeight * itemNum}px`;
this.scrollHandlers.setDisabled(this.props.disabled);
this.select(this.state.selectedValue, this.itemHeight, this.scrollTo);
const passiveSupported = this.passiveSupported();
const willPreventDefault = passiveSupported ? {passive: false} : false;
const willNotPreventDefault = passiveSupported ? {passive: true} : false;
Object.keys(this.scrollHandlers).forEach(key => {
if (key.indexOf('touch') === 0 || key.indexOf('mouse') === 0) {
const pd = key.indexOf('move') >= 0 ? willPreventDefault : willNotPreventDefault;
// @ts-ignore
rootRef.addEventListener(key, this.scrollHandlers[key], pd);
}
});
}
componentWillReceiveProps(nextProps:PickerProps) {
if ('selectedValue' in nextProps) {
if (this.state.selectedValue !== nextProps.selectedValue) {
this.setState(
{
selectedValue: nextProps.selectedValue,
},
() => {
this.select(
nextProps.selectedValue,
this.itemHeight,
nextProps.noAnimate ? this.scrollToWithoutAnimation : this.scrollTo,
);
},
);
}
}
this.scrollHandlers.setDisabled(nextProps.disabled);
}
shouldComponentUpdate(nextProps:PickerProps, nextState:any) {
return this.state.selectedValue !== nextState.selectedValue || this.props.children !== nextProps.children;
}
componentDidUpdate() {
this.select(this.state.selectedValue, this.itemHeight, this.scrollToWithoutAnimation);
}
componentWillUnmount() {
Object.keys(this.scrollHandlers).forEach(key => {
if (key.indexOf('touch') === 0 || key.indexOf('mouse') === 0) {
// @ts-ignore
this.rootRef.removeEventListener(key, this.scrollHandlers[key]);
}
});
}
select(value:any, itemHeight:number, scrollTo:any) {
const children = React.Children.toArray(this.props.children);
for (let i = 0, len = children.length; i < len; i++) {
// @ts-ignore
if (children[i].props.value === value) {
this.selectByIndex(i, itemHeight, scrollTo);
return;
}
}
this.selectByIndex(0, itemHeight, scrollTo);
}
selectByIndex(index:number, itemHeight:number, zscrollTo:any) {
if (index < 0 || index >=React.Children.count(this.props.children) || !itemHeight) {
return;
}
zscrollTo(index * itemHeight);
}
computeChildIndex(top:number, itemHeight:number, childrenLength:number) {
let index = top / itemHeight;
const floor = Math.floor(index);
if (index - floor > 0.5) {
index = floor + 1;
} else {
index = floor;
}
return Math.min(index, childrenLength - 1);
}
doScrollingComplete(top:number, itemHeight:number, fireValueChange:any) {
const children = React.Children.toArray(this.props.children);
const index = this.computeChildIndex(top, itemHeight, children.length);
const child: any = children[index];
if (child) {
fireValueChange(child.props.value);
} else if (console.warn) {
console.warn('child not found', child, index);
}
}
render() {
const {className, prefixCls, style, indicatorStyle, itemStyle, children} = this.props;
const cls = classNames(prefixCls, {
// @ts-ignore
[className]: !!className,
});
const map = (item: any) => {
const {className = '', style, value} = item.props;
return (
<div
style={{...itemStyle, ...style}}
key={value}
className={classNames(`${prefixCls}-item`, className, {
[`${prefixCls}-item-selected`]: value === this.state.selectedValue,
})}
>
{item.children || item.props.children}
</div>
);
};
// @ts-ignore
const items = React.Children ? React.Children.map(children, map) : [].concat(children).map(map);
return (
<div className={cls} style={style} ref={this.createRootRef}>
<div className={`${prefixCls}-mask`} ref={this.createMaskRef} />
<div className={`${prefixCls}-indicator`} style={indicatorStyle} ref={this.createIndicatorRef} />
<div className={`${prefixCls}-content`} ref={this.createContentRef}>
{items}
</div>
</div>
);
}
}
export default Picker; | the_stack |
import {
AnnotationMotivation,
ExternalResourceType,
} from "@iiif/vocabulary/dist-commonjs/";
import { basename, dirname, extname, join } from "path";
import { Directory } from "./Directory";
import { IConfigJSON } from "./IConfigJSON";
import { promise as glob } from "glob-promise";
import {
cloneJson,
compare,
fileExists,
formatMetadata,
generateImageTiles,
getFileDimensions,
getFormatByExtension,
getFormatByExtensionAndType,
getFormatByType,
getLabel,
getThumbnail,
getTypeByExtension,
getTypeByFormat,
isDirectory,
isURL,
log,
normaliseFilePath,
normaliseType,
readYml,
warn,
} from "./Utils";
import annotationBoilerplate from "./boilerplate/annotation.json";
import config from "./config.json";
import imageServiceBoilerplate from "./boilerplate/imageservice.json";
import urljoin from "url-join";
export class Canvas {
public canvasJson: any;
public directory: Directory;
public parentDirectory: Directory;
public filePath: string;
public directoryFilePath: string;
public infoYml: any = {};
public url: URL;
private _config: IConfigJSON = config;
constructor(filePath: string, parentDirectory: Directory) {
this.filePath = filePath;
if (!isDirectory(this.filePath)) {
this.directoryFilePath = dirname(this.filePath);
} else {
this.directoryFilePath = this.filePath;
}
this.parentDirectory = parentDirectory;
// we only need a directory object to reference the parent directory when determining the virtual path of this canvas
// this.directory.read() is never called.
this.directory = new Directory(
this.directoryFilePath,
this.parentDirectory.url.href,
undefined,
this.parentDirectory
);
this.url = parentDirectory.url;
}
private _isCanvasDirectory(): boolean {
return basename(this.directoryFilePath).startsWith("_");
}
public async read(canvasJson: any): Promise<void> {
if (this.directory.parentDirectory.isManifest) {
this.directory.isCanvas = true;
} else {
// there's no parent manifest directory, so this must be a manifest directory
this.directory.isManifest = true;
}
this.canvasJson = canvasJson;
await this._getInfo();
this._applyInfo();
// if the directoryPath starts with an underscore
if (this._isCanvasDirectory()) {
// first, determine if there are any custom annotations (files ending in .yml that aren't info.yml)
// if there are, loop through them creating the custom annotations.
// if none of them has a motivation of 'painting', loop through all paintable file types adding them to the canvas.
const customAnnotationFiles: string[] = await glob(
this.directoryFilePath + "/*.yml",
{
ignore: ["**/info.yml"],
}
);
// sort files
customAnnotationFiles.sort((a, b) => {
return compare(a, b);
});
await Promise.all(
customAnnotationFiles.map(async (file: string) => {
let directoryName: string = dirname(file);
directoryName = directoryName.substr(directoryName.lastIndexOf("/"));
const name: string = basename(file, extname(file));
const annotationJson: any = cloneJson(annotationBoilerplate);
const yml: any = await readYml(file);
annotationJson.id = urljoin(
canvasJson.id,
"annotation",
canvasJson.items[0].items.length
);
let motivation: string | undefined = yml.motivation;
if (!motivation) {
// assume painting
motivation = normaliseType(AnnotationMotivation.PAINTING);
warn(
`motivation property missing in ${file} guessed ${motivation}`
);
}
motivation = normaliseType(motivation);
annotationJson.motivation = motivation;
annotationJson.target = canvasJson.id;
let id: string;
// if the motivation is painting, or isn't recognised, set the id to the path of the yml value
if (
(motivation.toLowerCase() ===
normaliseType(AnnotationMotivation.PAINTING) ||
!this._config.annotation.motivations[motivation]) &&
yml.value &&
extname(yml.value)
) {
if (isURL(yml.value)) {
id = yml.value;
} else {
id = urljoin(this.url.href, directoryName, yml.value);
}
// if the painting annotation has a target.
if (yml.xywh) {
id += "#xywh=" + yml.xywh;
}
} else {
id = urljoin(this.url.href, "index.json", "annotations", name);
}
annotationJson.body.id = id;
if (yml.type) {
annotationJson.body.type = yml.type;
} else if (yml.value && extname(yml.value)) {
// guess the type from the extension
const type: string | null = getTypeByExtension(
motivation,
extname(yml.value)
);
if (type) {
annotationJson.body.type = type;
warn(`type property missing in ${file}, guessed ${type}`);
}
} else if (yml.format) {
// guess the type from the format
const type: string | null = getTypeByFormat(motivation, yml.format);
if (type) {
annotationJson.body.type = type;
warn(`type property missing in ${file}, guessed ${type}`);
}
}
if (!annotationJson.body.type) {
delete annotationJson.body.type;
warn(`unable to determine type of ${file}`);
}
if (yml.format) {
annotationJson.body.format = yml.format;
} else if (yml.value && extname(yml.value) && yml.type) {
// guess the format from the extension and type
const format: string | null = getFormatByExtensionAndType(
motivation,
extname(yml.value),
yml.type
);
if (format) {
annotationJson.body.format = format;
warn(`format property missing in ${file}, guessed ${format}`);
}
} else if (yml.value && extname(yml.value)) {
// guess the format from the extension
const format: string | null = getFormatByExtension(
motivation,
extname(yml.value)
);
if (format) {
annotationJson.body.format = format;
warn(`format property missing in ${file}, guessed ${format}`);
}
} else if (yml.type) {
// can only guess the format from the type if there is one typeformat for this motivation.
const format: string | null = getFormatByType(motivation, yml.type);
if (format) {
annotationJson.body.format = format;
warn(`format property missing in ${file}, guessed ${format}`);
}
}
if (!annotationJson.body.format) {
delete annotationJson.body.format;
warn(`unable to determine format of ${file}`);
}
if (yml.label) {
annotationJson.body.label = getLabel(yml.label);
canvasJson.label = getLabel(yml.label);
} else {
annotationJson.body.label = getLabel(this.infoYml.label);
}
// if the annotation is an image and the id points to an info.json
// add an image service pointing to the info.json
if (
annotationJson.body.type &&
annotationJson.body.type.toLowerCase() ===
ExternalResourceType.IMAGE &&
extname(annotationJson.body.id) === ".json"
) {
const service: any = cloneJson(imageServiceBoilerplate);
service[0].id = annotationJson.body.id.substr(
0,
annotationJson.body.id.lastIndexOf("/")
);
annotationJson.body.service = service;
}
// if there's a value, and we're using a recognised motivation (except painting)
if (
yml.value &&
this._config.annotation.motivations[motivation] &&
motivation !== normaliseType(AnnotationMotivation.PAINTING)
) {
annotationJson.body.value = yml.value;
}
if (yml.value && !isURL(yml.value) && annotationJson.body.type) {
// get the path to the annotated file
const dirName: string = dirname(file);
let path: string = join(dirName, yml.value);
path = normaliseFilePath(path);
await getFileDimensions(
annotationJson.body.type,
path,
canvasJson,
annotationJson
);
}
canvasJson.items[0].items.push(annotationJson);
})
);
// for each jpg/pdf/mp4/obj in the canvas directory
// add a painting annotation
const paintableFiles: string[] = await glob(this.directoryFilePath + "/*.*", {
ignore: [
"**/thumb.*", // ignore thumbs
"**/info.yml*", // ignore info.yml
],
});
// sort files
paintableFiles.sort((a, b) => {
return compare(a, b);
});
await this._annotateFiles(canvasJson, paintableFiles);
} else {
// a file was passed (not a directory starting with an underscore)
// therefore, just annotate that file onto the canvas.
await this._annotateFiles(canvasJson, [this.filePath]);
}
if (!canvasJson.items[0].items.length) {
warn(`Could not find any files to annotate onto ${this.directoryFilePath}`);
}
// if there's no thumb.[jpg, gif, png]
// generate one from the first painted image
await getThumbnail(this.canvasJson, this.directory, this.directoryFilePath);
}
private async _annotateFiles(
canvasJson: any,
files: string[]
): Promise<void> {
await Promise.all(
files.map(async (file: string) => {
file = normaliseFilePath(file);
const extName: string = extname(file);
// if this._config.annotation has a matching extension
let defaultPaintingExtension: any = this._config.annotation.motivations
.painting[extName];
let directoryName: string = "";
// if the canvas is being generated from a canvas directory (starts with an _)
if (this._isCanvasDirectory()) {
directoryName = dirname(file);
directoryName = directoryName.substr(directoryName.lastIndexOf("/"));
}
const fileName: string = basename(file);
const id: string = urljoin(this.url.href, directoryName, fileName);
if (defaultPaintingExtension) {
defaultPaintingExtension = defaultPaintingExtension[0];
const annotationJson: any = cloneJson(annotationBoilerplate);
annotationJson.id = urljoin(
canvasJson.id,
"annotation",
canvasJson.items[0].items.length
);
annotationJson.motivation = normaliseType(
AnnotationMotivation.PAINTING
);
annotationJson.target = canvasJson.id;
annotationJson.body.id = id;
annotationJson.body.type = defaultPaintingExtension.type;
annotationJson.body.format = defaultPaintingExtension.format;
annotationJson.body.label = getLabel(this.infoYml.label);
canvasJson.items[0].items.push(annotationJson);
await getFileDimensions(
defaultPaintingExtension.type,
file,
canvasJson,
annotationJson
);
if (
defaultPaintingExtension.type.toLowerCase() ===
ExternalResourceType.IMAGE
) {
await generateImageTiles(
file,
this.url.href,
directoryName,
this.directoryFilePath,
annotationJson
);
}
}
})
);
}
private async _getInfo(): Promise<void> {
this.infoYml = {};
// if there's an info.yml
const ymlPath: string = join(this.directoryFilePath, "info.yml");
const exists: boolean = await fileExists(ymlPath);
if (exists) {
this.infoYml = await readYml(ymlPath);
log(`got metadata for: ${this.directoryFilePath}`);
} else {
log(`no metadata found for: ${this.directoryFilePath}`);
}
if (!this.infoYml.label) {
// default to the directory name
this.infoYml.label = basename(this.directoryFilePath);
}
}
private _applyInfo(): void {
this.canvasJson.label = getLabel(this.infoYml.label); // defaults to directory name
if (this.infoYml.width) {
this.canvasJson.width = this.infoYml.width;
}
if (this.infoYml.height) {
this.canvasJson.height = this.infoYml.height;
}
if (this.infoYml.duration) {
this.canvasJson.duration = this.infoYml.duration;
}
if (this.infoYml.metadata) {
this.canvasJson.metadata = formatMetadata(this.infoYml.metadata);
}
}
} | the_stack |
import EventEmitter from 'eventemitter3';
import logger from '../../../Utils/Logger';
import * as ADTS from './adts';
import MpegAudio from './mpegaudio';
import Events from '../Events/index';
import ExpGolomb from './exp-golomb';
import { ErrorTypes, ErrorDetails } from '../errors';
import {
track,
pesData,
parsedPesData,
avcSample,
NALUnit,
TSTextTrack,
TSId3Track,
TSAudioTrack,
TSVideoTrack,
SampleLike,
typeSupported,
agentInfo
} from '../TSCodecInterface';
import createAVCSample from '../TSUtils/createAVCSample';
import MP4Remuxer from '../Remuxer/mp4-remuxer';
import { videoTrack } from '../../FLVCodec/Interface';
// We are using fixed track IDs for driving the MP4 remuxer
// instead of following the TS PIDs.
// There is no reason not to do this and some browsers/SourceBuffer-demuxers
// may not like if there are TrackID "switches"
// See https://github.com/video-dev/hls.js/issues/1331
// Here we are mapping our internal track types to constant MP4 track IDs
// With MSE currently one can only have one track of each, and we are muxing
// whatever video/audio rendition in them.
const RemuxerTrackIdConfig: Record<string, number> = {
video: 1,
audio: 2,
id3: 3,
text: 4
};
class TSDemuxer {
/**
* 事件中心
*/
private _emitter: EventEmitter
/**
* 设置
*/
private config: Record<string, any>
/**
* 浏览器支持回放类型
*/
private typeSupported: typeSupported
/**
* 浏览器代理信息
*/
agentInfo: agentInfo
/**
* 上一个加载的fragment
*/
private frag: any
/**
* TS 转码器
*/
private remuxer: MP4Remuxer
/**
* 待查明
*/
private sampleAes: any
/**
* 上报错误的方法
*/
private _onError: Function | null
/**
* 媒体信息
*/
private _mediaInfo: Record<string, any>
/**
* 上报媒体信息的方法
*/
private _onMediaInfo: Function | null
/**
* 上报metaData的方法
*/
private _onMetaDataArrived: Function | null
/**
* 上报 ScriptData 的方法 (TS解码器没用);
*/
private _onScriptDataArrived: Function | null
/**
* 上报 TrackMetadata 的方法
*/
private _onTrackMetadata: Function | null
/**
* 上报数据的方法
*/
private _onDataAvailable: Function | null
/**
* fragment的序列号
*/
private sequenceNumber: number
/**
* 时间基础值
*/
private _timestampBase: number
/**
* 是否对有声音的标识进行过覆盖
*/
private _hasAudioFlagOverrided: boolean
/**
* 视频是否有声音
*/
private _hasAudio: boolean
/**
* 是否对有视频的标识进行过覆盖
*/
private _hasVideoFlagOverrided: boolean
/**
* 视频有视频
*/
private _hasVideo: boolean
/**
* 媒体文件长度
*/
private _duration: number
/**
* 是否对duration进行过覆盖
*/
private _durationOverrided: boolean
/**
* fragment 的 ID, 等同于 sequenceNumber
*/
private id: any
/**
* PMT表格是否已经解析
*/
private pmtParsed: boolean
/**
* PMT的ID是多少
*/
private _pmtId: number
/**
* AVC Track
*/
private _avcTrack: TSVideoTrack
/**
* audio track
*/
private _audioTrack: TSAudioTrack
/**
* id3 track
*/
private _id3Track: TSId3Track
/**
* txt track
*/
private _txtTrack: TSTextTrack
/**
* 溢出的AAC数据
*/
aacOverFlow: Uint8Array | null
/**
* 音频最后的PTS时间
*/
aacLastPTS: number | undefined
/**
* AVC Sample 的存储单元
*/
avcSample: avcSample | null
/**
* 音频解码器类型
*/
audioCodec: string | undefined
/**
* 视频解码器类型
*/
videoCodec: string | undefined
/**
* 是否连续
*/
contiguous: boolean
/**
* 初始的PTS
*/
_initPTS: undefined
/**
* 初始的DTS
*/
_initDTS: undefined
constructor(
emitter: EventEmitter,
config: Record<string, any>,
typeSupported: typeSupported,
agentInfo: agentInfo
) {
this._emitter = emitter;
this.config = config;
this.typeSupported = typeSupported;
this.agentInfo = agentInfo;
this.frag = null;
this.remuxer = new MP4Remuxer(this._emitter, config, typeSupported, agentInfo);
this.sampleAes = null;
this._onError = null;
this._mediaInfo = Object.create(null);
this._onMediaInfo = null;
this._onMetaDataArrived = null;
this._onScriptDataArrived = null;
this._onTrackMetadata = null;
this._onDataAvailable = null;
this.sequenceNumber = 0;
this._timestampBase = 0;
this._avcTrack = TSDemuxer.createVideoTrack();
this._audioTrack = TSDemuxer.createAudioTrack(0);
this._id3Track = TSDemuxer.createId3Track();
this._txtTrack = TSDemuxer.createTextTrack();
this._hasAudioFlagOverrided = false;
this._hasAudio = false;
this._hasVideoFlagOverrided = false;
this._hasVideo = false;
this._durationOverrided = false;
this._duration = 0;
this.pmtParsed = false;
this._pmtId = -1;
this.contiguous = false;
this.avcSample = null;
this.aacOverFlow = null;
this.aacLastPTS = undefined;
}
/**
* 文件标签
*/
static Tag: 'TSDemuxer'
// prototype: function(type: string, metadata: any): void
get onTrackMetadata() {
return this._onTrackMetadata;
}
set onTrackMetadata(callback) {
this._onTrackMetadata = callback;
}
// prototype: function(mediaInfo: MediaInfo): void
get onMediaInfo() {
return this._onMediaInfo;
}
set onMediaInfo(callback) {
this._onMediaInfo = callback;
}
get onMetaDataArrived() {
return this._onMetaDataArrived;
}
set onMetaDataArrived(callback) {
this._onMetaDataArrived = callback;
}
get onScriptDataArrived() {
return this._onScriptDataArrived;
}
set onScriptDataArrived(callback) {
this._onScriptDataArrived = callback;
}
// prototype: function(type: number, info: string): void
get onError() {
return this._onError;
}
set onError(callback) {
this._onError = callback;
}
// prototype: function(videoTrack: any, audioTrack: any): void
get onDataAvailable() {
return this._onDataAvailable;
}
set onDataAvailable(callback) {
this._onDataAvailable = callback;
}
// timestamp base for output samples, must be in milliseconds
get timestampBase() {
return this._timestampBase;
}
set timestampBase(base) {
this._timestampBase = base;
}
get overridedDuration() {
return this._duration;
}
// Force-override media duration. Must be in milliseconds, int32
set overridedDuration(duration) {
this._durationOverrided = true;
this._duration = duration;
this._mediaInfo.duration = duration;
}
// Force-override audio track present flag, boolean
set overridedHasAudio(hasAudio: boolean) {
this._hasAudioFlagOverrided = true;
this._hasAudio = hasAudio;
this._mediaInfo.hasAudio = hasAudio;
}
// Force-override video track present flag, boolean
set overridedHasVideo(hasVideo: boolean) {
this._hasVideoFlagOverrided = true;
this._hasVideo = hasVideo;
this._mediaInfo.hasVideo = hasVideo;
}
on(event: string, listener: EventEmitter.ListenerFn) {
this._emitter.on(event, listener);
}
once(event: string, listener: EventEmitter.ListenerFn) {
this._emitter.once(event, listener);
}
off(event: string, listener: EventEmitter.ListenerFn) {
this._emitter.off(event, listener);
}
// TODO 和 push 结合在一起
bindDataSource(loader: any) {
loader.onDataArrival = this.parseChunks.bind(this);
return this;
}
/**
* 解析数据
* @param { Uint8Aarray } chunks loader返回的额数据
* @param { Number } byteStart 累计的bytelength
* @param { * } extraData fragment-loader 返回的数据
*/
parseChunks(chunks: Uint8Array, extraData: any) {
/**
* 发送过来数据块所属的fragment
*/
const frag = extraData.fragCurrent;
/**
* 时间偏移
*/
const timeOffset = Number.isFinite(frag.startPTS) ? frag.startPTS : frag.start;
/**
* 解码数据
*/
const { decryptdata } = frag;
/**
* 上一个frag
*/
const lastFrag = this.frag;
/**
* 是否不连续
*/
const discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
/**
* 是不是变了level
*/
const trackSwitch = !(lastFrag && frag.level === lastFrag.level);
/**
* SN号是否连续的
*/
const nextSN = lastFrag && frag.sn === lastFrag.sn + 1;
/**
* fragment是否是相邻的
*/
const contiguous = !trackSwitch && nextSN;
if(discontinuity) {
logger.debug(TSDemuxer.Tag, `${this.id}:discontinuity detected`);
}
if(trackSwitch) {
logger.debug(TSDemuxer.Tag, `${this.id}:switch detected`);
}
this.frag = frag;
// 暂时不解密
this.pushDecrypted(
chunks,
decryptdata,
new Uint8Array(extraData.initSegmentData),
extraData.audioCodec,
extraData.videoCodec,
timeOffset,
discontinuity,
trackSwitch,
contiguous,
extraData.totalduration,
extraData.accurateTimeOffset,
extraData.defaultInitPTS
);
}
/**
* 推入已经解密过的数据
* @param data 要解析的数据块
* @param decryptdata 解密相关参数
* @param initSegment 初始化片段数据
* @param audioCodec 音频编码格式
* @param videoCodec 视频编码格式
* @param timeOffset 时间偏移
* @param discontinuity 是否不连续
* @param trackSwitch 是都切换了level
* @param contiguous 是否连续
* @param duration 媒体时长
* @param accurateTimeOffset 是否为精确的时间偏移
* @param defaultInitPTS 默认初始的PTS
*/
pushDecrypted(
data: Uint8Array,
decryptdata: any,
initSegment: Uint8Array,
audioCodec: string | undefined,
videoCodec: string | undefined,
timeOffset: number,
discontinuity: boolean,
trackSwitch: boolean,
contiguous: boolean,
duration: number,
accurateTimeOffset: boolean,
defaultInitPTS: number | undefined
) {
// 如果过不连续或者变更了level 则重新生成初始化segment
if(discontinuity || trackSwitch) {
this.resetInitSegment(initSegment, audioCodec, videoCodec, duration);
this.remuxer.resetInitSegment();
}
// 如果过不连续 重置 时间基础值
if(discontinuity) {
this.resetTimeStamp(defaultInitPTS);
this.remuxer.resetTimeStamp(defaultInitPTS);
}
this.append(new Uint8Array(data), timeOffset, contiguous, accurateTimeOffset);
}
/**
* 判断Uint8Array是否为TS数据
* @param data 侦测的数据
*/
static probe(data: Uint8Array) {
const syncOffset = TSDemuxer._syncOffset(data);
if(syncOffset < 0) {
return false;
}
if(syncOffset) {
logger.warn(
TSDemuxer.Tag,
`MPEG2-TS detected but first sync word found @ offset ${syncOffset}, junk ahead ?`
);
}
return true;
}
/**
* 查找同步位所在位置, 如果没有找到返回 -1, 找到就返回找到的位置, 一般为 0
* @param data 要查找的数据
*/
static _syncOffset(data: Uint8Array): number {
// scan 1000 first bytes
const scanwindow = Math.min(1000, data.length - 3 * 188);
let i = 0;
while(i < scanwindow) {
// a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47
if(data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) {
return i;
}
i++;
}
return -1;
}
/**
* 创建一个 track 模板, 用于 转码时放数据
* @param {string} type 'audio' | 'video' | 'id3' | 'text'
* @param {number} duration
* @return { track }
*/
static createTrack(type: string, duration: number): track {
return {
container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
type,
id: RemuxerTrackIdConfig[type],
pid: -1,
inputTimeScale: 90000,
sequenceNumber: 0,
samples: [],
dropped: type === 'video' ? 0 : undefined,
isAAC: type === 'audio' ? true : undefined,
duration: type === 'audio' ? duration : undefined
};
}
/**
* 创建视频序列
*/
static createVideoTrack(): TSVideoTrack {
return {
container: 'video/mp2t',
type: 'video',
id: RemuxerTrackIdConfig.video,
pid: -1,
inputTimeScale: 90000,
sequenceNumber: 0,
samples: [],
dropped: 0,
isAAC: undefined,
duration: undefined
};
}
/**
* 创建音频序列
* @param duration 时长
*/
static createAudioTrack(duration: number): TSAudioTrack {
return {
container: 'video/mp2t',
type: 'audio',
id: RemuxerTrackIdConfig.audio,
pid: -1,
inputTimeScale: 90000,
sequenceNumber: 0,
samples: [],
dropped: undefined,
isAAC: true,
duration
};
}
/**
* 创建Id3序列
*/
static createId3Track(): TSId3Track {
return {
container: undefined,
type: 'id3',
id: RemuxerTrackIdConfig.id3,
pid: -1,
inputTimeScale: 90000,
sequenceNumber: 0,
samples: [],
dropped: undefined,
isAAC: undefined,
duration: undefined
};
}
/**
* 创建文本序列
*/
static createTextTrack(): TSTextTrack {
return {
container: undefined,
type: 'text',
id: RemuxerTrackIdConfig.text,
pid: -1,
inputTimeScale: 90000,
sequenceNumber: 0,
samples: [],
dropped: undefined,
isAAC: undefined,
duration: undefined
};
}
/**
* Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
* Resets all internal track instances of the demuxer.
* 重新初始化初始化片段, 初始化各个track等相关参数, 会在 frament不连续, 切换level或者刚开始的时候调用
* @override Implements generic demuxing/remuxing interface (see DemuxerInline)
* @param { Uint8Array } initSegment
* @param { string } audioCodec
* @param { string } videoCodec
* @param { number } duration (in TS timescale = 90kHz)
*/
resetInitSegment(
initSegment: Uint8Array,
audioCodec: string | undefined,
videoCodec: string | undefined,
duration: number
) {
this.pmtParsed = false;
this._pmtId = -1;
this._avcTrack = TSDemuxer.createVideoTrack();
this._audioTrack = TSDemuxer.createAudioTrack(duration);
this._id3Track = TSDemuxer.createId3Track();
this._txtTrack = TSDemuxer.createTextTrack();
// flush any partial content
this.aacOverFlow = null;
this.aacLastPTS = undefined;
this.avcSample = null;
this.audioCodec = audioCodec;
this.videoCodec = videoCodec;
this._duration = duration;
}
/**
* 重置时间基准值
*/
resetTimeStamp(defaultInitPTS: number | undefined) {}
/**
* 重置媒体信息
*/
resetMediaInfo() {
this._mediaInfo = Object.create(null);
}
// feed incoming data to the front of the parsing pipeline
/**
* 想解码器添加数据
* @param data 要解码的数据
* @param timeOffset 时间偏移值
* @param contiguous 是否连续
* @param accurateTimeOffset 是否是精确的时间偏移
*/
append(data: Uint8Array, timeOffset: number, contiguous: boolean, accurateTimeOffset: boolean) {
let start;
/**
* 要解析数据的长度
*/
let len = data.length;
/**
* ISOIEC13818-1 规定 负载单元起始标示符 为 true 时代表该包中含有 PES packets (refer to 2.4.3.6) or PSI data (refer to 2.4.4).
*/
let stt = false;
/**
* ts packet id 包ID
*/
let pid;
/**
* adaptation_field_control 自适应域标志
*/
let atf;
/**
* 偏移量
*/
let offset;
/**
* 经 parsePES 方法解析后的 pes 包数据
*/
let pes;
/**
* 是否为未知的PID
*/
let unknownPIDs = false;
this.contiguous = contiguous;
let { pmtParsed } = this;
const avcTrack = this._avcTrack;
const audioTrack = this._audioTrack;
const id3Track = this._id3Track;
let avcId = avcTrack ? avcTrack.pid : -1;
let audioId = audioTrack ? audioTrack.pid : -1;
let id3Id = id3Track ? id3Track.pid : -1;
let pmtId = this._pmtId;
let avcData: pesData | undefined = avcTrack.pesData;
let audioData: pesData | undefined = audioTrack.pesData;
let id3Data: pesData | undefined = id3Track.pesData;
const parsePAT = this._parsePAT;
const parsePMT = this._parsePMT;
const parsePES = this._parsePES;
const parseAVCPES = this._parseAVCPES.bind(this);
const parseAACPES = this._parseAACPES.bind(this);
const parseMPEGPES = this._parseMPEGPES.bind(this);
const parseID3PES = this._parseID3PES.bind(this);
const syncOffset = TSDemuxer._syncOffset(data);
// don't parse last TS packet if incomplete
len -= (len + syncOffset) % 188;
// loop through TS packets
for(start = syncOffset; start < len; start += 188) {
if(data[start] === 0x47) {
stt = !!(data[start + 1] & 0x40);
// pid is a 13-bit field starting at the last bit of TS[1]
pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
atf = (data[start + 3] & 0x30) >> 4;
// if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
if(atf > 1) {
offset = start + 5 + data[start + 4];
// continue if there is only adaptation field
if(offset === start + 188) {
continue;
}
} else {
offset = start + 4;
}
switch(pid) {
case avcId:
if(stt) {
avcData && (pes = parsePES(avcData));
if(avcData && pes && pes.pts !== undefined) {
parseAVCPES(pes, false);
}
avcData = {
data: [],
size: 0
};
}
if(avcData) {
avcData.data.push(data.subarray(offset, start + 188));
avcData.size += start + 188 - offset;
}
break;
case audioId:
if(stt) {
audioData && (pes = parsePES(audioData));
if(audioData && pes && pes.pts !== undefined) {
if(audioTrack.isAAC) {
parseAACPES(pes);
} else {
parseMPEGPES(pes);
}
}
audioData = {
data: [],
size: 0
};
}
if(audioData) {
audioData.data.push(data.subarray(offset, start + 188));
audioData.size += start + 188 - offset;
}
break;
case id3Id:
if(stt) {
id3Data && (pes = parsePES(id3Data));
if(id3Data && pes && pes.pts !== undefined) {
parseID3PES(pes);
}
id3Data = {
data: [],
size: 0
};
}
if(id3Data) {
id3Data.data.push(data.subarray(offset, start + 188));
id3Data.size += start + 188 - offset;
}
break;
case 0:
if(stt) {
offset += data[offset] + 1;
}
this._pmtId = parsePAT(data, offset);
pmtId = this._pmtId;
break;
// eslint-disable-next-line no-case-declarations
case pmtId: {
if(stt) {
offset += data[offset] + 1;
}
const parsedPIDs = parsePMT(
data,
offset,
this.typeSupported.mpeg === true || this.typeSupported.mp3 === true,
this.sampleAes !== null
);
// only update track id if track PID found while parsing PMT
// this is to avoid resetting the PID to -1 in case
// track PID transiently disappears from the stream
// this could happen in case of transient missing audio samples for example
// NOTE this is only the PID of the track as found in TS,
// but we are not using this for MP4 track IDs.
avcId = parsedPIDs.avc;
if(avcId > 0) {
avcTrack.pid = avcId;
}
audioId = parsedPIDs.audio;
if(audioId > 0) {
audioTrack.pid = audioId;
audioTrack.isAAC = parsedPIDs.isAAC;
}
id3Id = parsedPIDs.id3;
if(id3Id > 0) {
id3Track.pid = id3Id;
}
if(unknownPIDs && !pmtParsed) {
logger.log(TSDemuxer.Tag, 'reparse from beginning');
unknownPIDs = false;
// we set it to -188, the += 188 in the for loop will reset start to 0
start = syncOffset - 188;
}
this.pmtParsed = true;
pmtParsed = true;
break;
}
case 17:
case 0x1fff:
break;
default:
unknownPIDs = true;
break;
}
} else {
this._emitter.emit(Events.ERROR, {
type: ErrorTypes.MEDIA_ERROR,
details: ErrorDetails.FRAG_PARSING_ERROR,
fatal: false,
code: -2,
reason: 'TS packet did not start with 0x47'
});
}
}
// try to parse last PES packets
avcData && (pes = parsePES(avcData));
if(avcData && pes && pes.pts !== undefined) {
parseAVCPES(pes, true);
avcTrack.pesData = undefined;
} else {
// either avcData null or PES truncated, keep it for next frag parsing
avcTrack.pesData = avcData;
}
audioData && (pes = parsePES(audioData));
if(audioData && pes && pes.pts !== undefined) {
if(audioTrack.isAAC) {
parseAACPES(pes, true);
} else {
parseMPEGPES(pes);
}
audioTrack.pesData = undefined;
} else {
if(audioData && audioData.size) {
logger.log(
TSDemuxer.Tag,
'last AAC PES packet truncated,might overlap between fragments'
);
}
// either audioData null or PES truncated, keep it for next frag parsing
audioTrack.pesData = audioData;
}
id3Data && (pes = parsePES(id3Data));
if(id3Data && pes && pes.pts !== undefined) {
parseID3PES(pes);
id3Track.pesData = undefined;
} else {
// either id3Data null or PES truncated, keep it for next frag parsing
id3Track.pesData = id3Data;
}
this.sequenceNumber += 1;
const { sequenceNumber } = this;
audioTrack.sequenceNumber = sequenceNumber;
avcTrack.sequenceNumber = sequenceNumber;
this._parseMediaInfo(audioTrack, avcTrack);
this._createMetadata(audioTrack, avcTrack);
this.remuxer.remux(
audioTrack,
avcTrack,
id3Track,
this._txtTrack,
timeOffset,
contiguous,
accurateTimeOffset
);
}
/**
* 销毁功能
*/
destroy() {
this._initDTS = undefined;
this._initPTS = undefined;
this._duration = 0;
this.sequenceNumber = 0;
this._emitter.removeAllListeners();
delete this._emitter;
delete this.config;
delete this.typeSupported;
delete this.agentInfo;
this.frag = null;
delete this.remuxer;
this.sampleAes = null;
this._onError = null;
delete this._mediaInfo;
this._onMediaInfo = null;
this._onMetaDataArrived = null;
this._onScriptDataArrived = null;
this._onTrackMetadata = null;
this._onDataAvailable = null;
this.sequenceNumber = 0;
this._timestampBase = 0;
delete this._avcTrack;
delete this._audioTrack;
delete this._id3Track;
delete this._txtTrack;
this._hasAudioFlagOverrided = false;
this._hasAudio = false;
this._hasVideoFlagOverrided = false;
this._hasVideo = false;
this._durationOverrided = false;
this._duration = 0;
this.pmtParsed = false;
this._pmtId = -1;
this.contiguous = false;
this.avcSample = null;
this.aacOverFlow = null;
this.aacLastPTS = undefined;
}
/**
* 解析 PAT表, 获取 PMT值
* @param data 要解析的Uint8Array 数据
* @param offset 偏移量
*/
_parsePAT(data: Uint8Array, offset: number): number {
// skip the PSI header and parse the first PMT entry
return ((data[offset + 10] & 0x1f) << 8) | data[offset + 11];
// logger.log('PMT PID:' + this._pmtId);
}
/**
*
* @param data 解析的UInt8Array
* @param offset 偏移数
* @param mpegSupported 浏览器是否支持MPEG回放
* @param isSampleAes 是否有解密程序
*/
_parsePMT(data: Uint8Array, offset: number, mpegSupported: boolean, isSampleAes: boolean) {
let pid;
const result = {
audio: -1,
avc: -1,
id3: -1,
isAAC: true
};
const sectionLength = ((data[offset + 1] & 0x0f) << 8) | data[offset + 2];
const tableEnd = offset + 3 + sectionLength - 4;
// to determine where the table is, we have to figure out how
// long the program info descriptors are
const programInfoLength = ((data[offset + 10] & 0x0f) << 8) | data[offset + 11];
// advance the offset to the first entry in the mapping table
offset += 12 + programInfoLength;
while(offset < tableEnd) {
pid = ((data[offset + 1] & 0x1f) << 8) | data[offset + 2];
switch(data[offset]) {
case 0xcf: // SAMPLE-AES AAC
if(!isSampleAes) {
logger.log(TSDemuxer.Tag, `unkown stream type:${data[offset]}`);
break;
}
/* falls through */
// ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
// eslint-disable-next-line no-fallthrough
case 0x0f:
// logger.log('AAC PID:' + pid);
if(result.audio === -1) {
result.audio = pid;
}
break;
// Packetized metadata (ID3)
case 0x15:
// logger.log('ID3 PID:' + pid);
if(result.id3 === -1) {
result.id3 = pid;
}
break;
case 0xdb: // SAMPLE-AES AVC
if(!isSampleAes) {
logger.log(TSDemuxer.Tag, `unkown stream type:${data[offset]}`);
break;
}
/* falls through */
// ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
// eslint-disable-next-line no-fallthrough
case 0x1b:
// logger.log('AVC PID:' + pid);
if(result.avc === -1) {
result.avc = pid;
}
break;
// ISO/IEC 11172-3 (MPEG-1 audio)
// or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
case 0x03:
case 0x04:
// logger.log('MPEG PID:' + pid);
if(!mpegSupported) {
logger.log(
TSDemuxer.Tag,
'MPEG audio found, not supported in this browser for now'
);
} else if(result.audio === -1) {
result.audio = pid;
result.isAAC = false;
}
break;
case 0x24:
logger.log(TSDemuxer.Tag, 'HEVC stream type found, not supported for now');
break;
default:
logger.log(TSDemuxer.Tag, `unkown stream type:${data[offset]}`);
break;
}
// move to the next table entry
// skip past the elementary stream descriptors, if present
offset += (((data[offset + 3] & 0x0f) << 8) | data[offset + 4]) + 5;
}
return result;
}
/**
* 解析PES包
* @param stream PES包
*/
_parsePES(stream: pesData): parsedPesData | null {
let i = 0;
let frag;
let pesFlags;
let pesLen;
let pesHdrLen;
let pesData;
let pesPts: number | undefined;
let pesDts: number | undefined;
let payloadStartOffset;
const { data } = stream;
// safety check
if(!stream || stream.size === 0) {
return null;
}
// we might need up to 19 bytes to read PES header
// if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
// usually only one merge is needed (and this is rare ...)
while(data[0].length < 19 && data.length > 1) {
const newData = new Uint8Array(data[0].length + data[1].length);
newData.set(data[0]);
newData.set(data[1], data[0].length);
data[0] = newData;
data.splice(1, 1);
}
// retrieve PTS/DTS from first fragment
frag = data[0];
const pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
if(pesPrefix === 1) {
pesLen = (frag[4] << 8) + frag[5];
// if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
// minus 6 : PES header size
if(pesLen && pesLen > stream.size - 6) {
return null;
}
pesFlags = frag[7];
if(pesFlags & 0xc0) {
/* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
as Bitwise operators treat their operands as a sequence of 32 bits */
pesPts = (frag[9] & 0x0e) * 536870912 // 1 << 29
+ (frag[10] & 0xff) * 4194304 // 1 << 22
+ (frag[11] & 0xfe) * 16384 // 1 << 14
+ (frag[12] & 0xff) * 128 // 1 << 7
+ (frag[13] & 0xfe) / 2;
// check if greater than 2^32 -1
if(pesPts > 4294967295) {
// decrement 2^33
pesPts -= 8589934592;
}
if(pesFlags & 0x40) {
pesDts = (frag[14] & 0x0e) * 536870912 // 1 << 29
+ (frag[15] & 0xff) * 4194304 // 1 << 22
+ (frag[16] & 0xfe) * 16384 // 1 << 14
+ (frag[17] & 0xff) * 128 // 1 << 7
+ (frag[18] & 0xfe) / 2;
// check if greater than 2^32 -1
if(pesDts > 4294967295) {
// decrement 2^33
pesDts -= 8589934592;
}
if(pesPts - pesDts > 60 * 90000) {
logger.warn(
TSDemuxer.Tag,
`${Math.round(
(pesPts - pesDts) / 90000
)}s delta between PTS and DTS, align them`
);
pesPts = pesDts;
}
} else {
pesDts = pesPts;
}
}
pesHdrLen = frag[8];
// 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
payloadStartOffset = pesHdrLen + 9;
stream.size -= payloadStartOffset;
// reassemble PES packet
pesData = new Uint8Array(stream.size);
for(let j = 0, dataLen = data.length; j < dataLen; j++) {
frag = data[j];
let len = frag.byteLength;
if(payloadStartOffset) {
if(payloadStartOffset > len) {
// trim full frag if PES header bigger than frag
payloadStartOffset -= len;
continue;
} else {
// trim partial frag if PES header smaller than frag
frag = frag.subarray(payloadStartOffset);
len -= payloadStartOffset;
payloadStartOffset = 0;
}
}
pesData.set(frag, i);
i += len;
}
if(pesLen) {
// payload size : remove PES header + PES extension
pesLen -= pesHdrLen + 3;
}
return {
data: pesData,
pts: pesPts,
dts: pesDts,
len: pesLen
};
}
return null;
}
pushAccesUnit(avcSample: avcSample, avcTrack: TSVideoTrack) {
if(avcSample.units.length && avcSample.frame) {
const { samples } = avcTrack;
const nbSamples = samples.length;
// only push AVC sample if starting with a keyframe is not mandatory OR
// if keyframe already found in this fragment OR
// keyframe found in last fragment (track.sps) AND
// samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous
if(
!this.config.forceKeyFrameOnDiscontinuity
|| avcSample.key === true
|| (avcTrack.sps && (nbSamples || this.contiguous))
) {
avcSample.id = nbSamples;
samples.push(avcSample);
} else {
// dropped samples, track it
avcTrack.dropped !== undefined && avcTrack.dropped++;
}
}
if(avcSample.debug.length) {
logger.info(TSDemuxer.Tag, `${avcSample.pts}/${avcSample.dts}:${avcSample.debug}`);
}
}
/**
* 解析AVC PES 数据
* @param pes 要解析的PES Data
* @param last 是否为最后一个
*/
_parseAVCPES(pes: parsedPesData, last?: boolean) {
const track = this._avcTrack;
const units = this._parseAVCNALu(pes.data);
const debug = false;
let expGolombDecoder;
let { avcSample } = this;
/**
* 是否插入到units中
*/
let push = false;
/**
* 是否找到SPS
*/
let spsfound = false;
let i;
const pushAccesUnit = this.pushAccesUnit.bind(this);
// free pes.data to save up some memory
delete pes.data;
// if new NAL units found and last sample still there, let's push ...
// this helps parsing streams with missing AUD (only do this if AUD never found)
if(avcSample && units.length && !track.audFound) {
pushAccesUnit(avcSample, track);
this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');
({ avcSample } = this);
}
units.forEach((unit) => {
switch(unit.type) {
// eslint-disable-next-line no-case-declarations
case 1: { // NDR
push = true;
if(!avcSample) {
this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
({ avcSample } = this);
}
if(!avcSample) {
return;
}
if(debug) {
avcSample.debug += 'NDR ';
}
avcSample.frame = true;
const { data } = unit;
// only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
if(spsfound && data.length > 4) {
// retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
const sliceType = new ExpGolomb(data).readSliceType();
// 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
// SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
// An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
// I slice: A slice that is not an SI slice that is decoded using intra prediction only.
// if (sliceType === 2 || sliceType === 7) {
// https://www.cnblogs.com/pengkunfan/p/3945445.html SliceType 简介
if(
sliceType === 2
|| sliceType === 4
|| sliceType === 7
|| sliceType === 9
) {
avcSample.key = true;
}
}
break;
}
// IDR
case 5:
push = true;
// handle PES not starting with AUD
if(!avcSample) {
this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
({ avcSample } = this);
}
if(!avcSample) {
return;
}
if(debug) {
avcSample.debug += 'IDR ';
}
avcSample.key = true;
avcSample.frame = true;
break;
// SEI
// eslint-disable-next-line no-case-declarations
case 6: {
push = true;
if(debug && avcSample) {
avcSample.debug += 'SEI ';
}
expGolombDecoder = new ExpGolomb(this.discardEPB(unit.data));
// skip frameType
expGolombDecoder.readUByte();
let payloadType = 0;
let payloadSize = 0;
let endOfCaptions = false;
let b = 0;
while(!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {
payloadType = 0;
do {
b = expGolombDecoder.readUByte();
payloadType += b;
} while(b === 0xff);
// Parse payload size.
payloadSize = 0;
do {
b = expGolombDecoder.readUByte();
payloadSize += b;
} while(b === 0xff);
// TODO: there can be more than one payload in an SEI packet...
// TODO: need to read type and size in a while loop to get them all
if(payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {
endOfCaptions = true;
const countryCode = expGolombDecoder.readUByte();
if(countryCode === 181) {
const providerCode = expGolombDecoder.readUShort();
if(providerCode === 49) {
const userStructure = expGolombDecoder.readUInt();
if(userStructure === 0x47413934) {
const userDataType = expGolombDecoder.readUByte();
// Raw CEA-608 bytes wrapped in CEA-708 packet
if(userDataType === 3) {
const firstByte = expGolombDecoder.readUByte();
const secondByte = expGolombDecoder.readUByte();
const totalCCs = 31 & firstByte;
const byteArray = [firstByte, secondByte];
for(i = 0; i < totalCCs; i++) {
// 3 bytes per CC
byteArray.push(expGolombDecoder.readUByte());
byteArray.push(expGolombDecoder.readUByte());
byteArray.push(expGolombDecoder.readUByte());
}
this._insertSampleInOrder(this._txtTrack.samples, {
type: 3,
pts: <number>pes.pts,
bytes: byteArray
});
}
}
}
}
} else if(payloadType === 5 && expGolombDecoder.bytesAvailable !== 0) {
endOfCaptions = true;
if(payloadSize > 16) {
const uuidStrArray = [];
const userDataPayloadBytes = [];
for(i = 0; i < 16; i++) {
uuidStrArray.push(expGolombDecoder.readUByte().toString(16));
if(i === 3 || i === 5 || i === 7 || i === 9) {
uuidStrArray.push('-');
}
}
for(i = 16; i < payloadSize; i++) {
userDataPayloadBytes.push(expGolombDecoder.readUByte());
}
this._insertSampleInOrder(this._txtTrack.samples, {
pts: pes.pts,
payloadType,
uuid: uuidStrArray.join(''),
userData: String.fromCharCode.apply(null, userDataPayloadBytes),
userDataBytes: userDataPayloadBytes
});
}
} else if(payloadSize < expGolombDecoder.bytesAvailable) {
for(i = 0; i < payloadSize; i++) {
expGolombDecoder.readUByte();
}
}
}
break;
}
// SPS
// eslint-disable-next-line no-case-declarations
case 7:
push = true;
spsfound = true;
if(debug && avcSample) {
avcSample.debug += 'SPS ';
}
if(!track.sps) {
expGolombDecoder = new ExpGolomb(unit.data);
const config = expGolombDecoder.readSPS();
track.width = config.width;
track.height = config.height;
track.pixelRatio = config.pixelRatio;
track.sps = [unit.data];
track.duration = this._duration;
const codecarray = unit.data.subarray(1, 4);
let codecstring = 'avc1.';
for(i = 0; i < 3; i++) {
let h = codecarray[i].toString(16);
if(h.length < 2) {
h = `0${h}`;
}
codecstring += h;
}
track.codec = codecstring;
}
break;
// PPS
case 8:
push = true;
if(debug && avcSample) {
avcSample.debug += 'PPS ';
}
if(!track.pps) {
track.pps = [unit.data];
}
break;
// AUD
case 9:
push = false;
track.audFound = true;
if(avcSample) {
pushAccesUnit(avcSample, track);
}
this.avcSample = createAVCSample(
false,
pes.pts,
pes.dts,
debug ? 'AUD ' : ''
);
({ avcSample } = this);
break;
// Filler Data
case 12:
push = false;
break;
default:
push = false;
if(avcSample) {
avcSample.debug += `unknown NAL ${unit.type} `;
}
break;
}
if(avcSample && push) {
const { units } = avcSample;
units.push(unit);
}
});
// if last PES packet, push samples
if(last && avcSample) {
pushAccesUnit(avcSample, track);
this.avcSample = null;
}
}
/**
* 按照pts排序 插入一个sample
* @param arr 被插入的avcsample
* @param data 要排序的数据
*/
_insertSampleInOrder(arr: Array<SampleLike>, data: SampleLike) {
const len = arr.length;
if(len > 0) {
if(data.pts && data.pts >= <number>arr[len - 1].pts) {
arr.push(data);
} else {
for(let pos = len - 1; pos >= 0; pos--) {
if(data.pts && data.pts < <number>arr[pos].pts) {
arr.splice(pos, 0, data);
break;
}
}
}
} else {
arr.push(data);
}
}
_getLastNalUnit(): NALUnit | undefined {
let { avcSample } = this;
let lastUnit;
// try to fallback to previous sample if current one is empty
if(!avcSample || avcSample.units.length === 0) {
const track = this._avcTrack;
const { samples } = track;
avcSample = samples[samples.length - 1];
}
if(avcSample) {
const { units } = avcSample;
lastUnit = units[units.length - 1];
}
return lastUnit;
}
/**
* 解析AVC的NAL Unit, 返回 NAL Unit 的数组
* @param array 要解析的Uint8Array
*/
_parseAVCNALu(array: Uint8Array): Array<NALUnit> {
let i = 0;
const len = array.byteLength;
let value;
let overflow;
const track = this._avcTrack;
let state = track.naluState || 0;
const lastState = state;
const units = [];
let unit: NALUnit;
let unitType: number;
let lastUnitStart = -1;
let lastUnitType = 0;
// logger.log('PES:' + Hex.hexDump(array));
if(state === -1) {
// special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
lastUnitStart = 0;
// NALu type is value read from offset 0
lastUnitType = array[0] & 0x1f;
state = 0;
i = 1;
}
while(i < len) {
value = array[i++];
// optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
if(!state) {
state = value ? 0 : 1;
continue;
}
if(state === 1) {
state = value ? 0 : 2;
continue;
}
// here we have state either equal to 2 or 3
if(!value) {
state = 3;
} else if(value === 1) {
if(lastUnitStart >= 0) {
unit = {
data: array.subarray(lastUnitStart, i - state - 1),
type: lastUnitType,
state: undefined
};
// logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
if(unit.type === 6) {
// 获取到SEI信息
this._emitter.emit(Events.GET_SEI_INFO, new Uint8Array(unit.data));
}
units.push(unit);
} else {
// lastUnitStart is undefined => this is the first start code found in this PES packet
// first check if start code delimiter is overlapping between 2 PES packets,
// ie it started in last packet (lastState not zero)
// and ended at the beginning of this PES packet (i <= 4 - lastState)
const lastUnit = this._getLastNalUnit();
if(lastUnit) {
if(lastState && i <= 4 - lastState) {
// start delimiter overlapping between PES packets
// strip start delimiter bytes from the end of last NAL unit
// check if lastUnit had a state different from zero
if(lastUnit.state) {
// strip last bytes
lastUnit.data = lastUnit.data.subarray(
0,
lastUnit.data.byteLength - lastState
);
}
}
// If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
overflow = i - state - 1;
if(overflow > 0) {
// logger.log('first NALU found with overflow:' + overflow);
const tmp = new Uint8Array(lastUnit.data.byteLength + overflow);
tmp.set(lastUnit.data, 0);
tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);
lastUnit.data = tmp;
}
}
}
// check if we can read unit type
if(i < len) {
unitType = array[i] & 0x1f;
// logger.log('find NALU @ offset:' + i + ',type:' + unitType);
lastUnitStart = i;
lastUnitType = unitType;
state = 0;
} else {
// not enough byte to read unit type. let's read it on next PES parsing
state = -1;
}
} else {
state = 0;
}
}
if(lastUnitStart >= 0 && state >= 0) {
unit = {
data: array.subarray(lastUnitStart, len),
type: lastUnitType,
state
};
units.push(unit);
// logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
}
// no NALu found
if(units.length === 0) {
// append pes.data to previous NAL unit
const lastUnit = this._getLastNalUnit();
if(lastUnit) {
const tmp = new Uint8Array(lastUnit.data.byteLength + array.byteLength);
tmp.set(lastUnit.data, 0);
tmp.set(array, lastUnit.data.byteLength);
lastUnit.data = tmp;
}
}
track.naluState = state;
return units;
}
/**
* remove Emulation Prevention bytes from a RBSP
*/
discardEPB(data: Uint8Array): Uint8Array {
const length = data.byteLength;
const EPBPositions = [];
let i = 1;
// Find all `Emulation Prevention Bytes`
while(i < length - 2) {
if(data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
EPBPositions.push(i + 2);
i += 2;
} else {
i++;
}
}
// If no Emulation Prevention Bytes were found just return the original
// array
if(EPBPositions.length === 0) {
return data;
}
// Create a new array to hold the NAL unit data
const newLength = length - EPBPositions.length;
const newData = new Uint8Array(newLength);
let sourceIndex = 0;
for(i = 0; i < newLength; sourceIndex++, i++) {
if(sourceIndex === EPBPositions[0]) {
// Skip this byte
sourceIndex++;
// Remove this position index
EPBPositions.shift();
}
newData[i] = data[sourceIndex];
}
return newData;
}
/**
* 解析AAC音频 PES 数据, 填充 AudioTrack的samples
* @param pes 要解析的PES 数据
* @param last 是否为最后一个PES
*/
_parseAACPES(pes: parsedPesData, last?: boolean) {
const track = this._audioTrack;
let { data } = pes;
let pts = <number>pes.pts;
const startOffset = 0;
let { aacOverFlow } = this;
const { aacLastPTS } = this;
let frameIndex;
let offset;
let stamp;
let len;
if(aacOverFlow) {
const tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);
tmp.set(aacOverFlow, 0);
tmp.set(data, aacOverFlow.byteLength);
// logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);
data = tmp;
}
// look for ADTS header (0xFFFx)
for(offset = startOffset, len = data.length; offset < len - 1; offset++) {
if(ADTS.isHeader(data, offset)) {
break;
}
}
// if ADTS header does not start straight from the beginning of the PES payload, raise an error
if(offset) {
let reason; let
fatal;
if(offset < len - 1) {
reason = `AAC PES did not start with ADTS header,offset:${offset}`;
fatal = false;
} else {
reason = 'no ADTS header found in AAC PES';
fatal = true;
}
logger.warn(TSDemuxer.Tag, `parsing error:${reason}`);
this._emitter.emit(Events.ERROR, {
type: ErrorTypes.MEDIA_ERROR,
details: ErrorDetails.FRAG_PARSING_ERROR,
fatal,
reason
});
if(fatal) {
return;
}
}
ADTS.initTrackConfig(track, this._emitter, data, offset, this.audioCodec);
frameIndex = 0;
const frameDuration = ADTS.getFrameDuration(track.samplerate);
// if last AAC frame is overflowing, we should ensure timestamps are contiguous:
// first sample PTS should be equal to last sample PTS + frameDuration
if(aacOverFlow && aacLastPTS && frameDuration) {
const newPTS = aacLastPTS + frameDuration;
if(pts && Math.abs(newPTS - pts) > 1) {
logger.log(
TSDemuxer.Tag,
`AAC: align PTS for overlapping frames by ${Math.round((newPTS - pts) / 90)}`
);
pts = newPTS;
}
}
// scan for aac samples
while(offset < len) {
if(ADTS.isHeader(data, offset) && offset + 5 < len && track) {
const frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);
if(frame) {
// logger.log(`${Math.round(frame.sample.pts)} : AAC`);
offset += frame.length;
stamp = frame.sample.pts;
frameIndex++;
} else {
// logger.log('Unable to parse AAC frame');
break;
}
} else {
// nothing found, keep looking
offset++;
}
}
if(offset < len) {
aacOverFlow = data.subarray(offset, len);
// logger.log(`AAC: overflow detected:${len-offset}`);
} else {
aacOverFlow = null;
}
this.aacOverFlow = aacOverFlow;
this.aacLastPTS = stamp;
}
/**
* 解析MPEG的PES包, 填充 _audioTrack的samples
* @param pes 待解析的 PES 包数据
*/
_parseMPEGPES(pes: parsedPesData) {
const { data } = pes;
const { length } = data;
let frameIndex = 0;
let offset = 0;
const { pts } = pes;
while(offset < length) {
if(MpegAudio.isHeader(data, offset)) {
const frame = MpegAudio.appendFrame(
this._audioTrack,
data,
offset,
pts as number,
frameIndex
);
if(frame) {
offset += frame.length;
frameIndex++;
} else {
// logger.log('Unable to parse Mpeg audio frame');
break;
}
} else {
// nothing found, keep looking
offset++;
}
}
}
_parseID3PES(pes: parsedPesData) {
this._id3Track.samples.push(pes);
}
/**
* 填充mediaInfo, 并向上发送
*/
_parseMediaInfo(audioTrack: track, videoTrack: track) {
this._mediaInfo = Object.assign(Object.create(null), this._mediaInfo, {
duration: Math.max(<number>audioTrack.duration, <number>videoTrack.duration),
audioChannelCount: audioTrack.channelCount,
audioCodec: audioTrack.codec,
audioSampleRate: audioTrack.samplerate,
fps: null,
hasAudio: !!audioTrack,
hasKeyframesIndex: false,
keyframesIndex: null,
hasVideo: !!videoTrack,
width: videoTrack.width,
height: videoTrack.height,
mimeType: `${videoTrack.container || audioTrack.container}; codecs="${
videoTrack.codec
},${audioTrack.codec}"`,
videoCodec: videoTrack.codec,
pixelRatio: videoTrack.pixelRatio,
pps: videoTrack.pps,
sps: videoTrack.sps
});
this._emitter.emit(Events.MEDIA_INFO, this._mediaInfo);
}
/**
* 创建metadata, 并用emitter发送出去
* @param audioTrack 音频序列
* @param videoTrack 视频序列
*/
_createMetadata(audioTrack: TSAudioTrack, videoTrack: TSVideoTrack) {
const MD = {
audiodatarate: 0,
audiosamplerate: audioTrack.samplerate,
compatibleBrands: 'isom',
duration: videoTrack.duration,
height: videoTrack.height,
majorBrand: 'isom',
minorVersion: '1',
width: videoTrack.width
};
this._emitter.emit(Events.META_DATA, MD);
}
}
export default TSDemuxer; | the_stack |
import AsyncStorage from '@react-native-community/async-storage';
import FSNetwork from '@brandingbrand/fsnetwork';
import DeviceInfo from 'react-native-device-info';
import * as RNLocalize from 'react-native-localize';
import {
AppSettings,
EngagementMessage,
EngagementProfile,
EngagmentEvent
} from './types';
export interface EngagementServiceConfig {
appId: string;
apiKey: string;
baseURL: string;
cacheTTL?: number; // default = 10 mins
}
export interface Segment {
id: number;
name: string;
attributes?: string[];
}
export interface Attribute {
key: string;
value: string;
}
export interface AttributePayload {
attributes: string;
}
export class EngagementService {
appId: string;
networkClient: FSNetwork;
events: EngagmentEvent[] = [];
profileId?: string;
profileData?: EngagementProfile;
messages: EngagementMessage[] = [];
environment?: string;
messageCache: number = 0;
cacheTTL: number = 1000 * 60 * 10;
constructor(config: EngagementServiceConfig) {
this.appId = config.appId;
if (typeof config.cacheTTL === 'number') {
this.cacheTTL = config.cacheTTL;
}
this.environment = ~config.baseURL.indexOf('uat') ? 'UAT' : 'PROD';
this.networkClient = new FSNetwork({
baseURL: config.baseURL,
headers: {
apikey: config.apiKey,
'Content-Type': 'application/json'
}
});
}
async setProfileAttributes(attributes: Attribute[]): Promise<boolean> {
return this.networkClient
.post(`/Profiles/${this.profileId}/setAttributes`, JSON.stringify(attributes))
.then((response: any) => {
if (response.status === 204) {
return true;
}
return false;
})
.catch((e: any) => {
console.warn('Unable to set profile attribute', e);
return false;
});
}
async setProfileAttribute(key: string, value: string): Promise<boolean> {
const data = {
key,
value,
appId: this.appId
};
return this.networkClient
.post(`/Profiles/${this.profileId}/setAttribute`, data)
.then((response: any) => {
if (response.status === 204) {
return true;
}
return false;
})
.catch((e: any) => {
console.warn('Unable to set profile attribute', e);
return false;
});
}
// @TODO: does the profile need to be resynced anytime during a session?
async getProfile(accountId?: string, forceProfileSync?: boolean): Promise<string> {
if (this.profileId && this.profileData && !forceProfileSync) {
return Promise.resolve(this.profileId);
}
const savedProfileId =
await AsyncStorage.getItem(`ENGAGEMENT_PROFILE_ID_${this.environment}_${this.appId}`);
if (savedProfileId && typeof savedProfileId === 'string' && !forceProfileSync) {
this.profileId = savedProfileId;
return Promise.resolve(savedProfileId);
}
const profileInfo: any = {
accountId,
locale: RNLocalize.getLocales() && RNLocalize.getLocales().length &&
RNLocalize.getLocales()[0].languageTag,
country: RNLocalize.getCountry(),
timezone: RNLocalize.getTimeZone(),
deviceIdentifier: DeviceInfo.getUniqueId(),
deviceInfo: JSON.stringify({
model: DeviceInfo.getModel(),
appName: DeviceInfo.getBundleId(),
appVersion: DeviceInfo.getReadableVersion(),
osName: DeviceInfo.getSystemName(),
osVersion: DeviceInfo.getSystemVersion()
})
};
return this.networkClient.post(`/App/${this.appId}/getProfile`, profileInfo)
.then((r: any) => r.data)
.then((data: any) => {
this.profileId = data.id;
this.profileData = data;
AsyncStorage
.setItem(`ENGAGEMENT_PROFILE_ID_${this.environment}_${this.appId}`, data.id).catch();
return data.id;
})
.catch((e: any) => {
console.log(e.response);
console.error(e);
});
}
async getSegments(attribute?: string): Promise<Segment[]> {
return this.networkClient.get(`/App/${this.appId}/getSegments`, {
params: {
attribute
}
})
.then(r => r.data)
.catch((e: any) => {
console.log(e.response);
console.error(e);
});
}
async setPushToken(pushToken: string): Promise<any> {
const uniqueId = DeviceInfo.getUniqueId();
const device = this.profileData && this.profileData.devices &&
this.profileData.devices[uniqueId];
if (device) {
if (!device.pushToken || device.pushToken !== pushToken) {
this.networkClient
.patch(`/Devices/${device.id}`, { pushToken })
.catch((e: any) => console.log('failed to set push token', e));
}
}
}
/**
* Get inbox messages for the current user
* @returns {EngagementMessage[]} inbox messages
*/
async getMessages(): Promise<EngagementMessage[]> {
// check we have a user profile
if (!this.profileId) {
throw new Error('Profile not loaded.');
}
// cache
if (this.messages.length) {
if (+new Date() - this.messageCache < this.cacheTTL) {
return Promise.resolve(this.messages);
}
}
return this.networkClient.get(`/PublishedMessages/getForProfile/${this.profileId}`)
.then((r: any) => r.data)
.then((list: any) => list.map((data: any) => ({
id: data.id,
published: new Date(data.published),
message: JSON.parse(data.message),
title: data.title,
inbox: data.inbox,
attributes: data.attributes
})))
.then((messages: EngagementMessage[]) => {
this.messages = messages;
this.messageCache = +new Date();
return messages;
})
.catch(async (e: any) => {
console.log('Unable to fetch inbox messages', e);
let ret: EngagementMessage[] = [];
// respond with stale cache if we have it
if (this.messages.length) {
ret = this.messages;
}
return Promise.resolve(ret);
});
}
async getInboxMessages(attributes?: AttributePayload): Promise<EngagementMessage[]> {
// check we have a user profile
if (!this.profileId) {
throw new Error('Profile not loaded.');
}
// cache
if (this.messages.length) {
if (+new Date() - this.messageCache < this.cacheTTL) {
return Promise.resolve(this.messages);
}
}
const lastEngagementFetch = await AsyncStorage.getItem('LAST_ENGAGEMENT_FETCH');
return this.networkClient.post(`/PublishedMessages/getInboxForProfile/${this.profileId}`,
JSON.stringify(attributes))
.then((r: any) => r.data)
.then((list: any) => list.map((data: any) => {
return {
id: data.id,
published: new Date(data.published),
isNew: lastEngagementFetch ?
Date.parse(data.published) > parseInt(lastEngagementFetch, 10) : false,
message: JSON.parse(data.message),
title: data.title,
inbox: data.inbox,
attributes: data.attributes
};
}))
.then((messages: EngagementMessage[]) => {
this.messages = messages;
this.messageCache = +new Date();
AsyncStorage.setItem('LAST_ENGAGEMENT_FETCH', Date.now().toString())
.catch();
return messages;
})
.catch(async (e: any) => {
console.log('Unable to fetch inbox messages', e);
let ret: EngagementMessage[] = [];
// respond with stale cache if we have it
if (this.messages.length) {
ret = this.messages;
}
return Promise.resolve(ret);
});
}
/**
* Accepts array of inbox messages
* Fetches sort order array (stored in app settings)
* @param {EngagementMessage[]} messages inbox messages to sort
* @returns {EngagementMessage[]} sorted inbox messages
*/
async sortInbox(
messages: EngagementMessage[]
): Promise<EngagementMessage[]> {
const order =
await this.networkClient.get(`/App/${this.appId}/getAppSettings`)
.then((r: any) => r.data)
.then((settings: AppSettings) => settings && settings.sort);
if (!order || !Array.isArray(order)) {
return messages;
}
// recently live - not yet sorted messages (they go at the top)
const liveNew = messages.filter((msg: EngagementMessage) => order.indexOf(msg.id) === -1);
const liveSort = messages.filter((msg: EngagementMessage) => order.indexOf(msg.id) > -1);
// sort the rest based on the sort array from `getAppSettings` (new core feature)
const sortedLive = liveSort.sort((a: EngagementMessage, b: EngagementMessage) => {
const A = a.id;
const B = b.id;
if (
order.indexOf(A) < order.indexOf(B) ||
order.indexOf(A) === -1 ||
order.indexOf(B) === -1
) {
return -1;
} else {
return 1;
}
});
const sortedAll = [...liveNew, ...sortedLive];
const pinnedTopIndexes: number[] = [];
const pinnedBottomIndexes: number[] = [];
const pinnedTop = sortedAll.filter((msg, idx) => {
if (msg.message && msg.message.content && msg.message.content.pin &&
msg.message.content.pin === 'top') {
pinnedTopIndexes.push(idx);
return true;
}
return false;
});
for (let i = pinnedTopIndexes.length - 1; i >= 0; i--) {
sortedAll.splice(pinnedTopIndexes[i], 1);
}
const pinnedBottom = sortedAll.filter((msg, idx) => {
if (msg.message && msg.message.content && msg.message.content.pin &&
msg.message.content.pin === 'bottom') {
pinnedBottomIndexes.push(idx);
return true;
}
return false;
});
for (let idx = pinnedBottomIndexes.length - 1; idx >= 0; idx--) {
sortedAll.splice(pinnedBottomIndexes[idx], 1);
}
return [...pinnedTop, ...sortedAll, ...pinnedBottom];
}
async getInboxBySegment(
segmentId: number | string,
segmentOnly?: boolean
): Promise<EngagementMessage[]> {
return this.networkClient.post(`/App/${this.appId}/getInboxBySegment/${segmentId}`, {
segmentOnly
})
.then((r: any) => r.data)
.then((list: any) => list.map((data: any) => {
return {
id: data.id,
published: new Date(data.published),
message: JSON.parse(data.message),
title: data.title,
inbox: data.inbox,
attributes: data.attributes
};
}))
.then((messages: EngagementMessage[]) => {
this.messages = messages;
this.messageCache = +new Date();
return messages;
})
.catch(async (e: any) => {
console.log('Unable to fetch inbox messages', e);
let ret: EngagementMessage[] = [];
// respond with stale cache if we have it
if (this.messages.length) {
ret = this.messages;
}
return Promise.resolve(ret);
});
}
} | the_stack |
import { Equatable } from "@siteimprove/alfa-equatable";
import { Serializable } from "@siteimprove/alfa-json";
import { Option, None } from "@siteimprove/alfa-option";
import { Result, Err } from "@siteimprove/alfa-result";
import { Slice } from "@siteimprove/alfa-slice";
import * as json from "@siteimprove/alfa-json";
import { Languages } from "./language/data";
/**
* @public
*/
export class Language implements Equatable, Serializable {
public static of(
primary: Language.Primary,
extended: Option<Language.Extended> = None,
script: Option<Language.Script> = None,
region: Option<Language.Region> = None,
variants: Array<Language.Variant> = []
): Language {
return new Language(primary, extended, script, region, variants);
}
private readonly _primary: Language.Primary;
private readonly _extended: Option<Language.Extended>;
private readonly _script: Option<Language.Script>;
private readonly _region: Option<Language.Region>;
private readonly _variants: Array<Language.Variant>;
constructor(
primary: Language.Primary,
extended: Option<Language.Extended>,
script: Option<Language.Script>,
region: Option<Language.Region>,
variants: Array<Language.Variant>
) {
this._primary = primary;
this._extended = extended;
this._script = script;
this._region = region;
this._variants = variants;
}
public get primary(): Language.Primary {
return this._primary;
}
public get extended(): Option<Language.Extended> {
return this._extended;
}
public get script(): Option<Language.Script> {
return this._script;
}
public get region(): Option<Language.Region> {
return this._region;
}
public get variants(): Iterable<Language.Variant> {
return this._variants;
}
public equals(value: unknown): value is this {
return (
value instanceof Language &&
value._primary.equals(this._primary) &&
value._extended.equals(this._extended) &&
value._script.equals(this._script) &&
value._region.equals(this._region) &&
value._variants.length === this._variants.length &&
value._variants.every((variant, i) => variant.equals(this._variants[i]))
);
}
public toJSON(): Language.JSON {
return {
type: "language",
primary: this._primary.toJSON(),
extended: this._extended.map((extended) => extended.toJSON()).getOr(null),
script: this._script.map((script) => script.toJSON()).getOr(null),
region: this._region.map((region) => region.toJSON()).getOr(null),
variants: this._variants.map((variant) => variant.toJSON()),
};
}
public toString(): string {
return [
this._primary,
...this._extended,
...this._script,
...this._region,
...this._variants,
].join("-");
}
}
/**
* @public
*/
export namespace Language {
export interface JSON {
[key: string]: json.JSON;
type: "language";
primary: Primary.JSON;
extended: Extended.JSON | null;
script: Script.JSON | null;
region: Region.JSON | null;
variants: Array<Variant.JSON>;
}
/**
* {@link https://tools.ietf.org/html/bcp47#section-3.1.11}
*/
export type Scope = Exclude<
Languages["primary"][Primary.Name]["scope"],
null
>;
/**
* {@link https://tools.ietf.org/html/bcp47#section-3.1.2}
*/
export abstract class Subtag<
T extends string = string,
N extends string = string
> implements Equatable, Serializable<Subtag.JSON<T, N>> {
protected readonly _name: N;
protected constructor(name: N) {
this._name = name;
}
/**
* {@link https://tools.ietf.org/html/bcp47#section-3.1.3}
*/
public abstract get type(): T;
/**
* {@link https://tools.ietf.org/html/bcp47#section-3.1.4}
*/
public get name(): N {
return this._name;
}
public abstract equals<T extends string, N extends string>(
value: Subtag<T, N>
): boolean;
public abstract equals(value: unknown): value is this;
public abstract toJSON(): Subtag.JSON<T, N>;
public toString(): string {
return this._name;
}
}
export namespace Subtag {
export interface JSON<
T extends string = string,
N extends string = string
> {
[key: string]: json.JSON;
type: T;
name: N;
}
}
/**
* {@link https://tools.ietf.org/html/bcp47#section-2.2.1}
*/
export class Primary extends Subtag<"primary", Primary.Name> {
public static of(name: Primary.Name): Primary {
return new Primary(name);
}
private constructor(name: Primary.Name) {
super(name);
}
public get type(): "primary" {
return "primary";
}
/**
* {@link https://tools.ietf.org/html/bcp47#section-3.1.11}
*/
public get scope(): Option<Scope> {
return Option.from(Languages.primary[this._name].scope);
}
public equals(value: Primary): boolean;
public equals(value: unknown): value is this;
public equals(value: unknown): boolean {
return value instanceof Primary && value._name === this._name;
}
public toJSON(): Primary.JSON {
return {
type: "primary",
name: this._name,
scope: this.scope.getOr(null),
};
}
}
export namespace Primary {
export type Name = keyof Languages["primary"];
export interface JSON extends Subtag.JSON<"primary", Name> {
scope: Scope | null;
}
export function isPrimary(value: unknown): value is Primary {
return value instanceof Primary;
}
export function isName(name: string): name is Name {
return name in Languages.primary;
}
}
export const { of: primary, isPrimary, isName: isPrimaryName } = Primary;
/**
* {@link https://tools.ietf.org/html/bcp47#section-2.2.2}
*/
export class Extended extends Subtag<"extended", Extended.Name> {
public static of(name: Extended.Name): Extended {
return new Extended(name);
}
private constructor(name: Extended.Name) {
super(name);
}
public get type(): "extended" {
return "extended";
}
/**
* {@link https://tools.ietf.org/html/bcp47#section-3.1.8}
*/
public get prefix(): Primary.Name {
return Languages.extended[this._name].prefix;
}
public equals(value: Extended): boolean;
public equals(value: unknown): value is this;
public equals(value: unknown): boolean {
return value instanceof Extended && value._name === this._name;
}
public toJSON(): Extended.JSON {
return {
type: "extended",
name: this._name,
prefix: this.prefix,
};
}
}
export namespace Extended {
export type Name = keyof Languages["extended"];
export interface JSON extends Subtag.JSON<"extended", Name> {
prefix: Primary.Name;
}
export function isExtended(value: unknown): value is Extended {
return value instanceof Extended;
}
export function isName(name: string): name is Name {
return name in Languages.extended;
}
}
export const { of: extended, isExtended, isName: isExtendedName } = Extended;
/**
* {@link https://tools.ietf.org/html/bcp47#section-2.2.3}
*/
export class Script extends Subtag<"script", Script.Name> {
public static of(name: Script.Name): Script {
return new Script(name);
}
private constructor(name: Script.Name) {
super(name);
}
public get type(): "script" {
return "script";
}
public equals(value: Script): boolean;
public equals(value: unknown): value is this;
public equals(value: unknown): boolean {
return value instanceof Script && value._name === this._name;
}
public toJSON(): Script.JSON {
return {
type: "script",
name: this._name,
};
}
}
export namespace Script {
export type Name = keyof Languages["script"];
export interface JSON extends Subtag.JSON<"script", Name> {}
export function isScript(value: unknown): value is Script {
return value instanceof Script;
}
export function isName(name: string): name is Name {
return name in Languages.script;
}
}
export const { of: script, isScript, isName: isScriptName } = Script;
/**
* {@link https://tools.ietf.org/html/bcp47#section-2.2.4}
*/
export class Region extends Subtag<"region", Region.Name> {
public static of(name: Region.Name): Region {
return new Region(name);
}
private constructor(name: Region.Name) {
super(name);
}
public get type(): "region" {
return "region";
}
public equals(value: Region): boolean;
public equals(value: unknown): value is this;
public equals(value: unknown): boolean {
return value instanceof Region && value._name === this._name;
}
public toJSON(): Region.JSON {
return {
type: "region",
name: this._name,
};
}
}
export namespace Region {
export type Name = keyof Languages["region"];
export interface JSON extends Subtag.JSON<"region", Name> {}
export function isRegion(value: unknown): value is Region {
return value instanceof Region;
}
export function isName(name: string): name is Name {
return name in Languages.region;
}
}
export const { of: region, isRegion, isName: isRegionName } = Region;
/**
* {@link https://tools.ietf.org/html/bcp47#section-2.2.5}
*/
export class Variant extends Subtag<"variant", Variant.Name> {
public static of(name: Variant.Name): Variant {
return new Variant(name);
}
private constructor(name: Variant.Name) {
super(name);
}
public get type(): "variant" {
return "variant";
}
/**
* {@link https://tools.ietf.org/html/bcp47#section-3.1.8}
*/
public get prefixes(): ReadonlyArray<string> {
return Languages.variant[this._name].prefixes;
}
public equals(value: Variant): boolean;
public equals(value: unknown): value is this;
public equals(value: unknown): boolean {
return value instanceof Variant && value._name === this._name;
}
public toJSON(): Variant.JSON {
return {
type: "variant",
name: this._name,
prefixes: [...this.prefixes],
};
}
}
export namespace Variant {
export type Name = keyof Languages["variant"];
export interface JSON extends Subtag.JSON<"variant", Name> {
prefixes: Array<string>;
}
export function isVariant(value: unknown): value is Variant {
return value instanceof Variant;
}
export function isName(name: string): name is Name {
return name in Languages.variant;
}
}
export const { of: variant, isVariant, isName: isVariantName } = Variant;
}
/**
* @public
*/
export namespace Language {
export function parse(input: string): Result<Language, string> {
let parts = Slice.of(input.toLowerCase().split("-"));
return parts
.get(0)
.map((name) => {
if (!isPrimaryName(name)) {
return Err.of(`${name} is not a valid primary language`);
}
const primary = Primary.of(name);
parts = parts.slice(1);
const extended = parts.get(0).filter(isExtendedName).map(Extended.of);
if (extended.isSome()) {
parts = parts.slice(1);
}
const script = parts.get(0).filter(isScriptName).map(Script.of);
if (script.isSome()) {
parts = parts.slice(1);
}
const region = parts.get(0).filter(isRegionName).map(Region.of);
if (region.isSome()) {
parts = parts.slice(1);
}
const variants: Array<Variant> = [];
while (true) {
const variant = parts.get(0).filter(isVariantName).map(Variant.of);
if (variant.isSome()) {
parts = parts.slice(1);
variants.push(variant.get());
} else {
break;
}
}
return Result.of<Language, string>(
Language.of(primary, extended, script, region, variants)
);
})
.getOrElse(() => Err.of(`Expected a primary language name`));
}
} | the_stack |
import { Phase } from './defs';
import { inSequence } from '../../../util/function-composer';
import { humanRole, divinerRole } from './roleInfo';
export const phases: Partial<Record<number, Phase>> = {
0: {
// Initial phase: automatically proceed
async step(driver) {
driver.addLog({
mode: 'prepare',
name: driver.t('guide.name'),
comment: driver.t('phase0.stepMessage'),
});
return 1;
},
getStory() {
return {};
},
},
1: {
// Phase 1: speak as audience
async step(driver) {
await driver.sleep(1000);
driver.addLog({
mode: 'prepare',
name: driver.t('guide.name'),
comment: driver.t('phase1.stepMessage1'),
});
await driver.sleep(3000);
driver.addLog({
mode: 'prepare',
name: driver.t('guide.name'),
comment: driver.t('phase1.stepMessage2'),
});
return 2;
},
getStory(driver) {
return {
gameInput: {
// go to next step if user speaks
onSpeak: inSequence(driver.getSpeakHandler(), driver.step),
},
roomHedaerInput: {
join: driver.getRejectionHandler(),
},
};
},
},
2: {
// Phase 2: enter the room
async step(driver) {
driver.join();
await driver.sleep(6e3);
driver.addLog({
mode: 'prepare',
name: driver.t('guide.name'),
comment: driver.t('phase2.stepMessage1'),
});
await driver.sleep(5e3);
driver.addLog({
mode: 'prepare',
name: driver.t('guide.name'),
comment: driver.t('phase2.stepMessage2'),
});
return 3;
},
getStory(driver) {
return {
gameInput: {
onSpeak: driver.getSpeakHandler(),
},
roomHedaerInput: {
join: inSequence(driver.getJoinHandler(), driver.step),
},
};
},
},
3: {
// Phase 3: get ready
async step(driver) {
driver.ready(true);
await driver.sleep(10e3);
// add 5 more players
for (let i = 0; i < 5; i++) {
const realid = `身代わりくん${i + 2}`;
driver.addPlayer({
id: realid,
realid,
name: driver.t(`guide.npc${i + 1}`),
anonymous: false,
icon: null,
winner: null,
jobname: null,
dead: false,
flags: ['ready'],
emitLog: true,
});
await driver.sleep(150);
}
return 4;
},
getStory(driver) {
return {
gameInput: {
onSpeak: driver.getSpeakHandler(),
},
roomHedaerInput: {
join: driver.getJoinHandler(),
unjoin: driver.getUnjoinHandler(),
ready: () => {
const newReady = driver.ready();
if (newReady) {
driver.step();
} else {
driver.cancelStep();
}
},
helper: driver.getRejectionHandler(),
},
};
},
},
4: {
// Phase 4: automatically start game
init(driver) {
driver.step();
},
async step(driver) {
await driver.sleep(600);
driver.addLog({
mode: 'prepare',
name: driver.t('guide.name'),
comment: driver.t('phase4.stepMessage1'),
});
await driver.sleep(5000);
driver.setRoleInfo(humanRole(driver.t, true));
driver.changeGamePhase({
day: 1,
night: true,
gameStart: true,
timer: {
enabled: true,
name: driver.t('game:phase.night'),
target: Date.now() + 30000,
},
});
return 5;
},
getStory(driver) {
return {
roomHedaerInput: {
ready: () => {
const newReady = driver.ready();
if (!newReady) {
driver.cancelStep();
} else {
driver.step();
}
},
},
};
},
},
5: {
// Phase 5: game stared
init(driver) {
driver.step();
},
async step(driver) {
await driver.sleep(3e3);
driver.addLog({
mode: 'gm',
name: driver.t('roles:jobname.GameMaster'),
comment: driver.t('phase5.stepMessage1'),
});
await driver.sleep(27e3);
driver.killPlayer('身代わりくん', 'normal');
driver.changeGamePhase({
day: 2,
night: false,
timer: {
enabled: true,
name: driver.t('game:phase.day'),
target: Date.now() + 330e3,
},
});
driver.setRoleInfo(humanRole(driver.t, false));
driver.openForm({
type: '_day',
objid: 'Human_day',
formType: 'required',
});
await driver.sleep(2e3);
driver.addLog({
mode: 'gm',
name: driver.t('roles:jobname.GameMaster'),
comment: driver.t('phase5.stepMessage2'),
});
await driver.sleep(1e3);
driver.addLog({
mode: 'gm',
name: driver.t('roles:jobname.GameMaster'),
comment: driver.t('phase5.stepMessage3'),
});
return 6;
},
getStory(driver) {
return {
gameInput: {
onSpeak: driver.getSpeakHandler(),
},
};
},
},
6: {
// Phase 6: during day 2
async step(driver, storage) {
// voted
if (storage.day2DayTarget == null) {
return;
}
if (!driver.voteTo(storage.day2DayTarget)) {
return;
}
driver.closeForm('Human_day');
await driver.sleep(4e3);
driver.addLog({
mode: 'gm',
name: driver.t('roles:jobname.GameMaster'),
comment: driver.t('phase6.stepMessage1'),
});
await driver.sleep(7e3);
driver.execute(storage.day2DayTarget, storage.day2DayTarget);
driver.killPlayer(storage.day2DayTarget, 'punish');
driver.changeGamePhase({
day: 2,
night: true,
timer: {
enabled: true,
name: driver.t('game:phase.night'),
target: Date.now() + 150e3,
},
});
driver.setRoleInfo(divinerRole(driver.t, true));
driver.openForm({
type: 'Diviner',
objid: 'Diviner_night',
formType: 'required',
});
return 7;
},
getStory(driver, storage) {
return {
gameInput: {
onSpeak: driver.getSpeakHandler(),
onJobQuery: query => {
console.log(query);
storage.day2DayTarget = query.target;
driver.step();
},
},
};
},
},
7: {
// Phase 7: transition to day 2 night
init(driver) {
driver.step();
},
async step(driver) {
await driver.sleep(3e3);
driver.addLog({
mode: 'gm',
name: driver.t('roles:jobname.GameMaster'),
comment: driver.t('phase7.stepMessage1'),
});
await driver.sleep(6e3);
driver.addLog({
mode: 'gm',
name: driver.t('roles:jobname.GameMaster'),
comment: driver.t('phase7.stepMessage2'),
});
return 8;
},
getStory(driver) {
return {};
},
},
8: {
// Phase 8: during night 2
async step(driver, storage) {
if (storage.day2NightTarget == null) {
return;
}
driver.closeForm('Diviner_night');
const divinerDriver = driver.divinerSkillTo(storage.day2NightTarget);
divinerDriver.select();
await driver.sleep(1e3);
driver.addLog({
mode: 'gm',
name: driver.t('roles:jobname.GameMaster'),
comment: driver.t('phase8.stepMessage1'),
});
await driver.sleep(8e3);
// decide today's werewolf target
storage.day2NightVictim = driver.randomAlivePlayer();
driver.changeGamePhase({
day: 3,
night: false,
timer: {
enabled: true,
name: driver.t('game:phase.day'),
target: Date.now() + 330e3,
},
});
if (storage.day2NightVictim != null) {
driver.killPlayer(storage.day2NightVictim, 'normal');
}
divinerDriver.result();
driver.setRoleInfo(divinerRole(driver.t, false));
driver.openForm({
type: '_day',
objid: 'Human_day',
formType: 'required',
});
await driver.sleep(2e3);
driver.addLog({
mode: 'gm',
name: driver.t('roles:jobname.GameMaster'),
comment: driver.t('phase8.stepMessage2'),
});
return 9;
},
getStory(driver, storage) {
return {
gameInput: {
onSpeak: driver.getSpeakHandler(),
onJobQuery: query => {
console.log(query);
storage.day2NightTarget = query.target;
driver.step();
},
},
};
},
},
9: {
async step(driver, storage) {
if (storage.day3DayTarget == null) {
return;
}
if (!driver.voteTo(storage.day3DayTarget)) {
return;
}
driver.closeForm('Human_day');
await driver.sleep(4e3);
// 2日目の占い先は白なので処刑者から除外
storage.day3DayVictim = driver.randomAlivePlayer(
storage.day2NightTarget || undefined,
);
if (storage.day3DayVictim != null) {
driver.execute(storage.day3DayVictim, storage.day3DayTarget);
driver.killPlayer(storage.day3DayVictim, 'punish');
}
driver.endGame({
loser: storage.day3DayVictim,
});
await driver.sleep(3e3);
driver.addLog({
mode: 'gm',
name: driver.t('roles:jobname.GameMaster'),
comment: driver.t('phase9.stepMessage1'),
});
return 10;
},
getStory(driver, storage) {
return {
gameInput: {
onSpeak: driver.getSpeakHandler(),
onJobQuery: query => {
storage.day3DayTarget = query.target;
driver.step();
},
},
};
},
},
10: {
isFinished: true,
async step() {},
getStory(driver) {
return {
gameInput: {
onSpeak: driver.getSpeakHandler(),
},
};
},
},
}; | the_stack |
import '@polymer/paper-dialog/paper-dialog';
import '@polymer/iron-icons/iron-icons';
import '@polymer/iron-pages/iron-pages';
import '@polymer/iron-icons/editor-icons';
import '@polymer/iron-icons/social-icons';
import '@polymer/paper-icon-button/paper-icon-button';
import '@polymer/paper-item/paper-item';
import '@polymer/paper-listbox/paper-listbox';
import '@polymer/paper-menu-button/paper-menu-button';
import '@polymer/paper-progress/paper-progress';
import '@polymer/paper-tabs/paper-tabs';
import '@polymer/paper-tooltip/paper-tooltip';
import './cloud-install-styles';
import './outline-iconset';
import './outline-help-bubble';
import './outline-metrics-option-dialog';
import './outline-server-progress-step';
import './outline-server-settings';
import './outline-share-dialog';
import './outline-sort-span';
import {html, PolymerElement} from '@polymer/polymer';
import {DirMixin} from '@polymer/polymer/lib/mixins/dir-mixin';
import * as formatting from '../data_formatting';
import {getShortName} from '../location_formatting';
import {getCloudIcon} from './cloud-assets';
import type {PolymerElementProperties} from '@polymer/polymer/interfaces';
import type {DomRepeat} from '@polymer/polymer/lib/elements/dom-repeat';
import type {CloudLocation} from '../../model/location';
import type {AccessKeyId} from '../../model/server';
import type {OutlineHelpBubble} from './outline-help-bubble';
import type {OutlineServerSettings} from './outline-server-settings';
export const MY_CONNECTION_USER_ID = '0';
const progressBarMaxWidthPx = 72;
// Makes an CustomEvent that bubbles up beyond the shadow root.
function makePublicEvent(eventName: string, detail?: object) {
const params: CustomEventInit = {bubbles: true, composed: true};
if (detail !== undefined) {
params.detail = detail;
}
return new CustomEvent(eventName, params);
}
function compare<T>(a: T, b: T): -1|0|1 {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
return 0;
}
interface KeyRowEvent extends Event {
model: { index: number; item: DisplayAccessKey; };
}
/**
* Allows using an optional number as a boolean value without 0 being falsey.
* @returns True if x is neither null nor undefined
*/
function exists(x: number): boolean {
return (x !== null && x !== undefined);
}
/** An access key to be displayed */
export type DisplayAccessKey = {
id: string;
placeholderName: string;
name: string;
accessUrl: string;
transferredBytes: number;
/** The data limit assigned to the key, if it exists. */
dataLimitBytes?: number;
dataLimit?: formatting.DisplayDataAmount;
};
export class ServerView extends DirMixin(PolymerElement) {
static get template() {
return html`
<style include="cloud-install-styles"></style>
<style>
.container {
display: flex;
flex-direction: column;
color: var(--light-gray);
}
#managementView,
#unreachableView {
padding: 24px;
}
.tabs-container {
display: flex;
flex-direction: row;
border-bottom: 1px solid var(--border-color);
}
.tabs-spacer {
flex: 2;
}
paper-tabs {
flex: 1;
--paper-tabs-selection-bar-color: var(--primary-green);
--paper-tab-ink: var(--primary-green);
--paper-tab-content-unselected {
color: var(--dark-gray);
}
}
div[name="connections"],
div[name="settings"],
.access-key-list {
margin-top: 24px;
}
.server-header {
display: flex;
flex-direction: column;
margin: 24px 0;
}
.server-name {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
}
.server-name h3 {
font-size: 36px;
font-weight: 400;
color: #ffffff;
flex: 11;
margin: 0 0 6px 0;
}
.server-location,
.unreachable-server paper-button {
color: var(--medium-gray);
}
.unreachable-server {
flex-direction: column;
align-items: center;
margin-top: 24px;
padding: 72px 48px;
}
.unreachable-server p {
line-height: 22px;
max-width: 50ch;
text-align: center;
color: var(--medium-gray);
}
.unreachable-server .button-container {
padding: 24px 0;
}
.unreachable-server paper-button.try-again-btn {
color: var(--primary-green);
}
.server-img {
width: 142px;
height: 142px;
margin: 24px;
}
.stats-container {
display: flex;
flex-direction: row;
margin: 0 -8px;
}
.stats-card {
flex-direction: column;
flex: 1;
margin: 0 8px;
}
.stats {
margin: 30px 0 18px 0;
color: #fff;
white-space: nowrap;
}
.stats > * {
font-weight: 300;
display: inline-block;
margin: 0;
}
.stats h3 {
font-size: 48px;
}
.stats p,
.stats-card p {
margin: 0;
font-size: 14px;
font-weight: normal;
}
@media (max-width: 938px) {
/* Reduce the cards' size so they fit comfortably on small displays. */
.stats {
margin-top: 24px;
}
.stats h3 {
font-size: 42px;
}
.stats-card p {
font-size: 12px;
}
}
.transfer-stats .stats,
.transfer-stats .stats p {
color: var(--primary-green);
}
.stats-card p,
.stats-card iron-icon {
color: var(--medium-gray);
}
.access-key-list {
flex-direction: column;
padding: 24px 16px 24px 30px;
}
.access-key-row {
display: flex;
align-items: center;
justify-content: center;
margin: 15px 0;
}
.header-row {
font-size: 12px;
color: var(--medium-gray);
margin-bottom: 12px;
}
.header-row paper-button {
color: white;
height: 32px;
font-size: 13px;
padding: 0 28px 0px 28px;
background-color: #00bfa5;
margin: 0px 12px 0px 96px;
height: 36px;
}
.header-row-spacer {
/* 24px (share icon) + 40px (overflow menu) + 8px (margin) */
min-width: 72px;
}
.measurement-container {
display: flex;
flex: 4;
align-items: center;
}
.measurement-container paper-progress {
max-width: 72px;
margin: 0 24px 0 12px;
--paper-progress-height: 8px;
--paper-progress-active-color: var(--primary-green);
}
.measurement-container paper-progress.data-limits {
border: 1px solid var(--primary-green);
border-radius: 2px;
}
@media (max-width: 640px) {
.measurement-container paper-progress {
width: 48px;
}
}
paper-progress.data-limits:hover {
cursor: pointer;
}
.measurement {
/* Space the usage bars evenly */
width: 19ch;
/* We don't want numbers separated from their units */
white-space: nowrap;
font-size: 14px;
color: var(--medium-gray);
line-height: 24px;
}
.access-key-container {
display: flex;
flex: 4;
align-items: center;
}
.sort-icon {
/* Disable click events on the sorting icons, so that the event gets propagated to the
parent, which defines the dataset elements needed for displaying the icon. */
pointer-events: none;
}
#manager-access-key-description {
font-size: 12px;
font-weight: 400;
margin-top: 4px;
color: var(--medium-gray);
}
.manager-access-key-icon.access-key-icon {
height: 48px;
}
.access-key-icon {
width: 42px;
height: 42px;
margin-right: 18px;
}
.access-key-name {
display: flex;
flex-direction: column;
font-weight: 500;
flex: 1;
}
input.access-key-name {
font-family: inherit;
font-size: inherit;
border-top: none;
border-left: none;
border-right: none;
border-bottom: 1px solid transparent;
border-radius: 2px;
padding: 4px 8px;
position: relative;
left: -8px; /* Align with padding */
background: var(--background-contrast-color);
color: var(--light-gray);
}
input.access-key-name::placeholder {
opacity: inherit;
color: inherit;
}
input.access-key-name:hover {
border-bottom-color: var(--border-color);
}
input.access-key-name:focus {
border-bottom-color: var(--primary-green);
border-radius: 0px;
outline: none;
font-weight: normal;
}
.overflow-menu {
display: flex;
justify-content: flex-end;
padding: 0px;
min-width: 40px;
margin-left: 8px;
color: var(--medium-gray);
}
.overflow-menu paper-item {
cursor: pointer;
}
paper-item {
font-size: 14px;
}
paper-listbox iron-icon {
margin-right: 10px;
width: 18px;
}
paper-dropdown {
box-shadow: 0px 0px 20px #999999;
}
#addAccessKeyButton {
background: var(--primary-green);
color: #fff;
border-radius: 50%;
}
.actions {
flex: 1;
display: flex;
justify-content: flex-end;
align-items: center;
text-align: end;
}
.connect-button,
.share-button {
color: white;
padding: 0;
margin: 0;
height: 24px;
width: 24px;
}
.add-new-key {
color: var(--primary-green);
cursor: pointer;
}
outline-help-bubble {
text-align: center;
}
outline-help-bubble h3 {
padding-bottom: 0;
font-weight: 500;
line-height: 28px;
font-size: 16px;
margin: 0px 0px 12px 0px;
}
outline-help-bubble img {
width: 76px;
height: auto;
margin: 12px 0px 24px 0px;
}
.cloud-icon {
opacity: 0.54;
}
.flex-1 {
flex: 1;
}
/* Mirror icons */
:host(:dir(rtl)) iron-icon,
:host(:dir(rtl)) .share-button,
:host(:dir(rtl)) .access-key-icon {
transform: scaleX(-1);
}
</style>
<div class="container">
<iron-pages id="pages" attr-for-selected="id" selected="[[selectedPage]]">
<outline-server-progress-step id="progressView" server-name="[[serverName]]" localize="[[localize]]" progress="[[installProgress]]"></outline-server-progress-step>
<div id="unreachableView">${this.unreachableViewTemplate}</div>
<div id="managementView">${this.managementViewTemplate}</div>
</iron-pages>
</div>
<outline-help-bubble id="getConnectedHelpBubble" vertical-align="bottom" horizontal-align="right">
<img src="images/connect-tip-2x.png">
<h3>[[localize('server-help-connection-title')]]</h3>
<p>[[localize('server-help-connection-description')]]</p>
<paper-button on-tap="_closeGetConnectedHelpBubble">[[localize('server-help-connection-ok')]]</paper-button>
</outline-help-bubble>
<outline-help-bubble id="addAccessKeyHelpBubble" vertical-align="bottom" horizontal-align="left">
<img src="images/key-tip-2x.png">
<h3>[[localize('server-help-access-key-title')]]</h3>
<p>[[localize('server-help-access-key-description')]]</p>
<paper-button on-tap="_closeAddAccessKeyHelpBubble">[[localize('server-help-access-key-next')]]</paper-button>
</outline-help-bubble>
<outline-help-bubble id="dataLimitsHelpBubble" vertical-align="top" horizontal-align="right">
<h3>[[localize('data-limits-dialog-title')]]</h3>
<p>[[localize('data-limits-dialog-text')]]</p>
<paper-button on-tap="_closeDataLimitsHelpBubble">[[localize('ok')]]</paper-button>
</outline-help-bubble>
`;
}
static get unreachableViewTemplate() {
return html`
<div class="server-header">
<div class="server-name">
<h3>[[serverName]]</h3>
</div>
</div>
<div class="card-section unreachable-server">
<img class="server-img" src="images/server-unreachable.png">
<h3>[[localize('server-unreachable')]]</h3>
<p></p>
<div>[[localize('server-unreachable-description')]]</div>
<span hidden\$="[[_isServerManaged(cloudId)]]">[[localize('server-unreachable-managed-description')]]</span>
<span hidden\$="[[!_isServerManaged(cloudId)]]">[[localize('server-unreachable-manual-description')]]</span>
<div class="button-container">
<paper-button on-tap="removeServer" hidden\$="[[_isServerManaged(cloudId)]]">[[localize('server-remove')]]</paper-button>
<paper-button on-tap="destroyServer" hidden\$="[[!_isServerManaged(cloudId)]]">[[localize('server-destroy')]]</paper-button>
<paper-button on-tap="retryDisplayingServer" class="try-again-btn">[[localize('retry')]]</paper-button>
</div>
</div>`;
}
static get managementViewTemplate() {
return html`
<div class="server-header">
<div class="server-name">
<h3>[[serverName]]</h3>
<paper-menu-button horizontal-align="right" class="overflow-menu flex-1" close-on-activate="" no-animations="" dynamic-align="" no-overlap="">
<paper-icon-button icon="more-vert" slot="dropdown-trigger"></paper-icon-button>
<paper-listbox slot="dropdown-content">
<paper-item hidden\$="[[!_isServerManaged(cloudId)]]" on-tap="destroyServer">
<iron-icon icon="icons:remove-circle-outline"></iron-icon>[[localize('server-destroy')]]
</paper-item>
<paper-item hidden\$="[[_isServerManaged(cloudId)]]" on-tap="removeServer">
<iron-icon icon="icons:remove-circle-outline"></iron-icon>[[localize('server-remove')]]
</paper-item>
</paper-listbox>
</paper-menu-button>
</div>
<div class="server-location">[[getShortName(cloudLocation, localize)]]</div>
</div>
<div class="tabs-container">
<div class="tabs-spacer"></div>
<paper-tabs selected="{{selectedTab}}" attr-for-selected="name" noink="">
<paper-tab name="connections">[[localize('server-connections')]]</paper-tab>
<paper-tab name="settings" id="settingsTab">[[localize('server-settings')]]</paper-tab>
</paper-tabs>
</div>
<iron-pages selected="[[selectedTab]]" attr-for-selected="name" on-selected-changed="_selectedTabChanged">
<div name="connections">
<div class="stats-container">
<div class="stats-card transfer-stats card-section">
<iron-icon icon="icons:swap-horiz"></iron-icon>
<div class="stats">
<h3>[[_formatInboundBytesValue(totalInboundBytes, language)]]</h3>
<p>[[_formatInboundBytesUnit(totalInboundBytes, language)]]</p>
</div>
<p>[[localize('server-data-transfer')]]</p>
</div>
<div hidden\$="[[!monthlyOutboundTransferBytes]]" class="stats-card card-section">
<div>
<img class="cloud-icon" src="[[getCloudIcon(cloudId)]]">
</div>
<div class="stats">
<h3>[[_computeManagedServerUtilizationPercentage(totalInboundBytes, monthlyOutboundTransferBytes)]]</h3>
<p>/[[_formatBytesTransferred(monthlyOutboundTransferBytes, language)]]</p>
</div>
<p>[[localize('server-data-used')]]</p>
</div>
<div class="stats-card card-section">
<iron-icon icon="outline-iconset:key"></iron-icon>
<div class="stats">
<h3>[[accessKeyRows.length]]</h3>
<p>[[localize('server-keys')]]</p>
</div>
<p>[[localize('server-access')]]</p>
</div>
</div>
<div class="access-key-list card-section">
<!-- header row -->
<div class="access-key-row header-row">
<outline-sort-span class="access-key-container"
direction="[[_computeColumnDirection('name', accessKeySortBy, accessKeySortDirection)]]"
on-tap="_setSortByOrToggleDirection" data-sort-by="name">
[[localize('server-access-keys')]]
</outline-sort-span>
<outline-sort-span class="measurement-container"
direction="[[_computeColumnDirection('usage', accessKeySortBy, accessKeySortDirection)]]"
on-tap="_setSortByOrToggleDirection" data-sort-by="usage">
[[localize('server-usage')]]
</outline-sort-span>
<span class="flex-1 header-row-spacer"></span>
</div>
<!-- admin row -->
<div class="access-key-row" id="managerRow">
<span class="access-key-container">
<img class="manager-access-key-icon access-key-icon" src="images/manager-key-avatar.svg">
<div class="access-key-name">
<div>[[localize('server-my-access-key')]]</div>
<div id="manager-access-key-description">[[localize('server-connect-devices')]]</div>
</div>
</span>
<span class="measurement-container">
<span class="measurement">
<bdi>[[_formatBytesTransferred(myConnection.transferredBytes, language, "...")]]</bdi>
/
<bdi>[[_formatDataLimitForKey(myConnection, language, localize)]]</bdi>
</span>
<paper-progress max="[[_getRelevantTransferAmountForKey(myConnection)]]" value="[[myConnection.transferredBytes]]" class\$="[[_computePaperProgressClass(myConnection)]]" style\$="[[_computeProgressWidthStyling(myConnection, baselineDataTransfer)]]"></paper-progress>
<paper-tooltip animation-delay="0" offset="0" position="top" hidden\$="[[!_activeDataLimitForKey(myConnection)]]">
[[_getDataLimitsUsageString(myConnection, language, localize)]]
</paper-tooltip>
</span>
<span class="actions">
<span class="flex-1">
<paper-icon-button icon="outline-iconset:devices" class="connect-button" on-tap="_handleConnectPressed"></paper-icon-button>
</span>
<span class="flex-1">
<paper-icon-button icon="icons:perm-data-setting" hidden\$="[[!hasPerKeyDataLimitDialog]]" on-tap="_handleShowPerKeyDataLimitDialogPressed"></paper-icon-button>
</span>
</span>
</div>
<div id="accessKeysContainer">
<!-- rows for each access key -->
<template is="dom-repeat" items="{{accessKeyRows}}" filter="isRegularConnection" sort="{{_sortAccessKeys(accessKeySortBy, accessKeySortDirection)}}" observe="name transferredBytes">
<!-- TODO(alalama): why is observe not responding to rename? -->
<div class="access-key-row">
<span class="access-key-container">
<img class="access-key-icon" src="images/key-avatar.svg">
<input type="text" class="access-key-name" id\$="access-key-[[item.id]]" placeholder="{{item.placeholderName}}" value="[[item.name]]" on-blur="_handleNameInputBlur" on-keydown="_handleNameInputKeyDown">
</span>
<span class="measurement-container">
<span class="measurement">
<bdi>[[_formatBytesTransferred(item.transferredBytes, language, "...")]]</bdi>
/
<bdi>[[_formatDataLimitForKey(item, language, localize)]]</bdi>
</span>
<paper-progress max="[[_getRelevantTransferAmountForKey(item)]]" value="[[item.transferredBytes]]" class\$="[[_computePaperProgressClass(item)]]" style\$="[[_computeProgressWidthStyling(item, baselineDataTransfer)]]"></paper-progress>
<paper-tooltip animation-delay="0" offset="0" position="top" hidden\$="[[!_activeDataLimitForKey(item)]]">
[[_getDataLimitsUsageString(item, language, localize)]]
</paper-tooltip>
</span>
<span class="actions">
<span class="flex-1">
<paper-icon-button icon="outline-iconset:share" class="share-button" on-tap="_handleShareCodePressed"></paper-icon-button>
</span>
<span class="flex-1">
<paper-menu-button horizontal-align="right" class="overflow-menu" close-on-activate="" no-animations="" no-overlap="" dynamic-align="">
<paper-icon-button icon="more-vert" slot="dropdown-trigger"></paper-icon-button>
<paper-listbox slot="dropdown-content">
<paper-item on-tap="_handleRenameAccessKeyPressed">
<iron-icon icon="icons:create"></iron-icon>[[localize('server-access-key-rename')]]
</paper-item>
<paper-item on-tap="_handleRemoveAccessKeyPressed">
<iron-icon icon="icons:delete"></iron-icon>[[localize('remove')]]
</paper-item>
<paper-item hidden\$="[[!hasPerKeyDataLimitDialog]]" on-tap="_handleShowPerKeyDataLimitDialogPressed">
<iron-icon icon="icons:perm-data-setting"></iron-icon>[[localize('data-limit')]]
</paper-item>
</paper-listbox>
</paper-menu-button>
</span>
</span>
</div>
</template>
</div>
<!-- add key button -->
<div class="access-key-row" id="addAccessKeyRow">
<span class="access-key-container">
<paper-icon-button icon="icons:add" on-tap="_handleAddAccessKeyPressed" id="addAccessKeyButton" class="access-key-icon"></paper-icon-button>
<div class="add-new-key" on-tap="_handleAddAccessKeyPressed">[[localize('server-access-key-new')]]</div>
</span>
</div>
</div>
</div>
<div name="settings">
<outline-server-settings id="serverSettings" metrics-id="[[metricsId]]" server-hostname="[[serverHostname]]" server-name="[[serverName]]" server-version="[[serverVersion]]" is-hostname-editable="[[isHostnameEditable]]" server-management-api-url="[[serverManagementApiUrl]]" server-port-for-new-access-keys="[[serverPortForNewAccessKeys]]" is-access-key-port-editable="[[isAccessKeyPortEditable]]" default-data-limit="[[_computeDisplayDataLimit(defaultDataLimitBytes)]]" is-default-data-limit-enabled="{{isDefaultDataLimitEnabled}}" supports-default-data-limit="[[supportsDefaultDataLimit]]" show-feature-metrics-disclaimer="[[showFeatureMetricsDisclaimer]]" server-creation-date="[[serverCreationDate]]" server-monthly-cost="[[monthlyCost]]" server-monthly-transfer-limit="[[_formatBytesTransferred(monthlyOutboundTransferBytes, language)]]" cloud-id="[[cloudId]]" cloud-location="[[cloudLocation]]" metrics-enabled="[[metricsEnabled]]" language="[[language]]" localize="[[localize]]">
</outline-server-settings>
</div>
</iron-pages>`;
}
static get is() {
return 'outline-server-view';
}
static get properties(): PolymerElementProperties {
return {
metricsId: String,
serverId: String,
serverName: String,
serverHostname: String,
serverVersion: String,
isHostnameEditable: Boolean,
serverManagementApiUrl: String,
serverPortForNewAccessKeys: Number,
isAccessKeyPortEditable: Boolean,
serverCreationDate: Date,
cloudLocation: Object,
cloudId: String,
defaultDataLimitBytes: Number,
isDefaultDataLimitEnabled: Boolean,
supportsDefaultDataLimit: Boolean,
showFeatureMetricsDisclaimer: Boolean,
installProgress: Number,
isServerReachable: Boolean,
retryDisplayingServer: Function,
myConnection: Object,
totalInboundBytes: Number,
baselineDataTransfer: Number,
accessKeyRows: Array,
hasNonAdminAccessKeys: Boolean,
metricsEnabled: Boolean,
monthlyOutboundTransferBytes: Number,
monthlyCost: Number,
accessKeySortBy: String,
accessKeySortDirection: Number,
language: String,
localize: Function,
selectedPage: String,
selectedTab: String,
};
}
static get observers() {
return [
'_accessKeysAddedOrRemoved(accessKeyRows.splices)',
'_myConnectionChanged(myConnection)',
];
}
serverId = '';
metricsId = '';
serverName = '';
serverHostname = '';
serverVersion = '';
isHostnameEditable = false;
serverManagementApiUrl = '';
serverPortForNewAccessKeys: number = null;
isAccessKeyPortEditable = false;
serverCreationDate = new Date(0);
cloudLocation: CloudLocation = null;
cloudId = '';
readonly getShortName = getShortName;
readonly getCloudIcon = getCloudIcon;
defaultDataLimitBytes: number = null;
isDefaultDataLimitEnabled = false;
hasPerKeyDataLimitDialog = false;
/** Whether the server supports default data limits. */
supportsDefaultDataLimit = false;
showFeatureMetricsDisclaimer = false;
installProgress = 0;
isServerReachable = false;
/** Callback for retrying to display an unreachable server. */
retryDisplayingServer: () => void = null;
/**
* myConnection has the same fields as each item in accessKeyRows. It may
* be unset in some old versions of Outline that allowed deleting this row
*
* TODO(JonathanDCohen) Refactor out special casing for myConnection. It exists as a separate
* item in the view even though it's also in accessKeyRows. We can have the special casing
* be in display only, so we can just use accessKeyRows[0] and not have extra logic when it's
* not needed.
*/
myConnection: DisplayAccessKey = null;
totalInboundBytes = 0;
/** The number to which access key transfer amounts are compared for progress bar display */
baselineDataTransfer = Number.POSITIVE_INFINITY;
accessKeyRows: DisplayAccessKey[] = [];
hasNonAdminAccessKeys = false;
metricsEnabled = false;
// Initialize monthlyOutboundTransferBytes and monthlyCost to 0, so they can
// be bound to hidden attributes. Initializing to undefined does not
// cause hidden$=... expressions to be evaluated and so elements may be
// shown incorrectly. See:
// https://stackoverflow.com/questions/33700125/polymer-1-0-hidden-attribute-negate-operator
// https://www.polymer-project.org/1.0/docs/devguide/data-binding.html
monthlyOutboundTransferBytes = 0;
monthlyCost = 0;
accessKeySortBy = 'name';
/** The direction to sort: 1 == ascending, -1 == descending */
accessKeySortDirection: -1|1 = 1;
language = 'en';
localize: (msgId: string, ...params: string[]) => string = null;
selectedPage: 'progressView'|'unreachableView'|'managementView' = 'managementView';
selectedTab: 'connections'|'settings' = 'connections';
addAccessKey(accessKey: DisplayAccessKey) {
// TODO(fortuna): Restore loading animation.
// TODO(fortuna): Restore highlighting.
this.push('accessKeyRows', accessKey);
// Force render the access key list so that the input is present in the DOM
this.$.accessKeysContainer.querySelector<DomRepeat>('dom-repeat').render();
const input = this.shadowRoot.querySelector<HTMLInputElement>(`#access-key-${accessKey.id}`);
input.select();
}
removeAccessKey(accessKeyId: string) {
for (let ui = 0; ui < this.accessKeyRows.length; ui++) {
if (this.accessKeyRows[ui].id === accessKeyId) {
this.splice('accessKeyRows', ui, 1);
return;
}
}
}
updateAccessKeyRow(accessKeyId: string, fields: object) {
let newAccessKeyRow;
if (accessKeyId === MY_CONNECTION_USER_ID) {
newAccessKeyRow = Object.assign({}, this.get('myConnection'), fields);
this.set('myConnection', newAccessKeyRow);
}
for (const accessKeyRowIndex in this.accessKeyRows) {
if (this.accessKeyRows[accessKeyRowIndex].id === accessKeyId) {
newAccessKeyRow = Object.assign({}, this.get(['accessKeyRows', accessKeyRowIndex]), fields);
this.set(['accessKeyRows', accessKeyRowIndex], newAccessKeyRow);
return;
}
}
}
// Help bubbles should be shown after this outline-server-view
// is on the screen (e.g. selected in iron-pages). If help bubbles
// are initialized before this point, setPosition will not work and
// they will appear in the top left of the view.
showGetConnectedHelpBubble() {
return this._showHelpBubble('getConnectedHelpBubble', 'managerRow');
}
showAddAccessKeyHelpBubble() {
return this._showHelpBubble('addAccessKeyHelpBubble', 'addAccessKeyRow', 'down', 'left');
}
showDataLimitsHelpBubble() {
return this._showHelpBubble('dataLimitsHelpBubble', 'settingsTab', 'up', 'right');
}
/** Returns the UI access key with the given ID. */
findUiKey(id: AccessKeyId): DisplayAccessKey {
return id === MY_CONNECTION_USER_ID ? this.myConnection :
this.accessKeyRows.find(key => key.id === id);
}
_closeAddAccessKeyHelpBubble() {
(this.$.addAccessKeyHelpBubble as OutlineHelpBubble).hide();
}
_closeGetConnectedHelpBubble() {
(this.$.getConnectedHelpBubble as OutlineHelpBubble).hide();
}
_closeDataLimitsHelpBubble() {
(this.$.dataLimitsHelpBubble as OutlineHelpBubble).hide();
}
_handleAddAccessKeyPressed() {
this.dispatchEvent(makePublicEvent('AddAccessKeyRequested'));
(this.$.addAccessKeyHelpBubble as OutlineHelpBubble).hide();
}
_handleNameInputKeyDown(event: KeyRowEvent&KeyboardEvent) {
const input = event.target as HTMLInputElement;
if (event.key === 'Escape') {
const accessKey = event.model.item;
input.value = accessKey.name;
input.blur();
} else if (event.key === 'Enter') {
input.blur();
}
}
_handleNameInputBlur(event: KeyRowEvent&FocusEvent) {
const input = event.target as HTMLInputElement;
const accessKey = event.model.item;
const displayName = input.value;
if (displayName === accessKey.name) {
return;
}
input.disabled = true;
this.dispatchEvent(makePublicEvent('RenameAccessKeyRequested', {
accessKeyId: accessKey.id,
newName: displayName,
entry: {
commitName: () => {
input.disabled = false;
// Update accessKeyRows so the UI is updated.
this.accessKeyRows = this.accessKeyRows.map((row) => {
if (row.id !== accessKey.id) {
return row;
}
return {...row, name: displayName};
});
},
revertName: () => {
input.value = accessKey.name;
input.disabled = false;
},
},
}));
}
_handleShowPerKeyDataLimitDialogPressed(event: KeyRowEvent) {
const accessKey = event.model?.item || this.myConnection;
const keyId = accessKey.id;
const keyDataLimitBytes = accessKey.dataLimitBytes;
const keyName = accessKey === this.myConnection ? this.localize('server-my-access-key') :
accessKey.name || accessKey.placeholderName;
const defaultDataLimitBytes =
this.isDefaultDataLimitEnabled ? this.defaultDataLimitBytes : undefined;
const serverId = this.serverId;
this.dispatchEvent(makePublicEvent(
'OpenPerKeyDataLimitDialogRequested',
{keyId, keyDataLimitBytes, keyName, serverId, defaultDataLimitBytes}));
}
_handleRenameAccessKeyPressed(event: KeyRowEvent) {
const input = this.$.accessKeysContainer.querySelectorAll<HTMLInputElement>(
'.access-key-row .access-key-container > input')[event.model.index];
// This needs to be deferred because the closing menu messes up with the focus.
window.setTimeout(() => {
input.focus();
}, 0);
}
_handleConnectPressed() {
(this.$.getConnectedHelpBubble as OutlineHelpBubble).hide();
this.dispatchEvent(makePublicEvent(
'OpenGetConnectedDialogRequested', {accessKey: this.myConnection.accessUrl}));
}
_handleShareCodePressed(event: KeyRowEvent) {
const accessKey = event.model.item;
this.dispatchEvent(
makePublicEvent('OpenShareDialogRequested', {accessKey: accessKey.accessUrl}));
}
_handleRemoveAccessKeyPressed(e: KeyRowEvent) {
const accessKey = e.model.item;
this.dispatchEvent(makePublicEvent('RemoveAccessKeyRequested', {accessKeyId: accessKey.id}));
}
_formatDataLimitForKey(key: DisplayAccessKey, language: string, localize: Function) {
return this._formatDisplayDataLimit(this._activeDataLimitForKey(key), language, localize);
}
_computeDisplayDataLimit(limit?: number) {
return formatting.bytesToDisplayDataAmount(limit);
}
_formatDisplayDataLimit(limit: number, language: string, localize: Function) {
return exists(limit) ? formatting.formatBytes(limit, language) : localize('no-data-limit');
}
_formatInboundBytesUnit(totalBytes: number, language: string) {
// This happens during app startup before we set the language
if (!language) {
return '';
}
return formatting.formatBytesParts(totalBytes, language).unit;
}
_formatInboundBytesValue(totalBytes: number, language: string) {
// This happens during app startup before we set the language
if (!language) {
return '';
}
return formatting.formatBytesParts(totalBytes, language).value;
}
_formatBytesTransferred(numBytes: number, language: string, emptyValue = '') {
if (!numBytes) {
// numBytes may not be set for manual servers, or may be 0 for
// unused access keys.
return emptyValue;
}
return formatting.formatBytes(numBytes, language);
}
_formatMonthlyCost(monthlyCost: number, language: string) {
if (!monthlyCost) {
return '';
}
return new Intl
.NumberFormat(language, {style: 'currency', currency: 'USD', currencyDisplay: 'code'})
.format(monthlyCost);
}
_computeManagedServerUtilizationPercentage(numBytes: number, monthlyLimitBytes: number) {
let utilizationPercentage = 0;
if (monthlyLimitBytes && numBytes) {
utilizationPercentage = Math.round((numBytes / monthlyLimitBytes) * 100);
}
if (document.documentElement.dir === 'rtl') {
return `%${utilizationPercentage}`;
}
return `${utilizationPercentage}%`;
}
_accessKeysAddedOrRemoved(changeRecord: unknown) {
// Check for myConnection and regular access keys.
let hasNonAdminAccessKeys = false;
for (const ui in this.accessKeyRows) {
if (this.accessKeyRows[ui].id === MY_CONNECTION_USER_ID) {
this.myConnection = this.accessKeyRows[ui];
} else {
hasNonAdminAccessKeys = true;
}
}
this.hasNonAdminAccessKeys = hasNonAdminAccessKeys;
}
_myConnectionChanged(myConnection: DisplayAccessKey) {
if (!myConnection) {
(this.$.getConnectedHelpBubble as OutlineHelpBubble).hide();
}
}
_selectedTabChanged() {
if (this.selectedTab === 'settings') {
this._closeAddAccessKeyHelpBubble();
this._closeGetConnectedHelpBubble();
this._closeDataLimitsHelpBubble();
(this.$.serverSettings as OutlineServerSettings).setServerName(this.serverName);
}
}
_showHelpBubble(
helpBubbleId: string, positionTargetId: string, arrowDirection = 'down', arrowAlignment = 'right') {
return new Promise(resolve => {
const helpBubble = this.$[helpBubbleId] as OutlineHelpBubble;
helpBubble.show(this.$[positionTargetId], arrowDirection, arrowAlignment);
helpBubble.addEventListener('outline-help-bubble-dismissed', resolve);
});
}
isRegularConnection(item: DisplayAccessKey) {
return item.id !== MY_CONNECTION_USER_ID;
}
_computeColumnDirection(columnName: string, accessKeySortBy: string,
accessKeySortDirection: -1|1) {
if (columnName === accessKeySortBy) {
return accessKeySortDirection;
}
return 0;
}
_setSortByOrToggleDirection(e: MouseEvent) {
const element = e.target as HTMLElement;
const sortBy = element.dataset.sortBy;
if (this.accessKeySortBy !== sortBy) {
this.accessKeySortBy = sortBy;
this.accessKeySortDirection = sortBy === 'usage' ? -1 : 1;
} else {
this.accessKeySortDirection *= -1;
}
}
_sortAccessKeys(accessKeySortBy: string, accessKeySortDirection: -1|1) {
if (accessKeySortBy === 'usage') {
return (a: DisplayAccessKey, b: DisplayAccessKey) => {
return (a.transferredBytes - b.transferredBytes) * accessKeySortDirection;
};
}
// Default to sorting by name.
return (a: DisplayAccessKey, b: DisplayAccessKey) => {
if (a.name && b.name) {
return compare(a.name.toUpperCase(), b.name.toUpperCase()) * accessKeySortDirection;
} else if (a.name) {
return -1;
} else if (b.name) {
return 1;
} else {
return 0;
}
};
}
destroyServer() {
this.dispatchEvent(makePublicEvent('DeleteServerRequested', {serverId: this.serverId}));
}
removeServer() {
this.dispatchEvent(makePublicEvent('ForgetServerRequested', {serverId: this.serverId}));
}
_isServerManaged(cloudId: string) {
return !!cloudId;
}
_activeDataLimitForKey(accessKey?: DisplayAccessKey): number {
if (!accessKey) {
// We're in app startup
return null;
}
if (exists(accessKey.dataLimitBytes)) {
return accessKey.dataLimitBytes;
}
return this.isDefaultDataLimitEnabled ? this.defaultDataLimitBytes : null;
}
_computePaperProgressClass(accessKey: DisplayAccessKey) {
return exists(this._activeDataLimitForKey(accessKey)) ? 'data-limits' : '';
}
_getRelevantTransferAmountForKey(accessKey: DisplayAccessKey) {
if (!accessKey) {
// We're in app startup
return null;
}
const activeLimit = this._activeDataLimitForKey(accessKey);
return exists(activeLimit) ? activeLimit : accessKey.transferredBytes;
}
_computeProgressWidthStyling(
accessKey: DisplayAccessKey, baselineDataTransfer: number) {
const relativeTransfer = this._getRelevantTransferAmountForKey(accessKey);
const width = Math.floor(progressBarMaxWidthPx * relativeTransfer / baselineDataTransfer);
// It's important that there's no space in between width and "px" in order for Chrome to accept
// the inline style string.
return `width: ${width}px;`;
}
_getDataLimitsUsageString(accessKey: DisplayAccessKey, language: string,
localize: Function) {
if (!accessKey) {
// We're in app startup
return '';
}
const activeDataLimit = this._activeDataLimitForKey(accessKey);
const used = this._formatBytesTransferred(accessKey.transferredBytes, language, '0');
const total = this._formatDisplayDataLimit(activeDataLimit, language, localize);
return localize('data-limits-usage', 'used', used, 'total', total);
}
}
customElements.define(ServerView.is, ServerView); | the_stack |
import { $TSAny, $TSContext, $TSObject, JSONUtilities, pathManager, stateManager } from 'amplify-cli-core';
import { FunctionBreadcrumbs, FunctionParameters, FunctionTriggerParameters } from 'amplify-function-plugin-interface';
import * as fs from 'fs-extra';
import _ from 'lodash';
import * as path from 'path';
import { categoryName } from '../../../constants';
import { cfnTemplateSuffix, functionParametersFileName, parametersFileName, provider, ServiceName } from './constants';
import { generateLayerCfnObj } from './lambda-layer-cloudformation-template';
import { convertLambdaLayerMetaToLayerCFNArray } from './layerArnConverter';
import { FunctionSecretsStateManager } from '../secrets/functionSecretsStateManager';
import { isFunctionPushed } from './funcionStateUtils';
import { hasExistingSecrets, hasSetSecrets } from '../secrets/secretDeltaUtilities';
import { LayerCloudState } from './layerCloudState';
import { isMultiEnvLayer, isNewVersion, loadPreviousLayerHash } from './layerHelpers';
import { createLayerConfiguration, loadLayerParametersJson, saveLayerPermissions } from './layerConfiguration';
import { LayerParameters, LayerRuntime, LayerVersionMetadata } from './layerParams';
import { removeLayerFromTeamProviderInfo } from './layerMigrationUtils';
import { saveEnvironmentVariables } from './environmentVariablesHelper';
// handling both FunctionParameters and FunctionTriggerParameters here is a hack
// ideally we refactor the auth trigger flows to use FunctionParameters directly and get rid of FunctionTriggerParameters altogether
export async function createFunctionResources(context: $TSContext, parameters: FunctionParameters | FunctionTriggerParameters) {
context.amplify.updateamplifyMetaAfterResourceAdd(
categoryName,
parameters.resourceName || parameters.functionName,
translateFuncParamsToResourceOpts(parameters),
);
// copy template, CFN and parameter files
copyTemplateFiles(context, parameters);
await saveMutableState(context, parameters);
saveCFNParameters(parameters);
context.amplify.leaveBreadcrumbs(categoryName, parameters.resourceName, createBreadcrumbs(parameters));
}
export const createLayerArtifacts = (context: $TSContext, parameters: LayerParameters): string => {
const layerDirPath = ensureLayerFolders(parameters);
createLayerState(parameters, layerDirPath);
createLayerCfnFile(parameters, layerDirPath);
addLayerToAmplifyMeta(context, parameters);
return layerDirPath;
};
// updates the layer resources and returns the resource directory
const defaultOpts = {
updateLayerParams: true,
generateCfnFile: true,
updateMeta: true,
updateDescription: true,
};
export const updateLayerArtifacts = async (
context: $TSContext,
parameters: LayerParameters,
options: Partial<typeof defaultOpts> = {},
): Promise<boolean> => {
options = _.assign(defaultOpts, options);
const layerDirPath = ensureLayerFolders(parameters);
let updated = false;
if (options.updateLayerParams) {
updated ||= saveLayerPermissions(layerDirPath, parameters.permissions);
}
if (options.updateDescription) {
updated ||= saveLayerDescription(parameters.layerName, parameters.description);
}
if (options.generateCfnFile) {
const cfnTemplateFilePath = path.join(layerDirPath, getCfnTemplateFileName(parameters.layerName));
const currentCFNTemplate = JSONUtilities.readJson(cfnTemplateFilePath, {
throwIfNotExist: false,
});
const updatedCFNTemplate = await updateLayerCfnFile(context, parameters, layerDirPath);
updated ||= _.isEqual(currentCFNTemplate, updatedCFNTemplate);
}
if (options.updateMeta) {
updateLayerInAmplifyMeta(parameters);
}
return updated;
};
export function removeLayerArtifacts(context: $TSContext, layerName: string) {
if (isMultiEnvLayer(layerName)) {
removeLayerFromTeamProviderInfo(undefined, context.amplify.getEnvInfo().envName, layerName);
}
}
// ideally function update should be refactored so this function does not need to be exported
export async function saveMutableState(
context: $TSContext,
parameters:
| Partial<
Pick<
FunctionParameters,
'mutableParametersState' | 'resourceName' | 'lambdaLayers' | 'functionName' | 'secretDeltas' | 'environmentVariables'
>
>
| FunctionTriggerParameters,
) {
createParametersFile(buildParametersFileObj(parameters), parameters.resourceName || parameters.functionName, functionParametersFileName);
saveEnvironmentVariables(context, parameters.resourceName, parameters.environmentVariables);
await syncSecrets(context, parameters);
}
// ideally function update should be refactored so this function does not need to be exported
export function saveCFNParameters(
parameters: Partial<Pick<FunctionParameters, 'cloudwatchRule' | 'resourceName'>> | FunctionTriggerParameters,
) {
if ('trigger' in parameters) {
const params = {
modules: parameters.modules.join(),
resourceName: parameters.resourceName,
};
createParametersFile(params, parameters.resourceName, parametersFileName);
}
if ('cloudwatchRule' in parameters) {
const params = {
CloudWatchRule: parameters.cloudwatchRule,
};
createParametersFile(params, parameters.resourceName, parametersFileName);
}
}
async function syncSecrets(context: $TSContext, parameters: Partial<FunctionParameters> | Partial<FunctionTriggerParameters>) {
if ('secretDeltas' in parameters) {
const doConfirm = hasSetSecrets(parameters.secretDeltas) && isFunctionPushed(parameters.resourceName);
const confirmed = doConfirm
? await context.amplify.confirmPrompt('This will immediately update secret values in the cloud. Do you want to continue?', true)
: true;
if (confirmed) {
const functionSecretsStateManager = await FunctionSecretsStateManager.getInstance(context);
await functionSecretsStateManager.syncSecretDeltas((parameters as FunctionParameters)?.secretDeltas, parameters.resourceName);
}
if (hasExistingSecrets(parameters.secretDeltas)) {
context.print.info('Use the AWS SSM GetParameter API to retrieve secrets in your Lambda function.');
context.print.info(
'More information can be found here: https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetParameter.html',
);
}
}
}
function createLayerState(parameters: LayerParameters, layerDirPath: string) {
writeLayerRuntimesToParametersFile(parameters);
saveLayerDescription(parameters.layerName, parameters.description);
createLayerConfiguration(layerDirPath, { permissions: parameters.permissions, runtimes: parameters.runtimes });
}
function writeLayerRuntimesToParametersFile(parameters: LayerParameters) {
const runtimes = parameters.runtimes.reduce((runtimes, r) => {
runtimes = runtimes.concat(r.cloudTemplateValues);
return runtimes;
}, []);
if (runtimes.length > 0) {
stateManager.setResourceParametersJson(undefined, categoryName, parameters.layerName, { runtimes });
}
}
function saveLayerDescription(layerName: string, description?: string): boolean {
const layerConfig = loadLayerParametersJson(layerName);
let updated = false;
if (layerConfig.description !== description) {
stateManager.setResourceParametersJson(undefined, categoryName, layerName, {
...layerConfig,
description,
});
updated = true;
}
return updated;
}
function copyTemplateFiles(context: $TSContext, parameters: FunctionParameters | FunctionTriggerParameters) {
// copy function template files
const destDir = pathManager.getBackendDirPath();
const copyJobs = parameters.functionTemplate.sourceFiles.map(file => {
return {
dir: parameters.functionTemplate.sourceRoot,
template: file,
target: path.join(
destDir,
categoryName,
parameters.resourceName,
_.get(parameters.functionTemplate.destMap, file, file.replace(/\.ejs$/, '')),
),
};
});
// this is a hack to reuse some old code
let templateParams: $TSAny = parameters;
if ('trigger' in parameters) {
let triggerEnvs = context.amplify.loadEnvResourceParameters(context, categoryName, parameters.resourceName);
parameters.triggerEnvs = JSONUtilities.parse(parameters.triggerEnvs) || [];
parameters.triggerEnvs.forEach(c => {
triggerEnvs[c.key] = c.value;
});
templateParams = _.assign(templateParams, triggerEnvs);
}
templateParams = _.assign(templateParams, {
enableCors: process.env.AMPLIFY_CLI_LAMBDA_CORS_HEADER === 'true',
});
context.amplify.copyBatch(context, copyJobs, templateParams, false);
// copy cloud resource template
const cloudTemplateJob = {
dir: '',
template: parameters.cloudResourceTemplatePath,
target: path.join(destDir, categoryName, parameters.resourceName, `${parameters.resourceName}-cloudformation-template.json`),
};
const copyJobParams: $TSAny = parameters;
if ('lambdaLayers' in parameters) {
const layerCFNValues = convertLambdaLayerMetaToLayerCFNArray(parameters.lambdaLayers, context.amplify.getEnvInfo().envName);
copyJobParams.lambdaLayersCFNArray = layerCFNValues;
}
context.amplify.copyBatch(context, [cloudTemplateJob], copyJobParams, false);
}
export function ensureLayerFolders(parameters: LayerParameters) {
const projectBackendDirPath = pathManager.getBackendDirPath();
const layerDirPath = path.join(projectBackendDirPath, categoryName, parameters.layerName);
fs.ensureDirSync(path.join(layerDirPath, 'opt'));
parameters.runtimes.forEach(runtime => ensureLayerRuntimeFolder(layerDirPath, runtime));
return layerDirPath;
}
// Default files are only created if the path does not exist
function ensureLayerRuntimeFolder(layerDirPath: string, runtime: LayerRuntime) {
const runtimeDirPath = path.join(layerDirPath, 'lib', runtime.layerExecutablePath);
if (!fs.pathExistsSync(runtimeDirPath)) {
fs.ensureDirSync(runtimeDirPath);
fs.writeFileSync(path.join(runtimeDirPath, 'README.txt'), 'Replace this file with your layer files');
(runtime.layerDefaultFiles || []).forEach(defaultFile =>
fs.writeFileSync(path.join(layerDirPath, 'lib', defaultFile.path, defaultFile.filename), defaultFile.content),
);
}
}
function createLayerCfnFile(parameters: LayerParameters, layerDirPath: string) {
const layerCfnObj = generateLayerCfnObj(true, parameters);
const layerCfnFilePath = path.join(layerDirPath, getCfnTemplateFileName(parameters.layerName));
JSONUtilities.writeJson(layerCfnFilePath, layerCfnObj);
}
async function updateLayerCfnFile(context: $TSContext, parameters: LayerParameters, layerDirPath: string): Promise<$TSObject> {
let layerVersionList: LayerVersionMetadata[] = [];
if (loadPreviousLayerHash(parameters.layerName)) {
const layerCloudState = LayerCloudState.getInstance(parameters.layerName);
layerVersionList = await layerCloudState.getLayerVersionsFromCloud(context, parameters.layerName);
}
const _isNewVersion = await isNewVersion(parameters.layerName);
const cfnTemplate = saveCFNFileWithLayerVersion(layerDirPath, parameters, _isNewVersion, layerVersionList);
return cfnTemplate;
}
const setParametersInAmplifyMeta = (layerName: string, parameters: LayerMetaAndBackendConfigParams) => {
const amplifyMeta = stateManager.getMeta();
_.set(amplifyMeta, [categoryName, layerName], parameters);
stateManager.setMeta(undefined, amplifyMeta);
};
const assignParametersInAmplifyMeta = (layerName: string, parameters: LayerMetaAndBackendConfigParams) => {
const amplifyMeta = stateManager.getMeta();
const layer = _.get(amplifyMeta, [categoryName, layerName], {});
_.assign(layer, parameters);
_.set(amplifyMeta, [categoryName, layerName], layer);
stateManager.setMeta(undefined, amplifyMeta);
};
const addLayerToAmplifyMeta = (context: $TSContext, parameters: LayerParameters) => {
context.amplify.updateamplifyMetaAfterResourceAdd(categoryName, parameters.layerName, amplifyMetaAndBackendParams(parameters));
setParametersInAmplifyMeta(parameters.layerName, amplifyMetaAndBackendParams(parameters));
};
const updateLayerInAmplifyMeta = (parameters: LayerParameters) => {
assignParametersInAmplifyMeta(parameters.layerName, amplifyMetaAndBackendParams(parameters));
};
interface LayerMetaAndBackendConfigParams {
providerPlugin: string;
service: string;
build: boolean;
versionHash?: string;
}
const amplifyMetaAndBackendParams = (parameters: LayerParameters): LayerMetaAndBackendConfigParams => {
const metadata: LayerMetaAndBackendConfigParams = {
providerPlugin: parameters.providerContext.provider,
service: parameters.providerContext.service,
build: parameters.build,
};
if (parameters.versionHash) {
metadata.versionHash = parameters.versionHash;
}
return metadata;
};
export function createParametersFile(parameters: $TSObject, resourceName: string, parametersFileName: string) {
const parametersFilePath = path.join(pathManager.getBackendDirPath(), categoryName, resourceName, parametersFileName);
const currentParameters = JSONUtilities.readJson<$TSAny>(parametersFilePath, { throwIfNotExist: false }) || {};
delete currentParameters.mutableParametersState; // this field was written in error in a previous version of the cli
JSONUtilities.writeJson(parametersFilePath, { ...currentParameters, ...parameters });
}
function buildParametersFileObj(
parameters: Partial<Pick<FunctionParameters, 'mutableParametersState' | 'lambdaLayers'>> | FunctionTriggerParameters,
): $TSAny {
if ('trigger' in parameters) {
return _.omit(parameters, ['functionTemplate', 'cloudResourceTemplatePath']);
}
return { ...parameters.mutableParametersState, ..._.pick(parameters, ['lambdaLayers']) };
}
function translateFuncParamsToResourceOpts(params: FunctionParameters | FunctionTriggerParameters): $TSAny {
let result: $TSObject = {
build: true,
providerPlugin: provider,
service: ServiceName.LambdaFunction,
};
if (!('trigger' in params)) {
result.dependsOn = params.dependsOn;
}
return result;
}
function createBreadcrumbs(params: FunctionParameters | FunctionTriggerParameters): FunctionBreadcrumbs {
if ('trigger' in params) {
return {
pluginId: 'amplify-nodejs-function-runtime-provider',
functionRuntime: 'nodejs',
useLegacyBuild: true,
defaultEditorFile: 'src/index.js',
};
}
return {
pluginId: params.runtimePluginId,
functionRuntime: params.runtime.value,
useLegacyBuild: params.runtime.value === 'nodejs' ? true : false, // so we can update node builds in the future
defaultEditorFile: params.functionTemplate.defaultEditorFile,
};
}
function saveCFNFileWithLayerVersion(
layerDirPath: string,
parameters: LayerParameters,
_isNewVersion: boolean,
layerVersionList: LayerVersionMetadata[],
) {
const cfnTemplate = generateLayerCfnObj(_isNewVersion, parameters, layerVersionList);
JSONUtilities.writeJson(path.join(layerDirPath, getCfnTemplateFileName(parameters.layerName)), cfnTemplate);
return cfnTemplate;
}
const getCfnTemplateFileName = (layerName: string) => `${layerName}${cfnTemplateSuffix}`; | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.