text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
declare module 'hamjest' { type Value = any; export class Matcher { constructor(fns?: {matches?: (value: Value) => boolean; describeTo?: (description: Description) => void; describeMismatch?: (value: Value, description: Description) => void}); matches(actual: Value): boolean; describeTo(description: Description): void; describeMismatch(value: Value, description: Description): void; } type ValueOrMatcher = Value | Matcher; export class TypeSafeMatcher<T> extends Matcher { constructor(fns?: {isExpectedType?: (value: Value) => boolean; matchesSafely?: (actual: T) => boolean; describeTo?: (description: Description) => void; describeMismatchSafely?: (value: T, description: Description) => void}); isExpectedType(actual: Value): boolean; matchesSafely(actual: T): boolean; describeMismatchSafely(value: T, description: Description): void; } export class FeatureMatcher<T> extends Matcher { constructor(valueOrMatcher: ValueOrMatcher, featureDescription: string, featureName: string, featureFunction: (actual: Value) => T) } export class Description { useJsonForObjects: boolean; indentation: number; append(text: string): Description; indented(describingfn: () => Description): Description | Promise<void>; appendDescriptionOf(selfDescribing: Matcher): Description; appendValue(value: Value): Description; appendNonJson(value: Value): void; appendList(start: string, separator: string, end: string, list: Value): Description; get(): string; } export function assertThat(actual: Value, matcher: ValueOrMatcher): void; export function assertThat(reason: string, actual: Value, matcher: ValueOrMatcher): void; export function promiseThat(actual: Promise<Value>, matcher: Matcher): Promise<any>; export function promiseThat(reason: string, actual: Promise<Value>, matcher: Matcher): Promise<any>; export function fail(reason?: string): void; // anything: require('./matchers/IsAnything').anything,; export function anything(): Matcher; // strictlyEqualTo: require('./matchers/IsSame').strictlyEqualTo,; export function strictlyEqualTo(expectedValue: Value): Matcher; // is: require('./matchers/Is').is,; export function is(valueOrMatcher: ValueOrMatcher): Matcher; // not: require('./matchers/IsNot').not,; export function not(valueOrMatcher: ValueOrMatcher): Matcher; // equalTo: IsEqual.equalTo,; export function equalTo(expectedValue: Value): Matcher; // truthy: require('./matchers/truthy'),; export function truthy(): Matcher; // falsy: require('./matchers/falsy'),; export function falsy(): Matcher; // falsey: require('./matchers/falsy'),; export function falsey(): Matcher; // defined: require('./matchers/IsDefined').defined,; export function defined(): Matcher; // undefined: require('./matchers/IsDefined').undefined,; export function undefined(): Matcher; // undef: require('./matchers/IsDefined').undefined,; export function undef(): Matcher; // instanceOf: require('./matchers/IsInstanceOf').instanceOf,; export function instanceOf(expectedType: Value): Matcher; // array: require('./matchers/IsArray').array,; export function array(): TypeSafeMatcher<Array<any>>; // bool: require('./matchers/IsBoolean').bool,; export function bool(): TypeSafeMatcher<boolean>; // boolean: require('./matchers/IsBoolean').bool,; export function boolean(): TypeSafeMatcher<boolean>; // date: require('./matchers/IsDate').date,; export function date(): TypeSafeMatcher<Date>; // func: require('./matchers/IsFunction').func,; export function func(): Matcher; // number: require('./matchers/IsNumber').number,; export function number(): TypeSafeMatcher<number>; // object: require('./matchers/IsObject').object,; export function object(): TypeSafeMatcher<object>; // regExp: require('./matchers/IsRegExp').regExp,; export function regExp(): TypeSafeMatcher<RegExp>; // string: require('./matchers/IsString').string,; export function string(): TypeSafeMatcher<string>; // containsString: SubstringMatcher.containsString,; export function containsString(subString: string): TypeSafeMatcher<string>; // containsStrings: SubstringMatcher.containsStrings,; export function containsStrings(...subStrings: string[]): TypeSafeMatcher<string>; // startsWith: SubstringMatcher.startsWith,; export function startsWith(subString: string): TypeSafeMatcher<string>; // endsWith: SubstringMatcher.endsWith,; export function endsWith(subString: string): TypeSafeMatcher<string>; // matchesPattern: require('./matchers/IsStringMatching').matchesPattern,; export function matchesPattern(stringOrPattern: string | RegExp): TypeSafeMatcher<string>; // matches: require('./matchers/matches'),; export function matches(target: Value): TypeSafeMatcher<Matcher>; // failsToMatch: require('./matchers/failsToMatch'),; export function failsToMatch(target: Value, descriptionMatcher?: ValueOrMatcher): TypeSafeMatcher<Matcher>; // hasDescription: require('./matchers/hasDescription'),; export function hasDescription(matcher: ValueOrMatcher): TypeSafeMatcher<Matcher>; // lessThan: NumberComparisonMatcher.lessThan,; export function lessThan(number: number): TypeSafeMatcher<number>; // lessThanOrEqualTo: NumberComparisonMatcher.lessThanOrEqualTo,; export function lessThanOrEqualTo(number: number): TypeSafeMatcher<number>; // greaterThan: NumberComparisonMatcher.greaterThan,; export function greaterThan(number: number): TypeSafeMatcher<number>; // greaterThanOrEqualTo: NumberComparisonMatcher.greaterThanOrEqualTo,; export function greaterThanOrEqualTo(number: number): TypeSafeMatcher<number>; // closeTo: require('./matchers/IsCloseTo').closeTo,; export function closeTo(number: number, delta: number): TypeSafeMatcher<number>; // inRange: require('./matchers/inRange'),; export function inRange(upperBound: number): TypeSafeMatcher<number>; export function inRange(lowerBound: number, upperBound: number): TypeSafeMatcher<number>; // after: DateComparisonMatcher.after,; export function after(date: Date): TypeSafeMatcher<Date>; // afterOrEqualTo: DateComparisonMatcher.afterOrEqualTo,; export function afterOrEqualTo(date: Date): TypeSafeMatcher<Date>; // before: DateComparisonMatcher.before,; export function before(date: Date): TypeSafeMatcher<Date>; // beforeOrEqualTo: DateComparisonMatcher.beforeOrEqualTo,; export function beforeOrEqualTo(date: Date): TypeSafeMatcher<Date>; // allOf: require('./matchers/AllOf').allOf,; export function allOf(...matchers: Matcher[]): Matcher; // anyOf: require('./matchers/AnyOf').anyOf,; export function anyOf(...matchers: Matcher[]): Matcher; // everyItem: require('./matchers/Every').everyItem,; export function everyItem(valueOrMatcher: ValueOrMatcher): Matcher; // hasItem: require('./matchers/IsArrayWithItem').hasItem,; export function hasItem(valueOrMatcher: ValueOrMatcher): TypeSafeMatcher<Array<any>>; // hasItems: require('./matchers/IsArrayWithItems').hasItems,; export function hasItems(...valueOrMatcher: ValueOrMatcher[]): TypeSafeMatcher<Array<any>>; // hasExactlyOneItem: require('./matchers/hasExactlyOneItem'),; export function hasExactlyOneItem(valueOrMatcher: ValueOrMatcher): TypeSafeMatcher<Array<any>>; // contains: require('./matchers/IsArrayContaining').contains,; export function contains(...valueOrMatcher: ValueOrMatcher[]): TypeSafeMatcher<Array<any>>; // containsInAnyOrder: require('./matchers/IsArrayContainingInAnyOrder').containsInAnyOrder,; export function containsInAnyOrder(...valueOrMatcher: ValueOrMatcher[]): TypeSafeMatcher<Array<any>>; // orderedBy: require('./matchers/IsArrayOrderedBy').orderedBy,; export function orderedBy(comparisonFunction: (a: Value, b: Value) => boolean, orderName?: string): TypeSafeMatcher<Array<any>>; // hasSize: require('./matchers/hasSize'),; export function hasSize(size: ValueOrMatcher): Matcher; // isEmpty: require('./matchers/isEmpty'),; export function isEmpty(): Matcher; // empty: require('./matchers/isEmpty'),; export function empty(): Matcher; type PropertiesMatcher = TypeSafeMatcher<object> & {verbose: () => PropertiesMatcher}; // hasProperties: require('./matchers/IsObjectWithProperties').hasProperties,; export function hasProperties(matcher: { [key: string]: ValueOrMatcher }): PropertiesMatcher; export function hasDeepProperties(matcher: { [key: string]: ValueOrMatcher }): PropertiesMatcher; // hasProperty: require('./matchers/IsObjectWithProperties').hasProperty,; export function hasProperty(path: string, valueOrMatcher?: ValueOrMatcher): PropertiesMatcher; // throws: require('./matchers/IsFunctionThrowing').throws,; export function throws(valueOrMatcher?: ValueOrMatcher): Matcher; // returns: require('./matchers/returns'),; export function returns(valueOrMatcher?: ValueOrMatcher): Matcher; // typedError: require('./matchers/typedError'),; export function typedError(type: Value, messageValueOrMatcher: ValueOrMatcher): Matcher; // promise: require('./matchers/IsPromise').promise,; export function promise(): TypeSafeMatcher<Promise<any>>; // fulfilled: require('./matchers/IsFulfilled').fulfilled,; export function fulfilled(valueOrMatcher?: ValueOrMatcher): TypeSafeMatcher<Promise<any>>; // isFulfilledWith: require('./matchers/IsFulfilled').isFulfilledWith,; export function isFulfilledWith(valueOrMatcher?: ValueOrMatcher): TypeSafeMatcher<Promise<any>>; // willBe: require('./matchers/IsFulfilled').isFulfilledWith,; export function willBe(valueOrMatcher: ValueOrMatcher): TypeSafeMatcher<Promise<any>>; // rejected: require('./matchers/IsRejected').rejected,; export function rejected(valueOrMatcher?: ValueOrMatcher): TypeSafeMatcher<Promise<any>>; // isRejectedWith: require('./matchers/IsRejected').isRejectedWith,; export function isRejectedWith(valueOrMatcher?: ValueOrMatcher): TypeSafeMatcher<Promise<any>>; // isMatcher: Matcher.isMatcher,; export function isMatcher(valueOrMatcher: ValueOrMatcher): boolean; // asMatcher: require('./utils/asMatcher'),; export function asMatcher(valueOrMatcher: ValueOrMatcher): Matcher; type ComposingMatcher = (valueOrMatcher: ValueOrMatcher) => Matcher; // acceptingMatcher: require('./utils/acceptingMatcher'),; export function acceptingMatcher<Rtn>(fn: (matcher: Matcher) => Matcher): ComposingMatcher; export function describe(matcher: Matcher): Description; }
the_stack
import { assertActiveElement, assertFocusable, assertNotFocusable, assertRadioGroupLabel, getByText, getRadioGroupOptions, } from "$lib/test-utils/accessibility-assertions"; import { render } from "@testing-library/svelte"; import { RadioGroup, RadioGroupLabel, RadioGroupOption } from "."; import { suppressConsoleLogs } from "$lib/test-utils/suppress-console-logs"; import { click, Keys, press, shift } from "$lib/test-utils/interactions"; import svelte from "svelte-inline-compile"; let mockId = 0; jest.mock('../../hooks/use-id', () => { return { useId: jest.fn(() => ++mockId), } }) beforeEach(() => mockId = 0) beforeAll(() => { // jest.spyOn(window, 'requestAnimationFrame').mockImplementation(setImmediate as any) // jest.spyOn(window, 'cancelAnimationFrame').mockImplementation(clearImmediate as any) }) afterAll(() => jest.restoreAllMocks()) describe('Safe guards', () => { it.each([['RadioGroupOption', RadioGroupOption]])( 'should error when we are using a <%s /> without a parent <RadioGroup />', suppressConsoleLogs((name, Component) => { expect(() => render(Component)).toThrowError( `<${name} /> is missing a parent <RadioGroup /> component.` ) }) ) it( 'should be possible to render a RadioGroup without crashing', suppressConsoleLogs(async () => { render(svelte` <RadioGroup value={undefined} on:change={console.log}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> `); assertRadioGroupLabel({ textContent: 'Pizza Delivery' }) }) ) it('should be possible to render a RadioGroup without options and without crashing', () => { render(RadioGroup, { value: undefined }) }) }) describe('Rendering', () => { it('should be possible to render a RadioGroup, where the first element is tabbable (value is undefined)', async () => { render(svelte` <RadioGroup value={undefined} on:change={console.log}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> `); expect(getRadioGroupOptions()).toHaveLength(3) assertFocusable(getByText('Pickup')) assertNotFocusable(getByText('Home delivery')) assertNotFocusable(getByText('Dine in')) }) it('should be possible to render a RadioGroup, where the first element is tabbable (value is null)', async () => { render(svelte` <RadioGroup value={null} on:change={console.log}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> `); expect(getRadioGroupOptions()).toHaveLength(3) assertFocusable(getByText('Pickup')) assertNotFocusable(getByText('Home delivery')) assertNotFocusable(getByText('Dine in')) }) it('should be possible to render a RadioGroup with an active value', async () => { render(svelte` <RadioGroup value={"home-delivery"} on:change={console.log}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> `); expect(getRadioGroupOptions()).toHaveLength(3) assertNotFocusable(getByText('Pickup')) assertFocusable(getByText('Home delivery')) assertNotFocusable(getByText('Dine in')) }) it('should guarantee the radio option order after a few unmounts', async () => { render(svelte` <script> let showFirst = false; let active; </script> <button on:click={() => showFirst = !showFirst}>Toggle</button> <RadioGroup value={active} on:change={(e) => active = e.detail}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> {#if showFirst} <RadioGroupOption value="pickup">Pickup</RadioGroupOption> {/if} <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> `) await click(getByText('Toggle')) // Render the pickup again await press(Keys.Tab) // Focus first element assertActiveElement(getByText('Pickup')) await press(Keys.ArrowUp) // Loop around assertActiveElement(getByText('Dine in')) await press(Keys.ArrowUp) // Up again assertActiveElement(getByText('Home delivery')) }) it('should be possible to disable a RadioGroup', async () => { let changeFn = jest.fn() render(svelte` <script> let disabled = true; </script> <button on:click={() => disabled = !disabled}>Toggle</button> <RadioGroup value={undefined} on:change={changeFn} {disabled}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> <RadioGroupOption value="slot-prop" data-value="slot-prop" let:checked let:disabled let:active> {JSON.stringify({ checked, disabled, active })} </RadioGroupOption> </RadioGroup> `) // Try to click one a few options await click(getByText('Pickup')) await click(getByText('Dine in')) // Verify that the RadioGroupOption gets the disabled state expect(document.querySelector('[data-value="slot-prop"]')).toHaveTextContent( JSON.stringify({ checked: false, disabled: true, active: false, }) ) // Make sure that the onChange handler never got called expect(changeFn).toHaveBeenCalledTimes(0) // Make sure that all the options get an `aria-disabled` let options = getRadioGroupOptions() expect(options).toHaveLength(4) for (let option of options) expect(option).toHaveAttribute('aria-disabled', 'true') // Toggle the disabled state await click(getByText('Toggle')) // Verify that the RadioGroupOption gets the disabled state expect(document.querySelector('[data-value="slot-prop"]')).toHaveTextContent( JSON.stringify({ checked: false, disabled: false, active: false, }) ) // Try to click one a few options await click(getByText('Pickup')) // Make sure that the onChange handler got called expect(changeFn).toHaveBeenCalledTimes(1) }) it('should be possible to disable a RadioGroupOption', async () => { let changeFn = jest.fn() render(svelte` <script> let disabled = true; </script> <button on:click={() => disabled = !disabled}>Toggle</button> <RadioGroup value={undefined} on:change={changeFn}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> <RadioGroupOption value="slot-prop" {disabled} data-value="slot-prop" let:checked let:disabled let:active> {JSON.stringify({ checked, disabled, active })} </RadioGroupOption> </RadioGroup> `) // Try to click the disabled option await click(document.querySelector('[data-value="slot-prop"]')) // Verify that the RadioGroupOption gets the disabled state expect(document.querySelector('[data-value="slot-prop"]')).toHaveTextContent( JSON.stringify({ checked: false, disabled: true, active: false, }) ) // Make sure that the onChange handler never got called expect(changeFn).toHaveBeenCalledTimes(0) // Make sure that the option with value "slot-prop" gets an `aria-disabled` let options = getRadioGroupOptions() expect(options).toHaveLength(4) for (let option of options) { if (option.dataset.value) { expect(option).toHaveAttribute('aria-disabled', 'true') } else { expect(option).not.toHaveAttribute('aria-disabled') } } // Toggle the disabled state await click(getByText('Toggle')) // Verify that the RadioGroupOption gets the disabled state expect(document.querySelector('[data-value="slot-prop"]')).toHaveTextContent( JSON.stringify({ checked: false, disabled: false, active: false, }) ) // Try to click one a few options await click(document.querySelector('[data-value="slot-prop"]')) // Make sure that the onChange handler got called expect(changeFn).toHaveBeenCalledTimes(1) }) }) describe('Keyboard interactions', () => { describe('`Tab` key', () => { it('should be possible to tab to the first item', async () => { render(svelte` <RadioGroup value={undefined} on:change={console.log}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> `); await press(Keys.Tab) assertActiveElement(getByText('Pickup')) }) it('should not change the selected element on focus', async () => { let changeFn = jest.fn() render(svelte` <RadioGroup value={undefined} on:change={changeFn}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> `); await press(Keys.Tab) assertActiveElement(getByText('Pickup')) expect(changeFn).toHaveBeenCalledTimes(0) }) it('should be possible to tab to the active item', async () => { render(svelte` <RadioGroup value={"home-delivery"} on:change={console.log}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> `); await press(Keys.Tab) assertActiveElement(getByText('Home delivery')) }) it('should not change the selected element on focus (when selecting the active item)', async () => { let changeFn = jest.fn() render(svelte` <RadioGroup value={"home-delivery"} on:change={changeFn}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> `); await press(Keys.Tab) assertActiveElement(getByText('Home delivery')) expect(changeFn).toHaveBeenCalledTimes(0) }) it('should be possible to tab out of the radio group (no selected value)', async () => { render(svelte` <button>Before</button> <RadioGroup value={undefined} on:change={console.log}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> <button>After</button> `); await press(Keys.Tab) assertActiveElement(getByText('Before')) await press(Keys.Tab) assertActiveElement(getByText('Pickup')) await press(Keys.Tab) assertActiveElement(getByText('After')) }) it('should be possible to tab out of the radio group (selected value)', async () => { render(svelte` <button>Before</button> <RadioGroup value={"home-delivery"} on:change={console.log}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> <button>After</button> `); await press(Keys.Tab) assertActiveElement(getByText('Before')) await press(Keys.Tab) assertActiveElement(getByText('Home delivery')) await press(Keys.Tab) assertActiveElement(getByText('After')) }) }) describe('`Shift+Tab` key', () => { it('should be possible to tab to the first item', async () => { render(svelte` <RadioGroup value={undefined} on:change={console.log}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> <button>After</button> `); getByText('After')?.focus() await press(shift(Keys.Tab)) assertActiveElement(getByText('Pickup')) }) it('should not change the selected element on focus', async () => { let changeFn = jest.fn() render(svelte` <RadioGroup value={undefined} on:change={changeFn}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> <button>After</button> `); getByText('After')?.focus() await press(shift(Keys.Tab)) assertActiveElement(getByText('Pickup')) expect(changeFn).toHaveBeenCalledTimes(0) }) it('should be possible to tab to the active item', async () => { render(svelte` <RadioGroup value={"home-delivery"} on:change={console.log}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> <button>After</button> `); getByText('After')?.focus() await press(shift(Keys.Tab)) assertActiveElement(getByText('Home delivery')) }) it('should not change the selected element on focus (when selecting the active item)', async () => { let changeFn = jest.fn() render(svelte` <RadioGroup value={"home-delivery"} on:change={changeFn}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> <button>After</button> `); getByText('After')?.focus() await press(shift(Keys.Tab)) assertActiveElement(getByText('Home delivery')) expect(changeFn).toHaveBeenCalledTimes(0) }) it('should be possible to tab out of the radio group (no selected value)', async () => { render(svelte` <button>Before</button> <RadioGroup value={undefined} on:change={console.log}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> <button>After</button> `); getByText('After')?.focus() await press(shift(Keys.Tab)) assertActiveElement(getByText('Pickup')) await press(shift(Keys.Tab)) assertActiveElement(getByText('Before')) }) it('should be possible to tab out of the radio group (selected value)', async () => { render(svelte` <button>Before</button> <RadioGroup value={"home-delivery"} on:change={console.log}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> <button>After</button> `); getByText('After')?.focus() await press(shift(Keys.Tab)) assertActiveElement(getByText('Home delivery')) await press(shift(Keys.Tab)) assertActiveElement(getByText('Before')) }) }) describe('`ArrowLeft` key', () => { it('should go to the previous item when pressing the ArrowLeft key', async () => { let changeFn = jest.fn() render(svelte` <button>Before</button> <RadioGroup value={undefined} on:change={(e) => changeFn(e.detail)}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> <button>After</button> `); // Focus the "Before" button await press(Keys.Tab) // Focus the RadioGroup await press(Keys.Tab) assertActiveElement(getByText('Pickup')) await press(Keys.ArrowLeft) // Loop around assertActiveElement(getByText('Dine in')) await press(Keys.ArrowLeft) assertActiveElement(getByText('Home delivery')) expect(changeFn).toHaveBeenCalledTimes(2) expect(changeFn).toHaveBeenNthCalledWith(1, 'dine-in') expect(changeFn).toHaveBeenNthCalledWith(2, 'home-delivery') }) }) describe('`ArrowUp` key', () => { it('should go to the previous item when pressing the ArrowUp key', async () => { let changeFn = jest.fn() render(svelte` <button>Before</button> <RadioGroup value={undefined} on:change={(e) => changeFn(e.detail)}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> <button>After</button> `); // Focus the "Before" button await press(Keys.Tab) // Focus the RadioGroup await press(Keys.Tab) assertActiveElement(getByText('Pickup')) await press(Keys.ArrowUp) // Loop around assertActiveElement(getByText('Dine in')) await press(Keys.ArrowUp) assertActiveElement(getByText('Home delivery')) expect(changeFn).toHaveBeenCalledTimes(2) expect(changeFn).toHaveBeenNthCalledWith(1, 'dine-in') expect(changeFn).toHaveBeenNthCalledWith(2, 'home-delivery') }) }) describe('`ArrowRight` key', () => { it('should go to the next item when pressing the ArrowRight key', async () => { let changeFn = jest.fn() render(svelte` <button>Before</button> <RadioGroup value={undefined} on:change={(e) => changeFn(e.detail)}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> <button>After</button> `); // Focus the "Before" button await press(Keys.Tab) // Focus the RadioGroup await press(Keys.Tab) assertActiveElement(getByText('Pickup')) await press(Keys.ArrowRight) assertActiveElement(getByText('Home delivery')) await press(Keys.ArrowRight) assertActiveElement(getByText('Dine in')) await press(Keys.ArrowRight) // Loop around assertActiveElement(getByText('Pickup')) expect(changeFn).toHaveBeenCalledTimes(3) expect(changeFn).toHaveBeenNthCalledWith(1, 'home-delivery') expect(changeFn).toHaveBeenNthCalledWith(2, 'dine-in') expect(changeFn).toHaveBeenNthCalledWith(3, 'pickup') }) }) describe('`ArrowDown` key', () => { it('should go to the next item when pressing the ArrowDown key', async () => { let changeFn = jest.fn() render(svelte` <button>Before</button> <RadioGroup value={undefined} on:change={(e) => changeFn(e.detail)}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> <button>After</button> `); // Focus the "Before" button await press(Keys.Tab) // Focus the RadioGroup await press(Keys.Tab) assertActiveElement(getByText('Pickup')) await press(Keys.ArrowDown) assertActiveElement(getByText('Home delivery')) await press(Keys.ArrowDown) assertActiveElement(getByText('Dine in')) await press(Keys.ArrowDown) // Loop around assertActiveElement(getByText('Pickup')) expect(changeFn).toHaveBeenCalledTimes(3) expect(changeFn).toHaveBeenNthCalledWith(1, 'home-delivery') expect(changeFn).toHaveBeenNthCalledWith(2, 'dine-in') expect(changeFn).toHaveBeenNthCalledWith(3, 'pickup') }) }) describe('`Space` key', () => { it('should select the current option when pressing space', async () => { let changeFn = jest.fn() render(svelte` <button>Before</button> <RadioGroup value={undefined} on:change={(e) => changeFn(e.detail)}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> <button>After</button> `); // Focus the "Before" button await press(Keys.Tab) // Focus the RadioGroup await press(Keys.Tab) assertActiveElement(getByText('Pickup')) await press(Keys.Space) assertActiveElement(getByText('Pickup')) expect(changeFn).toHaveBeenCalledTimes(1) expect(changeFn).toHaveBeenNthCalledWith(1, 'pickup') }) it('should select the current option only once when pressing space', async () => { let changeFn = jest.fn() render(svelte` <script> let value; </script> <button>Before</button> <RadioGroup {value} on:change={(e) => { value = e.detail; changeFn(e.detail)} }> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> <button>After</button> `); // Focus the "Before" button await press(Keys.Tab) // Focus the RadioGroup await press(Keys.Tab) assertActiveElement(getByText('Pickup')) await press(Keys.Space) await press(Keys.Space) await press(Keys.Space) await press(Keys.Space) await press(Keys.Space) assertActiveElement(getByText('Pickup')) expect(changeFn).toHaveBeenCalledTimes(1) expect(changeFn).toHaveBeenNthCalledWith(1, 'pickup') }) }) }) describe('Mouse interactions', () => { it('should be possible to change the current radio group value when clicking on a radio option', async () => { let changeFn = jest.fn() render(svelte` <button>Before</button> <RadioGroup value={undefined} on:change={(e) => changeFn(e.detail)}> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> <button>After</button> `); await click(getByText('Home delivery')) assertActiveElement(getByText('Home delivery')) expect(changeFn).toHaveBeenNthCalledWith(1, 'home-delivery') }) it('should be a no-op when clicking on the same item', async () => { let changeFn = jest.fn() render(svelte` <script> let value; </script> <button>Before</button> <RadioGroup {value} on:change={(e) => { value = e.detail; changeFn(e.detail)} }> <RadioGroupLabel>Pizza Delivery</RadioGroupLabel> <RadioGroupOption value="pickup">Pickup</RadioGroupOption> <RadioGroupOption value="home-delivery">Home delivery</RadioGroupOption> <RadioGroupOption value="dine-in">Dine in</RadioGroupOption> </RadioGroup> <button>After</button> `); await click(getByText('Home delivery')) await click(getByText('Home delivery')) await click(getByText('Home delivery')) await click(getByText('Home delivery')) assertActiveElement(getByText('Home delivery')) expect(changeFn).toHaveBeenCalledTimes(1) }) })
the_stack
import { UserRepresentation } from '@alfresco/js-api'; import { TaskDetailsModel } from '../../task-list/models/task-details.model'; export let standaloneTaskWithForm = new TaskDetailsModel({ id: '100', name: 'Standalone Task With Form', description: null, category: null, assignee: { id: 1001, firstName: 'Wilbur', lastName: 'Adams', email: 'wilbur@app.activiti.com' }, created: '2016-11-03T15:25:42.749+0000', dueDate: null, endDate: null, duration: null, priority: 50, parentTaskId: null, parentTaskName: null, processInstanceId: null, processInstanceName: null, processDefinitionId: null, processDefinitionName: null, processDefinitionDescription: null, processDefinitionKey: null, processDefinitionCategory: null, processDefinitionVersion: null, processDefinitionDeploymentId: null, formKey: '222', processInstanceStartUserId: null, initiatorCanCompleteTask: false, adhocTaskCanBeReassigned: false, taskDefinitionKey: 'sid-DDECD9E4-0299-433F-9193-C3D905C3EEBE', executionId: '86', involvedGroups: [], involvedPeople: [], memberOfCandidateUsers: false, managerOfCandidateGroup: false, memberOfCandidateGroup: false }); export let standaloneTaskWithoutForm = new TaskDetailsModel({ id: '200', name: 'Standalone Task Without Form', description: null, category: null, assignee: { id: 1001, firstName: 'Wilbur', lastName: 'Adams', email: 'wilbur@app.activiti.com' }, created: '2016-11-03T15:25:42.749+0000', dueDate: null, endDate: null, duration: null, priority: 50, parentTaskId: null, parentTaskName: null, processInstanceId: null, processInstanceName: null, processDefinitionId: null, processDefinitionName: null, processDefinitionDescription: null, processDefinitionKey: null, processDefinitionCategory: null, processDefinitionVersion: null, processDefinitionDeploymentId: null, formKey: null, processInstanceStartUserId: null, initiatorCanCompleteTask: false, adhocTaskCanBeReassigned: false, taskDefinitionKey: 'sid-DDECD9E4-0299-433F-9193-C3D905C3EEBE', executionId: '86', involvedGroups: [], involvedPeople: [], memberOfCandidateUsers: false, managerOfCandidateGroup: false, memberOfCandidateGroup: false }); export let completedStandaloneTaskWithoutForm = new TaskDetailsModel({ id: '200', name: 'Standalone Task Without Form', description: null, category: null, assignee: { id: 1001, firstName: 'Wilbur', lastName: 'Adams', email: 'wilbur@app.activiti.com' }, created: '2016-11-03T15:25:42.749+0000', dueDate: null, endDate: new Date(), duration: null, priority: 50, parentTaskId: null, parentTaskName: null, processInstanceId: null, processInstanceName: null, processDefinitionId: null, processDefinitionName: null, processDefinitionDescription: null, processDefinitionKey: null, processDefinitionCategory: null, processDefinitionVersion: null, processDefinitionDeploymentId: null, formKey: null, processInstanceStartUserId: null, initiatorCanCompleteTask: false, adhocTaskCanBeReassigned: false, taskDefinitionKey: 'sid-DDECD9E4-0299-433F-9193-C3D905C3EEBE', executionId: '86', involvedGroups: [], involvedPeople: [], memberOfCandidateUsers: false, managerOfCandidateGroup: false, memberOfCandidateGroup: false }); export let taskDetailsMock = new TaskDetailsModel({ id: '91', name: 'Request translation', description: null, category: null, assignee: { id: 1001, firstName: 'Wilbur', lastName: 'Adams', email: 'wilbur@app.activiti.com' }, created: '2016-11-03T15:25:42.749+0000', dueDate: null, endDate: null, duration: null, priority: 50, parentTaskId: null, parentTaskName: null, processInstanceId: '86', processInstanceName: null, processDefinitionId: 'TranslationProcess:2:8', processDefinitionName: 'Translation Process', processDefinitionDescription: null, processDefinitionKey: 'TranslationProcess', processDefinitionCategory: 'http://www.activiti.org/processdef', processDefinitionVersion: 2, processDefinitionDeploymentId: '5', formKey: '4', processInstanceStartUserId: '1001', initiatorCanCompleteTask: false, adhocTaskCanBeReassigned: false, taskDefinitionKey: 'sid-DDECD9E4-0299-433F-9193-C3D905C3EEBE', executionId: '86', involvedGroups: [], involvedPeople: [], memberOfCandidateUsers: false, managerOfCandidateGroup: false, memberOfCandidateGroup: false }); export let initiatorCanCompleteTaskDetailsMock = new TaskDetailsModel({ id: '91', name: 'Request translation', description: null, category: null, assignee: { email: 'mock-user-email' }, created: '2016-11-03T15:25:42.749+0000', dueDate: null, endDate: null, duration: null, priority: 50, parentTaskId: null, parentTaskName: null, processInstanceId: '86', processInstanceName: null, processDefinitionId: 'TranslationProcess:2:8', processDefinitionName: 'Translation Process', processDefinitionDescription: null, processDefinitionKey: 'TranslationProcess', processDefinitionCategory: 'http://www.activiti.org/processdef', processDefinitionVersion: 2, processDefinitionDeploymentId: '5', formKey: '4', processInstanceStartUserId: '1001', initiatorCanCompleteTask: true, adhocTaskCanBeReassigned: false, taskDefinitionKey: 'sid-DDECD9E4-0299-433F-9193-C3D905C3EEBE', executionId: '86', involvedGroups: [], involvedPeople: [], memberOfCandidateUsers: false, managerOfCandidateGroup: false, memberOfCandidateGroup: false }); export let initiatorWithCandidatesTaskDetailsMock = new TaskDetailsModel({ id: '91', name: 'Request translation', description: null, category: null, assignee: null, created: '2016-11-03T15:25:42.749+0000', dueDate: null, endDate: null, duration: null, priority: 50, parentTaskId: null, parentTaskName: null, processInstanceId: '86', processInstanceName: null, processDefinitionId: 'TranslationProcess:2:8', processDefinitionName: 'Translation Process', processDefinitionDescription: null, processDefinitionKey: 'TranslationProcess', processDefinitionCategory: 'http://www.activiti.org/processdef', processDefinitionVersion: 2, processDefinitionDeploymentId: '5', formKey: '4', processInstanceStartUserId: '1001', initiatorCanCompleteTask: true, adhocTaskCanBeReassigned: false, taskDefinitionKey: 'sid-DDECD9E4-0299-433F-9193-C3D905C3EEBE', executionId: '86', involvedGroups: [], involvedPeople: [ { id: 1001, firstName: 'Wilbur', lastName: 'Adams', email: 'wilbur@app.activiti.com' }, { id: 111, firstName: 'fake-first-name', lastName: 'fake-last-name', email: 'fake@app.activiti.com' } ], memberOfCandidateUsers: true, managerOfCandidateGroup: true, memberOfCandidateGroup: true }); export let taskDetailsWithOutAssigneeMock = new TaskDetailsModel({ id: '91', name: 'Request translation', description: null, category: null, assignee: undefined, created: '2016-11-03T15:25:42.749+0000', dueDate: null, endDate: null, duration: null, priority: 50, parentTaskId: null, parentTaskName: null, processInstanceId: '86', processInstanceName: null, processDefinitionId: 'TranslationProcess:2:8', processDefinitionName: 'Translation Process', processDefinitionDescription: null, processDefinitionKey: 'TranslationProcess', processDefinitionCategory: 'http://www.activiti.org/processdef', processDefinitionVersion: 2, processDefinitionDeploymentId: '5', formKey: '4', processInstanceStartUserId: '1001', initiatorCanCompleteTask: false, adhocTaskCanBeReassigned: false, taskDefinitionKey: 'sid-DDECD9E4-0299-433F-9193-C3D905C3EEBE', executionId: '86', involvedGroups: [], involvedPeople: [], memberOfCandidateUsers: false, managerOfCandidateGroup: false, memberOfCandidateGroup: false }); export let claimableTaskDetailsMock = new TaskDetailsModel({ id: '91', name: 'Request translation', description: null, category: null, assignee: null, created: '2016-11-03T15:25:42.749+0000', dueDate: null, endDate: null, duration: null, priority: 50, formKey: '4', parentTaskId: null, parentTaskName: null, processInstanceId: '86', processInstanceName: null, processDefinitionId: 'TranslationProcess:2:8', processDefinitionName: 'Translation Process', involvedGroups: [ { id: 7007, name: 'group1', externalId: null, status: 'active', groups: null }, { id: 8008, name: 'group2', externalId: null, status: 'active', groups: null } ], involvedPeople: [], managerOfCandidateGroup: true, memberOfCandidateGroup: true, memberOfCandidateUsers: false }); export let claimedTaskDetailsMock = new TaskDetailsModel({ id: '91', name: 'Request translation', description: null, category: null, assignee: { id: 1001, firstName: 'Wilbur', lastName: 'Adams', email: 'wilbur@app.activiti.com' }, created: '2016-11-03T15:25:42.749+0000', dueDate: null, endDate: null, duration: null, priority: 50, formKey: '4', parentTaskId: null, parentTaskName: null, processInstanceId: '86', processInstanceName: null, processInstanceStartUserId: '1002', initiatorCanCompleteTask: false, processDefinitionId: 'TranslationProcess:2:8', processDefinitionName: 'Translation Process', involvedGroups: [ { id: 7007, name: 'group1', externalId: null, status: 'active', groups: null } ], involvedPeople: [ { id: 1001, firstName: 'Wilbur', lastName: 'Adams', email: 'wilbur@app.activiti.com' }, { id: 111, firstName: 'fake-first-name', lastName: 'fake-last-name', email: 'fake@app.activiti.com' } ], managerOfCandidateGroup: true, memberOfCandidateGroup: true, memberOfCandidateUsers: true }); export let claimedByGroupMemberMock = new TaskDetailsModel({ id: '91', name: 'Request translation', description: null, category: null, assignee: { id: 111, firstName: 'fake-first-name', lastName: 'fake-last-name', email: 'fake@app.activiti.com' }, created: '2016-11-03T15:25:42.749+0000', dueDate: null, endDate: null, duration: null, priority: 50, parentTaskId: null, parentTaskName: null, processInstanceId: '86', processInstanceName: null, processDefinitionId: 'TranslationProcess:2:8', processDefinitionName: 'Translation Process', involvedGroups: [ { id: 7007, name: 'group1', externalId: null, status: 'active', groups: null } ], involvedPeople: [ { id: 1001, firstName: 'Wilbur', lastName: 'Adams', email: 'wilbur@app.activiti.com' }, { id: 111, firstName: 'fake-first-name', lastName: 'fake-last-name', email: 'fake@app.activiti.com' } ], managerOfCandidateGroup: true, memberOfCandidateGroup: true, memberOfCandidateUsers: true }); export let taskDetailsWithOutCandidateGroup = new TaskDetailsModel({ id: '91', name: 'Request translation', description: null, category: null, assignee: { id: 1001, firstName: 'Wilbur', lastName: 'Adams', email: 'wilbur@app.activiti.com' }, created: '2016-11-03T15:25:42.749+0000', dueDate: null, endDate: null, duration: null, priority: 50, parentTaskId: null, parentTaskName: null, processInstanceId: null, processInstanceName: null, processDefinitionId: 'TranslationProcess:2:8', processDefinitionName: 'Translation Process', managerOfCandidateGroup: false, memberOfCandidateGroup: false, memberOfCandidateUsers: false, involvedGroups: [], involvedPeople: [ { id: 1001, firstName: 'Wilbur', lastName: 'Adams', email: 'wilbur@app.activiti.com' }, { id: 111, firstName: 'fake-first-name', lastName: 'fake-last-name', email: 'fake@app.activiti.com' } ] }); export let completedTaskWithFormMock = new TaskDetailsModel({ id: '91', name: 'Request translation', description: null, category: null, assignee: { id: 1001, firstName: 'Wilbur', lastName: 'Adams', email: 'wilbur@app.activiti.com' }, created: '2016-11-03T15:25:42.749+0000', dueDate: null, endDate: new Date(), duration: null, priority: 50, formKey: '91', parentTaskId: null, parentTaskName: null, processInstanceId: '86', processInstanceName: null, processDefinitionId: 'TranslationProcess:2:8', processDefinitionName: 'Translation Process', involvedGroups: [], involvedPeople: [], managerOfCandidateGroup: true, memberOfCandidateGroup: true, memberOfCandidateUsers: false }); export let completedTaskDetailsMock = new TaskDetailsModel({ id: '91', name: 'Request translation', description: null, category: null, assignee: { id: 1001, firstName: 'Wilbur', lastName: 'Adams', email: 'wilbur@app.activiti.com' }, created: '2016-11-03T15:25:42.749+0000', dueDate: null, endDate: new Date(), duration: null, priority: 50, formKey: null, parentTaskId: null, parentTaskName: null, processInstanceId: '86', processInstanceName: null, processDefinitionId: 'TranslationProcess:2:8', processDefinitionName: 'Translation Process', involvedGroups: [], involvedPeople: [], managerOfCandidateGroup: true, memberOfCandidateGroup: true, memberOfCandidateUsers: false }); export let taskDetailsWithOutFormMock = new TaskDetailsModel({ 'id': '91', 'name': 'Request translation', 'description': 'fake description', 'category': null, 'assignee': {'id': 1001, 'firstName': 'Admin', 'lastName': 'Paul', 'email': 'fake-email@gmail.com' }, 'created': '2016-11-03T15:25:42.749+0000', 'dueDate': '2016-11-03T15:25:42.749+0000', 'endDate': null, 'duration': null, 'priority': 50, 'parentTaskId': null, 'parentTaskName': null, 'processInstanceId': '86', 'processInstanceName': null, 'processDefinitionId': 'TranslationProcess:2:8', 'processDefinitionName': 'Translation Process', 'processDefinitionDescription': null, 'processDefinitionKey': 'TranslationProcess', 'processDefinitionCategory': 'http://www.activiti.org/processdef', 'processDefinitionVersion': 2, 'processDefinitionDeploymentId': '5', 'formKey': null, 'processInstanceStartUserId': '1001', 'initiatorCanCompleteTask': false, 'adhocTaskCanBeReassigned': false, 'taskDefinitionKey': 'sid-DDECD9E4-0299-433F-9193-C3D905C3EEBE', 'executionId': '86', 'involvedPeople': [], 'memberOfCandidateUsers': false, 'managerOfCandidateGroup': false, 'memberOfCandidateGroup': false }); export const taskFormMock = { id: 4, name: 'Translation request', processDefinitionId: 'TranslationProcess:2:8', processDefinitionName: 'Translation Process', processDefinitionKey: 'TranslationProcess', taskId: '91', taskDefinitionKey: 'sid-DDECD9E4-0299-433F-9193-C3D905C3EEBE', tabs: [], fields: [ { fieldType: 'ContainerRepresentation', id: '1582747048995', name: 'Label', type: 'container', value: null, required: false, readOnly: false, overrideId: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, minValue: null, maxValue: null, regexPattern: null, optionType: null, hasEmptyValue: null, options: null, restUrl: null, restResponsePath: null, restIdProperty: null, restLabelProperty: null, tab: null, className: null, dateDisplayFormat: null, layout: null, sizeX: 2, sizeY: 1, row: -1, col: -1, visibilityCondition: null, numberOfColumns: 2, fields: { '1': [ { fieldType: 'FormFieldRepresentation', id: 'text1', name: 'Text1', type: 'text', value: null, required: false, readOnly: false, overrideId: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, minValue: null, maxValue: null, regexPattern: null, optionType: null, hasEmptyValue: null, options: null, restUrl: null, restResponsePath: null, restIdProperty: null, restLabelProperty: null, tab: null, className: null, params: { existingColspan: 1, maxColspan: 2 }, dateDisplayFormat: null, layout: { row: -1, column: -1, colspan: 1 }, sizeX: 1, sizeY: 1, row: -1, col: -1, visibilityCondition: null } ], '2': [ { fieldType: 'FormFieldRepresentation', id: 'text2', name: 'Text2', type: 'text', value: null, required: false, readOnly: false, overrideId: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, minValue: null, maxValue: null, regexPattern: null, optionType: null, hasEmptyValue: null, options: null, restUrl: null, restResponsePath: null, restIdProperty: null, restLabelProperty: null, tab: null, className: null, params: { existingColspan: 1, maxColspan: 1 }, dateDisplayFormat: null, layout: { row: -1, column: -1, colspan: 1 }, sizeX: 1, sizeY: 1, row: -1, col: -1, visibilityCondition: null } ] } }, { fieldType: 'ContainerRepresentation', id: '1582747052793', name: 'Label', type: 'container', value: null, required: false, readOnly: false, overrideId: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, minValue: null, maxValue: null, regexPattern: null, optionType: null, hasEmptyValue: null, options: null, restUrl: null, restResponsePath: null, restIdProperty: null, restLabelProperty: null, tab: null, className: null, dateDisplayFormat: null, layout: null, sizeX: 2, sizeY: 1, row: -1, col: -1, visibilityCondition: null, numberOfColumns: 2, fields: { '1': [ { fieldType: 'FormFieldRepresentation', id: 'text3', name: 'Text3', type: 'text', value: null, required: false, readOnly: false, overrideId: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, minValue: null, maxValue: null, regexPattern: null, optionType: null, hasEmptyValue: null, options: null, restUrl: null, restResponsePath: null, restIdProperty: null, restLabelProperty: null, tab: null, className: null, params: { existingColspan: 1, maxColspan: 2 }, dateDisplayFormat: null, layout: { row: -1, column: -1, colspan: 1 }, sizeX: 1, sizeY: 1, row: -1, col: -1, visibilityCondition: { leftFormFieldId: 'text1', leftRestResponseId: null, operator: '==', rightValue: '', rightType: null, rightFormFieldId: 'text2', rightRestResponseId: '', nextConditionOperator: '', nextCondition: null } } ], '2': [ { fieldType: 'FormFieldRepresentation', id: 'numberField', name: 'numberField', type: 'integer', value: null, required: false, readOnly: false, overrideId: false, colspan: 1, placeholder: null, minLength: 0, maxLength: 0, minValue: null, maxValue: null, regexPattern: null, optionType: null, hasEmptyValue: null, options: null, restUrl: null, restResponsePath: null, restIdProperty: null, restLabelProperty: null, tab: null, className: null, params: { existingColspan: 1, maxColspan: 1 }, dateDisplayFormat: null, layout: { row: -1, column: -1, colspan: 1 }, sizeX: 1, sizeY: 1, row: -1, col: -1, visibilityCondition: null } ] } } ], outcomes: [], javascriptEvents: [], className: '', style: '', customFieldTemplates: {}, metadata: {}, variables: [], customFieldsValueInfo: {}, gridsterForm: false, globalDateFormat: 'D-M-YYYY' }; export let tasksMock = [new TaskDetailsModel(taskDetailsMock)]; export let noDataMock = [ new TaskDetailsModel({ id: 1005, message: 'example-message', created: '2017-10-06T11:54:53.443+0000', createdBy: { id: 4004, firstName: 'gadget', lastName: 'inspector', email: 'gadget@inspector.com' } }) ]; export const involvedUserTaskForm = { id: '20259', name: 'Shared task', description: '', category: null, assignee: { id: 347, firstName: 'Fake', lastName: 'assignee', email: 'fake-assignee@test.com' }, created: '2020-08-14T11:02:44.992+0000', dueDate: null, endDate: null, duration: null, priority: 50, parentTaskId: null, parentTaskName: null, processInstanceId: null, processInstanceName: null, processDefinitionId: null, processDefinitionName: null, processDefinitionDescription: null, processDefinitionKey: null, processDefinitionCategory: null, processDefinitionVersion: 0, processDefinitionDeploymentId: null, formKey: '3896', processInstanceStartUserId: null, initiatorCanCompleteTask: false, adhocTaskCanBeReassigned: true, taskDefinitionKey: null, executionId: null, involvedPeople: [ { id: 1001, email: 'fake-email@gmail.com', firstName: 'fake', lastName: 'user' } ], involvedGroups: [], memberOfCandidateGroup: false, memberOfCandidateUsers: false, managerOfCandidateGroup: false }; export const involvedGroupTaskForm = { id: '20259', name: 'Shared task', description: '', category: null, assignee: { id: 347, firstName: 'Fake', lastName: 'assignee', email: 'fake-assignee@test.com' }, created: '2020-08-14T11:02:44.992+0000', dueDate: null, endDate: null, duration: null, priority: 50, parentTaskId: null, parentTaskName: null, processInstanceId: null, processInstanceName: null, processDefinitionId: null, processDefinitionName: null, processDefinitionDescription: null, processDefinitionKey: null, processDefinitionCategory: null, processDefinitionVersion: 0, processDefinitionDeploymentId: null, formKey: '3896', processInstanceStartUserId: null, initiatorCanCompleteTask: false, adhocTaskCanBeReassigned: true, taskDefinitionKey: null, executionId: null, involvedPeople: [], involvedGroups: [ { id: 637, name: 'one-group' } ], memberOfCandidateGroup: false, memberOfCandidateUsers: false, managerOfCandidateGroup: false }; export const fakeUser = new UserRepresentation({ id: 1001, email: 'fake-email@gmail.com', firstName: 'fake', lastName: 'user', externalId: null, company: null, pictureId: null, fullname: 'One Alfrsco', password: null, type: 'enterprise', status: 'active', created: '2020-08-14T09:21:52.306Z', lastUpdate: '2020-08-14T09:22:48.147Z', tenantId: 310, groups: [ { id: 637, name: 'one-group', externalId: null, status: 'active', parentGroupId: null, tenantId: 310, type: 1, userCount: null, users: null, capabilities: null, groups: null } ], capabilities: null, apps: [], tenantPictureId: null, tenantName: 'abc' }); export const completedProcessTaskWithoutForm = new TaskDetailsModel({ id: '49', name: 'process task without form', description: null, category: null, assignee: { id: 3, firstName: 'HR', lastName: 'User', email: 'hruser@example.com' }, created: '2021-07-08T07:39:27.046+0000', dueDate: null, endDate: '2021-07-08T07:39:35.817+0000', duration: 8771, priority: 0, parentTaskId: null, parentTaskName: null, processInstanceId: '37', processInstanceName: null, processDefinitionId: 'process:1:36', processDefinitionName: 'process', processDefinitionDescription: null, processDefinitionKey: 'process', processDefinitionCategory: 'http://www.activiti.org/processdef', processDefinitionVersion: 1, processDefinitionDeploymentId: '34', formKey: null, processInstanceStartUserId: '3', initiatorCanCompleteTask: false, adhocTaskCanBeReassigned: false, taskDefinitionKey: 'sid-1E90524A-8270-4031-89B6-5D18F414BFB8', executionId: '41', involvedPeople: [], involvedGroups: [], memberOfCandidateGroup: false, memberOfCandidateUsers: false, managerOfCandidateGroup: false });
the_stack
import * as ABIDecoder from "abi-decoder"; import * as compact from "lodash.compact"; import * as Web3 from "web3"; import { BigNumber } from "../../../../utils/bignumber"; import * as Units from "../../../../utils/units"; import { Web3Utils } from "../../../../utils/web3_utils"; import { AdaptersAPI, ContractsAPI, OrderAPI, ServicingAPI, SignerAPI } from "../../../../src/apis"; import { DebtOrderData } from "../../../../src/types"; import { DummyTokenContract, RepaymentRouterContract, TokenTransferProxyContract, } from "../../../../src/wrappers"; import { ACCOUNTS } from "../../../accounts"; import { MakeRepaymentScenario } from "../scenarios"; const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); const web3Utils = new Web3Utils(web3); const contractsApi = new ContractsAPI(web3); const adaptersApi = new AdaptersAPI(web3, contractsApi); const orderApi = new OrderAPI(web3, contractsApi, adaptersApi); const signerApi = new SignerAPI(web3, contractsApi); const servicingApi = new ServicingAPI(web3, contractsApi); const TX_DEFAULTS = { from: ACCOUNTS[0].address, gas: 400000 }; export class MakeRepaymentRunner { public static testMakeRepaymentScenario(scenario: MakeRepaymentScenario) { describe(scenario.description, () => { let principalToken: DummyTokenContract; let nonPrincipalToken: DummyTokenContract; let tokenTransferProxy: TokenTransferProxyContract; let debtOrderData: DebtOrderData; let issuanceHash: string; const CONTRACT_OWNER = ACCOUNTS[0].address; // The creditor is initially the beneficiary of repayments const BENEFICIARY = ACCOUNTS[1].address; const CREDITOR = ACCOUNTS[1].address; const DEBTOR = ACCOUNTS[2].address; let txHash: string; // From token address to amount. const debtorBalanceBefore = {}; const beneficiaryBalanceBefore = {}; // From address to token. const repaymentTokenMap = {}; let repaymentToken: any; let repaymentTokenAddress: string; beforeEach(async () => { const tokenRegistry = await contractsApi.loadTokenRegistry(); const principalTokenAddress = await tokenRegistry.getTokenAddressBySymbol.callAsync( "REP", ); const nonPrincipalTokenAddress = await tokenRegistry.getTokenAddressBySymbol.callAsync( "ZRX", ); const repaymentRouter = await contractsApi.loadRepaymentRouterAsync(); tokenTransferProxy = await contractsApi.loadTokenTransferProxyAsync(); principalToken = await DummyTokenContract.at( principalTokenAddress, web3, TX_DEFAULTS, ); nonPrincipalToken = await DummyTokenContract.at( nonPrincipalTokenAddress, web3, TX_DEFAULTS, ); repaymentTokenMap[principalToken.address] = principalToken; repaymentTokenMap[nonPrincipalToken.address] = nonPrincipalToken; // Grant creditor a balance of tokens await principalToken.setBalance.sendTransactionAsync(CREDITOR, Units.ether(10), { from: CONTRACT_OWNER, }); // Grant debtor a balance of tokens await principalToken.setBalance.sendTransactionAsync(DEBTOR, Units.ether(10), { from: CONTRACT_OWNER, }); // Approve the token transfer proxy for a sufficient // amount of tokens for an order fill. await principalToken.approve.sendTransactionAsync( tokenTransferProxy.address, Units.ether(10), { from: CREDITOR }, ); debtOrderData = await adaptersApi.simpleInterestLoan.toDebtOrder({ debtor: DEBTOR, creditor: CREDITOR, principalAmount: Units.ether(1), principalTokenSymbol: "REP", interestRate: new BigNumber(0.1), amortizationUnit: "months", termLength: new BigNumber(2), }); debtOrderData.debtorSignature = await signerApi.asDebtor(debtOrderData, false); issuanceHash = await orderApi.getIssuanceHash(debtOrderData); // NOTE: We fill debt orders in the `beforeEach` block to ensure // that the blockchain is snapshotted *before* order filling // in the parent scope's `beforeEach` block. For more information, // read about Jest's order of execution in scoped tests: // https://facebook.github.io/jest/docs/en/setup-teardown.html#scoping await orderApi.fillAsync(debtOrderData, { from: CREDITOR }); ABIDecoder.addABI(repaymentRouter.abi); await principalToken.setBalance.sendTransactionAsync(DEBTOR, scenario.balance, { from: CONTRACT_OWNER, }); await principalToken.approve.sendTransactionAsync( tokenTransferProxy.address, scenario.allowance, { from: DEBTOR }, ); await nonPrincipalToken.setBalance.sendTransactionAsync(DEBTOR, scenario.balance, { from: CONTRACT_OWNER, }); await nonPrincipalToken.approve.sendTransactionAsync( tokenTransferProxy.address, scenario.allowance, { from: DEBTOR }, ); debtorBalanceBefore[ principalToken.address ] = await principalToken.balanceOf.callAsync(DEBTOR); beneficiaryBalanceBefore[ principalToken.address ] = await principalToken.balanceOf.callAsync(BENEFICIARY); debtorBalanceBefore[ nonPrincipalToken.address ] = await nonPrincipalToken.balanceOf.callAsync(DEBTOR); beneficiaryBalanceBefore[ nonPrincipalToken.address ] = await nonPrincipalToken.balanceOf.callAsync(BENEFICIARY); repaymentTokenAddress = scenario.repaymentToken( principalToken.address, nonPrincipalToken.address, ); repaymentToken = repaymentTokenMap[repaymentTokenAddress]; if (!scenario.throws) { for (let i = 0; i < scenario.repaymentAttempts; i++) { txHash = await servicingApi.makeRepayment( scenario.agreementId(issuanceHash), scenario.amount, repaymentTokenAddress, { from: DEBTOR }, ); } } }); if (scenario.throws) { test(`throws ${scenario.errorMessage} error`, async () => { await expect( servicingApi.makeRepayment( scenario.agreementId(issuanceHash), scenario.amount, repaymentTokenAddress, { from: DEBTOR }, ), ).rejects.toThrow(scenario.errorMessage); }); } else { if (scenario.successfullyRepays) { test("should emit log indicating successful repayment", async () => { const receipt = await web3Utils.getTransactionReceiptAsync(txHash); const [repaymentSuccessLog] = compact(ABIDecoder.decodeLogs(receipt.logs)); expect(repaymentSuccessLog.name).toBe("LogRepayment"); }); test("should debit payer amount repaid", async () => { await expect(repaymentToken.balanceOf.callAsync(DEBTOR)).resolves.toEqual( debtorBalanceBefore[repaymentTokenAddress].minus( scenario.amount.mul(scenario.repaymentAttempts), ), ); }); test("should credit beneficiary amount repaid", async () => { await expect( repaymentToken.balanceOf.callAsync(BENEFICIARY), ).resolves.toEqual( beneficiaryBalanceBefore[repaymentTokenAddress].plus( scenario.amount.mul(scenario.repaymentAttempts), ), ); }); } else { // Doesn't throw, but it did not repay debit funds. test("should emit log indicating terms contract rejection", async () => { const receipt = await web3Utils.getTransactionReceiptAsync(txHash); const [repaymentErrorLog] = compact(ABIDecoder.decodeLogs(receipt.logs)); expect(repaymentErrorLog.name).toBe("LogError"); }); test("should not debit payer amount repaid", async () => { await expect(repaymentToken.balanceOf.callAsync(DEBTOR)).resolves.toEqual( debtorBalanceBefore[repaymentTokenAddress], ); }); test("should not credit beneficiary amount repaid", async () => { await expect( repaymentToken.balanceOf.callAsync(BENEFICIARY), ).resolves.toEqual(beneficiaryBalanceBefore[repaymentTokenAddress]); }); } } }); } }
the_stack
import { Spy, spy } from "@mysticatea/spy" import assert from "assert" import { Event, EventTarget } from "../src/index" import { Global } from "../src/lib/global" import { CanceledInPassiveListener, EventListenerWasDuplicated, InvalidEventListener, NonCancelableEventWasCanceled, OptionWasIgnored, } from "../src/lib/warnings" import { AbortSignalStub } from "./lib/abort-signal-stub" import { countEventListeners } from "./lib/count-event-listeners" import { setupErrorCheck } from "./lib/setup-error-check" const NativeDOMException: typeof DOMException = Global?.DOMException const NativeEventTarget: typeof Event = Global?.EventTarget const NativeEvent: typeof Event = Global?.Event const NativeKeyboardEvent: typeof KeyboardEvent = Global?.KeyboardEvent const NativeMouseEvent: typeof MouseEvent = Global?.MouseEvent describe("'EventTarget' class", () => { const { assertError, assertWarning } = setupErrorCheck() describe("constructor", () => { it("should not throw", () => { assert(new EventTarget()) }) it("should throw a TypeError if called as a function.", () => { assert.throws(() => { // @ts-expect-error EventTarget() // eslint-disable-line new-cap }, TypeError) }) const nativeDescribe = NativeEventTarget ? describe : xdescribe nativeDescribe("if native EventTarget class is present", () => { it("`target instanceof window.EventTarget` should be true", () => { const target = new EventTarget() assert(target instanceof NativeEventTarget) }) }) }) describe("'addEventListener' method", () => { let target: EventTarget beforeEach(() => { target = new EventTarget() }) it("should do nothing if callback is nothing.", () => { // @ts-expect-error target.addEventListener() target.addEventListener("foo") target.addEventListener("foo", null) target.addEventListener("foo", undefined) assert.strictEqual(countEventListeners(target), 0) assertWarning(InvalidEventListener, undefined) assertWarning(InvalidEventListener, undefined) assertWarning(InvalidEventListener, null) assertWarning(InvalidEventListener, undefined) }) it("should throw a TypeError if callback is a primitive.", () => { assert.throws(() => { // @ts-expect-error target.addEventListener("foo", true) }, TypeError) assert.throws(() => { // @ts-expect-error target.addEventListener("foo", 1) }, TypeError) assert.throws(() => { // @ts-expect-error target.addEventListener("foo", "function") }, TypeError) assert.throws(() => { // @ts-expect-error target.addEventListener("foo", Symbol("symbol")) }, TypeError) assert.throws(() => { // @ts-expect-error target.addEventListener("foo", 0n) }, TypeError) assert.strictEqual(countEventListeners(target), 0) }) it("should add a given event listener.", () => { target.addEventListener("foo", () => {}) assert.strictEqual(countEventListeners(target), 1) }) it("should add a given object.", () => { const f = {} // @ts-expect-error target.addEventListener("foo", f) assert.strictEqual(countEventListeners(target), 1) assertWarning(InvalidEventListener, f) }) it("should add multiple given event listeners.", () => { target.addEventListener("foo", () => {}) target.addEventListener("foo", () => {}) target.addEventListener("foo", () => {}) target.addEventListener("bar", () => {}) assert.strictEqual(countEventListeners(target), 4) assert.strictEqual(countEventListeners(target, "foo"), 3) assert.strictEqual(countEventListeners(target, "bar"), 1) }) it("should handle non-string types as string types.", () => { // @ts-expect-error target.addEventListener(null, () => {}) // @ts-expect-error target.addEventListener(undefined, () => {}) // @ts-expect-error target.addEventListener(1e3, () => {}) assert.strictEqual(countEventListeners(target), 3) assert.strictEqual(countEventListeners(target, "null"), 1) assert.strictEqual(countEventListeners(target, "undefined"), 1) assert.strictEqual(countEventListeners(target, "1000"), 1) }) it("should not add the same listener twice.", () => { const f = () => {} target.addEventListener("foo", f) target.addEventListener("foo", f) target.addEventListener("bar", f) assert.strictEqual(countEventListeners(target), 2) assert.strictEqual(countEventListeners(target, "foo"), 1) assert.strictEqual(countEventListeners(target, "bar"), 1) assertWarning(EventListenerWasDuplicated, "bubble", f) }) it("should add the same listener twice if capture flag is different.", () => { const f = () => {} target.addEventListener("foo", f, { capture: true }) target.addEventListener("foo", f, { capture: false }) assert.strictEqual(countEventListeners(target), 2) assert.strictEqual(countEventListeners(target, "foo"), 2) }) it("should add the same listener twice if capture flag is different. (boolean option)", () => { const f = () => {} target.addEventListener("foo", f, true) target.addEventListener("foo", f, false) assert.strictEqual(countEventListeners(target), 2) assert.strictEqual(countEventListeners(target, "foo"), 2) }) it("should not add the same listener twice even if passive flag is different.", () => { const f = () => {} target.addEventListener("foo", f, { passive: true }) target.addEventListener("foo", f, { passive: false }) assert.strictEqual(countEventListeners(target), 1) assertWarning(EventListenerWasDuplicated, "bubble", f) assertWarning(OptionWasIgnored, "passive") }) it("should not add the same listener twice even if once flag is different.", () => { const f = () => {} target.addEventListener("foo", f, { once: true }) target.addEventListener("foo", f, { once: false }) assert.strictEqual(countEventListeners(target), 1) assertWarning(EventListenerWasDuplicated, "bubble", f) assertWarning(OptionWasIgnored, "once") }) it("should not add the same listener twice even if signal flag is different.", () => { const f = () => {} target.addEventListener("foo", f, { signal: null }) target.addEventListener("foo", f, { signal: new AbortSignalStub() }) assert.strictEqual(countEventListeners(target), 1) assertWarning(EventListenerWasDuplicated, "bubble", f) assertWarning(OptionWasIgnored, "signal") }) it("should not add the same listener twice even if flags are different.", () => { const f = () => {} target.addEventListener("foo", f, { passive: true, once: true, signal: null, }) target.addEventListener("foo", f, { passive: false, once: false, signal: new AbortSignalStub(), }) assert.strictEqual(countEventListeners(target), 1) assertWarning(EventListenerWasDuplicated, "bubble", f) assertWarning(OptionWasIgnored, "passive") assertWarning(OptionWasIgnored, "once") assertWarning(OptionWasIgnored, "signal") }) it("should not add the listener if abort signal is present and the `signal.aborted` is true.", () => { const signal = new AbortSignalStub() signal.abort() target.addEventListener("foo", () => {}, { signal }) assert.strictEqual(countEventListeners(target), 0) }) it("should remove the listener if abort signal was notified.", () => { const signal = new AbortSignalStub() target.addEventListener("foo", () => {}, { signal }) assert.strictEqual(countEventListeners(target), 1) signal.abort() assert.strictEqual(countEventListeners(target), 0) }) }) describe("'removeEventListener' method", () => { const f = () => {} let target: EventTarget beforeEach(() => { target = new EventTarget() target.addEventListener("foo", f) assert.strictEqual(countEventListeners(target), 1) }) it("should do nothing if callback is nothing.", () => { // @ts-expect-error target.removeEventListener() target.removeEventListener("foo") target.removeEventListener("foo", null) target.removeEventListener("foo", undefined) assert.strictEqual(countEventListeners(target, "foo"), 1) assertWarning(InvalidEventListener, undefined) assertWarning(InvalidEventListener, undefined) assertWarning(InvalidEventListener, null) assertWarning(InvalidEventListener, undefined) }) it("should throw a TypeError if callback is a primitive.", () => { assert.throws(() => { // @ts-expect-error target.removeEventListener("foo", true) }, TypeError) assert.throws(() => { // @ts-expect-error target.removeEventListener("foo", 1) }, TypeError) assert.throws(() => { // @ts-expect-error target.removeEventListener("foo", "function") }, TypeError) assert.throws(() => { // @ts-expect-error target.removeEventListener("foo", Symbol("symbol")) }, TypeError) assert.throws(() => { // @ts-expect-error target.removeEventListener("foo", 0n) }, TypeError) assert.strictEqual(countEventListeners(target), 1) }) it("should remove a given event listener.", () => { target.removeEventListener("foo", f) assert.strictEqual(countEventListeners(target), 0) }) it("should not remove any listeners if the event type is different.", () => { target.removeEventListener("bar", f) assert.strictEqual(countEventListeners(target), 1) }) it("should not remove any listeners if the callback function is different.", () => { target.removeEventListener("foo", () => {}) assert.strictEqual(countEventListeners(target), 1) }) it("should not remove any listeners if the capture flag is different.", () => { target.removeEventListener("foo", f, true) target.removeEventListener("foo", f, { capture: true }) assert.strictEqual(countEventListeners(target), 1) }) it("should handle capture flag correctly.", () => { target.addEventListener("foo", f, { capture: true }) assert.strictEqual(countEventListeners(target), 2) target.removeEventListener("foo", f, { capture: true }) target.removeEventListener("foo", f, { capture: true }) assert.strictEqual(countEventListeners(target), 1) }) it("should remove a given event listener even if the passive flag is present.", () => { // @ts-expect-error target.removeEventListener("foo", f, { passive: true }) assert.strictEqual(countEventListeners(target), 0) }) it("should remove a given event listener even if the once flag is present.", () => { // @ts-expect-error target.removeEventListener("foo", f, { once: true }) assert.strictEqual(countEventListeners(target), 0) }) it("should remove a given event listener even if the signal is present.", () => { // @ts-expect-error target.removeEventListener("foo", f, { signal: new AbortSignalStub(), }) assert.strictEqual(countEventListeners(target), 0) }) it("should handle non-string types as string types.", () => { target.addEventListener("null", f) target.addEventListener("undefined", f) target.addEventListener("1000", f) assert.strictEqual(countEventListeners(target, "null"), 1) assert.strictEqual(countEventListeners(target, "undefined"), 1) assert.strictEqual(countEventListeners(target, "1000"), 1) // @ts-expect-error target.removeEventListener(null, f) assert.strictEqual(countEventListeners(target, "null"), 0) // @ts-expect-error target.removeEventListener(undefined, f) assert.strictEqual(countEventListeners(target, "undefined"), 0) // @ts-expect-error target.removeEventListener(1e3, f) assert.strictEqual(countEventListeners(target, "1000"), 0) }) }) describe("'dispatchEvent' method", () => { let target: EventTarget<{ foo: Event }> beforeEach(() => { target = new EventTarget() }) it("should throw a TypeError if the argument was not present", () => { assert.throws(() => { // @ts-expect-error target.dispatchEvent() }, TypeError) }) it("should not throw even if listeners don't exist", () => { const retv = target.dispatchEvent(new Event("foo")) assert.strictEqual(retv, true) }) it("should not throw even if empty object had been added", () => { const f = {} // @ts-expect-error target.addEventListener("foo", f) const retv = target.dispatchEvent(new Event("foo")) assert.strictEqual(retv, true) assertWarning(InvalidEventListener, f) }) it("should call obj.handleEvent method even if added later", () => { const event = new Event("foo") const f: { handleEvent?: Spy<(event: Event) => void> } = {} // @ts-expect-error target.addEventListener("foo", f) f.handleEvent = spy() const retv = target.dispatchEvent(event) assert.strictEqual( f.handleEvent.calls.length, 1, "handleEvent should be called", ) assert.strictEqual(f.handleEvent.calls[0].this, f) assert.strictEqual(f.handleEvent.calls[0].arguments[0], event) assert.strictEqual(retv, true) assertWarning(InvalidEventListener, f) }) it("should call a registered listener.", () => { const f1 = spy((_event: Event) => {}) const f2 = spy((_event: Event) => {}) target.addEventListener("foo", f1) target.addEventListener("bar", f2) const event = new Event("foo") const retv = target.dispatchEvent(event) assert.strictEqual(f1.calls.length, 1, "foo should be called once") assert.strictEqual( f1.calls[0].arguments.length, 1, "the argument of callback should be one", ) assert.strictEqual( f1.calls[0].arguments[0], event, "the argument of callback should be the given Event object", ) assert.strictEqual(f2.calls.length, 0, "bar should not be called") assert.strictEqual(retv, true) }) it("should not call subsequent listeners if a listener called `event.stopImmediatePropagation()`.", () => { const f1 = spy((_event: Event) => {}) const f2 = spy((event: Event) => { event.stopImmediatePropagation() }) const f3 = spy((_event: Event) => {}) const f4 = spy((_event: Event) => {}) target.addEventListener("foo", f1) target.addEventListener("foo", f2) target.addEventListener("foo", f3) target.addEventListener("foo", f4) const retv = target.dispatchEvent(new Event("foo")) assert.strictEqual(f1.calls.length, 1, "f1 should be called") assert.strictEqual(f2.calls.length, 1, "f2 should be called") assert.strictEqual(f3.calls.length, 0, "f3 should not be called") assert.strictEqual(f4.calls.length, 0, "f4 should not be called") assert.strictEqual(retv, true) }) it("should return true even if a listener called 'event.preventDefault()' if the event is not cancelable.", () => { target.addEventListener("foo", event => { event.preventDefault() }) const retv = target.dispatchEvent(new Event("foo")) assert.strictEqual(retv, true) assertWarning(NonCancelableEventWasCanceled) }) it("should return false if a listener called 'event.preventDefault()' and the event is cancelable.", () => { target.addEventListener("foo", event => { event.preventDefault() }) const retv = target.dispatchEvent( new Event("foo", { cancelable: true }), ) assert.strictEqual(retv, false) }) it("should return true even if a listener called 'event.preventDefault()' if passive option is present.", () => { target.addEventListener( "foo", event => { event.preventDefault() }, { passive: true }, ) const retv = target.dispatchEvent( new Event("foo", { cancelable: true }), ) assert.strictEqual(retv, true) assertWarning(CanceledInPassiveListener) }) it("should return true even if a listener called 'event.returnValue = false' if the event is not cancelable.", () => { target.addEventListener("foo", event => { event.returnValue = false }) const retv = target.dispatchEvent(new Event("foo")) assert.strictEqual(retv, true) assertWarning(NonCancelableEventWasCanceled) }) it("should return false if a listener called 'event.returnValue = false' and the event is cancelable.", () => { target.addEventListener("foo", event => { event.returnValue = false }) const retv = target.dispatchEvent( new Event("foo", { cancelable: true }), ) assert.strictEqual(retv, false) }) it("should return true even if a listener called 'event.returnValue = false' if passive option is present.", () => { target.addEventListener( "foo", event => { event.returnValue = false }, { passive: true }, ) const retv = target.dispatchEvent( new Event("foo", { cancelable: true }), ) assert.strictEqual(retv, true) assertWarning(CanceledInPassiveListener) }) it("should remove a listener if once option is present.", () => { const f1 = spy() const f2 = spy() const f3 = spy() target.addEventListener("foo", f1, { once: true }) target.addEventListener("foo", f2, { once: true }) target.addEventListener("foo", f3, { once: true }) const retv = target.dispatchEvent(new Event("foo")) target.dispatchEvent(new Event("foo")) assert.strictEqual(f1.calls.length, 1, "f1 should be called once") assert.strictEqual(f2.calls.length, 1, "f2 should be called once") assert.strictEqual(f3.calls.length, 1, "f3 should be called once") assert.strictEqual(countEventListeners(target), 0) assert.strictEqual(retv, true) }) it("should handle removing in event listeners correctly. Remove 0 at 0.", () => { const f1 = spy(() => { target.removeEventListener("foo", f1) }) const f2 = spy() const f3 = spy() target.addEventListener("foo", f1) target.addEventListener("foo", f2) target.addEventListener("foo", f3) target.dispatchEvent(new Event("foo")) target.dispatchEvent(new Event("foo")) assert.strictEqual(f1.calls.length, 1, "f1 should be called once") assert.strictEqual(f2.calls.length, 2, "f2 should be called twice") assert.strictEqual(f3.calls.length, 2, "f3 should be called twice") }) it("should handle removing in event listeners correctly. Remove 1 at 0.", () => { const f1 = spy(() => { target.removeEventListener("foo", f2) }) const f2 = spy() const f3 = spy() target.addEventListener("foo", f1) target.addEventListener("foo", f2) target.addEventListener("foo", f3) target.dispatchEvent(new Event("foo")) target.dispatchEvent(new Event("foo")) assert.strictEqual(f1.calls.length, 2, "f1 should be called twice") assert.strictEqual(f2.calls.length, 0, "f2 should not be called") assert.strictEqual(f3.calls.length, 2, "f3 should be called twice") }) it("should handle removing in event listeners correctly. Remove 0 at 1.", () => { const f1 = spy() const f2 = spy(() => { target.removeEventListener("foo", f1) }) const f3 = spy() target.addEventListener("foo", f1) target.addEventListener("foo", f2) target.addEventListener("foo", f3) target.dispatchEvent(new Event("foo")) target.dispatchEvent(new Event("foo")) assert.strictEqual(f1.calls.length, 1, "f1 should be called once") assert.strictEqual(f2.calls.length, 2, "f2 should be called twice") assert.strictEqual(f3.calls.length, 2, "f3 should be called twice") }) it("should handle removing in event listeners correctly. Remove 1 at 1.", () => { const f1 = spy() const f2 = spy(() => { target.removeEventListener("foo", f2) }) const f3 = spy() target.addEventListener("foo", f1) target.addEventListener("foo", f2) target.addEventListener("foo", f3) target.dispatchEvent(new Event("foo")) target.dispatchEvent(new Event("foo")) assert.strictEqual(f1.calls.length, 2, "f1 should be called twice") assert.strictEqual(f2.calls.length, 1, "f2 should be called once") assert.strictEqual(f3.calls.length, 2, "f3 should be called twice") }) it("should handle removing in event listeners correctly. Remove 2 at 1.", () => { const f1 = spy() const f2 = spy(() => { target.removeEventListener("foo", f3) }) const f3 = spy() target.addEventListener("foo", f1) target.addEventListener("foo", f2) target.addEventListener("foo", f3) target.dispatchEvent(new Event("foo")) target.dispatchEvent(new Event("foo")) assert.strictEqual(f1.calls.length, 2, "f1 should be called twice") assert.strictEqual(f2.calls.length, 2, "f2 should be called twice") assert.strictEqual(f3.calls.length, 0, "f3 should be not called") }) it("should handle removing in event listeners correctly. Remove 2 at 2.", () => { const f1 = spy() const f2 = spy() const f3 = spy(() => { target.removeEventListener("foo", f3) }) target.addEventListener("foo", f1) target.addEventListener("foo", f2) target.addEventListener("foo", f3) target.dispatchEvent(new Event("foo")) target.dispatchEvent(new Event("foo")) assert.strictEqual(f1.calls.length, 2, "f1 should be called twice") assert.strictEqual(f2.calls.length, 2, "f2 should be called twice") assert.strictEqual(f3.calls.length, 1, "f3 should be called once") }) it("should handle removing in event listeners correctly along with once flag.", () => { const f1 = spy() const f2 = spy(() => { target.removeEventListener("foo", f2) }) const f3 = spy() target.addEventListener("foo", f1) target.addEventListener("foo", f2, { once: true }) target.addEventListener("foo", f3) target.dispatchEvent(new Event("foo")) target.dispatchEvent(new Event("foo")) assert.strictEqual(f1.calls.length, 2, "f1 should be called twice") assert.strictEqual(f2.calls.length, 1, "f2 should be called once") assert.strictEqual(f3.calls.length, 2, "f3 should be called twice") }) it("should handle removing in event listeners correctly along with once flag. (2)", () => { const f1 = spy() const f2 = spy(() => { target.removeEventListener("foo", f3) }) const f3 = spy() const f4 = spy() target.addEventListener("foo", f1) target.addEventListener("foo", f2, { once: true }) target.addEventListener("foo", f3) target.addEventListener("foo", f4) target.dispatchEvent(new Event("foo")) target.dispatchEvent(new Event("foo")) assert.strictEqual(f1.calls.length, 2, "f1 should be called twice") assert.strictEqual(f2.calls.length, 1, "f2 should be called once") assert.strictEqual(f3.calls.length, 0, "f3 should not be called") assert.strictEqual(f4.calls.length, 2, "f4 should be called twice") }) it("should handle removing once and remove", () => { const f1 = spy(() => { target.removeEventListener("foo", f1) }) target.addEventListener("foo", f1, { once: true }) target.dispatchEvent(new Event("foo")) target.dispatchEvent(new Event("foo")) assert.strictEqual(f1.calls.length, 1, "f1 should be called once") }) it("should handle removing once and signal", () => { const signal = new AbortSignalStub() const f1 = spy(() => { signal.abort() }) target.addEventListener("foo", f1, { once: true, signal }) target.dispatchEvent(new Event("foo")) target.dispatchEvent(new Event("foo")) assert.strictEqual(f1.calls.length, 1, "f1 should be called once") }) it("should handle once in nested dispatches", () => { const f1 = spy(() => { target.dispatchEvent(new Event("foo")) assert.strictEqual( f2.calls.length, 1, "f2 should be called only once", ) }) const f2 = spy() target.addEventListener("foo", f1, { once: true }) target.addEventListener("foo", f2, { once: true }) target.dispatchEvent(new Event("foo")) target.dispatchEvent(new Event("foo")) assert.strictEqual( f1.calls.length, 1, "f1 should be called only once", ) assert.strictEqual( f2.calls.length, 1, "f2 should be called only once", ) }) it("should not call the listeners that were added after the 'dispatchEvent' method call.", () => { const f1 = spy() const f2 = spy(() => { target.addEventListener("foo", f3) }) const f3 = spy() target.addEventListener("foo", f1) target.addEventListener("foo", f2) target.dispatchEvent(new Event("foo")) target.dispatchEvent(new Event("foo")) assert.strictEqual(f1.calls.length, 2, "f1 should be called twice") assert.strictEqual(f2.calls.length, 2, "f2 should be called twice") assert.strictEqual(f3.calls.length, 1, "f3 should be called once") // happens at the second dispatch. assertWarning(EventListenerWasDuplicated, "bubble", f3) }) it("should not call the listeners that were added after the 'dispatchEvent' method call. (the last listener is removed at first dispatch)", () => { const f1 = spy() const f2 = spy(() => { target.addEventListener("foo", f3) }) const f3 = spy() target.addEventListener("foo", f1) target.addEventListener("foo", f2, { once: true }) target.dispatchEvent(new Event("foo")) target.dispatchEvent(new Event("foo")) assert.strictEqual(f1.calls.length, 2, "f1 should be called twice") assert.strictEqual(f2.calls.length, 1, "f2 should be called once") assert.strictEqual(f3.calls.length, 1, "f3 should be called once") }) it("should catch exceptions that are thrown from listeners and call the error handler.", () => { const error = new Error("test") const f1 = spy() const f2 = spy(() => { throw error }) const f3 = spy() target.addEventListener("foo", f1) target.addEventListener("foo", f2) target.addEventListener("foo", f3) target.dispatchEvent(new Event("foo")) assert.strictEqual(f1.calls.length, 1, "f1 should be called") assert.strictEqual(f2.calls.length, 1, "f2 should be called") assert.strictEqual(f3.calls.length, 1, "f3 should be called") assertError(error) }) it("should catch exceptions that are thrown from listeners and call the error handler, even if the exception was not an Error object.", () => { const error = "error" const f1 = spy() const f2 = spy(() => { throw error }) const f3 = spy() target.addEventListener("foo", f1) target.addEventListener("foo", f2) target.addEventListener("foo", f3) target.dispatchEvent(new Event("foo")) assert.strictEqual(f1.calls.length, 1, "f1 should be called") assert.strictEqual(f2.calls.length, 1, "f2 should be called") assert.strictEqual(f3.calls.length, 1, "f3 should be called") assertError(error) }) it("should throw a InvalidStateError if the given event is being used", () => { const event = new Event("foo") const f = spy(() => { target.dispatchEvent(event) }) target.addEventListener("foo", f, { once: true }) target.dispatchEvent(event) assert.strictEqual(f.calls.length, 1, "f should be called") assert.strictEqual(f.calls[0].type, "throw" as const) assert.strictEqual(f.calls[0].throw.name, "InvalidStateError") assert.strictEqual(f.calls[0].throw.code, 11) assertError("This event has been in dispatching.") }) const withNativeDOME = NativeDOMException ? describe : xdescribe withNativeDOME( "if the native DOMException is present, the InvalidStateError", () => { it("should be a DOMException instance.", () => { const event = new Event("foo") const f = spy(() => { target.dispatchEvent(event) }) target.addEventListener("foo", f, { once: true }) target.dispatchEvent(event) assert.strictEqual(f.calls.length, 1, "f should be called") assert(f.calls[0].type === "throw", "f shold throw a value") assert( f.calls[0].throw instanceof NativeDOMException, "the thrown value should be a DOMException", ) assertError("This event has been in dispatching.") }) }, ) it("should not call event listeners if given event was stopped", () => { const event = new Event("foo") const f = spy() event.stopPropagation() target.addEventListener("foo", f) target.dispatchEvent(event) assert.strictEqual(f.calls.length, 0, "f should not be called") }) const withNativeEvent = NativeEvent ? describe : xdescribe withNativeEvent("if native Event class is present", () => { it("should call a registered listener even if the argument is a native Event object.", () => { const f1 = spy((_event: Event) => {}) target.addEventListener("foo", f1) const retv = target.dispatchEvent(new NativeEvent("foo")) assert.strictEqual( f1.calls.length, 1, "foo should be called once", ) assert( f1.calls[0].arguments[0] instanceof Event, "the argument of callback should be an instance of our Event class (wrapper)", ) assert.strictEqual(retv, true) }) describe("if the argument is a native Event object, the event object in the listener", () => { it("'type' property should be the same value as the original.", () => { const event = new NativeEvent("foo") let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual(wrapper.type, event.type) }) target.dispatchEvent(event) assert(ok) }) it("'target' property should be the event target that is dispatching.", () => { const event = new NativeEvent("foo") let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual(wrapper.target, target) }) target.dispatchEvent(event) assert(ok) }) it("'currentTarget' property should be the event target that is dispatching.", () => { const event = new NativeEvent("foo") let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual(wrapper.currentTarget, target) }) target.dispatchEvent(event) assert(ok) }) it("'eventPhase' property should be 2.", () => { const event = new NativeEvent("foo") let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual(wrapper.eventPhase, 2) }) target.dispatchEvent(event) assert(ok) }) it("'stopPropagation()' method should change both 'cancelBubble' property.", () => { const event = new NativeEvent("foo") let ok = false target.addEventListener("foo", wrapper => { ok = true wrapper.stopPropagation() assert.strictEqual(wrapper.cancelBubble, true) assert.strictEqual(event.cancelBubble, true) }) target.dispatchEvent(event) assert(ok) }) it("'cancelBubble' property should be the same value as the original.", () => { const event = new NativeEvent("foo") event.stopPropagation() let ok = true target.addEventListener("foo", wrapper => { ok = false }) target.dispatchEvent(event) assert(ok) }) // Node.js's `Event` class is buggy. const isStopImmediatePropagationBuggy = (() => { if (!NativeEvent) { return false } const e = new NativeEvent("foo") e.stopImmediatePropagation() return !e.cancelBubble })() ;(isStopImmediatePropagationBuggy ? xit : it)( "'stopImmediatePropagation()' method should change both 'cancelBubble' property.", () => { const event = new NativeEvent("foo") let ok = false target.addEventListener("foo", wrapper => { ok = true wrapper.stopImmediatePropagation() assert.strictEqual( wrapper.cancelBubble, true, "wrapper's cancelBubble should be true", ) assert.strictEqual( event.cancelBubble, true, "original's cancelBubble should be true", ) }) target.dispatchEvent(event) assert(ok) }, ) it("'bubbles' property should be the same value as the original.", () => { const event = new NativeEvent("foo", { bubbles: true }) let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual(wrapper.bubbles, event.bubbles) }) target.dispatchEvent(event) assert(ok) }) it("'cancelable' property should be the same value as the original.", () => { const event = new NativeEvent("foo", { cancelable: true }) let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual(wrapper.cancelable, event.cancelable) }) target.dispatchEvent(event) assert(ok) }) it("'returnValue' property should be the same value as the original.", () => { const event = new NativeEvent("foo", { cancelable: true }) event.preventDefault() let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual( wrapper.returnValue, event.returnValue, ) }) target.dispatchEvent(event) assert(ok) }) it("'preventDefault()' method should change both 'defaultPrevented' property.", () => { const event = new NativeEvent("foo", { cancelable: true }) let ok = false target.addEventListener("foo", wrapper => { ok = true wrapper.preventDefault() assert.strictEqual(wrapper.defaultPrevented, true) assert.strictEqual(event.defaultPrevented, true) }) target.dispatchEvent(event) assert(ok) }) it("'defaultPrevented' property should be the same value as the original.", () => { const event = new NativeEvent("foo", { cancelable: true }) event.preventDefault() let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual( wrapper.defaultPrevented, event.defaultPrevented, ) }) target.dispatchEvent(event) assert(ok) }) it("'composed' property should be the same value as the original.", () => { const event = new NativeEvent("foo", { composed: true }) let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual(wrapper.composed, event.composed) }) target.dispatchEvent(event) assert(ok) }) it("'timeStamp' property should be the same value as the original.", async () => { const event = new NativeEvent("foo") await new Promise(resolve => setTimeout(resolve, 100)) let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual(wrapper.timeStamp, event.timeStamp) }) target.dispatchEvent(event) assert(ok) }) }) }) const withNativeKE = NativeKeyboardEvent ? describe : xdescribe withNativeKE("if native KeyboardEvent class is present", () => { describe("if the argument is a native KeyboardEvent object, the event object in the listener", () => { it("'key' property should be the same value as the original.", () => { const customTarget = new EventTarget<{ foo: KeyboardEvent }>() const event = new NativeKeyboardEvent("foo", { key: "Enter", }) let ok = false customTarget.addEventListener("foo", wrapper => { ok = true assert.strictEqual(wrapper.key, event.key) }) customTarget.dispatchEvent(event) assert(ok) }) it("'getModifierState' method should return the same value as the original.", () => { const customTarget = new EventTarget<{ foo: KeyboardEvent }>() const event = new NativeKeyboardEvent("foo", { shiftKey: true, }) let ok = false customTarget.addEventListener("foo", wrapper => { ok = true assert.strictEqual( wrapper.getModifierState("Shift"), event.getModifierState("Shift"), ) }) customTarget.dispatchEvent(event) assert(ok) }) }) }) const withNativeME = NativeMouseEvent ? describe : xdescribe withNativeME("if native MouseEvent class is present", () => { describe("if the argument is a native MouseEvent object, the event object in the listener", () => { it("'button' property should be the same value as the original.", () => { const customTarget = new EventTarget<{ foo: MouseEvent }>() const event = new NativeMouseEvent("foo", { button: 1 }) let ok = false customTarget.addEventListener("foo", wrapper => { ok = true assert.strictEqual(wrapper.button, event.button) }) customTarget.dispatchEvent(event) assert(ok) }) it("'getModifierState' method should return the same value as the original.", () => { const customTarget = new EventTarget<{ foo: MouseEvent }>() const event = new NativeMouseEvent("foo", { shiftKey: true, }) let ok = false customTarget.addEventListener("foo", wrapper => { ok = true assert.strictEqual( wrapper.getModifierState("Shift"), event.getModifierState("Shift"), ) }) customTarget.dispatchEvent(event) assert(ok) }) }) }) describe("if the argument is a plain object, the event object in the listener", () => { class MyEvent extends Event { writable: number constructor(writable: number) { super("myevent") this.writable = writable } } // eslint-disable-next-line no-shadow let target: EventTarget<{ foo: Event; bar: MyEvent }, "strict"> beforeEach(() => { target = new EventTarget() }) it("'type' property should be the same value as the original.", () => { const event = { type: "foo" } as const let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual(wrapper.type, event.type) }) target.dispatchEvent(event) assert(ok) }) it("'target' property should be the event target that is dispatching.", () => { const event = { type: "foo" } as const let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual(wrapper.target, target) }) target.dispatchEvent(event) assert(ok) }) it("'currentTarget' property should be the event target that is dispatching.", () => { const event = { type: "foo" } as const let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual(wrapper.currentTarget, target) }) target.dispatchEvent(event) assert(ok) }) it("'eventPhase' property should be 2.", () => { const event = { type: "foo" } as const let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual(wrapper.eventPhase, 2) }) target.dispatchEvent(event) assert(ok) }) it("'stopPropagation()' method should call the 'stopPropagation()' method on the original.", () => { const event = { type: "foo", stopPropagation: spy() } as const target.addEventListener("foo", wrapper => { wrapper.stopPropagation() }) target.dispatchEvent(event) assert.strictEqual( event.stopPropagation.calls.length, 1, "stopPropagation method should be called", ) }) it("'stopPropagation()' method should not throw any error even if the original didn't have the 'stopPropagation()' method.", () => { const event = { type: "foo" } as const let ok = true target.addEventListener("foo", wrapper => { ok = true wrapper.stopPropagation() }) target.dispatchEvent(event) assert(ok) }) it("'cancelBubble' property should be the same value as the original.", () => { const event = { type: "foo", cancelBubble: true } as const let ok = true target.addEventListener("foo", wrapper => { ok = false }) target.dispatchEvent(event) assert(ok) }) it("assigning to 'cancelBubble' property should change both the wrapper and the original.", () => { const event = { type: "foo", cancelBubble: false } as const let ok = false target.addEventListener("foo", wrapper => { ok = true wrapper.cancelBubble = true assert.strictEqual(wrapper.cancelBubble, true) assert.strictEqual(event.cancelBubble, true) }) target.dispatchEvent(event) assert(ok) }) it("assigning to 'cancelBubble' property should change only the wrapper if the original didn't have the property.", () => { const event = { type: "foo" } as const let ok = false target.addEventListener("foo", wrapper => { ok = true wrapper.cancelBubble = true assert.strictEqual(wrapper.cancelBubble, true) // @ts-expect-error assert.strictEqual(event.cancelBubble, undefined) }) target.dispatchEvent(event) assert(ok) }) it("'stopImmediatePropagation()' method should call the 'stopImmediatePropagation()' method on the original.", () => { const event = { type: "foo", stopImmediatePropagation: spy(), } as const target.addEventListener("foo", wrapper => { wrapper.stopImmediatePropagation() }) target.dispatchEvent(event) assert.strictEqual( event.stopImmediatePropagation.calls.length, 1, "stopImmediatePropagation method should be called", ) }) it("'stopImmediatePropagation()' method should not throw any error even if the original didn't have the 'stopImmediatePropagation()' method.", () => { const event = { type: "foo" } as const let ok = true target.addEventListener("foo", wrapper => { ok = true wrapper.stopImmediatePropagation() }) target.dispatchEvent(event) assert(ok) }) it("'bubbles' property should be the same value as the original.", () => { const event = { type: "foo", bubbles: true } as const let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual(wrapper.bubbles, event.bubbles) }) target.dispatchEvent(event) assert(ok) }) it("'cancelable' property should be the same value as the original.", () => { const event = { type: "foo", cancelable: true } as const let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual(wrapper.cancelable, event.cancelable) }) target.dispatchEvent(event) assert(ok) }) it("'returnValue' property should be the same value as the original.", () => { const event = { type: "foo", returnValue: true } as const let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual(wrapper.returnValue, event.returnValue) }) target.dispatchEvent(event) assert(ok) }) it("assigning to 'returnValue' property should change both the wrapper and the original.", () => { const event = { type: "foo", cancelable: true, returnValue: true, } as const let ok = false target.addEventListener("foo", wrapper => { ok = true wrapper.returnValue = false assert.strictEqual(wrapper.returnValue, false) assert.strictEqual(event.returnValue, false) }) target.dispatchEvent(event) assert(ok) }) it("assigning to 'returnValue' property should change only the wrapper if the original didn't have the property.", () => { const event = { type: "foo", cancelable: true, } as const let ok = false target.addEventListener("foo", wrapper => { ok = true wrapper.returnValue = false assert.strictEqual(wrapper.returnValue, false) // @ts-expect-error assert.strictEqual(event.returnValue, undefined) }) target.dispatchEvent(event) assert(ok) }) it("'preventDefault()' method should call the 'preventDefault()' method on the original.", () => { const event = { type: "foo", cancelable: true, preventDefault: spy(), } as const target.addEventListener("foo", wrapper => { wrapper.preventDefault() }) target.dispatchEvent(event) assert.strictEqual( event.preventDefault.calls.length, 1, "preventDefault method should be called", ) }) it("'preventDefault()' method should not throw any error even if the original didn't have the 'preventDefault()' method.", () => { const event = { type: "foo", cancelable: true } as const let ok = true target.addEventListener("foo", wrapper => { ok = true wrapper.preventDefault() }) target.dispatchEvent(event) assert(ok) }) it("'composed' property should be the same value as the original.", () => { const event = { type: "foo", composed: true } as const let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual(wrapper.composed, event.composed) }) target.dispatchEvent(event) assert(ok) }) it("'timeStamp' property should be the same value as the original.", async () => { const event = { type: "foo", timeStamp: Date.now() } as const await new Promise(resolve => setTimeout(resolve, 100)) let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual(wrapper.timeStamp, event.timeStamp) }) target.dispatchEvent(event) assert(ok) }) it("'timeStamp' property should be a number even if the original didn't have the 'timeStamp' property.", () => { const event = { type: "foo" } as const let ok = false target.addEventListener("foo", wrapper => { ok = true assert.strictEqual(typeof wrapper.timeStamp, "number") }) target.dispatchEvent(event) assert(ok) }) it("should redirect instance properties.", () => { const event = { type: "bar", writable: 1 } as const target.addEventListener("bar", wrapper => { assert.strictEqual(wrapper.writable, 1) wrapper.writable = 2 }) target.dispatchEvent(event) assert.strictEqual(event.writable, 2) }) it("should not throw even if prototype is null.", () => { const event = Object.assign( Object.create(null) as {}, { type: "bar", writable: 1 } as const, ) target.addEventListener("bar", wrapper => { assert.strictEqual(wrapper.writable, 1) wrapper.writable = 2 }) target.dispatchEvent(event) assert.strictEqual(event.writable, 2) }) }) }) describe("for-in", () => { it("should enumerate 3 property names", () => { const target = new EventTarget() const actualKeys = [] const expectedKeys = [ "addEventListener", "removeEventListener", "dispatchEvent", ] // eslint-disable-next-line @mysticatea/prefer-for-of for (const key in target) { actualKeys.push(key) } assert.deepStrictEqual( actualKeys.sort(undefined), expectedKeys.sort(undefined), ) }) it("should enumerate no property names in static", () => { const keys = new Set() // eslint-disable-next-line @mysticatea/prefer-for-of for (const key in EventTarget) { keys.add(key) } assert.deepStrictEqual(keys, new Set()) }) }) })
the_stack
import * as S from '@apollo-elements/test/schema'; import type { ApolloSubscriptionController } from '@apollo-elements/core'; import { c, html, useEffect, useState, useRef, useLayoutEffect } from 'atomico'; import { useSubscription } from './useSubscription'; import { aTimeout, defineCE, expect, nextFrame } from '@open-wc/testing'; import { fixture } from 'atomico/test-dom'; import { ApolloError } from '@apollo/client/core'; import { setupClient, teardownClient, resetMessages } from '@apollo-elements/test'; import { spy, SinonSpy } from 'sinon'; describe('[atomico] useSubscription', function() { describe('with noAutoSubscribe set', function() { let element: HTMLElement & { updated: Promise<void> }; beforeEach(async function define() { function Renderer() { const { data } = useSubscription(S.NullableParamSubscription, { noAutoSubscribe: true }); return html`<host shadowDom>${data?.nullableParam?.nullable ?? 'nothing'}</host>`; } const Component = c(Renderer) as any; defineCE(Component); element = fixture(html`<${Component}></${Component}>`); await element.updated; }); beforeEach(nextFrame); it('renders nothing', function() { expect(element).shadowDom.to.equal('nothing'); }); }); describe('without options', function() { let options: ApolloSubscriptionController< S.NullableParamSubscriptionData, S.NullableParamSubscriptionVariables >['options']; beforeEach(async function define() { function Renderer() { const { options: opts } = useSubscription(S.NullableParamSubscription); options = opts; return html`<host></host>`; } const Component = c(Renderer) as any; defineCE(Component); const element = fixture(html`<${Component}></${Component}>`); // @ts-expect-error: upstream types await element.updated; }); beforeEach(nextFrame); afterEach(() => options = undefined as unknown as typeof options); it('sets empty options', function() { expect(options).to.be.empty; }); }); describe('with shouldSubscribe set to constant false', function() { let element: HTMLElement & { updated: Promise<void> }; let doSubscribe: ApolloSubscriptionController< S.NullableParamSubscriptionData, S.NullableParamSubscriptionVariables >['subscribe']; beforeEach(async function define() { function Renderer() { const { data, subscribe } = useSubscription(S.NullableParamSubscription, { shouldSubscribe: () => false, }); doSubscribe = subscribe; return html`<host shadowDom>${data?.nullableParam?.nullable ?? 'nothing'}</host>`; } const Component = c(Renderer) as any; defineCE(Component); element = fixture(html`<${Component}></${Component}>`); await element.updated; }); beforeEach(nextFrame); it('renders nothing', function() { expect(element).shadowDom.to.equal('nothing'); }); describe('without setting query or variables', function() { describe('subscribe()', function() { it('throws', function() { expect(() => doSubscribe()) .to.throw('No Apollo client'); }); }); }); }); describe('with global client', function() { beforeEach(setupClient); afterEach(teardownClient); describe('README examples', function() { describe('without variables', function() { let element: HTMLElement & { updated: Promise<void> }; let sub: ApolloSubscriptionController< S.NoParamSubscriptionData, S.NoParamSubscriptionVariables >['subscribe']; beforeEach(async function define() { function Renderer() { const { data, error, loading, subscribe } = useSubscription(S.NoParamSubscription, { noAutoSubscribe: true, }); useEffect(() => { sub = subscribe; }, [subscribe]); const spinRef = useRef(); useLayoutEffect(() => { spinRef.current.toggleAttribute('active', loading); }, [loading]); return html` <host shadowDom> <what-spin-such-loader ref=${spinRef}></what-spin-such-loader> <article id="error" hidden=${!error}> <h2>${'😢 Such Sad, Very Error! 😰'}</h2> <pre><code>${error?.message}</code></pre> </article> <p>${data?.noParam!.noParam ?? 'fail'}</p> </host> `; } const Component = c(Renderer) as any; defineCE(Component); element = fixture(html`<${Component}></${Component}>`); await element.updated; }); beforeEach(() => sub()); describe('on mount', function() { beforeEach(() => element.updated); it('renders loading state', function() { expect(element).shadowDom.to.equal(` <what-spin-such-loader active></what-spin-such-loader> <article id="error" hidden> <h2>${'😢 Such Sad, Very Error! 😰'}</h2> <pre><code></code></pre> </article> <p>fail</p> `); }); }); describe('eventually', function() { beforeEach(() => aTimeout(20)); it('renders data', function() { expect(element).shadowDom.to.equal(` <what-spin-such-loader></what-spin-such-loader> <article id="error" hidden> <h2>😢 Such Sad, Very Error! 😰</h2> <pre><code></code></pre> </article> <p>noParam</p> `); }); }); }); describe('with variables', function() { let element: HTMLElement & { updated: Promise<void> }; let sub: ApolloSubscriptionController<typeof S.NullableParamSubscription>['subscribe']; beforeEach(async function define() { function Renderer() { const { data, error, loading, subscribe } = useSubscription(S.NullableParamSubscription, { noAutoSubscribe: true, variables: { nullable: 'POW', delay: 20, }, }); // @ts-expect-error: whatev useEffect(() => { sub = subscribe; }, [subscribe]); const spinRef = useRef(); useLayoutEffect(() => { spinRef.current.toggleAttribute('active', loading); }, [loading]); const nullable = data?.nullableParam!.nullable ?? 'NullableParam'; return html` <host shadowDom> <what-spin-such-loader ref=${spinRef}></what-spin-such-loader> <article id="error" hidden=${!error}> <h2>${'😢 Such Sad, Very Error! 😰'}</h2> <pre><code>${error?.message}</code></pre> </article> <p>${nullable}</p> </host> `; } const Component = c(Renderer) as any; defineCE(Component); element = fixture(html`<${Component}></${Component}>`); await element.updated; }); beforeEach(() => sub()); beforeEach(nextFrame); it('renders loading state', function() { expect(element).shadowDom.to.equal(` <what-spin-such-loader active></what-spin-such-loader> <article id="error" hidden> <h2>😢 Such Sad, Very Error! 😰</h2> <pre><code></code></pre> </article> <p>NullableParam</p> `); }); describe('eventually', function() { beforeEach(() => aTimeout(20)); it('renders data', function() { expect(element).shadowDom.to.equal(` <what-spin-such-loader></what-spin-such-loader> <article id="error" hidden> <h2>😢 Such Sad, Very Error! 😰</h2> <pre><code></code></pre> </article> <p>POW</p> `); }); }); }); }); describe('setting shouldSubscribe to constant false', function() { let element: HTMLElement & { subscription: ApolloSubscriptionController< S.NullableParamSubscriptionData, S.NullableParamSubscriptionVariables > }; let subscription: typeof element['subscription']; beforeEach(async function define() { const Component = c( function Renderer() { subscription = useSubscription(S.NullableParamSubscription, { shouldSubscribe: () => false, onData: spy(), onError: spy(), }); return html`<host></host>`; } ); defineCE(Component as any); element = fixture(html`<${Component}></${Component}>`); // @ts-expect-error: upstream types await element.updated; }); it('reads document from query', function() { expect(subscription.subscription) .to.be.ok .and.to.equal(subscription.document); }); describe('setting subscription', function() { beforeEach(function() { subscription.subscription = S.NullableParamSubscription; }); it('sets document', function() { expect(subscription.document).to.equal(S.NullableParamSubscription); }); describe('then calling subscribe', function() { beforeEach(() => subscription.subscribe()); it('sets loading', function() { expect(subscription.loading).to.be.true; }); describe('when subscription resolves', function() { beforeEach(() => aTimeout(50)); it('refetches', function() { expect(subscription.data?.nullableParam?.nullable).to.be.a.string; }); it('unsets loading', function() { expect(subscription.loading).to.be.false; }); }); }); }); beforeEach(() => aTimeout(100)); it('does not fetch data', function() { expect(subscription?.options?.onData).to.not.have.been.called; expect(subscription?.options?.onError).to.not.have.been.called; }); describe('when query will reject', function() { beforeEach(function() { subscription.variables = { nullable: 'error' }; }); describe('calling subscribe()', function() { beforeEach(function() { subscription.subscribe(); }); beforeEach(nextFrame); it('calls onError', function() { expect(subscription.options.onError).to.have.been.calledWithMatch({ message: 'error', }); }); }); }); }); describe('with noAutoSubscribe option and NullableParamSubscription', function() { let element: HTMLElement & { subscription: ApolloSubscriptionController<any> }; let s: ApolloSubscriptionController< S.NullableParamSubscriptionData, S.NullableParamSubscriptionVariables >; beforeEach(async function define() { function Renderer(this: typeof element) { const subscription = useSubscription(S.NullableParamSubscription, { noAutoSubscribe: true, onData: spy(), onError: spy(), onComplete: spy(), }); useEffect(() => { s = subscription; }, [subscription]); return html`<host></host>`; } const Component = c(Renderer) as any; defineCE(Component); element = fixture(html`<${Component}></${Component}>`); // @ts-expect-error: upstream types await element.updated; }); beforeEach(nextFrame); beforeEach(function spyClientSubscription() { spy(s.client!, 'subscribe'); }); afterEach(function restoreClientSubscription() { (s.client?.subscribe as SinonSpy).restore?.(); }); afterEach(function teardownElement() { element.remove(); element = undefined as unknown as typeof element; s = undefined as unknown as typeof s; }); it('does not subscribe', function() { expect(s.options?.onData).to.not.have.been.called; }); describe('when subscribe() rejects', function() { beforeEach(function() { s.subscribe({ variables: { nullable: 'error', } }); }); beforeEach(() => aTimeout(50)); it('sets error', function() { expect(s.error?.message, 'message').to.equal('error'); expect(s.options.onError).to.have.been.calledWithMatch({ message: 'error', }); expect(s.error, 'element error') .to.be.ok .and.to.equal(s.error) .and.to.be.an.instanceof(ApolloError); }); }); describe('with empty options', function() { beforeEach(function() { s.options = {}; }); describe('subscribe({ variables })', function() { beforeEach(function() { s.subscribe({ variables: { nullable: 'whoop', }, }); }); beforeEach(() => aTimeout(50)); it('refetches and updates state', function() { expect(s.data).to.deep.equal({ nullableParam: { __typename: 'Nullable', nullable: 'whoop', }, }); }); }); }); describe('with context option', function() { beforeEach(function() { s.options.context = 'none'; }); describe('subscribe()', function() { beforeEach(() => s.subscribe()); it('uses context option', function() { expect(s.client!.subscribe).to.have.been.calledWithMatch({ context: 'none', }); }); }); describe('subscribe({ context })', function() { const context = {}; beforeEach(() => (s.client!.subscribe as SinonSpy).resetHistory?.()); beforeEach(() => s.subscribe({ context })); it('uses provided context', function() { expect(s.client!.subscribe).to.have.been.calledWithMatch({ context, }); }); }); }); describe('with errorPolicy option', function() { beforeEach(function() { s.options.errorPolicy = 'none'; }); describe('subscribe()', function() { beforeEach(() => s.subscribe()); it('uses errorPolicy option', function() { expect(s.client!.subscribe).to.have.been.calledWithMatch({ errorPolicy: 'none', }); }); }); describe('subscribe({ errorPolicy })', function() { beforeEach(() => (s.client!.subscribe as SinonSpy).resetHistory?.()); beforeEach(() => s.subscribe({ errorPolicy: 'all' })); it('uses provided errorPolicy', function() { expect(s.client!.subscribe).to.have.been.calledWithMatch({ errorPolicy: 'all', }); }); }); }); describe('with fetchPolicy option', function() { beforeEach(function() { s.options.fetchPolicy = 'no-cache'; }); describe('subscribe()', function() { beforeEach(() => s.subscribe()); it('uses fetchPolicy option', function() { expect(s.client!.subscribe).to.have.been.calledWithMatch({ fetchPolicy: 'no-cache', }); }); }); describe('subscribe({ fetchPolicy })', function() { beforeEach(() => s.subscribe({ fetchPolicy: 'cache-first' })); it('uses provided fetchPolicy', function() { expect(s.client!.subscribe).to.have.been.calledWithMatch({ fetchPolicy: 'cache-first', }); }); }); }); describe('with shouldResubscribe option', function() { beforeEach(function() { s.options.shouldResubscribe = true; }); describe('calling subscribe()', function() { function callSubscribe() { s.subscribe(); } beforeEach(callSubscribe); describe('then calling subscribe() again', function() { beforeEach(callSubscribe); it('calls client.subscribe() twice', function() { expect(s.client?.subscribe).to.have.been.calledTwice; }); }); }); }); describe('subscribe()', function() { function callSubscribe() { s.subscribe(); } beforeEach(callSubscribe); beforeEach(() => aTimeout(50)); it('calls client.subscribe() with controller subscription', function() { expect(s.client?.subscribe).to.have.been.calledWithMatch({ query: S.NullableParamSubscription, }); }); it('refetches and updates state', function() { const data = { nullableParam: { __typename: 'Nullable', nullable: 'Hello World', }, }; expect(s.data).to.deep.equal(data); expect(s.options.onData) .to.have.calledOnce .and.to.have.been.calledWithMatch({ subscriptionData: { data, loading: false, error: null, }, }); }); describe('then calling subscribe() again', function() { beforeEach(callSubscribe); it('does not call client.subscribe() a second time', function() { expect(s.client?.subscribe).to.have.been.calledOnce; }); }); }); describe('subscribe({ subscription })', function() { beforeEach(function() { s.subscribe({ subscription: S.NullableParamSubscription }); }); beforeEach(nextFrame); it('calls client.subscribe() with passed subscribe', function() { expect(s.client?.subscribe).to.have.been.calledWithMatch({ subscription: S.NullableParamSubscription, }); }); }); describe('subscribe({ variables })', function() { beforeEach(function() { s.subscribe({ variables: { nullable: 'שלום עליכם, רבי ומורי', }, }); }); beforeEach(() => aTimeout(50)); it('refetches and updates state', function() { expect(s.data).to.deep.equal({ nullableParam: { __typename: 'Nullable', nullable: 'שלום עליכם, רבי ומורי', }, }); }); }); }); describe('with NullableParamSubscription', function() { let element: HTMLElement & { subscription: ApolloSubscriptionController<any> }; let subscription: ApolloSubscriptionController< S.NullableParamSubscriptionData, S.NullableParamSubscriptionVariables >; beforeEach(async function define() { function Renderer(this: typeof element) { subscription = useSubscription(S.NullableParamSubscription, { onData: spy(), onComplete: spy(), onError: spy(), }); return html`<host></host>`; } const Component = c(Renderer) as any; defineCE(Component); element = fixture(html`<${Component}></${Component}>`); // @ts-expect-error: upstream types await element.updated; }); let querySpy: SinonSpy; let subscribeSpy: SinonSpy; beforeEach(() => { querySpy = spy(subscription.client!, 'query'); subscribeSpy = spy(subscription.client!, 'subscribe'); }); afterEach(() => { querySpy.restore(); subscribeSpy.restore(); }); beforeEach(() => aTimeout(50)); it('sets data, error, and loading', function() { expect(subscription.data?.nullableParam?.nullable, 'data.nullableParam.nullable') .to.equal('Hello World'); expect(subscription.loading, 'loading') .to.equal(subscription.loading) .and.to.be.false; expect(subscription.error, 'error') .to.equal(subscription.error) .and.to.not.be.ok; }); it('calls onData', function() { expect(subscription.options.onData) .to.have.been.calledOnce .and.to.have.been.calledWithMatch({ // client: subscription.client, subscriptionData: { loading: false, error: null, data: { nullableParam: { nullable: 'Hello World', }, }, }, }); const [{ client }] = (subscription.options.onData as SinonSpy).lastCall.args; expect(client).to.equal(subscription.client); }); describe('setting subscription variables', function() { beforeEach(function() { subscription.variables = { nullable: 'אין עוד מלבדו', }; }); beforeEach(() => aTimeout(50)); it('refetches', function() { expect(subscription.options.onData).to.have.been.calledTwice; const [{ client, subscriptionData, ...res }] = (subscription.options.onData as SinonSpy).lastCall.args; expect(res).to.be.empty; expect(client, 'client') .to.equal(subscription.client) .and.to.equal(window.__APOLLO_CLIENT__); expect(subscriptionData, 'client').to.deep.equal({ loading: false, error: null, data: { nullableParam: { __typename: 'Nullable', nullable: 'אין עוד מלבדו', }, }, }); expect(subscription.data, 'element.subscription.data').to.deep.equal({ nullableParam: { __typename: 'Nullable', nullable: 'אין עוד מלבדו', }, }); }); }); }); describe('with MessageSentSubscription', function() { let element: HTMLElement & { subscription: ApolloSubscriptionController<any> }; beforeEach(resetMessages); afterEach(resetMessages); const onData = spy(); beforeEach(async function define() { function Renderer(this: typeof element) { const { data } = useSubscription(S.MessageSentSubscription, { onData }); const [messages, setMessages] = useState<string[]>([]); useEffect(() => { if (data?.messageSent?.message) setMessages([...messages, data.messageSent.message]); }, [data]); return html` <host shadowDom> <ol>${messages.map(x => html`<li>${x}</li>`)}</ol> </host> `; } const Component = c(Renderer) as any; defineCE(Component); element = fixture(html`<${Component}></${Component}>`); // @ts-expect-error: upstream types await element.updated; }); beforeEach(nextFrame); it('renders initial data', function() { expect(onData).to.have.been.calledOnce; expect(element).shadowDom.to.equal(` <ol> <li>Message 1</li> </ol> `); }); }); }); });
the_stack
import { Component, OnInit } from "@angular/core"; import { GlobalVarsService } from "../global-vars.service"; import { BackendApiService } from "../backend-api.service"; import { SwalHelper } from "../../lib/helpers/swal-helper"; import { InfiniteScroller } from "../infinite-scroller"; import { IAdapter, IDatasource } from "ngx-ui-scroll"; @Component({ selector: "nft-drop-mgr", templateUrl: "./nft-drop-mgr.component.html", }) export class NftDropMgrComponent implements OnInit { globalVars: GlobalVarsService; loading: boolean = false; loadingNewDrop: boolean = false; settingDate: boolean = false; togglingActivation: boolean = false; addingNFT: boolean = false; hideDateTimeAdjuster: boolean = false; dropSelectorError: string = ""; nftToAdd: string = ""; nftBeingRemoved: string = ""; dropNumber: number = 1; latestDropNumber: number = 1; latestDropEntry: any; dropTime: Date = new Date(); dropEntry: any; posts = []; isUpdatable = false; static PAGE_SIZE = 10; static WINDOW_VIEWPORT = true; static BUFFER_SIZE = 5; static PADDING = 0.5; lastPage: number; infiniteScroller: InfiniteScroller = new InfiniteScroller( NftDropMgrComponent.PAGE_SIZE, this.getPage.bind(this), NftDropMgrComponent.WINDOW_VIEWPORT, NftDropMgrComponent.BUFFER_SIZE, NftDropMgrComponent.PADDING ); datasource: IDatasource<IAdapter<any>> = this.infiniteScroller.getDatasource(); constructor(private _globalVars: GlobalVarsService, private backendApi: BackendApiService) { this.globalVars = _globalVars; } ngOnInit(): void { // Get the latest NFT drop this.loading = true; this.backendApi .AdminGetNFTDrop(this.globalVars.localNode, this.globalVars.loggedInUser.PublicKeyBase58Check, -1 /*DropNumber*/) .subscribe( (res: any) => { this.dropEntry = res.DropEntry; if (res.DropEntry.DropNumber === 0) { // If the drop number is zero, we could not find any drops and use the defaults. } else { this.latestDropNumber = res.DropEntry.DropNumber; this.latestDropEntry = res.DropEntry; this.updateStateBasedOnNewDropEntry(res.DropEntry, res.Posts); } }, (error) => { this.globalVars._alertError(error.error.error); } ) .add(() => { this.loading = false; }); } getPage(page: number) { if (this.lastPage != null && page > this.lastPage) { return []; } const startIdx = page * NftDropMgrComponent.PAGE_SIZE; const endIdx = (page + 1) * NftDropMgrComponent.PAGE_SIZE; return new Promise((resolve, reject) => { resolve(this.posts.slice(startIdx, Math.min(endIdx, this.posts.length))); }); } isWorking() { return this.loading || this.settingDate || this.togglingActivation || this.addingNFT; } updateStateBasedOnNewDropEntry(dropEntry: any, posts: any) { this.posts = posts ? posts : []; this.dropEntry = dropEntry; this.dropEntry.Date = new Date(this.dropEntry.DropTstampNanos / 1e6); this.dropNumber = dropEntry.DropNumber; this.dropTime = new Date(dropEntry.DropTstampNanos / 1e6); let currentTime = new Date(); this.hideDateTimeAdjuster = this.dropTime < currentTime; this.lastPage = Math.floor(this.posts.length / NftDropMgrComponent.PAGE_SIZE); this.setIsUpdatable(); } updateErrorWithTimeout(errorMsg: string) { this.dropSelectorError = errorMsg; setTimeout(() => { this.dropSelectorError = ""; }, 1500); } resetDatasource(): void { this.infiniteScroller.reset(); this.datasource.adapter.reset().then(() => { this.loadingNewDrop = false; this.loading = false; }); } nextDrop() { if (this.isWorking()) { return; } this.dropSelectorError = ""; let currentTime = new Date(); if (this.dropTime > currentTime) { this.updateErrorWithTimeout("Cannot make a new drop while this drop is pending."); return; } let nextDropNumber = this.dropNumber + 1; if (nextDropNumber == this.latestDropNumber + 1) { // If the next drop is a new drop, initialize it. this.posts = []; this.dropNumber = nextDropNumber; this.dropTime = new Date(); this.dropEntry = null; this.hideDateTimeAdjuster = false; this.resetDatasource(); return; } this.loading = true; this.loadingNewDrop = true; this.backendApi .AdminGetNFTDrop( this.globalVars.localNode, this.globalVars.loggedInUser.PublicKeyBase58Check, nextDropNumber /*DropNumber*/ ) .subscribe( (res: any) => { this.updateStateBasedOnNewDropEntry(res.DropEntry, res.Posts); }, (error) => { this.updateErrorWithTimeout("Error getting drop #" + nextDropNumber.toString() + "."); } ) .add(() => { this.resetDatasource(); }); } previousDrop() { if (this.isWorking()) { return; } this.dropSelectorError = ""; let prevDropNumber = this.dropNumber - 1; this.loading = true; this.loadingNewDrop = true; this.backendApi .AdminGetNFTDrop( this.globalVars.localNode, this.globalVars.loggedInUser.PublicKeyBase58Check, prevDropNumber /*DropNumber*/ ) .subscribe( (res: any) => { this.updateStateBasedOnNewDropEntry(res.DropEntry, res.Posts); }, (error) => { this.updateErrorWithTimeout("Error getting drop #" + prevDropNumber.toString() + "."); } ) .add(() => { this.resetDatasource(); }); } setDate() { if (this.isWorking()) { return; } this.settingDate = true; this.backendApi .AdminUpdateNFTDrop( this.globalVars.localNode, this.globalVars.loggedInUser.PublicKeyBase58Check, this.dropNumber, this.dropTime.getTime() * 1e6, false /*IsActive*/, "" /*NFTHashHexToAdd*/, "" /*NFTHashHexToRemove*/ ) .subscribe( (res: any) => { this.updateStateBasedOnNewDropEntry(res.DropEntry, res.Posts); if (res.DropEntry.DropNumber > this.latestDropNumber) { this.latestDropNumber = res.DropEntry.DropNumber; } }, (error) => { this.globalVars._alertError(error.error.error); } ) .add(() => { this.settingDate = false; }); } toggleActivation() { if (this.isWorking()) { return; } this.togglingActivation = true; this.backendApi .AdminUpdateNFTDrop( this.globalVars.localNode, this.globalVars.loggedInUser.PublicKeyBase58Check, this.dropEntry.DropNumber, this.dropEntry.DropTstampNanos, !this.dropEntry.IsActive /*IsActive*/, "" /*NFTHashHexToAdd*/, "" /*NFTHashHexToRemove*/ ) .subscribe( (res: any) => { this.updateStateBasedOnNewDropEntry(res.DropEntry, res.Posts); }, (error) => { this.globalVars._alertError(error.error.error); } ) .add(() => { this.togglingActivation = false; }); } addAnNFT() { if (this.isWorking()) { return; } this.addingNFT = true; this.backendApi .AdminUpdateNFTDrop( this.globalVars.localNode, this.globalVars.loggedInUser.PublicKeyBase58Check, this.dropEntry.DropNumber, this.dropEntry.DropTstampNanos, this.dropEntry.IsActive /*IsActive*/, this.nftToAdd /*NFTHashHexToAdd*/, "" /*NFTHashHexToRemove*/ ) .subscribe( (res: any) => { this.updateStateBasedOnNewDropEntry(res.DropEntry, res.Posts); }, (error) => { this.globalVars._alertError(error.error.error); } ) .add(() => { this.addingNFT = false; }); } removeNFT(postHashHex: string) { if (this.isWorking()) { return; } SwalHelper.fire({ target: this.globalVars.getTargetComponentSelector(), html: `Are you sure you want to remove this NFT from the drop?`, showCancelButton: true, showConfirmButton: true, focusConfirm: true, customClass: { confirmButton: "btn btn-light", cancelButton: "btn btn-light no", }, confirmButtonText: "Yes", cancelButtonText: "No", reverseButtons: true, }).then(async (res: any) => { if (res.isConfirmed) { this.nftBeingRemoved = postHashHex; this.backendApi .AdminUpdateNFTDrop( this.globalVars.localNode, this.globalVars.loggedInUser.PublicKeyBase58Check, this.dropEntry.DropNumber, this.dropEntry.DropTstampNanos, this.dropEntry.IsActive /*IsActive*/, "" /*NFTHashHexToAdd*/, postHashHex /*NFTHashHexToRemove*/ ) .subscribe( (res: any) => { this.updateStateBasedOnNewDropEntry(res.DropEntry, res.Posts); }, (error) => { this.globalVars._alertError(error.error.error); } ) .add(() => { this.nftBeingRemoved = ""; }); } }); } setIsUpdatable() { // There are only two possible drops that can be updated (you can't update past drops): // - The current "active" drop. // - The next "pending" drop. let canUpdateDrop = false; let currentTime = new Date(); let latestDropIsPending = this.latestDropEntry.DropTstampNanos / 1e6 > currentTime.getTime(); if (latestDropIsPending && this.dropEntry.DropNumber >= this.latestDropEntry.DropNumber - 1) { // In this case their is a pending drop so the latest drop and the previous drop are editable. canUpdateDrop = true; } else if (!latestDropIsPending && this.dropEntry.DropNumber == this.latestDropEntry.DropNumber) { // In this case there is no pending drop so you can only update the latest drop. canUpdateDrop = true; } this.isUpdatable = canUpdateDrop; } }
the_stack
import { Nullable } from "../../../../shared/types"; import * as React from "react"; import { ParticleSystem, IParticleEmitterType, ConeParticleEmitter, BoxParticleEmitter, PointParticleEmitter, SphereParticleEmitter, HemisphericParticleEmitter, CylinderParticleEmitter, MeshParticleEmitter, } from "babylonjs"; import { Inspector, IObjectInspectorProps } from "../../components/inspector"; import { InspectorList } from "../../gui/inspector/fields/list"; import { InspectorColor } from "../../gui/inspector/fields/color"; import { InspectorString } from "../../gui/inspector/fields/string"; import { InspectorButton } from "../../gui/inspector/fields/button"; import { InspectorNumber } from "../../gui/inspector/fields/number"; import { InspectorSection } from "../../gui/inspector/fields/section"; import { InspectorBoolean } from "../../gui/inspector/fields/boolean"; import { InspectorVector3 } from "../../gui/inspector/fields/vector3"; import { InspectorColorPicker } from "../../gui/inspector/fields/color-picker"; import { Tools } from "../../tools/tools"; import { AbstractInspector } from "../abstract-inspector"; export interface IParticleSystemInspectorState { /** * Defines the reference to the current emitter of the particle system. */ emitter: IParticleEmitterType; /** * Defines the name of the emitter type constructor. */ emitterTypeName: string; } export class ParticleSystemInspector extends AbstractInspector<ParticleSystem, IParticleSystemInspectorState> { /** * Constructor. * @param props defines the component's props. */ public constructor(props: IObjectInspectorProps) { super(props); this.state = { emitter: this.selectedObject.particleEmitterType, emitterTypeName: Tools.GetConstructorName(this.selectedObject.particleEmitterType), }; } /** * Renders the content of the inspector. */ public renderContent(): React.ReactNode { return ( <> <InspectorSection title="Controls"> <InspectorButton label="Start" small={true} onClick={() => this.selectedObject.start()} /> <InspectorButton label="Stop" small={true} onClick={() => this.selectedObject.stop()} /> </InspectorSection> <InspectorSection title="Common"> <InspectorString object={this.selectedObject} property="name" label="Name" /> <InspectorVector3 object={this.selectedObject} property="gravity" label="Gravity" step={0.01} /> <InspectorVector3 object={this.selectedObject} property="worldOffset" label="World Offset" step={0.01} /> </InspectorSection> <InspectorSection title="Billboard"> <InspectorBoolean object={this.selectedObject} property="isBillboardBased" label="Is Billboard Based" /> <InspectorList object={this.selectedObject} property="billboardMode" label="Mode" items={[ { label: "Y", data: ParticleSystem.BILLBOARDMODE_Y }, { label: "All", data: ParticleSystem.BILLBOARDMODE_ALL }, { label: "Stretched", data: ParticleSystem.BILLBOARDMODE_STRETCHED }, ]} /> </InspectorSection> <InspectorSection title="Textures"> <InspectorList object={this.selectedObject} property="particleTexture" label="Texture" items={this.getTexturesList()} /> <InspectorList object={this.selectedObject} property="textureMask" label="Mask" items={this.getTexturesList()} /> <InspectorList object={this.selectedObject} property="blendMode" label="Blend Mode" items={[ { label: "One One", data: ParticleSystem.BLENDMODE_ONEONE }, { label: "Standard", data: ParticleSystem.BLENDMODE_STANDARD }, { label: "Add", data: ParticleSystem.BLENDMODE_ADD }, { label: "Multiply", data: ParticleSystem.BLENDMODE_MULTIPLY }, { label: "Multiple Add", data: ParticleSystem.BLENDMODE_MULTIPLYADD }, ]} /> </InspectorSection> <InspectorSection title="Emitter Type"> <InspectorList object={this.state} property="emitterTypeName" label="Type" items={[ { label: "Point", data: "PointParticleEmitter" }, { label: "Box", data: "BoxParticleEmitter" }, { label: "Sphere", data: "SphereParticleEmitter" }, { label: "Hemispheric", data: "HemisphericParticleEmitter" }, { label: "Cylinder", data: "CylinderParticleEmitter" }, { label: "Cone", data: "ConeParticleEmitter" }, // { label: "Mesh", data: "MeshParticleEmitter" }, ]} onChange={(v) => { this._handleParticleEmitterTypeChanged(v); }} /> {this.getParticleEmitterTypeInspector()} </InspectorSection> <InspectorSection title="Emission"> <InspectorNumber object={this.selectedObject} property="emitRate" label="Emit Rate" min={0} step={0.01} /> <InspectorNumber object={this.selectedObject} property="minEmitPower" label="Min Emit Power" min={0} step={0.01} /> <InspectorNumber object={this.selectedObject} property="maxEmitPower" label="Max Emit Porwer" min={0} step={0.01} /> </InspectorSection> <InspectorSection title="Size"> <InspectorNumber object={this.selectedObject} property="minSize" label="Min Size" step={0.01} /> <InspectorNumber object={this.selectedObject} property="maxSize" label="Max Size" step={0.01} /> <InspectorNumber object={this.selectedObject} property="minScaleX" label="Min Scale X" step={0.01} /> <InspectorNumber object={this.selectedObject} property="maxScaleX" label="Max Scale X" step={0.01} /> <InspectorNumber object={this.selectedObject} property="minScaleY" label="Min Scale Y" step={0.01} /> <InspectorNumber object={this.selectedObject} property="maxScaleY" label="Max Scale Y" step={0.01} /> </InspectorSection> <InspectorSection title="Life Time"> <InspectorNumber object={this.selectedObject} property="minLifeTime" label="Min Life Time" step={0.01} /> <InspectorNumber object={this.selectedObject} property="maxLifeTime" label="Max Life Time" step={0.01} /> </InspectorSection> <InspectorSection title="Colors"> <InspectorSection title="Color 1"> <InspectorColor object={this.selectedObject} property="color1" label="Color" step={0.01} /> <InspectorColorPicker object={this.selectedObject} property="color1" label="Hex Color" /> </InspectorSection> <InspectorSection title="Color 2"> <InspectorColor object={this.selectedObject} property="color2" label="Color" step={0.01} /> <InspectorColorPicker object={this.selectedObject} property="color2" label="Hex Color" /> </InspectorSection> <InspectorSection title="Color Dead"> <InspectorColor object={this.selectedObject} property="colorDead" label="Color" step={0.01} /> <InspectorColorPicker object={this.selectedObject} property="colorDead" label="Hex Color" /> </InspectorSection> </InspectorSection> <InspectorSection title="Rotation"> <InspectorNumber object={this.selectedObject} property="minAngularSpeed" label="Min Angular Speed" step={0.01} /> <InspectorNumber object={this.selectedObject} property="maxAngularSpeed" label="Max Angular Speed" step={0.01} /> <InspectorNumber object={this.selectedObject} property="minInitialRotation" label="Min Initial Rotation" step={0.01} /> <InspectorNumber object={this.selectedObject} property="maxInitialRotation" label="Max Initial Rotation" step={0.01} /> </InspectorSection> <InspectorSection title="Spritesheet"> <InspectorBoolean object={this.selectedObject} property="isAnimationSheetEnabled" label="nimation Sheet Enabled" /> <InspectorBoolean object={this.selectedObject} property="spriteRandomStartCell" label="Random Start Cell Index" /> <InspectorNumber object={this.selectedObject} property="startSpriteCellID" label="First Sprite Index" step={1} /> <InspectorNumber object={this.selectedObject} property="endSpriteCellID" label="Last Sprite Index" step={1} /> <InspectorNumber object={this.selectedObject} property="spriteCellWidth" label="Cell Width" step={1} /> <InspectorNumber object={this.selectedObject} property="spriteCellHeight" label="Cell Height" step={1} /> <InspectorNumber object={this.selectedObject} property="spriteCellChangeSpeed" label="Cell Change Speed" step={0.01} /> </InspectorSection> </> ); } /** * Called on the user changes the current particle emitter type. */ private _handleParticleEmitterTypeChanged(type: string): void { let emitter: Nullable<IParticleEmitterType> = null; switch (type) { case "PointParticleEmitter": emitter = new PointParticleEmitter(); break; case "BoxParticleEmitter": emitter = new BoxParticleEmitter(); break; case "SphereParticleEmitter": emitter = new SphereParticleEmitter(); break; case "HemisphericParticleEmitter": emitter = new HemisphericParticleEmitter(); break; case "CylinderParticleEmitter": emitter = new CylinderParticleEmitter(); break; case "ConeParticleEmitter": emitter = new ConeParticleEmitter(); break; case "MeshParticleEmitter": emitter = new MeshParticleEmitter(); break; } if (emitter) { this.selectedObject.particleEmitterType = emitter; this.setState({ emitter }); } } /** * Returns the inspector used to configure and edit the current emitter type. */ protected getParticleEmitterTypeInspector(): React.ReactNode { const emitter = this.selectedObject.particleEmitterType; if (emitter instanceof PointParticleEmitter) { return ( <InspectorSection title="Point"> <InspectorVector3 object={emitter} property="direction1" label="Direction 1" step={0.01} /> <InspectorVector3 object={emitter} property="direction2" label="Direction 2" step={0.01} /> </InspectorSection> ); } if (emitter instanceof BoxParticleEmitter) { return ( <InspectorSection title="Box"> <InspectorVector3 object={emitter} property="direction1" label="Direction 1" step={0.01} /> <InspectorVector3 object={emitter} property="direction2" label="Direction 2" step={0.01} /> <InspectorVector3 object={emitter} property="minEmitBox" label="Min Emit Box" step={0.01} /> <InspectorVector3 object={emitter} property="maxEmitBox" label="Max Emit Box" step={0.01} /> </InspectorSection> ); } if (emitter instanceof SphereParticleEmitter) { return ( <InspectorSection title="Sphere"> <InspectorNumber object={emitter} property="radius" label="Radius" step={0.01} /> <InspectorNumber object={emitter} property="radiusRange" label="Radius Range" step={0.01} /> <InspectorNumber object={emitter} property="directionRandomizer" label="Direction Randomizer" step={0.01} /> </InspectorSection> ); } if (emitter instanceof HemisphericParticleEmitter) { return ( <InspectorSection title="Hemispheric"> <InspectorNumber object={emitter} property="radius" label="Radius" step={0.01} /> <InspectorNumber object={emitter} property="radiusRange" label="Radius Range" step={0.01} /> <InspectorNumber object={emitter} property="directionRandomizer" label="Direction Randomizer" step={0.01} /> </InspectorSection> ); } if (emitter instanceof CylinderParticleEmitter) { return ( <InspectorSection title="Cylinder"> <InspectorNumber object={emitter} property="radius" label="Radius" step={0.01} /> <InspectorNumber object={emitter} property="height" label="Height" step={0.01} /> <InspectorNumber object={emitter} property="radiusRange" label="Radius Range" step={0.01} /> <InspectorNumber object={emitter} property="directionRandomizer" label="Direction Randomizer" step={0.01} /> </InspectorSection> ); } if (emitter instanceof ConeParticleEmitter) { return ( <InspectorSection title="Cone"> <InspectorNumber object={emitter} property="directionRandomizer" label="Direction Randomizer" step={0.01} /> <InspectorNumber object={emitter} property="radiusRange" label="Radius Range" step={0.01} /> <InspectorNumber object={emitter} property="heightRange" label="Height Range" step={0.01} /> <InspectorNumber object={emitter} property="radius" label="Radius" step={0.01} /> <InspectorNumber object={emitter} property="angle" label="Angle" step={0.01} /> <InspectorBoolean object={emitter} property="emitFromSpawnPointOnly" label="Emit From Spawn Point Only" /> </InspectorSection> ); } return undefined; } } Inspector.RegisterObjectInspector({ ctor: ParticleSystemInspector, ctorNames: ["ParticleSystem"], title: "Particle System", });
the_stack
function array_map(obj: any, callback: any, thisArg?: any) { var T, A, k; if (obj === null) { throw new TypeError('this is null or not defined'); } // 1. Let O be the result of calling ToObject passing the |this| // value as the argument. var O = Object(obj); // 2. Let lenValue be the result of calling the Get internal // method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception. // See: http://es5.github.com/#x9.11 if (typeof callback !== 'function') { throw new TypeError(callback + ' is not a function'); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 2) { T = arguments[2]; } // 6. Let A be a new array created as if by the expression new Array(len) // where Array is the standard built-in constructor with that name and // len is the value of len. A = new Array(len); // 7. Let k be 0 k = 0; // 8. Repeat, while k < len while (k < len) { var kValue, mappedValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal // method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal // method of O with argument Pk. kValue = O[k]; // ii. Let mappedValue be the result of calling the Call internal // method of callback with T as the this value and argument // list containing kValue, k, and O. mappedValue = callback.call(T, kValue, k, O); // iii. Call the DefineOwnProperty internal method of A with arguments // Pk, Property Descriptor // { Value: mappedValue, // Writable: true, // Enumerable: true, // Configurable: true }, // and false. // In browsers that support Object.defineProperty, use the following: // Object.defineProperty(A, k, { // value: mappedValue, // writable: true, // enumerable: true, // configurable: true // }); // For best browser support, use the following: A[k] = mappedValue; } // d. Increase k by 1. k++; } // 9. return A return A; } function array_filter(obj: any, fun: any/*, thisArg*/) { 'use strict'; if (obj === void 0 || obj === null) { throw new TypeError(); } var t = Object(obj); var len = t.length >>> 0; if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; } function array_sort(o: any, comparator?: any): any { "use strict"; function min(a: any, b: any) { return a < b ? a : b; } function stringComparator(a: any, b: any) { var aString = a.string; var bString = b.string; var aLength = aString.length; var bLength = bString.length; var length = min(aLength, bLength); for (var i = 0; i < length; ++i) { var aCharCode = aString.charCodeAt(i); var bCharCode = bString.charCodeAt(i); if (aCharCode === bCharCode) { continue; } return aCharCode - bCharCode; } return aLength - bLength; } // Move undefineds and holes to the end of a sparse array. Result is [values..., undefineds..., holes...]. function compactSparse(array: any, dst: any, src: any, length: any) { var seen: any = { }; var valueCount = 0; var undefinedCount = 0; // Clean up after the in-progress non-sparse compaction that failed. for (let i = dst; i < src; ++i) { delete array[i]; } for (var obj = array; obj; obj = Object.getPrototypeOf(obj)) { var propertyNames = Object.getOwnPropertyNames(obj); for (var i = 0; i < propertyNames.length; ++i) { var index = propertyNames[i]; if (index < length) { // Exclude non-numeric properties and properties past length. if (seen[index]) { // Exclude duplicates. continue; } seen[index] = 1; var value = array[index]; delete array[index]; if (value === undefined) { ++undefinedCount; continue; } array[valueCount++] = value; } } } for (var i = valueCount; i < valueCount + undefinedCount; ++i) { array[i] = undefined; } return valueCount; } function compactSlow(array: any, length: any) { var holeCount = 0; for (var dst = 0, src = 0; src < length; ++src) { if (!(src in array)) { ++holeCount; if (holeCount < 256) { continue; } return compactSparse(array, dst, src, length); } var value = array[src]; if (value === undefined) { continue; } array[dst++] = value; } var valueCount = dst; var undefinedCount = length - valueCount - holeCount; for (var i = valueCount; i < valueCount + undefinedCount; ++i) { array[i] = undefined; } for (var i = valueCount + undefinedCount; i < length; ++i) { delete array[i]; } return valueCount; } // Move undefineds and holes to the end of an array. Result is [values..., undefineds..., holes...]. function compact(array: any, length: any) { for (var i = 0; i < array.length; ++i) { if (array[i] === undefined) { return compactSlow(array, length); } } return length; } function merge(dst: any, src: any, srcIndex: any, srcEnd: any, width: any, comparator: any) { var left = srcIndex; var leftEnd = min(left + width, srcEnd); var right = leftEnd; var rightEnd = min(right + width, srcEnd); for (var dstIndex = left; dstIndex < rightEnd; ++dstIndex) { if (right < rightEnd) { if (left >= leftEnd) { dst[dstIndex] = src[right++]; continue; } let comparisonResult = comparator(src[right], src[left]); if ((typeof comparisonResult === "boolean" && !comparisonResult) || comparisonResult < 0) { dst[dstIndex] = src[right++]; continue; } } dst[dstIndex] = src[left++]; } } function mergeSort(array: any, valueCount: any, comparator: any) { var buffer : any = [ ]; buffer.length = valueCount; var dst = buffer; var src = array; for (var width = 1; width < valueCount; width *= 2) { for (var srcIndex = 0; srcIndex < valueCount; srcIndex += 2 * width) { merge(dst, src, srcIndex, valueCount, width, comparator); } var tmp = src; src = dst; dst = tmp; } if (src !== array) { for(var i = 0; i < valueCount; i++) { array[i] = src[i]; } } } function bucketSort(array: any, dst: any, bucket: any, depth: any) { if (bucket.length < 32 || depth > 32) { mergeSort(bucket, bucket.length, stringComparator); for (var i = 0; i < bucket.length; ++i) { array[dst++] = bucket[i].value; } return dst; } var buckets: any = [ ]; for (var i = 0; i < bucket.length; ++i) { var entry = bucket[i]; var string = entry.string; if (string.length === depth) { array[dst++] = entry.value; continue; } var c = string.charCodeAt(depth); if (!buckets[c]) { buckets[c] = [ ]; } buckets[c][buckets[c].length] = entry; } for (var i = 0; i < buckets.length; ++i) { if (!buckets[i]) { continue; } dst = bucketSort(array, dst, buckets[i], depth + 1); } return dst; } function comparatorSort(array: any, length: any, comparator: any) { var valueCount = compact(array, length); mergeSort(array, valueCount, comparator); } function stringSort(array: any, length: any) { var valueCount = compact(array, length); var strings = new Array(valueCount); for (var i = 0; i < valueCount; ++i) { strings[i] = { string: array[i], value: array[i] }; } bucketSort(array, 0, strings, 0); } var array = o; var length = array.length >>> 0; // For compatibility with Firefox and Chrome, do nothing observable // to the target array if it has 0 or 1 sortable properties. if (length < 2) { return array; } if (typeof comparator === "function") { comparatorSort(array, length, comparator); } else if (comparator === null || comparator === undefined) { stringSort(array, length); } else { throw new TypeError("Array.prototype.sort requires the comparsion function be a function or undefined"); } return array; } export function map(o: any, ...args: any[]): any { if (o instanceof Array) { return array_map(o, args[0], args[1]); } else { return o.map.call(o, ...args); } } export function filter(o: any, args: any): any { if (o instanceof Array) { return array_filter(o, args); } else { return o.filter.call(o, args); } } var stopifyArrayPrototype = { __proto__: Array.prototype, map: function(f: any) { return stopifyArray(map(this, f, this)); }, filter: function(f: any) { return stopifyArray(filter(this, f)); }, reduceRight: function(this: any[], f: any, init: any): any { // NOTE(arjun): The MDN polyfill did not pass a simple test. I am quite sure // we never tested it before. This version works just fine. var arrLen = this.length; var acc = arguments.length === 1 ? this[arrLen - 1] : init; var i = arguments.length === 1 ? arrLen - 2 : arrLen - 1; while (i >= 0) { acc = f(acc, this[i], i, this); i = i - 1; } return acc; }, reduce: function(this: any[], f: any, init: any) { // NOTE(arjun): The MDN polyfill did not pass a simple test. I am quite sure // we never tested it before. This version works just fine. var arrLen = this.length; var acc = arguments.length === 1 ? this[arrLen - 1] : init; var bound = arguments.length === 1 ? arrLen - 1 : arrLen; var i = 0; while (i < bound) { acc = f(acc, this[i], i, this); i = i + 1; } return acc; }, // NOTE(arjun): thisArg ignored some: function(this: any[], pred: any) { var i = 0; var l = this.length; while (i < l) { if (pred(this[i])) { return true; } i = i + 1; } return false; }, every: function(this: any[],pred: any) { var i = 0; var l = this.length; while (i < l) { if (!pred(this[i])) { return false; } i = i + 1; } return true; }, find: function(this: any[],pred: any) { var i = 0; var l = this.length; while (i < l) { if (pred(this[i])) { return this[i]; } i = i + 1; } }, findIndex: function(this: any[],pred: any) { var i = 0; var l = this.length; while (i < l) { if (pred(this[i])) { return i; } i = i + 1; } return -1; }, // NOTE(arjun): Ignores thisArg forEach(this: any[],f: any) { var i = 0; var l = this.length; while (i < l) { f(this[i], i, this); i = i + 1; } }, sort: function(comparator: any) { return stopifyArray(array_sort(this, comparator)); } }; export function stopifyArray(arr: any) { // @stopify flat Reflect.setPrototypeOf(arr, stopifyArrayPrototype); return arr; }
the_stack
declare module BABYLON { /** @hidden */ export var asciiartPixelShader: { name: string; shader: string; }; } declare module BABYLON { /** * AsciiArtFontTexture is the helper class used to easily create your ascii art font texture. * * It basically takes care rendering the font front the given font size to a texture. * This is used later on in the postprocess. */ export class AsciiArtFontTexture extends BABYLON.BaseTexture { private _font; private _text; private _charSize; /** * Gets the size of one char in the texture (each char fits in size * size space in the texture). */ readonly charSize: number; /** * Create a new instance of the Ascii Art FontTexture class * @param name the name of the texture * @param font the font to use, use the W3C CSS notation * @param text the caracter set to use in the rendering. * @param scene the scene that owns the texture */ constructor(name: string, font: string, text: string, scene?: BABYLON.Nullable<BABYLON.Scene>); /** * Gets the max char width of a font. * @param font the font to use, use the W3C CSS notation * @return the max char width */ private getFontWidth; /** * Gets the max char height of a font. * @param font the font to use, use the W3C CSS notation * @return the max char height */ private getFontHeight; /** * Clones the current AsciiArtTexture. * @return the clone of the texture. */ clone(): AsciiArtFontTexture; /** * Parses a json object representing the texture and returns an instance of it. * @param source the source JSON representation * @param scene the scene to create the texture for * @return the parsed texture */ static Parse(source: any, scene: BABYLON.Scene): AsciiArtFontTexture; } /** * Option available in the Ascii Art Post Process. */ export interface IAsciiArtPostProcessOptions { /** * The font to use following the w3c font definition. */ font?: string; /** * The character set to use in the postprocess. */ characterSet?: string; /** * This defines the amount you want to mix the "tile" or caracter space colored in the ascii art. * This number is defined between 0 and 1; */ mixToTile?: number; /** * This defines the amount you want to mix the normal rendering pass in the ascii art. * This number is defined between 0 and 1; */ mixToNormal?: number; } /** * AsciiArtPostProcess helps rendering everithing in Ascii Art. * * Simmply add it to your scene and let the nerd that lives in you have fun. * Example usage: var pp = new AsciiArtPostProcess("myAscii", "20px Monospace", camera); */ export class AsciiArtPostProcess extends BABYLON.PostProcess { /** * The font texture used to render the char in the post process. */ private _asciiArtFontTexture; /** * This defines the amount you want to mix the "tile" or caracter space colored in the ascii art. * This number is defined between 0 and 1; */ mixToTile: number; /** * This defines the amount you want to mix the normal rendering pass in the ascii art. * This number is defined between 0 and 1; */ mixToNormal: number; /** * Instantiates a new Ascii Art Post Process. * @param name the name to give to the postprocess * @camera the camera to apply the post process to. * @param options can either be the font name or an option object following the IAsciiArtPostProcessOptions format */ constructor(name: string, camera: BABYLON.Camera, options?: string | IAsciiArtPostProcessOptions); } } declare module BABYLON { /** @hidden */ export var digitalrainPixelShader: { name: string; shader: string; }; } declare module BABYLON { /** * DigitalRainFontTexture is the helper class used to easily create your digital rain font texture. * * It basically takes care rendering the font front the given font size to a texture. * This is used later on in the postprocess. */ export class DigitalRainFontTexture extends BABYLON.BaseTexture { private _font; private _text; private _charSize; /** * Gets the size of one char in the texture (each char fits in size * size space in the texture). */ readonly charSize: number; /** * Create a new instance of the Digital Rain FontTexture class * @param name the name of the texture * @param font the font to use, use the W3C CSS notation * @param text the caracter set to use in the rendering. * @param scene the scene that owns the texture */ constructor(name: string, font: string, text: string, scene?: BABYLON.Nullable<BABYLON.Scene>); /** * Gets the max char width of a font. * @param font the font to use, use the W3C CSS notation * @return the max char width */ private getFontWidth; /** * Gets the max char height of a font. * @param font the font to use, use the W3C CSS notation * @return the max char height */ private getFontHeight; /** * Clones the current DigitalRainFontTexture. * @return the clone of the texture. */ clone(): DigitalRainFontTexture; /** * Parses a json object representing the texture and returns an instance of it. * @param source the source JSON representation * @param scene the scene to create the texture for * @return the parsed texture */ static Parse(source: any, scene: BABYLON.Scene): DigitalRainFontTexture; } /** * Option available in the Digital Rain Post Process. */ export interface IDigitalRainPostProcessOptions { /** * The font to use following the w3c font definition. */ font?: string; /** * This defines the amount you want to mix the "tile" or caracter space colored in the digital rain. * This number is defined between 0 and 1; */ mixToTile?: number; /** * This defines the amount you want to mix the normal rendering pass in the digital rain. * This number is defined between 0 and 1; */ mixToNormal?: number; } /** * DigitalRainPostProcess helps rendering everithing in digital rain. * * Simmply add it to your scene and let the nerd that lives in you have fun. * Example usage: var pp = new DigitalRainPostProcess("digitalRain", "20px Monospace", camera); */ export class DigitalRainPostProcess extends BABYLON.PostProcess { /** * The font texture used to render the char in the post process. */ private _digitalRainFontTexture; /** * This defines the amount you want to mix the "tile" or caracter space colored in the digital rain. * This number is defined between 0 and 1; */ mixToTile: number; /** * This defines the amount you want to mix the normal rendering pass in the digital rain. * This number is defined between 0 and 1; */ mixToNormal: number; /** * Instantiates a new Digital Rain Post Process. * @param name the name to give to the postprocess * @camera the camera to apply the post process to. * @param options can either be the font name or an option object following the IDigitalRainPostProcessOptions format */ constructor(name: string, camera: BABYLON.Camera, options?: string | IDigitalRainPostProcessOptions); } } declare module BABYLON { /** @hidden */ export var oceanPostProcessPixelShader: { name: string; shader: string; }; } declare module BABYLON { /** * Option available in the Ocean Post Process. */ export interface IOceanPostProcessOptions { /** * The size of the reflection RTT (number if square, or {width: number, height:number} or {ratio:} to define a ratio from the main scene) */ reflectionSize?: number | { width: number; height: number; } | { ratio: number; }; /** * The size of the refraction RTT (number if square, or {width: number, height:number} or {ratio:} to define a ratio from the main scene) */ refractionSize?: number | { width: number; height: number; } | { ratio: number; }; } /** * OceanPostProcess helps rendering an infinite ocean surface that can reflect and refract environment. * * Simmply add it to your scene and let the nerd that lives in you have fun. * Example usage: * var pp = new OceanPostProcess("myOcean", camera); * pp.reflectionEnabled = true; * pp.refractionEnabled = true; */ export class OceanPostProcess extends BABYLON.PostProcess { /** * Gets a boolean indicating if the real-time reflection is enabled on the ocean. */ /** * Sets weither or not the real-time reflection is enabled on the ocean. * Is set to true, the reflection mirror texture will be used as reflection texture. */ reflectionEnabled: boolean; /** * Gets a boolean indicating if the real-time refraction is enabled on the ocean. */ /** * Sets weither or not the real-time refraction is enabled on the ocean. * Is set to true, the refraction render target texture will be used as refraction texture. */ refractionEnabled: boolean; /** * Gets wether or not the post-processes is supported by the running hardware. * This requires draw buffer supports. */ readonly isSupported: boolean; /** * This is the reflection mirror texture used to display reflections on the ocean. * By default, render list is empty. */ reflectionTexture: BABYLON.MirrorTexture; /** * This is the refraction render target texture used to display refraction on the ocean. * By default, render list is empty. */ refractionTexture: BABYLON.RenderTargetTexture; private _time; private _cameraRotation; private _cameraViewMatrix; private _reflectionEnabled; private _refractionEnabled; private _geometryRenderer; /** * Instantiates a new Ocean Post Process. * @param name the name to give to the postprocess. * @camera the camera to apply the post process to. * @param options optional object following the IOceanPostProcessOptions format used to customize reflection and refraction render targets sizes. */ constructor(name: string, camera: BABYLON.TargetCamera, options?: IOceanPostProcessOptions); /** * Returns the appropriate defines according to the current configuration. */ private _getDefines; /** * Computes the current camera rotation as the shader requires a camera rotation. */ private _computeCameraRotation; } }
the_stack
module CorsicaTests { "use strict"; var Key = WinJS.Utilities.Key, _LightDismissService = Helper.require("WinJS/_LightDismissService"), _element; var expectedDistanceFromAnchor = 4, anchorStyling = "position:absolute; top:50%; left:50%; height:10px; width:10px; background-color: red;" var Flyout = <typeof WinJS.UI.PrivateFlyout> WinJS.UI.Flyout; interface IMarginBox { top: number; bottom: number; left: number; right: number; }; export class FlyoutTests { setUp() { LiveUnit.LoggingCore.logComment("In setup"); var flyoutElement = document.createElement('div'); document.body.appendChild(flyoutElement); _element = flyoutElement; } tearDown() { LiveUnit.LoggingCore.logComment("In tearDown"); var flyouts = document.querySelectorAll(".win-flyout"); Array.prototype.forEach.call(flyouts, function (element) { OverlayHelpers.disposeAndRemove(element); element = null; }); OverlayHelpers.disposeAndRemove(_element); _element = null; } // Test flyout Instantiation testFlyoutInstantiation = function () { var flyout = new Flyout(_element); LiveUnit.LoggingCore.logComment("flyout has been instantiated."); LiveUnit.Assert.isNotNull(flyout, "flyout element should not be null when instantiated."); function verifyFunction(functionName) { LiveUnit.LoggingCore.logComment("Verifying that function " + functionName + " exists"); if (flyout[functionName] === undefined) { LiveUnit.Assert.fail(functionName + " missing from flyout"); } LiveUnit.Assert.isNotNull(flyout[functionName]); LiveUnit.Assert.isTrue(typeof (flyout[functionName]) === "function", functionName + " exists on flyout, but it isn't a function"); } verifyFunction("show"); verifyFunction("hide"); verifyFunction("addEventListener"); verifyFunction("removeEventListener"); } // Test flyout Instantiation with null element testFlyoutNullInstantiation = function () { LiveUnit.LoggingCore.logComment("Attempt to Instantiate the flyout with null element"); var flyout = new Flyout(null); LiveUnit.Assert.isNotNull(flyout, "flyout instantiation was null when sent a null flyout element."); } // Test multiple instantiation of the same flyout DOM element testFlyoutMultipleInstantiation() { FlyoutTests.prototype.testFlyoutMultipleInstantiation["LiveUnit.ExpectedException"] = { message: "Invalid argument: Controls may only be instantiated one time for each DOM element" }; var flyout = new Flyout(_element); LiveUnit.LoggingCore.logComment("flyout has been instantiated."); LiveUnit.Assert.isNotNull(flyout, "flyout element should not be null when instantiated."); new Flyout(_element); } // Test flyout parameters testFlyoutParams = function () { function testGoodInitOption(paramName, value) { LiveUnit.LoggingCore.logComment("Testing creating a flyout using good parameter " + paramName + "=" + value); var div = document.createElement("div"); document.body.appendChild(div); var options = {}; options[paramName] = value; var flyout = new Flyout(div, options); LiveUnit.Assert.isNotNull(flyout); } function testBadInitOption(paramName, value, expectedName, expectedMessage) { LiveUnit.LoggingCore.logComment("Testing creating a flyout using bad parameter " + paramName + "=" + value); var div = document.createElement("div"); document.body.appendChild(div); var options = {}; options[paramName] = value; var exception = null; try { new Flyout(div, options); LiveUnit.Assert.fail("Expected creating Flyout with " + paramName + "=" + value + " to throw an exception"); } catch (e) { exception = e; LiveUnit.LoggingCore.logComment(exception.message); LiveUnit.Assert.isTrue(exception !== null); LiveUnit.Assert.isTrue(exception.name === expectedName); LiveUnit.Assert.isTrue(exception.message === expectedMessage); } } LiveUnit.LoggingCore.logComment("Testing anchor"); testGoodInitOption("anchor", "ralph"); testGoodInitOption("anchor", "fred"); testGoodInitOption("anchor", -1); testGoodInitOption("anchor", 12); testGoodInitOption("anchor", {}); LiveUnit.LoggingCore.logComment("Testing alignment"); testGoodInitOption("alignment", "left"); testGoodInitOption("alignment", "right"); testGoodInitOption("alignment", "center"); var badAlignment = "Invalid argument: Flyout alignment should be 'center' (default), 'left', or 'right'."; testBadInitOption("alignment", "fred", "WinJS.UI.Flyout.BadAlignment", badAlignment); testBadInitOption("alignment", -1, "WinJS.UI.Flyout.BadAlignment", badAlignment); testBadInitOption("alignment", 12, "WinJS.UI.Flyout.BadAlignment", badAlignment); testBadInitOption("alignment", {}, "WinJS.UI.Flyout.BadAlignment", badAlignment); LiveUnit.LoggingCore.logComment("Testing placement"); testGoodInitOption("placement", "top"); testGoodInitOption("placement", "bottom"); testGoodInitOption("placement", "left"); testGoodInitOption("placement", "right"); testGoodInitOption("placement", "auto"); testGoodInitOption("placement", "autohorizontal"); testGoodInitOption("placement", "autovertical"); var badPlacement = "Invalid argument: Flyout placement should be 'top' (default), 'bottom', 'left', 'right', 'auto', 'autohorizontal', or 'autovertical'."; testBadInitOption("placement", "fred", "WinJS.UI.Flyout.BadPlacement", badPlacement); testBadInitOption("placement", -1, "WinJS.UI.Flyout.BadPlacement", badPlacement); testBadInitOption("placement", 12, "WinJS.UI.Flyout.BadPlacement", badPlacement); testBadInitOption("placement", {}, "WinJS.UI.Flyout.BadPlacement", badPlacement); } // Test defaults testDefaultflyoutParameters = function () { var flyout = new Flyout(_element); LiveUnit.LoggingCore.logComment("flyout has been instantiated."); LiveUnit.Assert.isNotNull(flyout, "flyout element should not be null when instantiated."); LiveUnit.Assert.areEqual(flyout.element, _element, "Verifying that element is what we set it with"); LiveUnit.Assert.areEqual(flyout['autoHide'], undefined, "Verifying that autoHide is undefined"); LiveUnit.Assert.areEqual(flyout['lightDismiss'], undefined, "Verifying that lightDismiss is undefined"); } // Simple Function Tests testSimpleflyoutFunctions = function () { var flyout = new Flyout(_element); LiveUnit.LoggingCore.logComment("flyout has been instantiated."); LiveUnit.Assert.isNotNull(flyout, "flyout element should not be null when instantiated."); LiveUnit.LoggingCore.logComment("show"); flyout.show(document.body, "top"); LiveUnit.LoggingCore.logComment("hide"); flyout.hide(); } testHiddenProperty = function (complete) { var flyout = new WinJS.UI.Flyout(_element); flyout.anchor = document.body; flyout.addEventListener("aftershow", function () { LiveUnit.Assert.isFalse(flyout.hidden); flyout.hidden = true; LiveUnit.Assert.isTrue(flyout.hidden); flyout.addEventListener("afterhide", function () { LiveUnit.Assert.isTrue(flyout.hidden); complete(); }); }); LiveUnit.Assert.isTrue(flyout.hidden); flyout.hidden = false; LiveUnit.Assert.isFalse(flyout.hidden); } testFlyoutDispose = function () { var flyout = new Flyout(); LiveUnit.Assert.isTrue(flyout.dispose); LiveUnit.Assert.isFalse(flyout._disposed); // Double dispose sentinel var sentinel: any = document.createElement("div"); sentinel.disposed = false; WinJS.Utilities.addClass(sentinel, "win-disposable"); flyout.element.appendChild(sentinel); sentinel.dispose = function () { if (sentinel.disposed) { LiveUnit.Assert.fail("Unexpected double dispose occured."); } sentinel.disposed = true; }; flyout.dispose(); LiveUnit.Assert.isTrue(sentinel.disposed); LiveUnit.Assert.isTrue(flyout._disposed); flyout.dispose(); } testFlyoutShowThrows = function (complete) { var flyout: any = new Flyout(_element); LiveUnit.LoggingCore.logComment("flyout has been instantiated."); LiveUnit.Assert.isNotNull(flyout, "flyout element should not be null when instantiated."); LiveUnit.LoggingCore.logComment("Calling show() with no parameters should throw"); try { flyout.show(); } catch (e) { LiveUnit.Assert.areEqual("Invalid argument: Flyout anchor element not found in DOM.", e.message); } LiveUnit.LoggingCore.logComment("Calling show() with null should throw"); try { flyout.show(null); } catch (e) { LiveUnit.Assert.areEqual("Invalid argument: Flyout anchor element not found in DOM.", e.message); } complete(); } testFlyoutInnerHTMLChangeDuringShowAnimation = function (complete) { LiveUnit.LoggingCore.logComment("Attempt to Instantiate the flyout element"); var flyout = new Flyout(_element); LiveUnit.LoggingCore.logComment("flyout has been instantiated."); LiveUnit.Assert.isNotNull(flyout, "flyout element should not be null when instantiated."); LiveUnit.LoggingCore.logComment("Remove HTML Elements from Flyout innerHTML before Flyout show animation completes."); flyout.show(document.body); flyout.element.innerHTML = "Not an HTML Element"; // A text Node !== an HTML Element Helper.waitForEvent(_element, "aftershow").done(complete); } testDisposeRemovesFlyoutClickEatingDiv = function (complete) { var flyout = new Flyout(); document.body.appendChild(flyout.element); flyout.show(document.body); flyout.addEventListener("aftershow", function () { var clickEater = <HTMLElement>document.querySelector("." + _LightDismissService._ClassNames._clickEater); LiveUnit.Assert.isTrue(clickEater); LiveUnit.Assert.areNotEqual("none", clickEater.style.display); flyout.dispose(); LiveUnit.Assert.isNull(document.querySelector("." + _LightDismissService._ClassNames._clickEater)); complete(); }); }; testTopPlacement = function (complete) { var anchor = document.createElement("DIV"); anchor.style.cssText = anchorStyling; document.body.appendChild(anchor); var flyout = new Flyout(_element); flyout.show(anchor, "top"); flyout.addEventListener('aftershow', function () { var anchorRect = anchor.getBoundingClientRect(); var flyoutRect = flyout.element.getBoundingClientRect(); // In High DPI scenarios the actual distance may be within 1px of the expected distance. var actualDistance = anchorRect.top - flyoutRect.bottom; LiveUnit.LoggingCore.logComment("Flyout should be on top of the anchor"); LiveUnit.LoggingCore.logComment("actual: " + actualDistance); LiveUnit.LoggingCore.logComment("expected: " + expectedDistanceFromAnchor); LiveUnit.Assert.isTrue(Math.abs(expectedDistanceFromAnchor - actualDistance) < 1, "Flyout is not in the right location"); document.body.removeChild(anchor); complete(); }, false); }; testBottomPlacement = function (complete) { var anchor = document.createElement("DIV"); anchor.style.cssText = anchorStyling; document.body.appendChild(anchor); var flyout = new Flyout(_element); flyout.show(anchor, "bottom"); flyout.addEventListener('aftershow', function () { var anchorRect = anchor.getBoundingClientRect(); var flyoutRect = flyout.element.getBoundingClientRect(); // In High DPI scenarios the actual distance may be within 1px of the expected distance. var actualDistance = flyoutRect.top - anchorRect.bottom; LiveUnit.LoggingCore.logComment("Flyout should be underneath the anchor"); LiveUnit.LoggingCore.logComment("actual: " + actualDistance); LiveUnit.LoggingCore.logComment("expected: " + expectedDistanceFromAnchor); LiveUnit.Assert.isTrue(Math.abs(expectedDistanceFromAnchor - actualDistance) < 1, "Flyout is not in the right location"); document.body.removeChild(anchor); complete(); }, false); }; testLeftPlacement = function (complete) { var anchor = document.createElement("DIV"); anchor.style.cssText = anchorStyling; document.body.appendChild(anchor); var flyout = new Flyout(_element); flyout.show(anchor, "left"); flyout.addEventListener('aftershow', function () { var anchorRect = anchor.getBoundingClientRect(); var flyoutRect = flyout.element.getBoundingClientRect(); // In High DPI scenarios the actual distance may be within 1px of the expected distance. var actualDistance = anchorRect.left - flyoutRect.right; LiveUnit.LoggingCore.logComment("Flyout should be to the left of the anchor"); LiveUnit.LoggingCore.logComment("actual: " + actualDistance); LiveUnit.LoggingCore.logComment("expected: " + expectedDistanceFromAnchor); LiveUnit.Assert.isTrue(Math.abs(expectedDistanceFromAnchor - actualDistance) < 1, "Flyout is not in the right location"); document.body.removeChild(anchor); complete(); }, false); }; testRightPlacement = function (complete) { var anchor = document.createElement("DIV"); anchor.style.cssText = anchorStyling; document.body.appendChild(anchor); var flyout = new Flyout(_element); flyout.show(anchor, "right"); flyout.addEventListener('aftershow', function () { var anchorRect = anchor.getBoundingClientRect(); var flyoutRect = flyout.element.getBoundingClientRect(); // In High DPI scenarios the actual distance may be within 1px of the expected distance. var actualDistance = flyoutRect.left - anchorRect.right; LiveUnit.LoggingCore.logComment("Flyout should be to the right of the anchor"); LiveUnit.LoggingCore.logComment("actual: " + actualDistance); LiveUnit.LoggingCore.logComment("expected: " + expectedDistanceFromAnchor); LiveUnit.Assert.isTrue(Math.abs(expectedDistanceFromAnchor - actualDistance) < 1, "Flyout is not in the right location"); document.body.removeChild(anchor); complete(); }, false); }; testAutoHorizontalPlacement = function (complete) { var anchor = document.createElement("DIV"); anchor.style.cssText = anchorStyling; document.body.appendChild(anchor); var flyout = new Flyout(_element); // By default, based on the configuration, this flyout would be shown to the top of the anchor, // but we are going to restrict it to only horizontal positions, so it will be shown at the left. flyout.show(anchor, "autohorizontal"); flyout.addEventListener('aftershow', function () { var anchorRect = anchor.getBoundingClientRect(); var flyoutRect = flyout.element.getBoundingClientRect(); // In High DPI scenarios the actual distance may be within 1px of the expected distance. var actualDistance = anchorRect.left - flyoutRect.right; LiveUnit.LoggingCore.logComment("Flyout should be on the left of the anchor") LiveUnit.LoggingCore.logComment("actual: " + actualDistance); LiveUnit.LoggingCore.logComment("expected: " + expectedDistanceFromAnchor); LiveUnit.Assert.isTrue(Math.abs(expectedDistanceFromAnchor - actualDistance) < 1, "Flyout is not in the right location"); document.body.removeChild(anchor); complete(); }, false); }; testAutoVerticalPlacement = function (complete) { var anchor = document.createElement("DIV"); anchor.style.cssText = anchorStyling; document.body.appendChild(anchor); _element.style.height = "90%"; _element.style.width = "100px"; _element.style.backgroundColor = "red"; var flyout = new Flyout(_element); // By default, based on the configuration, this tall flyout would be shown to the left side of the anchor, // but we are going to restrict it to only vertical positions, so it will be shown at the top. flyout.show(anchor, "autovertical"); flyout.addEventListener('aftershow', function () { var anchorRect = anchor.getBoundingClientRect(); var flyoutRect = flyout.element.getBoundingClientRect(); // In High DPI scenarios the actual distance may be within 1px of the expected distance. var actualDistance = anchorRect.top - flyoutRect.bottom; LiveUnit.LoggingCore.logComment("Flyout should be on the top of the anchor"); LiveUnit.LoggingCore.logComment("actual: " + actualDistance); LiveUnit.LoggingCore.logComment("expected: " + expectedDistanceFromAnchor); LiveUnit.Assert.isTrue(Math.abs(expectedDistanceFromAnchor - actualDistance) < 1, "Flyout is not in the right location"); document.body.removeChild(anchor); complete(); }, false); }; testDismissesWhenLosingFocus = function (complete) { var root = _element; root.innerHTML = "<button id='outsideFlyout'>outsideFlyout</button>" + "<div id='anchor'></div>" + "<div id='flyout'>" + "<button id='button0'>Button0</button>" + "<button id='button1'>Button1</button>" + "</div>"; var outsideFlyout = root.querySelector("#outsideFlyout"); var flyout = new Flyout(root.querySelector("#flyout"), { anchor: root.querySelector("#anchor") }); OverlayHelpers.Assert.dismissesWhenLosingFocus({ overlay: flyout, focusTo: outsideFlyout }).then(complete); }; testRemainsVisibleWhenMovingFocusInternally = function (complete) { var root = _element; root.innerHTML = "<div id='anchor'></div>" + "<div id='flyout'>" + "<button id='button0'>Button0</button>" + "<button id='button1'>Button1</button>" + "</div>"; var flyout = new Flyout(root.querySelector("#flyout"), { anchor: root.querySelector("#anchor") }); OverlayHelpers.Assert.remainsVisibleWhenMovingFocusInternally({ overlay: flyout, focusFrom: flyout.element.querySelector("#button0"), focusTo: flyout.element.querySelector("#button1") }).then(complete); }; testBackClickEventTriggersLightDismiss = function (complete) { // Verifies that a shown Flyout will light dismiss due to backclick. // Simulate function simulateBackClick() { var handled = _LightDismissService._onBackClick(); LiveUnit.Assert.isTrue(handled, "Flyout should have handled the 'backclick' event"); LiveUnit.Assert.isTrue(flyout.hidden, "Flyout should be hidden after light dismiss"); cleanup(); }; // Cleanup function cleanup() { flyout.dispose(); complete(); } // Setup var flyout = new Flyout(_element); flyout.addEventListener("aftershow", simulateBackClick, false); flyout.show(document.body); }; testEscapeKeyClosesFlyout = function (complete) { // Verifies that ESC key hides a Flyout function afterHide() { flyout.removeEventListener, ("afterhide", afterHide, false); complete(); } var flyout = new Flyout(_element, { anchor: document.body }); flyout.addEventListener("afterhide", afterHide, false); OverlayHelpers.show(flyout).then(() => { var msg = "ESC key should hide the flyout."; LiveUnit.LoggingCore.logComment("Test: " + msg); Helper.keydown(flyout.element, Key.escape); }); }; testShowMovesFocusSyncAndHideMovesFocusAsync = function (complete) { // Verifies Flyout.show moves focus at the beginning of the animation // and Flyout.hide moves focus at the end of the animation. var button = document.createElement("button"); document.body.appendChild(button); var flyout = new Flyout(_element, { anchor: document.body }); var msg = "", test1Ran = false; button.focus(); LiveUnit.Assert.areEqual(document.activeElement, button, "TEST ERROR: button should have focus"); function beforeShow() { flyout.removeEventListener("beforeshow", beforeShow, false); WinJS.Promise.timeout(0).then(() => { LiveUnit.Assert.areEqual(document.activeElement, _element, msg); test1Ran = true; }); }; flyout.addEventListener("beforeshow", beforeShow, false); function afterHide() { flyout.removeEventListener("afterhide", afterHide, false); LiveUnit.Assert.areEqual(document.activeElement, button, msg); complete(); } flyout.addEventListener("afterhide", afterHide, false); msg = "Flyout.show should take focus synchronously after the 'beforeshow' event"; LiveUnit.LoggingCore.logComment("Test: " + msg); OverlayHelpers.show(flyout).then(() => { LiveUnit.Assert.isTrue(test1Ran, "TEST ERROR: Test 1 did not run."); msg = "Flyout.hide should move focus before the 'afterhide' event"; LiveUnit.LoggingCore.logComment("Test: " + msg); return OverlayHelpers.hide(flyout); }); } testShowAt(complete) { // Verifies that calling Flyout.showAt(point) with an "in bounds point" will align the flyout borderbox with the point specified. // An "in bounds point" is defined as a point where the borderbox of the flyout can be positioned such that no edge of the flyout's // marginbox overruns any edge of the visual viewport. var flyout = new Flyout(_element, { anchor: document.body }); var requiredWindowDimension = 100; // For this test to be valid, the Flyout's MarginBox must fit within the confines of the visual. // viewport after we've aligned the top / left of the Flyout's borderbox to the specified point. // Otherwise its considered an out of bounds point and is handled in a later test case. LiveUnit.Assert.isTrue(window.innerWidth >= requiredWindowDimension, "TEST ERROR: test expects visual viewport width >= " + requiredWindowDimension + "px"); LiveUnit.Assert.isTrue(window.innerHeight >= requiredWindowDimension, "TEST ERROR: test expects visual viewport height >= " + requiredWindowDimension + "px"); // Find a valid "in bounds point" within the window to pass to Flyout.showAt() var style = flyout.element.style; var contentSize = 50; var margins = WinJS.Utilities._getPreciseMargins(flyout.element); style.width = contentSize + "px"; style.minWidth = contentSize + "px"; style.maxWidth = contentSize + "px"; style.height = contentSize + "px"; style.maxHeight = contentSize + "px"; style.minHeight = contentSize + "px"; // Make sure the point we choose for the top/left of the borderbox also leaves the marginbox clear of the viewport top/left edge. var testX = 2 + margins.left; var testY = 2 + margins.top; function testShowAt_WithCoordinates(): WinJS.Promise<any> { var coordinates = { x: testX, y: testY }; return verifyPositionOnScreen(coordinates, "Coordinates"); } function testShowAt_WithMouseEvent(): WinJS.Promise<any> { // API requires clientX and clientY properties. var mouseEventObjectShim = { clientX: testX, clientY: testY }; return verifyPositionOnScreen(mouseEventObjectShim, "MouseEventObj"); } function verifyPositionOnScreen(testParameter, testParameterType): WinJS.Promise<any> { // Verify that the flyout is positioned with the top left corner of its border box located at // the location specified by the testParameter. return new WinJS.Promise(function (completePromise) { flyout.onaftershow = () => { flyout.onaftershow = null; var flyoutRect = flyout.element.getBoundingClientRect(); LiveUnit.Assert.areEqual(testY, flyoutRect.top, testParameterType + ": Flyout borderbox should be top aligned with the y coordinate"); LiveUnit.Assert.areEqual(testX, flyoutRect.left, testParameterType + ": Flyout borderbox should be left aligned with the x coordinate"); flyout.onafterhide = function () { flyout.onafterhide = null; completePromise(); } flyout.hide(); }; flyout.showAt(testParameter); }); } testShowAt_WithCoordinates() .then(testShowAt_WithMouseEvent) .then(complete); } testShowAt_Boundaries(complete) { // Verify that when showAt is called: // if any edge of the flyout's marginbox would clip through the corresponding edge of the visual viewport, // then: the flyout's margin box is repositioned such that the clipping edge is instead pinned to the // corresponding viewport edge. function getLocation(flyout: WinJS.UI.PrivateFlyout): IMarginBox { // Returns locaton of the Flyout's margin box. var margins = WinJS.Utilities._getPreciseMargins(flyout.element); var borderBox = flyout.element.getBoundingClientRect(); return { top: borderBox.top - margins.top, right: borderBox.right + margins.right, bottom: borderBox.bottom + margins.bottom, left: borderBox.left - margins.left, } } function asyncShowAt(flyout: WinJS.UI.PrivateFlyout, options: { x: number; y: number; }) { return new WinJS.Promise((completePromise) => { flyout.addEventListener("aftershow", function afterShow() { flyout.removeEventListener("aftershow", afterShow, false); completePromise(); }, false); if (flyout.hidden) { flyout.showAt(options); } else { flyout.addEventListener("afterhide", function afterHide() { flyout.removeEventListener("afterhide", afterHide, false); flyout.showAt(options); }, false); flyout.hide(); } }); } var flyout = new Flyout(_element, { anchor: document.body }); var marginBox: IMarginBox; // Test Cases: var overrunTopLeft = { x: -2, y: -2 }; var overrunTopRight = { x: window.innerWidth, y: -2 }; var overrunBottomLeft = { x: -2, y: window.innerHeight }; var overrunBottomRight = { x: window.innerWidth, y: window.innerHeight }; var msg = "Top left boundary: "; asyncShowAt(flyout, overrunTopLeft) .then(() => { marginBox = getLocation(flyout); Helper.Assert.areFloatsEqual(0, marginBox.left, msg + "flyout should not overrun left edge", 1); Helper.Assert.areFloatsEqual(0, marginBox.top, msg + "flyout should not overrun top edge", 1); msg = "Top right boundary: "; return asyncShowAt(flyout, overrunTopRight); }) .then(() => { marginBox = getLocation(flyout); Helper.Assert.areFloatsEqual(window.innerWidth, marginBox.right, msg + "flyout should not overrun right edge", 1); Helper.Assert.areFloatsEqual(0, marginBox.top, msg + "flyout should not overrun top edge", 1); msg = "Bottom left boundary: "; return asyncShowAt(flyout, overrunBottomLeft) }) .then(() => { marginBox = getLocation(flyout); Helper.Assert.areFloatsEqual(0, marginBox.left, msg + "flyout should not overrun left edge", 1); Helper.Assert.areFloatsEqual(window.innerHeight, marginBox.bottom, msg + "flyout should not overrun bottom edge", 1); msg = "Bottom right boundary: "; return asyncShowAt(flyout, overrunBottomRight) }) .done(() => { marginBox = getLocation(flyout); Helper.Assert.areFloatsEqual(window.innerWidth, marginBox.right, msg + "flyout should not overrun right edge", 1); Helper.Assert.areFloatsEqual(window.innerHeight, marginBox.bottom, msg + "flyout should not overrun bottom edge", 1); complete(); }); } } } // register the object as a test class by passing in the name LiveUnit.registerTestClass("CorsicaTests.FlyoutTests");
the_stack
import AzureStorage = require("azure-storage"); import Process = require("process"); // Note: The 'import * as Foo from "./Foo' syntax avoids the "compiler re-write problem" that breaks debugger hover inspection import * as Configuration from "./Configuration" import * as StringEncoding from "./StringEncoding"; import * as Streams from "./Streams"; import * as Utils from "./Utils/Utils-Index"; import { RejectedPromise } from "./ICProcess"; // There is no re-write issue here as this is just a type /** Needed as a workaround for when 'strictNullChecks' is true in tsconfig.json. */ // @ts-tactical-any-cast: Suppress error "Type 'null' is not assignable to type 'TableContinuationToken'. ts(2322)" [because we use 'strictNullChecks', but the azure-storage npm package does not] const _nullTableSvcContinuationToken: AzureStorage.TableService.TableContinuationToken = null as any; // @ts-tactical-any-cast: Suppress error "Type 'null' is not assignable to type 'ContinuationToken'. ts(2322)" [because we use 'strictNullChecks', but the azure-storage npm package does not] const _nullCommonContinuationToken: AzureStorage.common.ContinuationToken = null as any; /** Returns the AZURE_STORAGE_CONN_STRING environment variable, or throws if it's missing or empty. */ function getConnString(): string { const connStr: string | undefined = Process.env["AZURE_STORAGE_CONN_STRING"]; if (!connStr || (connStr.trim().length === 0)) { throw new Error("The 'AZURE_STORAGE_CONN_STRING' environment variable is missing or empty"); } return (connStr.trim()); } /** Returns either "[(statusCode)] " or "" from the specified error. */ function getStatusCode(error: Error): string { const statusCode: number = ((error as any).statusCode !== undefined) ? (error as any).statusCode : undefined; return ((statusCode !== undefined) ? `[${statusCode}] ` : ""); } /** * [Internal] Asynchronously deletes all Azure data related to the specified instance.\ * TODO: This is brittle [to CRA internal data structure changes] so we need a better way to do this (eg. UnsafeDeregisterInstance.exe [which, as of 3/22/21, does only partial cleanup of Azure data]). */ export async function deleteRegisteredInstanceAsync(instanceName: string, replicaNumber: number = 0, verboseOutput: boolean = false): Promise<void> { let tableSvc: AzureStorage.TableService; /** [Local function] Logs a debug message. */ function log(msg: string): void { if (verboseOutput) { Utils.log(msg, null, Utils.LoggingLevel.Minimal); } } /** [Local function] Handles the success/failure of a Promise&lt;void>. */ function handlePromiseOutcome(error: Error, errorMsgPrefix: string, resolve: (value: void | PromiseLike<void>) => void, reject: RejectedPromise): void { if (error) { reject(new Error(`${errorMsgPrefix} (reason: ${getStatusCode(error)}${error.message})`)); } else { resolve(); } } /** [Local function] Excutes a task (a step) in the unregistering sequence. */ function executeTask(reject: RejectedPromise, unregisterTask: () => void): void { try { unregisterTask(); } catch (error: unknown) { reject(new Error(`Unable to unregister instance '${instanceName}' (reason: ${Utils.makeError(error).message})`)); } } /** [Local function] Deletes all rows from the specified 'tableName' where the PartitionKey equals the specified 'key'. */ function deleteFromTable(tableName: string, key: string, resolve: (value: void | PromiseLike<void>) => void, reject: RejectedPromise) { executeTask(reject, () => { tableSvc = tableSvc || AzureStorage.createTableService(getConnString()); // Note: This establishes a connection const query: AzureStorage.TableQuery = new AzureStorage.TableQuery().where("PartitionKey eq ?", key).select(["RowKey"]); // const entityGenerator = AzureStorage.TableUtilities.entityGenerator; let deletedRowCount: number = 0; // We cannot delete by PartitionKey alone, so we have to query for all the RowKey's in the partition tableSvc.queryEntities(tableName, query, _nullTableSvcContinuationToken, (error: Error, result: AzureStorage.TableService.QueryEntitiesResult<any>, response?: AzureStorage.ServiceResponse) => { try { if (error) { reject(new Error(`Failed to query table '${tableName}' (reason: ${getStatusCode(error)}${error.message})`)); } else { const numRows: number = result.entries.length; if (numRows === 0) { log(`No rows to delete from '${tableName}'`); resolve(); } else { for (let i = 0; i < numRows; i++) { const rowKey: string = result.entries[i].RowKey._; const entityDescriptor = { PartitionKey: { '_': key }, // PartitionKey is a required property of an entity RowKey: { '_': rowKey } // RowKey is a required property of an entity }; // Effectively: DELETE * FROM (tableName) WHERE PartitionKey = "(key)" AND RowKey = "(rowKey)" tableSvc.deleteEntity(tableName, entityDescriptor, (error: Error, response: AzureStorage.ServiceResponse) => { if (error) { reject(new Error(`Failed to delete row from '${tableName}' (reason: ${getStatusCode(error)}${error.message})`)); return; // Stop on the first failure } else { if (++deletedRowCount === numRows) { log(`${deletedRowCount} row(s) deleted from '${tableName}'`); resolve(); } } }); } } } } catch (error: unknown) { reject(new Error(`Failed to delete from table '${tableName}' (reason: ${Utils.makeError(error).message})`)); } }); }); } // 1) Delete the 'Block Blob' for the instance // Note: The 'executor' callback passed to the Promise() constructor executes immediately, so to defer execution we wrap the Promise in a function function deleteBlob(): Promise<void> { const promise: Promise<void> = new Promise<void>((resolve, reject: RejectedPromise) => { executeTask(reject, () => { // See https://azure.github.io/azure-storage-node/ and https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-nodejs const blobSvc: AzureStorage.BlobService = AzureStorage.createBlobService(getConnString()); // Note: This establishes a connection const containerName: string = "cra"; // Note: 'blobName' is a "pathed" name and is found by right-clicking on a blob and selecting 'Properties...' in Azure Storage Explorer const blobName: string = `AmbrosiaBinaries/${instanceName}-${instanceName}${replicaNumber}`; blobSvc.deleteBlobIfExists(containerName, blobName, (error: Error, result: boolean) => { if (!error) { log(`${result ? "" : "Warning: "}Blob '${blobName}' was ${result ? "deleted" : "not found"}`); } handlePromiseOutcome(error, `Failed to delete registration blob '${blobName}' in container '${containerName}'`, resolve, reject); }); }); }); return (promise); } // 2) Delete the table for the instance // Note: The 'executor' callback passed to the Promise() constructor executes immediately, so to defer execution we wrap the Promise in a function function deleteTable(): Promise<void> { const promise = new Promise<void>((resolve, reject: RejectedPromise) => { executeTask(reject, () => { tableSvc = tableSvc || AzureStorage.createTableService(getConnString()); // Note: This establishes a connection // Note: Unlike string data values (eg. a RowKey string), table names are case-insensitive [see https://docs.microsoft.com/en-us/rest/api/storageservices/understanding-the-table-service-data-model]. tableSvc.deleteTableIfExists(instanceName, (error: Error, result: boolean) => { if (!error) { log(`${result ? "" : "Warning: "}Table '${instanceName}' was ${result ? "deleted" : "not found"}`); } handlePromiseOutcome(error, `Failed to delete instance table '${instanceName}'`, resolve, reject); }); }); }); return (promise); } // 3) Delete inbound rows from the CraConnectionTable (these are connections from remote instances [excluding itself] to the instance). // Note that in order to find connections from remote instances that the instance has never connected to (ie. unidirectional // connections), ALL RowKeys of CraConnectionTable have to be examined exhaustively. // Note: The 'executor' callback passed to the Promise() constructor executes immediately, so to defer execution we wrap the Promise in a function function deleteConnectionTableInboundRows(): Promise<void> { const promise = new Promise<void>(async (resolve, reject: RejectedPromise) => { try { const tableName: string = "craconnectiontable"; const rows: { partitionKey: string, rowKey: string }[] = await getAllRowsAsync(tableName); const rowsToDelete: { partitionKey: string, rowKey: string }[] = []; // Find the rows to delete for (let i = 0; i < rows.length; i++) { const originatingInstanceName: string = rows[i].partitionKey; if (originatingInstanceName === instanceName) { // We're only looking for connections [to us] from other instances continue; } const toInstanceName: string = rows[i].rowKey.split(":")[1]; // This identifies the instance to connect to if (toInstanceName === instanceName) { // We found a connection from a remote instance to our instance, so flag it for deletion rowsToDelete.push(rows[i]); } } if (rowsToDelete.length === 0) { resolve(); return; } // Asynchronously delete the found rows for (let i = 0; i < rowsToDelete.length; i++) { const originatingInstanceName: string = rowsToDelete[i].partitionKey; const toInstanceName: string = rowsToDelete[i].rowKey.split(":")[1]; // This identifies the instance to connect to const entityDescriptor = { PartitionKey: { '_': rowsToDelete[i].partitionKey }, RowKey: { '_': rowsToDelete[i].rowKey } }; tableSvc.deleteEntity(tableName, entityDescriptor, (error: Error, response: AzureStorage.ServiceResponse) => { log(error ? `Error: Failed to delete CRA connection from IC '${originatingInstanceName}' to '${toInstanceName}' (${rowsToDelete[i].rowKey}) (reason: ${getStatusCode(error)}${error.message})` : `Deleted CRA connection from IC '${originatingInstanceName}' to '${toInstanceName}' (${rowsToDelete[i].rowKey})`); if (i === rowsToDelete.length - 1) { // We're reached the last row to delete, so deleteConnectionTableInboundRows() is done resolve(); } }); } } catch (error: unknown) { reject(new Error(`Error: deleteConnectionTableInboundRows() failed (reason: ${Utils.makeError(error).message})`)); } }); return (promise); } // 4) Delete outbound rows from the CraConnectionTable (these are connections from the instance to other instances [including itself]) // Note: The 'executor' callback passed to the Promise() constructor executes immediately, so to defer execution we wrap the Promise in a function function deleteConnectionTableOutboundRows(): Promise<void> { const promise = new Promise<void>((resolve, reject: RejectedPromise) => { deleteFromTable("craconnectiontable", instanceName, resolve, reject); }); return (promise); } // 5) Delete rows from the CraEndpointTable // Note: The 'executor' callback passed to the Promise() constructor executes immediately, so to defer execution we wrap the Promise in a function function deleteEndpointTableRows(): Promise<void> { const promise = new Promise<void>((resolve, reject: RejectedPromise) => { deleteFromTable("craendpointtable", instanceName, resolve, reject); }); return (promise); } // 6) Delete rows from the CraVertexTable // Note: The 'executor' callback passed to the Promise() constructor executes immediately, so to defer execution we wrap the Promise in a function function deleteVertexTableRows(): Promise<void> { const promise = new Promise<void>((resolve, reject: RejectedPromise) => { deleteFromTable("cravertextable", `${instanceName}${replicaNumber}`, resolve, reject); }); return (promise); } // 7) TODO: Delete rows from the CraShardedVertexTable // Note: The 'executor' callback passed to the Promise() constructor executes immediately, so to defer execution we wrap the Promise in a function // await deleteBlob(); // await deleteTable(); // await deleteConnectionTableInboundRows(); // await deleteConnectionTableOutboundRows(); // await deleteEndpointTableRows(); // await deleteVertexTableRows(); // In parallel (for performance): const replicaCount: number = (await getReplicaNumbersAsync(instanceName)).length; await Promise.all<any>([deleteBlob(), ...((replicaCount === 1) ? [deleteTable(), deleteConnectionTableInboundRows(), deleteConnectionTableOutboundRows(), deleteEndpointTableRows()] : []), deleteVertexTableRows()]); } /** Asynchronously returns all PartitionKey and RowKey values from the specified table. Can handle tables of any size. */ // Helpful links: // https://stackoverflow.com/questions/47786874/azure-table-storage-continuation-tokens-in-node-js // https://azure.github.io/azure-storage-node/TableService.html // https://stackoverflow.com/questions/53385166/retrieving-more-than-1000-records-from-azure-storage-table-js // https://docs.microsoft.com/en-us/rest/api/storageservices/query-timeout-and-pagination export async function getAllRowsAsync(tableName: string): Promise<{ partitionKey: string, rowKey: string }[]> { const tableSvc: AzureStorage.TableService = AzureStorage.createTableService(getConnString()); const query: AzureStorage.TableQuery = new AzureStorage.TableQuery().select(["PartitionKey", "RowKey"]); // @ts-tactical-any-cast: Suppress error "Type 'null' is not assignable to type 'TableContinuationToken'. ts(2322)" [because we use 'strictNullChecks', but the azure-storage npm package does not] let continuationToken: AzureStorage.TableService.TableContinuationToken = null as any; const rows: { partitionKey: string, rowKey: string }[] = []; /** [Local function] Returns the next segment (chunk) of rows from the table. */ async function getRowsSegmented(tableName: string, tableQuery: AzureStorage.TableQuery, continuationToken: AzureStorage.TableService.TableContinuationToken): Promise<AzureStorage.TableService.QueryEntitiesResult<any>> { let promise: Promise<AzureStorage.TableService.QueryEntitiesResult<any>> = new Promise<AzureStorage.TableService.QueryEntitiesResult<any>>((resolve, reject: RejectedPromise) => { tableSvc.queryEntities(tableName, query, continuationToken, (error: Error, result: AzureStorage.TableService.QueryEntitiesResult<any>, response?: AzureStorage.ServiceResponse) => { try { if (error) { reject(new Error(`Failed to query table '${tableName}' (reason: ${getStatusCode(error)}${error.message})`)); } else { resolve(result); } } catch (error: unknown) { reject(new Error(`Error: getAllRows() failed (reason: ${Utils.makeError(error).message})`)); } }); }); return (promise); } do { const result: AzureStorage.TableService.QueryEntitiesResult<any> = await getRowsSegmented(tableName, query, continuationToken); // @ts-tactical-any-cast: Suppress error "Type 'null' is not assignable to type 'TableContinuationToken'. ts(2322)" [because we use 'strictNullChecks', but the azure-storage npm package does not] continuationToken = !result.continuationToken ? null as any : continuationToken; if (result.entries) { for (let i = 0; i < result.entries.length; i++) { let partitionKey: string = result.entries[i].PartitionKey._; // Eg: "PTIClient" let rowKey: string = result.entries[i].RowKey._; // Eg: "Ambrosiacontrolout:PTIServer:Ambrosiacontrolin" rows.push({ partitionKey, rowKey }); } } } while (continuationToken !== null); return (rows); } /** * Asynchronously returns the list of replica numbers for the specified instance. * Note that replica 0 (ie. an instance registered with RegisterInstance, not AddReplica) counts as a replica. */ export async function getReplicaNumbersAsync(instanceName: string): Promise<number[]> { let promise: Promise<number[]> = new Promise<number[]>((resolve, reject: RejectedPromise) => { let tableSvc: AzureStorage.TableService = AzureStorage.createTableService(getConnString()); let query: AzureStorage.TableQuery = new AzureStorage.TableQuery().where("(PartitionKey ge ?) and (PartitionKey le ?) and (RowKey eq ?)", instanceName + "0", instanceName + "999", instanceName).select(["PartitionKey"]); let tableName: string = "cravertextable"; tableSvc.queryEntities(tableName, query, _nullTableSvcContinuationToken, async (error: Error, result: AzureStorage.TableService.QueryEntitiesResult<any>, response?: AzureStorage.ServiceResponse) => { try { if (error) { reject(new Error(`Failed to query table '${tableName}' (reason: ${getStatusCode(error)}${error.message})`)); } else { const countReplicas: number = result.entries.length; const replicaNumbers: number[] = []; for (let i = 0; i < countReplicas; i++) { const instanceNameWithReplica: string = result.entries[i].PartitionKey._; const replicaNumber: number = parseInt(instanceNameWithReplica.replace(instanceName, "")); replicaNumbers.push(replicaNumber); } resolve(replicaNumbers); } } catch (error: unknown) { reject(new Error(`Error: getReplicaNumbersAsync() failed (reason: ${Utils.makeError(error).message})`)); } }); }); return (promise); } /** Asynchronously determines if the instance has been registered. Will return false if UnsafeDeregisterInstance.exe has been called. */ export async function isRegisteredAsync(instanceName: string, replicaNumber: number): Promise<boolean> { let endpointExists: boolean = false; let registrationBlobExists: boolean = false; try { // Step 1: // Check for any rows for the instance in CraEndpointTable. Immediately after running "Ambrosia.exe RegisterInstance" (but // before starting the IC) there will be 4 rows. Critically, these rows are removed by BOTH UnsafeDeregisterInstance.exe and // Configuration.eraseInstanceAsync(), so their absence is a "universal tell" that the instance is not registered. const endpointCount: number = await getRowCountAsync("craendpointtable", instanceName); endpointExists = (endpointCount >= 4); // Step 2: // Check that the registration blob exists for the specified replicaNumber if (endpointExists) { await getRegistrationSettingsAsync(instanceName, replicaNumber); registrationBlobExists = true; } return (endpointExists && registrationBlobExists); } catch (error: unknown) { if (Utils.makeError(error).message.indexOf("[404] NotFound") !== -1) { return (false); } else { throw error; } } } /** * Asynchronously reads the IC registration settings (eg. icReceivePort, icSendPort, icLogFolder) by directly querying CRA's blob storage in Azure.\ * TODO: This is brittle [to CRA internal data structure changes] so we need a better way to do this. */ export async function getRegistrationSettingsAsync(instanceName: string, replicaNumber: number): Promise<Configuration.RegistrationSettings> { let promise: Promise<Configuration.RegistrationSettings> = new Promise<Configuration.RegistrationSettings>((resolve, reject: RejectedPromise) => { // See https://azure.github.io/azure-storage-node/ and https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-nodejs let blobSvc: AzureStorage.BlobService = AzureStorage.createBlobService(getConnString()); let containerName: string = "cra"; // Note: 'blobName' is a "pathed" name and is found by right-clicking on a blob and selecting 'Properties...' in Azure Storage Explorer let blobName: string = `AmbrosiaBinaries/${instanceName}-${instanceName}${replicaNumber}`; let memStream: Streams.MemoryStream = new Streams.MemoryStream(); // Note: We can't use blobSvc.getBlobToText() due to https://stackoverflow.com/questions/30609691/hash-mismatch-integrity-check-failed-with-azure-blob-storage blobSvc.getBlobToStream(containerName, blobName, memStream, (error: Error, result: AzureStorage.BlobService.BlobResult, response: AzureStorage.ServiceResponse) => { try { if (error) { let errorMsg: string = `Failed to query registration blob '${blobName}' in container '${containerName}' (reason: ${getStatusCode(error)}${error.message})`; if ((error as any).statusCode === 404) { errorMsg += `; check that the instanceName ('${instanceName}') and/or replicaNumber (${replicaNumber}) are correct (do you need to auto-register the instance?)`; } reject(new Error(errorMsg)); } else { let buf: Buffer = memStream.readAll(); let contents: string = StringEncoding.fromUTF8Bytes(buf); let startIndex: number = contents.indexOf("<AmbrosiaRuntimeParams"); let endIndex: number = contents.indexOf("</AmbrosiaRuntimeParams>") + 24; let xml: string = contents.substring(startIndex, endIndex).replace(/\\\\r\\\\n/g, "").replace(/\\\\\\/g, ""); let registrationSettings: Configuration.RegistrationSettings = new Configuration.RegistrationSettings(); // Redact the <storageConnectionString> [for security] to prevent accidental logging startIndex = xml.indexOf("<storageConnectionString>"); endIndex = xml.indexOf("</storageConnectionString>") + 26; xml = xml.substring(0, startIndex) + xml.substr(endIndex); // let formattedXml: string = Utils.formatXml(Utils.decodeXml(xml)); // Utils.log(formattedXml); registrationSettings.icReceivePort = parseInt(readElementText(xml, "serviceReceiveFromPort")); registrationSettings.icSendPort = parseInt(readElementText(xml, "serviceSendToPort")); registrationSettings.icLogFolder = Utils.ensurePathEndsWithSeparator(readElementText(xml, "serviceLogPath")); registrationSettings.appVersion = parseInt(readElementText(xml, "currentVersion")); // Note: This is not updated by the IC after an upgrade - we have to update it by re-registering registrationSettings.upgradeVersion = parseInt(readElementText(xml, "upgradeToVersion")); registrationSettings.activeActive = Utils.equalIgnoringCase(readElementText(xml, "activeActive"), "true"); Utils.log("Registration settings read (from Azure)"); resolve(registrationSettings); /** * [Local function] Returns the text of the specified XML element (eg. returns "Foo" from &lt;someElement>Foo&lt;/someElement>). * Throws if an element with 'elementName' does not exist in the specified XML. */ function readElementText(xml: string, elementName: string): string { const isEmptyElement: boolean = (xml.indexOf(`<${elementName} />`) !== -1); if (isEmptyElement) { return (""); } const startIndex: number = xml.indexOf(`<${elementName}>`) + elementName.length + 2; const endIndex: number = xml.indexOf(`</${elementName}>`); if ((startIndex >= 0) && (endIndex > startIndex)) { const elementText: string = xml.substring(startIndex, endIndex); return (elementText); } throw new Error(`Unable to read element '${elementName}' from registration XML`) } } } catch (innerError: unknown) { reject(new Error(`Unable to parse registration blob '${blobName}' in container '${containerName}' (reason: ${Utils.makeError(innerError).message})`)); } }); }); return (promise); } /** [Internal] Returns the value of 'columnName' for the row specified by 'partitionKey' and 'rowKey in table 'tableName'. */ export async function readAzureTableColumn(tableName: string, columnName: string, partitionKey: string, rowKey: string): Promise<unknown> { const promise: Promise<unknown> = new Promise<unknown>((resolve, reject: RejectedPromise) => { const tableSvc: AzureStorage.TableService = AzureStorage.createTableService(getConnString()); const query: AzureStorage.TableQuery = new AzureStorage.TableQuery().where("(PartitionKey eq ?) and (RowKey eq ?)", partitionKey, rowKey).select([columnName]); tableSvc.queryEntities(tableName, query, _nullTableSvcContinuationToken, (error: Error, result: AzureStorage.TableService.QueryEntitiesResult<Utils.SimpleObject>, response?: AzureStorage.ServiceResponse) => { if (error) { reject(new Error(`Failed to query table '${tableName}' (reason: ${getStatusCode(error)}${error.message})`)); } else { if (result.entries && (result.entries.length === 1)) { // An incorrect column name will always be included in the results, but the value (._) of the column will be null. // Note: The TableService does not persist null values (see https://docs.microsoft.com/en-us/rest/api/storageservices/understanding-the-table-service-data-model#property-types) // so there is no possibility of confusion between a bad column name and a correct column that has a null value. if (result.entries[0][columnName]._ !== null) { const columnValue: unknown = result.entries[0][columnName]._; resolve(columnValue); } else { reject(new Error(`Failed to query table '${tableName}' (reason: unknown column name '${columnName}')`)); } } else { reject(new Error(`Failed to query table '${tableName}' (reason: no row found for PartitionKey '${partitionKey}' and RowKey '${rowKey}')`)); } } }); }); return (promise); } /** * [Internal] Returns true if this is the first start of the specified 'instanceName' after being initially registered, * where "initially registered" means one of: * 1) The first ever registration. * 2) The first registration after running UnsafeDeregisterInstance. * 3) The first registration after calling Configuration.eraseInstanceAsync(). */ export async function isFirstStartAfterInitialRegistration(instanceName: string, replicaNumber: number = 0): Promise<boolean> { let promise: Promise<boolean> = new Promise<boolean>((resolve, reject: RejectedPromise) => { let tableSvc: AzureStorage.TableService = AzureStorage.createTableService(getConnString()); let query: AzureStorage.TableQuery = new AzureStorage.TableQuery().where("(PartitionKey eq ?) and (RowKey eq ?) and (IsActive eq false)", `${instanceName}${replicaNumber}`, instanceName); let tableName: string = "cravertextable"; tableSvc.queryEntities(tableName, query, _nullTableSvcContinuationToken, async (error: Error, result: AzureStorage.TableService.QueryEntitiesResult<any>, response?: AzureStorage.ServiceResponse) => { try { if (error) { reject(new Error(`Failed to query table '${tableName}' (reason: ${getStatusCode(error)}${error.message})`)); } else { let countDisabledVerticies: number = result.entries.length; let countConnections: number = 0; // The query will return 1 (or more?) rows even in the case of a simple re-registration (which is not an initial registration), // so we also have to check the CraConnectionTable for rows if (countDisabledVerticies > 0) { countConnections = await getRowCountAsync("craconnectiontable", instanceName); } resolve((countDisabledVerticies > 0) && (countConnections === 0)); } } catch (error: unknown) { reject(new Error(`Error: isFirstStartAfterInitialRegistration() failed (reason: ${Utils.makeError(error).message})`)); } }); }); return (promise); } /** Asynchronously returns the number of rows in the specified table where the PartitionKey matches the supplied 'partitionKey'. */ async function getRowCountAsync(tableName: string, partitionKey: string): Promise<number> { let promise: Promise<number> = new Promise<number>((resolve, reject: RejectedPromise) => { let tableSvc: AzureStorage.TableService = AzureStorage.createTableService(getConnString()); let query: AzureStorage.TableQuery = new AzureStorage.TableQuery().where("PartitionKey eq ?", partitionKey); tableSvc.queryEntities(tableName, query, _nullTableSvcContinuationToken, (error: Error, result: AzureStorage.TableService.QueryEntitiesResult<any>, response?: AzureStorage.ServiceResponse) => { try { if (error) { reject(new Error(`Failed to query table '${tableName}' (reason: ${getStatusCode(error)}${error.message})`)); } else { resolve(result.entries.length); } } catch (error: unknown) { reject(new Error(`Error: getRowCount() failed (reason: ${Utils.makeError(error).message})`)); } }); }); return (promise); } /** * Asynchronously returns a list of remote instance names that the supplied 'localInstanceName' connects to, by directly querying the CRAConnectionTable in Azure.\ * Optionally (based on deleteRemoteCRAConnections), deletes entries in CRAConnectionTable for connections (in both directions) between the local instance and * remote instances (but only if the local instance has a connection to the remote instance).\ * TODO: Ideally We would get/do this using either ImmortalCoordinator.exe or Ambrosia.exe, but no such mechanism currently exists. */ export async function getRemoteInstancesAsync(localInstanceName: string, deleteRemoteCRAConnections: boolean): Promise<string[]> { let promise: Promise<string[]> = new Promise<string[]>((resolve, reject: RejectedPromise) => { let tableSvc: AzureStorage.TableService = AzureStorage.createTableService(getConnString()); let query: AzureStorage.TableQuery = new AzureStorage.TableQuery().where("PartitionKey eq ?", localInstanceName).select(["RowKey"]); let tableName: string = "craconnectiontable"; let remoteInstanceNames: string[] = []; let deletedRemoteInstanceNames: string[] = []; // Effectively: SELECT RowKey FROM craconnectiontable WHERE PartitionKey = "(localInstanceName)" tableSvc.queryEntities(tableName, query, _nullTableSvcContinuationToken, (error: Error, result: AzureStorage.TableService.QueryEntitiesResult<any>, response?: AzureStorage.ServiceResponse) => { try { if (error) { reject(new Error(`Failed to query table '${tableName}' (reason: ${getStatusCode(error)}${error.message})`)); } else { for (let i = 0; i < result.entries.length; i++) { let rowKey: string = result.entries[i].RowKey._; // Eg: "Ambrosiacontrolout:server:Ambrosiacontrolin" let remoteInstanceName: string = rowKey.split(":")[1]; // This identifies the instance to connect to if (remoteInstanceName === localInstanceName) { // Don't include/delete the rows for self-connections continue; } // TODO: This is just temporary until we have a 'DeleteConnection' message implemented in the IC. // If we don't delete connection entries which refer to instances that are [currently] down // the CRA will hang (indefinitely) trying to re-establish those connections. Depending on the // ordering of the rows, this can prevent the local instance from being able to connect to itself. if (deleteRemoteCRAConnections) { let entityDescriptor = { PartitionKey: { '_': localInstanceName }, RowKey: { '_': rowKey } }; // Effectively: DELETE * FROM craconnectiontable WHERE PartitionKey = "(localInstanceName)" AND RowKey CONTAINS "(remoteInstanceName)" tableSvc.deleteEntity(tableName, entityDescriptor, (error: Error, response: AzureStorage.ServiceResponse) => { Utils.log(error ? `Error: Failed to delete CRA connection '${localInstanceName}': '${rowKey}' (reason: ${getStatusCode(error)}${error.message})` : `Deleted CRA connection for IC '${localInstanceName}' to '${remoteInstanceName}' (${rowKey})`); }); // Keep track of which instances we've deleted connections to if (deletedRemoteInstanceNames.indexOf(remoteInstanceName) === -1) { deletedRemoteInstanceNames.push(remoteInstanceName); } } else { if (remoteInstanceNames.indexOf(remoteInstanceName) === -1) { remoteInstanceNames.push(remoteInstanceName); } } } // TODO: Again, this is just temporary until we have a 'DeleteConnection' message implemented in the IC. if (deletedRemoteInstanceNames.length > 0) { removeConnectionsFromRemoteInstances(deletedRemoteInstanceNames, localInstanceName); } resolve(remoteInstanceNames); } } catch (innerError: unknown) { reject(new Error(`Error: getRemoteInstancesAsync() failed (reason: ${Utils.makeError(innerError).message})`)); } }); }); return (promise); } /** Asynchronously deletes connections from the specified remote instance(s) to the local instance. */ function removeConnectionsFromRemoteInstances(remoteInstanceNames: string[], localInstanceName: string): void { try { for (let remoteInstanceName of remoteInstanceNames) { let tableSvc: AzureStorage.TableService = AzureStorage.createTableService(getConnString()); let query: AzureStorage.TableQuery = new AzureStorage.TableQuery().where("PartitionKey eq ?", remoteInstanceName).select(["RowKey"]); let tableName: string = "craconnectiontable"; // Effectively: SELECT RowKey FROM craconnectiontable WHERE PartitionKey = "(remoteInstanceName)" tableSvc.queryEntities(tableName, query, _nullTableSvcContinuationToken, (error: Error, result: AzureStorage.TableService.QueryEntitiesResult<any>, response?: AzureStorage.ServiceResponse) => { if (error) { Utils.log(`Error: Failed to query table '${tableName}' (reason: ${getStatusCode(error)}${error.message})`); } else { for (let i = 0; i < result.entries.length; i++) { let rowKey: string = result.entries[i].RowKey._; // Eg: "Ambrosiacontrolout:server:Ambrosiacontrolin" let instanceName: string = rowKey.split(":")[1] // This identifies the instance to connect to if (instanceName === localInstanceName) { let entityDescriptor = { PartitionKey: { '_': remoteInstanceName }, RowKey: { '_': rowKey } }; // Effectively: DELETE * FROM craconnectiontable WHERE PartitionKey = "(remoteInstanceName)" AND RowKey CONTAINS "(localInstanceName)" tableSvc.deleteEntity(tableName, entityDescriptor, (error: Error, response: AzureStorage.ServiceResponse) => { Utils.log(error ? `Error: Failed to delete CRA connection '${remoteInstanceName}': '${rowKey}' (reason: ${getStatusCode(error)}${error.message})` : `Deleted CRA connection for IC '${remoteInstanceName}' to '${localInstanceName}' (${rowKey})`); }); } } } }); } } catch (innerError: unknown) { Utils.log(`Error: removeConnectionsFromRemoteInstances() failed (reason: ${Utils.makeError(innerError).message})`); } } /** The name of the Azure blob container for Ambrosia logs. */ const _logsContainerName: string = "ambrosialogs"; /** * Returns a modified version of the supplied 'folderPath' that's Azure-compatible.\ * For example, "sub1\sub2" will become "sub1/sub2".\ * A leading separator is always removed. A trailing separator is either added or removed based on 'addTrailingSeparator' (which defaults to false). */ export function convertToAzurePath(folderPath: string, addTrailingSeparator: boolean = false): string { const pathStartsWithDriveLetter: boolean = /^[A-Za-z]:[\/\\]?/.test(folderPath); if (pathStartsWithDriveLetter) { throw new Error(`Unable to convert path (reason: The specified 'folderPath' ("${folderPath}") refers to a file system path)`); } let modifiedPath: string = folderPath.replace(/\/+|[\\]+/g, "/"); if (modifiedPath.startsWith("/")) { modifiedPath = modifiedPath.substr(1); } if (addTrailingSeparator) { if ((modifiedPath.length > 0) && !modifiedPath.endsWith("/")) { modifiedPath += "/"; } } else { if ((modifiedPath.length > 0) && modifiedPath.endsWith("/")) { modifiedPath = modifiedPath.slice(0, -1); } } return (modifiedPath); } /** [Internal] Deletes Ambrosia log/checkpoint files from the specified Azure blob folder, and removes the folder. Returns the number of files deleted. */ export async function deleteBlobLogsAsync(folderName: string): Promise<number> { folderName = convertToAzurePath(folderName); const debug: boolean = false; const blobSvc: AzureStorage.BlobService = AzureStorage.createBlobService(getConnString()); // Note: This establishes a connection // An array of functions that return a Promise (we do it this way because the 'executor' callback passed to // the Promise() constructor executes immediately, so to defer execution we wrap the Promise in a function) const taskList: (() => Promise<boolean | void>)[] = []; let deletedFileCount: number = 0; try { await queueBlobDeletionTasksAsync(_logsContainerName, folderName); // Execute promises serially [because we want the tasks to execute in the order we queued them] if (debug) { Utils.log("DEBUG: Starting blob deletions..."); } for (let i = 0; i < taskList.length; i++) { const taskResult: boolean | void = await taskList[i](); if ((typeof taskResult === "boolean") && taskResult) // Only deleteBlobAsync() tasks return a boolean { deletedFileCount++; } } if (debug) { Utils.log("DEBUG: Blob deletions complete"); } return (deletedFileCount > 0 ? deletedFileCount - 1: 0); // The "folder shadow blob" (used by the IC for lease coordination) gets counted as a deleted file, so we adjust accordingly } catch (error: unknown) { throw new Error(`deleteBlobLogsAsync() failed (reason: ${Utils.makeError(error).message})`); } /** [Local function] Reads the available log blobs in the specified folderName and populates 'taskList' with delete tasks for each of them (including the folder itself). */ function queueBlobDeletionTasksAsync(containerName: string, folderName: string): Promise<void> { const promise: Promise<void> = new Promise<void>((resolve, reject: RejectedPromise) => { blobSvc.listBlobsSegmentedWithPrefix(containerName, folderName, _nullCommonContinuationToken, (error: Error, result: AzureStorage.BlobService.ListBlobsResult) => { if (error) { reject(new Error(`Failed to enumerate files (blobs) in folder '${folderName}' of container '${containerName}' (reason: ${getStatusCode(error)}${error.message})`)); } else { try { result.entries.forEach((blob) => { let blobName: string = blob.name; // Note: The folderName itself will be included in the result entries, but we must delete that last if (/\/serverlog[\d]+$/.test(blobName) || /\/serverchkpt[\d]+$/.test(blobName) || blobName.endsWith("serverkillFile")) { // Note: An "infinite" lease (which is the duration of the lease on the active log file) breaks immediately // (see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container) if (blob.lease && (blob.lease.state === "leased") && (blob.lease.duration === "infinite")) { // We have to break the lease to allow the file to be deleted taskList.push(() => breakBlobLeaseAsync(containerName, blobName)); } taskList.push(() => deleteBlobAsync(blobSvc, containerName, blobName)); } }); // Finally, delete the "folder shadow blob" (used by the IC for lease coordination) // Note: Azure deletes empty blob folders automatically (see https://docs.microsoft.com/en-us/answers/questions/466968/remove-azure-blob-storage-folders-with-sdk.html), // but the IC also creates [at the folder level] a blob file with the same name as the folder, which is what we delete here taskList.push(() => deleteBlobAsync(blobSvc, containerName, folderName)); resolve(); } catch (error: unknown) { const err: Error = Utils.makeError(error); reject(new Error(`queueBlobDeletionTasksAsync() failed (reason: ${getStatusCode(err)}${err.message})`)); } } }); }); return (promise); } /** [Local function] Breaks the lease on the specified blobName in the specified containerName. */ function breakBlobLeaseAsync(containerName: string, blobName: string): Promise<void> { const promise: Promise<void> = new Promise<void>((resolve, reject: RejectedPromise) => { blobSvc.breakLease(containerName, blobName, (error: Error, result: AzureStorage.BlobService.LeaseResult) => { if (error) { reject(new Error(`Failed to break lease on blob '${blobName}' in container '${containerName}' (reason: ${getStatusCode(error)}${error.message})`)); } else { if (debug) { Utils.log(`DEBUG: Lease broken for blob '${blobName}'`); } resolve(); } }); }); return (promise); } } /** Deletes the specified blobName (which may include a path) in the specified containerName. */ function deleteBlobAsync(blobSvc: AzureStorage.BlobService, containerName: string, blobName: string): Promise<boolean> { const promise: Promise<boolean> = new Promise<boolean>((resolve, reject: RejectedPromise) => { blobSvc.deleteBlobIfExists(containerName, blobName, (error: Error, result: boolean) => { if (error) { reject(new Error(`Failed to delete blob '${blobName}' in container '${containerName}' (reason: ${getStatusCode(error)}${error.message})`)); } else { // Even though 'result' will be false if blobName doesn't exist, we always return true. // We do this because of timing issues in Azure: sometimes, when the last file is deleted, Azure will automatically delete the // folder so 'result' ends up being false for the final folder delete task, which then throws off our count of deleted "files". resolve(true); } }); }); return (promise); } /** Returns true if there's a log file in the specified Azure blob folder, returns false otherwise (and removes the "folder shadow blob" (used by the IC for lease coordination) if the log folder is empty). */ export async function folderContainsBlobLogAsync(folderName: string): Promise<boolean> { folderName = convertToAzurePath(folderName); const blobSvc: AzureStorage.BlobService = AzureStorage.createBlobService(getConnString()); // Note: This establishes a connection const fileNames: string[] = await getFolderFileNamesAsync(_logsContainerName, folderName); let folderLockFileExists: boolean = false; // Whether the "folder shadow blob" exists let hasLog: boolean = false; for (let i = 0; i < fileNames.length; i++) { if (fileNames[i] === folderName) { folderLockFileExists = true; } if (/\/serverlog[\d]+$/.test(fileNames[i])) { hasLog = true; } } if (folderLockFileExists) { if (fileNames.length === 1) { // The folder is empty (the only "file" is the "folder shadow blob" (used by the IC for lease coordination)), so we [must] remove it // Note: Azure deletes empty blob folders automatically (see https://docs.microsoft.com/en-us/answers/questions/466968/remove-azure-blob-storage-folders-with-sdk.html), // but the IC also creates [at the folder level] a blob file with the same name as the folder, which is what we delete here await deleteBlobAsync(blobSvc, _logsContainerName, folderName); return (false); } else { return (hasLog); } } else { return (false); } /** * [Local function] Returns the names of all the files in the the specified folderName in the specified containerName. * The list will also include the "folder shadow blob" (used by the IC for lease coordination) that has the same name as the folder. */ function getFolderFileNamesAsync(containerName: string, folderName: string): Promise<string[]> { const promise: Promise<string[]> = new Promise<string[]>((resolve, reject: RejectedPromise) => { const fileNames: string[] = []; blobSvc.listBlobsSegmentedWithPrefix(containerName, folderName, _nullCommonContinuationToken, (error: Error, result: AzureStorage.BlobService.ListBlobsResult) => { if (error) { reject(new Error(`Failed to enumerate files (blobs) in folder '${folderName}' of container '${containerName}' (reason: ${getStatusCode(error)}${error.message})`)); } else { result.entries.forEach((blob) => { fileNames.push(blob.name); }); resolve(fileNames); } }); }); return (promise); } } /** * [Internal] Returns the list of "leaf" Azure log folder names (ie. the child folders of 'logFolder') for the specified instance.\ * Leaf folder names are of the form "{instanceName}_{versionNumber}". */ export async function getChildLogFoldersAsync(logFolder: string, instanceName: string): Promise<string[]> { logFolder = convertToAzurePath(logFolder, true); const blobSvc: AzureStorage.BlobService = AzureStorage.createBlobService(getConnString()); // Note: This establishes a connection const folderNames: string[] = []; const promise: Promise<string[]> = new Promise<string[]>((resolve, reject: RejectedPromise) => { blobSvc.listBlobDirectoriesSegmentedWithPrefix(_logsContainerName, `${logFolder}${instanceName}_`, _nullCommonContinuationToken, (error: Error, result: AzureStorage.BlobService.ListBlobDirectoriesResult) => { if (error) { reject(new Error(`Failed to enumerate log folders for '${instanceName}' in folder '${logFolder}' of container '${_logsContainerName}' (reason: ${getStatusCode(error)}${error.message})`)); } else { result.entries.forEach((folder) => { const folderName: string = folder.name.endsWith("/") ? folder.name.slice(0, -1) : folder.name; const parts: string[] = folderName.split("/"); const leafFolderName = parts[parts.length - 1]; if (RegExp(`${instanceName}_\\d+$`).test(leafFolderName)) { folderNames.push(leafFolderName); } }); resolve(folderNames); } }); }); return (promise); }
the_stack
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { TranslateService } from '@ngx-translate/core'; import { ArtemisTestModule } from '../../test.module'; import { ActivatedRoute, convertToParamMap, Router } from '@angular/router'; import { of } from 'rxjs'; import { RouterTestingModule } from '@angular/router/testing'; import { JhiLanguageHelper } from 'app/core/language/language.helper'; import { AccountService } from 'app/core/auth/account.service'; import { MockAccountService } from '../../helpers/mocks/service/mock-account.service'; import { MockRouter } from '../../helpers/mocks/mock-router'; import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; import { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; import { ExerciseType } from 'app/entities/exercise.model'; import { ExerciseService } from 'app/exercises/shared/exercise/exercise.service'; import { HttpHeaders, HttpResponse } from '@angular/common/http'; import { SortService } from 'app/shared/service/sort.service'; import { ProgrammingExerciseSubmissionsComponent } from 'app/exercises/programming/assess/programming-assessment-dashboard/programming-exercise-submissions.component'; import { ProgrammingSubmissionService } from 'app/exercises/programming/participate/programming-submission.service'; import { ProgrammingAssessmentManualResultService } from 'app/exercises/programming/assess/manual-result/programming-assessment-manual-result.service'; import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; import { AssessmentType } from 'app/entities/assessment-type.model'; const route = { params: of({ courseId: 3, exerciseId: 22 }) }; const programmingExercise1 = { id: 22, type: ExerciseType.PROGRAMMING, course: { id: 91 }, numberOfAssessmentsOfCorrectionRounds: {}, } as ProgrammingExercise; const programmingExercise2 = { id: 22, type: ExerciseType.PROGRAMMING, exerciseGroup: { id: 94, exam: { id: 777, course: { id: 92 } } }, numberOfAssessmentsOfCorrectionRounds: {}, } as ProgrammingExercise; const programmingSubmission1 = { id: 1, submitted: true, results: [{ id: 10, assessor: { id: 20, guidedTourSettings: [], internal: true } }], participation: { id: 41, exercise: programmingExercise1 }, }; const programmingSubmission2 = { id: 2, submitted: true, results: [{ id: 20, assessor: { id: 30, guidedTourSettings: [], internal: true } }], participation: { id: 41, exercise: programmingExercise2 }, }; describe('ProgrammingAssessmentDashboardComponent', () => { let component: ProgrammingExerciseSubmissionsComponent; let fixture: ComponentFixture<ProgrammingExerciseSubmissionsComponent>; let exerciseService: ExerciseService; let programmingSubmissionService: ProgrammingSubmissionService; let programmingAssessmentService: ProgrammingAssessmentManualResultService; let accountService: AccountService; let sortService: SortService; beforeEach(() => { TestBed.configureTestingModule({ imports: [RouterTestingModule, ArtemisTestModule], declarations: [ProgrammingExerciseSubmissionsComponent], providers: [ JhiLanguageHelper, { provide: Router, useValue: route }, { provide: LocalStorageService, useClass: MockSyncStorage }, { provide: SessionStorageService, useClass: MockSyncStorage }, { provide: TranslateService, useClass: MockTranslateService }, { provide: Router, useClass: MockRouter }, { provide: AccountService, useClass: MockAccountService }, { provide: ActivatedRoute, useValue: { snapshot: { paramMap: convertToParamMap({ exerciseId: programmingExercise2.id, }), }, }, }, ], }) .overrideTemplate(ProgrammingExerciseSubmissionsComponent, '') .compileComponents() .then(() => { fixture = TestBed.createComponent(ProgrammingExerciseSubmissionsComponent); component = fixture.componentInstance; exerciseService = fixture.debugElement.injector.get(ExerciseService); programmingSubmissionService = fixture.debugElement.injector.get(ProgrammingSubmissionService); programmingAssessmentService = fixture.debugElement.injector.get(ProgrammingAssessmentManualResultService); accountService = fixture.debugElement.injector.get(AccountService); sortService = fixture.debugElement.injector.get(SortService); }) .catch((e) => console.error(e)); }); it('should set parameters and call functions on init', fakeAsync(() => { // setup const exerciseServiceFindMock = jest.spyOn(exerciseService, 'find'); exerciseServiceFindMock.mockReturnValue(of(new HttpResponse({ body: programmingExercise1 }))); // test for init values expect(component).toBeTruthy(); expect(component.submissions).toEqual([]); expect(component.reverse).toEqual(false); expect(component.predicate).toEqual('id'); expect(component.filteredSubmissions).toEqual([]); // call component.ngOnInit(); tick(500); // check expect(exerciseServiceFindMock).toHaveBeenCalledWith(programmingExercise2.id); expect(component.exercise).toEqual(programmingExercise1 as ProgrammingExercise); })); it('should get Submissions', fakeAsync(() => { // test getSubmissions const exerciseServiceFindMock = jest.spyOn(exerciseService, 'find'); const getProgrammingSubmissionsForExerciseByCorrectionRoundStub = jest.spyOn(programmingSubmissionService, 'getProgrammingSubmissionsForExerciseByCorrectionRound'); const isAtLeastInstructorInCourseStub = jest.spyOn(accountService, 'isAtLeastInstructorInCourse'); exerciseServiceFindMock.mockReturnValue(of(new HttpResponse({ body: programmingExercise1 }))); getProgrammingSubmissionsForExerciseByCorrectionRoundStub.mockReturnValue(of(new HttpResponse({ body: [programmingSubmission1] }))); isAtLeastInstructorInCourseStub.mockReturnValue(true); jest.spyOn<any, any>(component, 'getSubmissions'); // call component.ngOnInit(); tick(500); // check expect(component['getSubmissions']).toHaveBeenCalled(); expect(getProgrammingSubmissionsForExerciseByCorrectionRoundStub).toHaveBeenCalled(); expect(getProgrammingSubmissionsForExerciseByCorrectionRoundStub).toHaveBeenCalledWith(programmingExercise2.id, { submittedOnly: true }); expect(exerciseServiceFindMock).toHaveBeenCalledWith(programmingExercise2.id); expect(component.submissions).toEqual([programmingSubmission1]); expect(component.filteredSubmissions).toEqual([programmingSubmission1]); })); it('should not get Submissions', fakeAsync(() => { const exerciseServiceFind = jest.spyOn(exerciseService, 'find'); const getProgrammingSubmissionsForExerciseByCorrectionRoundStub = jest.spyOn(programmingSubmissionService, 'getProgrammingSubmissionsForExerciseByCorrectionRound'); const isAtLeastInstructorInCourseStub = jest.spyOn(accountService, 'isAtLeastInstructorInCourse'); exerciseServiceFind.mockReturnValue(of(new HttpResponse({ body: programmingExercise1 }))); getProgrammingSubmissionsForExerciseByCorrectionRoundStub.mockReturnValue(of(new HttpResponse({ body: [] }))); isAtLeastInstructorInCourseStub.mockReturnValue(true); // findExerciseStub.mockReturnValue(of(new HttpResponse({ body: fileUploadExercise, headers: new HttpHeaders() }))); exerciseServiceFind.mockReturnValue(of(new HttpResponse({ body: programmingExercise2, headers: new HttpHeaders() }))); jest.spyOn<any, any>(component, 'getSubmissions'); component.exercise = programmingExercise2; // call component.ngOnInit(); tick(100); // check expect(component['getSubmissions']).toHaveBeenCalled(); expect(exerciseServiceFind).toHaveBeenCalledWith(programmingExercise2.id); expect(component.submissions).toEqual([]); expect(component.filteredSubmissions).toEqual([]); })); it('should update filtered submissions', () => { // test updateFilteredSubmissions // setup component.ngOnInit(); component.updateFilteredSubmissions([programmingSubmission1]); // check expect(component.filteredSubmissions).toEqual([programmingSubmission1]); }); it('should cancelAssessment', fakeAsync(() => { // test cancelAssessment const windowSpy = jest.spyOn(window, 'confirm').mockReturnValue(true); const modelAssServiceCancelAssSpy = jest.spyOn(programmingAssessmentService, 'cancelAssessment').mockReturnValue(of(undefined)); component.exercise = programmingExercise2; // call component.cancelAssessment(programmingSubmission2); tick(); // check expect(modelAssServiceCancelAssSpy).toHaveBeenCalledWith(programmingSubmission2.id); expect(windowSpy).toHaveBeenCalled(); })); it('should sortRows', () => { // test cancelAssessment const sortServiceSpy = jest.spyOn(sortService, 'sortByProperty'); component.predicate = 'predicate'; component.reverse = false; component.submissions = [programmingSubmission2]; component.sortRows(); expect(sortServiceSpy).toHaveBeenCalledWith([programmingSubmission2], 'predicate', false); }); it('should assessmentTypeTranslationKey', () => { const result = { id: 55, assessmentType: AssessmentType.SEMI_AUTOMATIC }; expect(component.assessmentTypeTranslationKey(result)).toEqual(`artemisApp.AssessmentType.${result.assessmentType}`); expect(component.assessmentTypeTranslationKey(undefined)).toEqual(`artemisApp.AssessmentType.null`); }); describe('shouldGetAssessmentLink', () => { it('should get assessment link for exam exercise', () => { const submissionId = 8; const participationId = 2; component.exercise = programmingExercise1; component.exerciseId = programmingExercise1.id!; component.courseId = programmingExercise1.course!.id!; expect(component.getAssessmentLink(participationId, submissionId)).toEqual([ '/course-management', component.exercise.course!.id!.toString(), 'programming-exercises', component.exercise.id!.toString(), 'submissions', submissionId.toString(), 'assessment', ]); }); it('should get assessment link for normal exercise', () => { const submissionId = 9; const participationId = 2; component.exercise = programmingExercise2; component.exerciseId = programmingExercise2.id!; component.courseId = programmingExercise2.exerciseGroup!.exam!.course!.id!; component.examId = programmingExercise2.exerciseGroup!.exam!.id!; component.exerciseGroupId = programmingExercise2.exerciseGroup!.id!; expect(component.getAssessmentLink(participationId, submissionId)).toEqual([ '/course-management', component.exercise.exerciseGroup!.exam!.course!.id!.toString(), 'exams', component.exercise.exerciseGroup!.exam!.id!.toString(), 'exercise-groups', component.exercise.exerciseGroup!.id!.toString(), 'programming-exercises', component.exercise.id!.toString(), 'submissions', submissionId.toString(), 'assessment', ]); }); }); });
the_stack
* @title: Morphing * @description: * This sample loads a model with four morph targets and blends between them. * This kind of geometry manipulation can make the model appear to stretch, squash or twist. * You can drag the sliders around to modify how much to apply each morph target to the original geometry. */ /*{{ javascript("jslib/camera.js") }}*/ /*{{ javascript("jslib/aabbtree.js") }}*/ /*{{ javascript("jslib/shadermanager.js") }}*/ /*{{ javascript("jslib/texturemanager.js") }}*/ /*{{ javascript("jslib/effectmanager.js") }}*/ /*{{ javascript("jslib/geometry.js") }}*/ /*{{ javascript("jslib/material.js") }}*/ /*{{ javascript("jslib/light.js") }}*/ /*{{ javascript("jslib/scenenode.js") }}*/ /*{{ javascript("jslib/scene.js") }}*/ /*{{ javascript("jslib/scenedebugging.js") }}*/ /*{{ javascript("jslib/renderingcommon.js") }}*/ /*{{ javascript("jslib/defaultrendering.js") }}*/ /*{{ javascript("jslib/resourceloader.js") }}*/ /*{{ javascript("jslib/observer.js") }}*/ /*{{ javascript("jslib/utilities.js") }}*/ /*{{ javascript("jslib/requesthandler.js") }}*/ /*{{ javascript("jslib/vertexbuffermanager.js") }}*/ /*{{ javascript("jslib/indexbuffermanager.js") }}*/ /*{{ javascript("jslib/services/turbulenzservices.js") }}*/ /*{{ javascript("jslib/services/turbulenzbridge.js") }}*/ /*{{ javascript("jslib/services/gamesession.js") }}*/ /*{{ javascript("jslib/services/mappingtable.js") }}*/ /*{{ javascript("scripts/sceneloader.js") }}*/ /*{{ javascript("scripts/htmlcontrols.js") }}*/ /*{{ javascript("scripts/motion.js") }}*/ /*{{ javascript("scripts/morph.js") }}*/ /*global TurbulenzEngine: true */ /*global Morph: false */ /*global MorphInstance: false */ /*global MorphShape: false */ /*global loadCustomFileShapeFn: false */ /*global RequestHandler: false */ /*global TextureManager: false */ /*global ShaderManager: false */ /*global EffectManager: false */ /*global Camera: false */ /*global CameraController: false */ /*global Scene: false */ /*global SceneLoader: false */ /*global HTMLControls: false */ /*global SceneNode: false */ /*global DefaultRendering: false */ /*global TurbulenzServices: false */ TurbulenzEngine.onload = function onloadFn() { var errorCallback = function errorCallback(msg) { window.alert(msg); }; var graphicsDeviceParameters = {}; var graphicsDevice = TurbulenzEngine.createGraphicsDevice(graphicsDeviceParameters); if (!graphicsDevice.shadingLanguageVersion) { errorCallback("No shading language support detected.\nPlease check your graphics drivers are up to date."); graphicsDevice = null; return; } // Clear the background color of the engine window var clearColor = [0.5, 0.5, 0.5, 1.0]; if (graphicsDevice.beginFrame()) { graphicsDevice.clear(clearColor); graphicsDevice.endFrame(); } var mathDeviceParameters = {}; var mathDevice = TurbulenzEngine.createMathDevice(mathDeviceParameters); var inputDeviceParameters = {}; var inputDevice = TurbulenzEngine.createInputDevice(inputDeviceParameters); var requestHandlerParameters = {}; var requestHandler = RequestHandler.create(requestHandlerParameters); var textureManager = TextureManager.create(graphicsDevice, requestHandler, null, errorCallback); var shaderManager = ShaderManager.create(graphicsDevice, requestHandler, null, errorCallback); var effectManager = EffectManager.create(); var assetName = "models/duck_morph.dae"; var shapes = {}; var fileShapeCount = 0; var morphs = []; var morphNodes = []; var morphInstances = []; var currentMaterial = "blinnMorphMaterial"; var materials = { debugNormalsMorphMaterial : { effect: "debug_normals_morph", parameters : { morphWeights : [0.0, 0.0, 0.0] } }, blinnMorphMaterial : { effect: "blinn_morph", parameters : { diffuse : "textures/duck.png", morphWeights : [0.0, 0.0, 0.0] } } }; var setMaterial = function setMaterialFn(materialName) { var morphInstancesLen = morphInstances.length; for (var i = 0; i < morphInstancesLen; i += 1) { morphInstances[i].setMaterial(materials[materialName]); } }; var renderer; // The maximum number of morph shapes the effects/shader supports (includes base shape) var maxMorphShapes = 4; // The weights that are modified at runtime, to calculate a relative morph var weights = [ 0.0, 0.0, 0.0 ]; // Slider settings for weights var weightScaleMax = 1.0; var weightScaleMin = 0.0; var weightStep = 0.01; // Slider settings for node rotation var rotation = 3.5; var lastRotation = 0; var rotationMax = Math.PI * 2; var rotationMin = 0; var rotationStep = 0.1; // Initial camera view var lookAtScaleFactor = 0.4; var cameraPos = mathDevice.v3Build(-5 * lookAtScaleFactor, 4 * lookAtScaleFactor, 5 * lookAtScaleFactor); var lightPos = mathDevice.v3Build(-1 * lookAtScaleFactor, 50 * lookAtScaleFactor, -5 * lookAtScaleFactor); var targetPos = mathDevice.v3Build(-0.3, 1, 0); var up = mathDevice.v3Build(0, 1, 0); // Setup camera & controller var camera = Camera.create(mathDevice); camera.nearPlane = 0.05; camera.lookAt(targetPos, up, cameraPos); camera.updateViewMatrix(); camera.updateProjectionMatrix(); var cameraController = CameraController.create(graphicsDevice, inputDevice, camera); var maxSpeed = cameraController.maxSpeed; var scene = Scene.create(mathDevice); var sceneLoader = SceneLoader.create(); // Controls var htmlControls = HTMLControls.create(); htmlControls.addRadioControl({ id : "radio04", groupName : "materialType", radioIndex : 0, value : "Debug Normals", fn : function () { currentMaterial = "debugNormalsMorphMaterial"; setMaterial(currentMaterial); }, isDefault : false }); htmlControls.addRadioControl({ id : "radio03", groupName : "materialType", radioIndex : 1, value : "Textured Blinn", fn : function () { currentMaterial = "blinnMorphMaterial"; setMaterial(currentMaterial); }, isDefault : true }); var sliderTarget1ID = "slider1"; var sliderTarget2ID = "slider2"; var sliderTarget3ID = "slider3"; var sliderRotateID = "slider4"; var registerSliders = function registerSlidersFn() { htmlControls.addSliderControl({ id: sliderTarget1ID, value: weights[0], max: weightScaleMax, min: weightScaleMin, step: weightStep, fn: function () { var val = this.value; weights[0] = val; htmlControls.updateSlider(sliderTarget1ID, val); } }); htmlControls.addSliderControl({ id: sliderTarget2ID, value: weights[1], max: weightScaleMax, min: weightScaleMin, step: weightStep, fn: function () { var val = this.value; weights[1] = val; htmlControls.updateSlider(sliderTarget2ID, val); } }); htmlControls.addSliderControl({ id: sliderTarget3ID, value: weights[2], max: weightScaleMax, min: weightScaleMin, step: weightStep, fn: function () { var val = this.value; weights[2] = val; htmlControls.updateSlider(sliderTarget3ID, val); } }); htmlControls.addSliderControl({ id: sliderRotateID, value: rotation, max: rotationMax, min: rotationMin, step: rotationStep, fn: function () { var val = this.value; rotation = val; htmlControls.updateSlider(sliderRotateID, val); } }); htmlControls.register(); }; // Initialize the previous frame time var previousFrameTime; var intervalID; // Callback for when the scene data is available, pre load var preLoadScene = function preLoadSceneFn(data) { var shapesArray; var geometries = data.geometries; if (geometries) { for (var g in geometries) { if (geometries.hasOwnProperty(g)) { shapesArray = shapes[assetName]; if (!shapesArray) { shapesArray = []; shapes[assetName] = shapesArray; } shapesArray[shapesArray.length] = { weight: 0.0, // Set weight to 0.0, could load default weight from file shape: geometries[g] }; fileShapeCount += 1; } } } }; var loadMorphShape = function loadMorphShapeFn(name, index) { var shapeArray = shapes[name]; if (!shapeArray) { return null; } var shape = shapeArray[index]; if (!shape) { return null; } var morphShape = MorphShape.create(shape.weight); var loadShapeParams = { graphicsDevice : graphicsDevice, useVertexBufferManager : false, dynamicVertexBuffers : false // Only works without vertexBufferManager }; // loadShapeParams also takes parameter "onGeometryDestroyed : function (data) {}" // Can be used as a callback for when the geometry is destroyed // Use a custom shape loader to process the shape data from file loadCustomFileShape(name, morphShape, shape.shape, loadShapeParams); return morphShape; }; // Callback for when the scene is loaded to assign nodes function loadSceneFinished(scene) { var morphShape = loadMorphShape(assetName, 0); var morph = Morph.create(morphShape); var morphShapes = []; var i; for (i = 1; i < maxMorphShapes; i += 1) { morphShape = loadMorphShape(assetName, i); if (morphShape) { morphShapes[morphShapes.length] = morphShape; weights[i - 1] = morphShape.initialWeight; } } if ((morphShapes.length !== 0) && morph.addShapes(morphShapes)) { morphs.push(morph); } else { window.alert("Could not add shapes to morph. Please check the morph shapes are compatible"); return; } var morphsLen = morphs.length; for (i = 0; i < morphsLen; i += 1) { morphNodes[i] = SceneNode.create({ name : "MorphNode" + i, dynamic : true}); scene.addRootNode(morphNodes[i]); } for (var m in materials) { if (materials.hasOwnProperty(m)) { scene.loadMaterial(graphicsDevice, textureManager, effectManager, m, materials[m]); } } // registerSliders having loaded the initial weights registerSliders(); } // // Update // var update = function updateFn() { var transform = null; var currentTime = TurbulenzEngine.time; var deltaTime = (currentTime - previousFrameTime); if (deltaTime > 0.1) { deltaTime = 0.1; } cameraController.maxSpeed = (deltaTime * maxSpeed); inputDevice.update(); cameraController.update(); var deviceWidth = graphicsDevice.width; var deviceHeight = graphicsDevice.height; var aspectRatio = (deviceWidth / deviceHeight); if (aspectRatio !== camera.aspectRatio) { camera.aspectRatio = aspectRatio; camera.updateProjectionMatrix(); } camera.updateViewProjectionMatrix(); if (rotation !== lastRotation) { transform = mathDevice.m43FromAxisRotation(up, rotation); lastRotation = rotation; } var morphNodesLen = morphNodes.length; for (var i = 0; i < morphNodesLen; i += 1) { if (transform) { morphNodes[i].setLocalTransform(transform); } morphInstances[i].setWeights(mathDevice.v3Build(weights[0], weights[1], weights[2])); } scene.update(); renderer.update(graphicsDevice, camera, scene, currentTime); if (graphicsDevice.beginFrame()) { if (renderer.updateBuffers(graphicsDevice, deviceWidth, deviceHeight)) { renderer.draw(graphicsDevice, clearColor); } graphicsDevice.endFrame(); } }; var loadingPostSceneEffects = function loadingPostSceneEffectsFn() { var material; if (graphicsDevice.beginFrame()) { graphicsDevice.clear(clearColor); graphicsDevice.endFrame(); } if ((!textureManager || 0 === textureManager.getNumPendingTextures()) && (!shaderManager || 0 === shaderManager.getNumPendingShaders())) { TurbulenzEngine.clearInterval(intervalID); for (var m in materials) { if (materials.hasOwnProperty(m)) { material = scene.getMaterial(m); if (material) { // Add additional references to materials, to avoid them being removed when not in use material.reference.add(); } materials[m] = material; } } var morphNodesLen = morphNodes.length; var morphInstance; for (var i = 0; i < morphNodesLen; i += 1) { morphInstance = MorphInstance.create(morphs[i], materials[currentMaterial]); morphNodes[i].addRenderable(morphInstance); morphInstances[i] = morphInstance; } // All resources loaded, start the render update intervalID = TurbulenzEngine.setInterval(update, 1000 / 60); } }; var loadingScene = function loadingSceneFn() { if (graphicsDevice.beginFrame()) { graphicsDevice.clear(clearColor); graphicsDevice.endFrame(); } if (sceneLoader.complete()) { TurbulenzEngine.clearInterval(intervalID); // Starts the loop that will wait for resources required, post scene load intervalID = TurbulenzEngine.setInterval(loadingPostSceneEffects, 1000 / 10); } }; var loadingDefaultEffects = function loadingDefaultEffectsFn() { if ((!textureManager || 0 === textureManager.getNumPendingTextures()) && (!shaderManager || 0 === shaderManager.getNumPendingShaders())) { TurbulenzEngine.clearInterval(intervalID); // Start the loading of the scene sceneLoader.load({ scene : scene, append : false, assetPath : assetName, graphicsDevice : graphicsDevice, mathDevice : mathDevice, textureManager : textureManager, shaderManager : shaderManager, effectManager : effectManager, requestHandler : requestHandler, preSceneLoadFn : preLoadScene, postSceneLoadFn : loadSceneFinished }); // Starts the loop that will wait for the scene to load intervalID = TurbulenzEngine.setInterval(loadingScene, 1000 / 10); } }; var loadAssets = function loadAssetsFn() { // Renderer for the scene (requires shader assets). renderer = DefaultRendering.create(graphicsDevice, mathDevice, shaderManager, effectManager); renderer.setAmbientColor(mathDevice.v3Build(0.3, 0.3, 0.4)); renderer.setDefaultTexture(textureManager.get("default")); // Setup light based on lookAtScaleFactor renderer.setGlobalLightPosition(lightPos); // Register the effects that are required for morphing MorphInstance.registerEffects(mathDevice, renderer, shaderManager, effectManager); // Starts the loop that will wait for the shaders and textures required by the default effects registered with the renderer intervalID = TurbulenzEngine.setInterval(loadingDefaultEffects, 1000 / 10); }; var mappingTableReceived = function mappingTableReceivedFn(mappingTable) { textureManager.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix); shaderManager.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix); sceneLoader.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix); loadAssets(); }; var gameSessionCreated = function gameSessionCreatedFn(gameSession) { TurbulenzServices.createMappingTable(requestHandler, gameSession, mappingTableReceived); }; var gameSession = TurbulenzServices.createGameSession(requestHandler, gameSessionCreated); TurbulenzEngine.onunload = function destroyScene() { TurbulenzEngine.clearInterval(intervalID); if (gameSession) { gameSession.destroy(); gameSession = null; } var material = null; for (var m in materials) { if (materials.hasOwnProperty(m)) { material = scene.getMaterial(m); if (material) { // Remove additional references to materials, we no longer need them material.reference.remove(); } } } currentMaterial = null; sliderTarget1ID = null; sliderTarget2ID = null; sliderTarget3ID = null; sliderRotateID = null; if (scene) { scene.destroy(); scene = null; } requestHandler = null; sceneLoader = null; cameraPos = null; lightPos = null; targetPos = null; up = null; assetName = null; if (renderer) { renderer.destroy(); renderer = null; } htmlControls = null; cameraController = null; camera = null; weights = null; morphInstances = null; morphNodes = null; morphs = null; shapes = null; materials = null; clearColor = null; if (textureManager) { textureManager.destroy(); textureManager = null; } if (shaderManager) { shaderManager.destroy(); shaderManager = null; } effectManager = null; TurbulenzEngine.flush(); inputDevice = null; graphicsDevice = null; mathDevice = null; }; previousFrameTime = TurbulenzEngine.time; };
the_stack
import React, { useContext, useRef, useState } from 'react'; import { debounce } from 'lodash'; import { DATA_SOURCE_ENUM, DATA_SOURCE_TEXT, formItemLayout, HELP_DOC_URL } from '@/constant'; import { isHaveTableColumn, isShowSchema, isES, isCacheOnlyAll, isCacheExceptLRU, isHaveAsyncPoolSize, isHaveCustomParams, isSchemaRequired, } from '@/utils/is'; import type { FormInstance } from 'antd'; import { Button, Form, Input, InputNumber, message, Popconfirm, Select, Switch, Table, Tooltip, } from 'antd'; import { QuestionCircleOutlined, CloseOutlined } from '@ant-design/icons'; import Editor from '@/components/editor'; import { asyncTimeoutNumDoc, queryFault, targetColText } from '@/components/helpDoc/docs'; import { CustomParams } from '../customParams'; import DataPreviewModal from '../../../components/streamCollection/source/dataPreviewModal'; import type { IDataColumnsProps, IDataSourceUsedInSyncProps, IFlinkSideProps } from '@/interface'; import { createSeries } from '@/utils'; import { NAME_FIELD } from '.'; import { FormContext } from '@/services/rightBarService'; const FormItem = Form.Item; const { Option } = Select; const DATA_SOURCE_OPTIONS = [DATA_SOURCE_ENUM.MYSQL]; type IFormFieldProps = IFlinkSideProps; interface IDimensionFormProps { /** * 表单 name 前缀 */ index: number; sourceOptions?: IDataSourceUsedInSyncProps[]; /** * @deprecated 暂时没有支持具有 schema 的数据源 */ schemaOptions?: string[]; /** * 以 searchkey 为键,搜索结果为 value */ tableOptions?: Record<string, string[]>; columnsOptions?: IDataColumnsProps[]; isFlink112?: boolean; onTableSearch?: ( type: DATA_SOURCE_ENUM, sourceId: number, schema?: string | undefined, searchKey?: string | undefined, ) => Promise<void>; // onValuesChange?: (preVal: Partial<IFormFieldProps>, nextVal: Partial<IFormFieldProps>) => void; } /** * 表格列操作枚举 */ enum ColOperatorKind { ADD, ADD_ALL, REMOVE_ALL, SET_COL, SET_TYPE, SET_TARGET, REMOVE, } export default function DimensionForm({ index, sourceOptions = [], schemaOptions = [], tableOptions = {}, columnsOptions = [], isFlink112 = true, onTableSearch, }: IDimensionFormProps) { const { form } = useContext(FormContext) as { form?: FormInstance<{ [NAME_FIELD]: IFormFieldProps[] }>; }; const [visible, setVisible] = useState(false); const [params, setParams] = useState<Record<string, any>>({}); const currentSearchKey = useRef(''); const handleSearchTable = debounce((key: string) => { currentSearchKey.current = key; const { sourceId, schema, type } = form!.getFieldsValue()[NAME_FIELD][index]; onTableSearch?.(type, sourceId, schema, key); }, 300); const handleColsChanged = (ops: ColOperatorKind, idx?: number, value?: string) => { switch (ops) { case ColOperatorKind.ADD: { const nextCols = form?.getFieldsValue()[NAME_FIELD][index].columns?.concat() || []; nextCols.push({}); const nextValue = form!.getFieldsValue(); nextValue[NAME_FIELD][index].columns = nextCols; form?.setFieldsValue(nextValue); break; } case ColOperatorKind.ADD_ALL: { const nextCols = columnsOptions.map((col) => ({ column: col.key, type: col.type, })); const nextValue = form!.getFieldsValue(); nextValue[NAME_FIELD][index].columns = nextCols; form?.setFieldsValue(nextValue); break; } case ColOperatorKind.REMOVE_ALL: { const nextValue = form!.getFieldsValue(); nextValue[NAME_FIELD][index].columns = []; form?.setFieldsValue(nextValue); break; } case ColOperatorKind.SET_COL: { const nextCols = form?.getFieldsValue()[NAME_FIELD][index].columns?.concat() || []; if (idx !== undefined && value) { nextCols[idx].column = value; nextCols[idx].type = columnsOptions.find((c) => c.key === value)?.type; const nextValue = form!.getFieldsValue(); nextValue[NAME_FIELD][index].columns = nextCols; form?.setFieldsValue(nextValue); } break; } case ColOperatorKind.SET_TYPE: { const nextCols = form?.getFieldsValue()[NAME_FIELD][index].columns?.concat() || []; if (idx !== undefined && value) { nextCols[idx].type = value; const nextValue = form!.getFieldsValue(); nextValue[NAME_FIELD][index].columns = nextCols; form?.setFieldsValue(nextValue); } break; } case ColOperatorKind.SET_TARGET: { const nextCols = form?.getFieldsValue()[NAME_FIELD][index].columns?.concat() || []; if (idx !== undefined && value) { nextCols[idx].targetCol = value; const nextValue = form!.getFieldsValue(); nextValue[NAME_FIELD][index].columns = nextCols; form?.setFieldsValue(nextValue); } break; } case ColOperatorKind.REMOVE: { const nextCols = form?.getFieldsValue()[NAME_FIELD][index].columns?.concat() || []; if (idx !== undefined) { nextCols.splice(idx, 1); const nextValue = form!.getFieldsValue(); nextValue[NAME_FIELD][index].columns = nextCols; form?.setFieldsValue(nextValue); } break; } default: break; } }; const showPreviewModal = () => { const { type, sourceId, index: tableIndex, table, schema, } = form!.getFieldsValue()[NAME_FIELD][index]; let nextParams = {}; switch (type) { case DATA_SOURCE_ENUM.ES7: { if (!sourceId || !tableIndex) { message.error('数据预览需要选择数据源和索引!'); return; } nextParams = { sourceId, tableName: tableIndex }; break; } case DATA_SOURCE_ENUM.REDIS: case DATA_SOURCE_ENUM.UPRedis: case DATA_SOURCE_ENUM.HBASE: case DATA_SOURCE_ENUM.TBDS_HBASE: case DATA_SOURCE_ENUM.HBASE_HUAWEI: case DATA_SOURCE_ENUM.MYSQL: case DATA_SOURCE_ENUM.UPDRDB: case DATA_SOURCE_ENUM.INCEPTOR: { if (!sourceId || !table) { message.error('数据预览需要选择数据源和表!'); return; } nextParams = { sourceId, tableName: table }; break; } case DATA_SOURCE_ENUM.ORACLE: { if (!sourceId || !table || !schema) { message.error('数据预览需要选择数据源、表和schema!'); return; } nextParams = { sourceId, tableName: table, schema }; break; } case DATA_SOURCE_ENUM.SQLSERVER: case DATA_SOURCE_ENUM.SQLSERVER_2017_LATER: { if (!sourceId || !table) { message.error('数据预览需要选择数据源和表!'); return; } nextParams = { sourceId, tableName: table, schema }; break; } default: break; } setVisible(true); setParams(nextParams); }; return ( <> <FormItem label="存储类型" name={[index, 'type']} rules={[{ required: true, message: '请选择存储类型' }]} > <Select showSearch filterOption={(input: any, option: any) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 } > {DATA_SOURCE_OPTIONS.map((v) => ( <Option value={v} key={v}> {DATA_SOURCE_TEXT[v]} </Option> ))} </Select> </FormItem> <FormItem label="数据源" name={[index, 'sourceId']} rules={[{ required: true, message: '请选择数据源' }]} > <Select placeholder="请选择数据源" showSearch filterOption={(input: any, option: any) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 } > {sourceOptions.map((v) => ( <Option key={v.dataInfoId} value={v.dataInfoId}> {v.dataName} </Option> ))} </Select> </FormItem> <FormItem noStyle dependencies={[[index, 'type']]}> {({ getFieldValue }) => isShowSchema(getFieldValue(NAME_FIELD)[index].type) && ( <FormItem label="Schema" name={[index, 'schema']} rules={[ { required: isSchemaRequired(getFieldValue('type')), message: '请输入Schema', }, ]} > <Select showSearch placeholder="请选择Schema" allowClear filterOption={(input: any, option: any) => option.props.children .toLowerCase() .indexOf(input.toLowerCase()) >= 0 } > {schemaOptions.map((v) => ( <Option key={v} value={v}> {v} </Option> ))} </Select> </FormItem> ) } </FormItem> <FormItem noStyle dependencies={[[index, 'type']]}> {({ getFieldValue }) => { const { type } = getFieldValue(NAME_FIELD)[index] as IFormFieldProps; switch (type) { case DATA_SOURCE_ENUM.REDIS: case DATA_SOURCE_ENUM.UPRedis: { return ( <FormItem label="表" name={[index, 'table']} rules={[{ required: true, message: '请输入表名' }]} > <Input placeholder="请输入表名" /> </FormItem> ); } case DATA_SOURCE_ENUM.ES6: case DATA_SOURCE_ENUM.ES7: { return null; } default: { return ( <FormItem label="表" name={[index, 'table']} rules={[{ required: true, message: '请选择表' }]} > <Select onSearch={handleSearchTable} filterOption={false} showSearch placeholder="请选择表" > {(tableOptions[currentSearchKey.current] || []).map((v) => ( <Option key={v} value={v}> {v} </Option> ))} </Select> </FormItem> ); } } }} </FormItem> <FormItem noStyle dependencies={[[index, 'type']]}> {({ getFieldValue }) => isES(getFieldValue(NAME_FIELD)[index].type) && ( <FormItem label="索引" name={[index, 'index']} rules={[{ required: true, message: '请输入索引' }]} > <Input placeholder="请输入索引" /> </FormItem> ) } </FormItem> <FormItem wrapperCol={{ offset: formItemLayout.labelCol.sm.span, span: formItemLayout.wrapperCol.sm.span, }} > <Button block type="link" onClick={showPreviewModal}> 数据预览 </Button> </FormItem> <FormItem noStyle dependencies={[[index, 'type']]}> {({ getFieldValue }) => isES(getFieldValue(NAME_FIELD)[index].type) && getFieldValue(NAME_FIELD)[index].type !== DATA_SOURCE_ENUM.ES7 && ( <FormItem label="索引类型" name={[index, 'esType']} rules={[{ required: true, message: '请输入索引类型' }]} > <Input placeholder="请输入索引类型" /> </FormItem> ) } </FormItem> <FormItem label="映射表" name={[index, 'tableName']} rules={[{ required: true, message: '请输入映射表名' }]} > <Input placeholder="请输入映射表名" /> </FormItem> <FormItem required label="字段" dependencies={[ [index, 'type'], [index, 'columns'], ]} > {({ getFieldValue }) => isHaveTableColumn(getFieldValue(NAME_FIELD)[index].type) ? ( <div className="column-container"> <Table rowKey="column" dataSource={getFieldValue(NAME_FIELD)[index].columns || []} pagination={false} size="small" > <Table.Column title="字段" dataIndex="column" key="字段" width="35%" render={(text, _, i) => { return ( <Select value={text} style={{ maxWidth: 74 }} onChange={(value) => handleColsChanged( ColOperatorKind.SET_COL, i, value, ) } showSearch > {columnsOptions.map((col) => ( <Option key={col.key} value={col.key}> <Tooltip placement="topLeft" title={col.key} > {col.key} </Tooltip> </Option> ))} </Select> ); }} /> <Table.Column title="类型" dataIndex="type" key="类型" width="25%" render={(text, _, i) => ( <span className={ text?.toLowerCase() === 'Not Support'.toLowerCase() ? 'has-error' : '' } > <Tooltip title={text} trigger="hover" placement="topLeft" > <Input value={text} onChange={(e) => handleColsChanged( ColOperatorKind.SET_TYPE, i, e.target.value, ) } /> </Tooltip> </span> )} /> <Table.Column title={ <div> <Tooltip placement="top" title={targetColText} arrowPointAtCenter > <span> 别名 &nbsp; <QuestionCircleOutlined /> </span> </Tooltip> </div> } dataIndex="targetCol" key="别名" width="30%" render={(text, _, i) => { return ( <Input value={text} onChange={(e) => handleColsChanged( ColOperatorKind.SET_TARGET, i, e.target.value, ) } /> ); }} /> <Table.Column key="delete" render={(_, __, i) => { return ( <CloseOutlined style={{ fontSize: 12, color: 'var(--editor-foreground)', }} onClick={() => handleColsChanged(ColOperatorKind.REMOVE, i) } /> ); }} /> </Table> <div style={{ padding: '0 20 20' }}> <div className="column-btn"> <span> <a onClick={() => handleColsChanged(ColOperatorKind.ADD)}> 添加输入 </a> </span> <span> <a onClick={() => handleColsChanged(ColOperatorKind.ADD_ALL) } style={{ marginRight: 12 }} > 导入全部字段 </a> <Popconfirm title="确认清空所有字段?" onConfirm={() => handleColsChanged(ColOperatorKind.REMOVE_ALL) } okText="确认" cancelText="取消" > <a>清空</a> </Popconfirm> </span> </div> </div> </div> ) : ( <Editor style={{ height: '100%', }} sync /> ) } </FormItem> <FormItem hidden name={[index, 'columns']} /> <FormItem noStyle dependencies={[ [index, 'type'], [index, 'columns'], ]} > {({ getFieldValue }) => { const { type, columns = [] } = getFieldValue(NAME_FIELD)[ index ] as IFormFieldProps; switch (type) { case DATA_SOURCE_ENUM.KUDU: case DATA_SOURCE_ENUM.POSTGRESQL: case DATA_SOURCE_ENUM.CLICKHOUSE: case DATA_SOURCE_ENUM.ORACLE: case DATA_SOURCE_ENUM.POLAR_DB_For_MySQL: case DATA_SOURCE_ENUM.MYSQL: case DATA_SOURCE_ENUM.UPDRDB: case DATA_SOURCE_ENUM.TIDB: case DATA_SOURCE_ENUM.IMPALA: case DATA_SOURCE_ENUM.INCEPTOR: case DATA_SOURCE_ENUM.KINGBASE8: case DATA_SOURCE_ENUM.SQLSERVER: case DATA_SOURCE_ENUM.SQLSERVER_2017_LATER: { return ( <FormItem label="主键" name={[index, 'primaryKey']}> <Select mode="multiple" showSearch showArrow filterOption={(input: any, option: any) => option.props.children .toLowerCase() .indexOf(input.toLowerCase()) >= 0 } > {columns.map((v) => ( <Option key={v.column} value={v.column}> {v.column} </Option> )) || []} </Select> </FormItem> ); } case DATA_SOURCE_ENUM.ES6: case DATA_SOURCE_ENUM.ES7: { return ( <FormItem name={[index, 'primaryKey']} label="主键"> <Input placeholder="请输入主键" /> </FormItem> ); } case DATA_SOURCE_ENUM.MONGODB: case DATA_SOURCE_ENUM.REDIS: case DATA_SOURCE_ENUM.UPRedis: { return ( <FormItem label="主键" name={[index, 'primaryKey']} rules={[{ required: true, message: '请选择主键' }]} > <Input placeholder={ type === DATA_SOURCE_ENUM.MONGODB ? '请输入主键' : '维表主键,多个字段用英文逗号隔开' } /> </FormItem> ); } case DATA_SOURCE_ENUM.HBASE: case DATA_SOURCE_ENUM.TBDS_HBASE: case DATA_SOURCE_ENUM.HBASE_HUAWEI: { return ( <FormItem label="主键" tooltip={ isFlink112 && ( <React.Fragment> Hbase 表主键字段支持类型可参考&nbsp; <a href={HELP_DOC_URL.HBASE} target="_blank" rel="noopener noreferrer" > 帮助文档 </a> </React.Fragment> ) } > <div style={{ display: 'flex' }}> <FormItem style={{ flex: 1 }} name={[index, 'hbasePrimaryKey']} rules={[ { required: true, message: '请输入主键' }, isFlink112 ? { pattern: /^\w{1,64}$/, message: '只能由字母,数字和下划线组成,且不超过64个字符', } : {}, ]} > <Input placeholder="请输入主键" /> </FormItem> {isFlink112 && ( <> <span>&nbsp; 类型:</span> <FormItem style={{ flex: 1 }} name={[index, 'hbasePrimaryKeyType']} rules={[ { required: true, message: '请输入类型', }, ]} > <Input placeholder="请输入类型" /> </FormItem> </> )} </div> </FormItem> ); } default: return null; } }} </FormItem> <FormItem name={[index, 'parallelism']} label="并行度"> <InputNumber style={{ width: '100%' }} min={1} /> </FormItem> <FormItem noStyle dependencies={[[index, 'type']]}> {({ getFieldValue }) => ( <FormItem label="缓存策略" name={[index, 'cache']} rules={[{ required: true, message: '请选择缓存策略' }]} > <Select placeholder="请选择" showSearch filterOption={(input: any, option: any) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 } > <Option key="None" value="None" disabled={isCacheOnlyAll(getFieldValue('type'))} > None </Option> <Option key="LRU" value="LRU" disabled={isCacheExceptLRU(getFieldValue('type'))} > LRU </Option> <Option key="ALL" value="ALL"> ALL </Option> </Select> </FormItem> )} </FormItem> <FormItem noStyle dependencies={[[index, 'cache']]}> {({ getFieldValue }) => { switch (getFieldValue(NAME_FIELD)[index].cache) { case 'LRU': return ( <> <FormItem label="缓存大小(行)" name={[index, 'cacheSize']} rules={[{ required: true, message: '请输入缓存大小' }]} > <InputNumber style={{ width: '100%' }} min={0} /> </FormItem> <FormItem label="缓存超时时间" name={[index, 'cacheTTLMs']} rules={[{ required: true, message: '请输入缓存超时时间' }]} > <InputNumber style={{ width: '100%' }} min={0} addonAfter="ms" /> </FormItem> </> ); case 'ALL': return ( <FormItem label="缓存超时时间" name={[index, 'cacheTTLMs']} rules={[{ required: true, message: '请输入缓存超时时间' }]} > <InputNumber style={{ width: '100%' }} min={0} addonAfter="ms" /> </FormItem> ); default: break; } }} </FormItem> <FormItem label="允许错误数据" tooltip={asyncTimeoutNumDoc} name={[index, 'errorLimit']} > <InputNumber style={{ width: '100%' }} placeholder="默认为无限制" min={0} /> </FormItem> <FormItem noStyle dependencies={[[index, 'type']]}> {({ getFieldValue }) => getFieldValue(NAME_FIELD)[index].type === DATA_SOURCE_ENUM.KUDU && ( <FormItem label="查询容错" tooltip={queryFault} name={[index, 'isFaultTolerant']} > <Switch /> </FormItem> ) } </FormItem> <FormItem noStyle dependencies={[[index, 'type']]}> {({ getFieldValue }) => isHaveAsyncPoolSize(getFieldValue(NAME_FIELD)[index].type) && ( <FormItem name={[index, 'asyncPoolSize']} label="异步线程池"> <Select> {createSeries(20).map((opt) => { return ( <Option key={opt} value={opt}> {opt} </Option> ); })} </Select> </FormItem> ) } </FormItem> <FormItem noStyle dependencies={[[index, 'type']]}> {({ getFieldValue }) => isHaveCustomParams(getFieldValue(NAME_FIELD)[index].type) && ( <CustomParams index={index} /> ) } </FormItem> <FormItem noStyle dependencies={[[index, 'type']]}> {({ getFieldValue }) => ( <DataPreviewModal visible={visible} type={getFieldValue(NAME_FIELD)[index].type} onCancel={() => setVisible(false)} params={params} /> )} </FormItem> </> ); }
the_stack
import { Router } from 'vue-router' import { ref, reactive, computed, h } from 'vue' import { UserManagerSettings, Log, Logger, User, UserManager, Profile, WebStorageStateStore, UserManagerEvents } from 'oidc-client' /** * Indicates the sign in behavior. */ export enum SignInType { /** * Uses the main browser window to do sign-in. */ Window, /** * Uses a popup window to do sign-in. */ Popup } /** * Logging level values used by createOidcAuth(). */ export enum LogLevel { /** * No logs messages. */ None = 0, /** * Only error messages. */ Error = 1, /** * Error and warning messages. */ Warn = 2, /** * Error, warning, and info messages. */ Info = 3, /** * Everything. */ Debug = 4 } /** * A wrapper on oidc-client with vue support. */ export interface OidcAuth { /** * Original app url used to create this instance. */ readonly appUrl: string /** * Name of this oidc authentication instance. * Use in a route's meta:{authName} property to protect that route. */ readonly authName: string /** * Gets whether the user is authenticated. */ readonly isAuthenticated: boolean /** * Gets the API access token if applicable. */ readonly accessToken: string /** * Gets the user claims if authenticated. */ readonly userProfile: Profile /** * Gets the auth events provided by oidc-client. */ readonly events: UserManagerEvents /** * Required call before all the properties are reliably initialized. * Should be called and waited on before starting the root Vue instance. */ startup(): Promise<boolean> /** * Hookup this auth instance with a vue-router instance. * This will guard routes with meta: { authName: `name of this auth` } * and register redirect callback routes. * @param router - the vue router instance. */ useRouter(router: Router): void /** * Starts the login flow explicitly. * @param args */ signIn(args?: any): Promise<User | void> /** * Starts the logout flow. * @param args */ signOut(args?: any): Promise<void> /** * Enables silent renew. */ startSilentRenew(): void /** * Disables silent renew. */ stopSilentRenew(): void } /** * Creates an openid-connect auth instance. * @param authName - short alpha-numeric name that identifies the auth instance for routing purposes. * This is used to generate default redirect urls (slugified) and identifying routes that needs auth. * @param defaultSignInType - the signin behavior when `signIn()` and `signOut()` are called. * @param appUrl - url to the app using this instance for routing purposes. Something like `https://domain/app/`. * @param oidcConfig - config object for oidc-client. * See https://github.com/IdentityModel/oidc-client-js/wiki#configuration for details. * @param logger - logger used by oidc-client. Defaults to console. * @param logLevel - minimum level to log. Defaults to LogLevel.Error. */ export function createOidcAuth( authName: string, defaultSignInType: SignInType, appUrl: string, oidcConfig: UserManagerSettings, logger?: Logger, logLevel?: LogLevel ): OidcAuth { // arg check if (!authName) { throw new Error('Auth name is required.') } if ( defaultSignInType !== SignInType.Window && defaultSignInType !== SignInType.Popup ) { throw new Error('Only window or popup are valid default signin types.') } if (!appUrl) { throw new Error('App base url is required.') } if (!oidcConfig) { throw new Error('No config provided to oidc auth.') } Log.logger = logger || console Log.level = logLevel || LogLevel.Error const nameSlug = slugify(authName) // merge passed oidcConfig with defaults const config = { response_type: 'id_token', scope: 'openid profile', automaticSilentRenew: true, userStore: new WebStorageStateStore({ store: sessionStorage }), post_logout_redirect_uri: appUrl, redirect_uri: `${appUrl}auth/signinwin/${nameSlug}`, popup_post_logout_redirect_uri: `${appUrl}auth/signoutpop/${nameSlug}`, popup_redirect_uri: `${appUrl}auth/signinpop/${nameSlug}`, silent_redirect_uri: `${appUrl}auth/signinsilent/${nameSlug}`, ...oidcConfig // everything can be overridden! } Log.debug(`Creating new oidc auth as ${authName}`) const mgr = new UserManager(config) let _inited = false let myRouter = null as Router | null const user = ref(null as User | null) const authObj = reactive({ appUrl, authName, user, isAuthenticated: computed(() => !!user.value && !user.value.expired), accessToken: computed(() => !!user.value && !user.value.expired ? user.value.access_token : '' ), userProfile: computed(() => !!user.value && !user.value.expired ? user.value.profile : { iss: '', sub: '', aud: '', exp: 0, iat: 0 } ), events: mgr.events, signIn(args?: any) { return signInReal(defaultSignInType, args) }, signOut(args?: any) { if (defaultSignInType === SignInType.Popup) { return mgr .signoutPopup(args) .then(() => { redirectAfterSignout(myRouter) }) .catch(() => { // could be window closed redirectAfterSignout(myRouter) }) } return mgr.signoutRedirect(args) }, startSilentRenew() { mgr.startSilentRenew() }, stopSilentRenew() { mgr.stopSilentRenew() }, startup() { let isCB = false // CB = callback if (matchesPath(config.popup_redirect_uri)) { Log.debug(`${authName} Popup signin callback`) mgr.signinPopupCallback() isCB = true } else if (matchesPath(config.silent_redirect_uri)) { Log.debug(`${authName} Silent signin callback`) mgr.signinSilentCallback() isCB = true } else if (matchesPath(config.popup_post_logout_redirect_uri)) { Log.debug(`${authName} Popup logout callback`) mgr.signoutPopupCallback() isCB = true } if (isCB) return Promise.resolve(false) if (_inited) { return Promise.resolve(true) } else { // load user from storage return mgr .getUser() .then(test => { _inited = true if (test && !test.expired) { user.value = test } return true }) .catch(err => { Log.warn(`Auth startup err = ${err}`) return false }) } }, useRouter(router: Router) { myRouter = router router.beforeEach((to, from, next) => { if ( to.matched.some(record => record.meta.authName === authObj.authName) ) { if (authObj.isAuthenticated) { Log.debug( `${authName} auth authenticated user entering protected route ${to.fullPath}` ) next() } else { Log.debug( `${authName} auth anon user entering protected route ${to.fullPath}` ) signInReal(defaultSignInType, { state: { to } }) .then(() => { if (defaultSignInType === SignInType.Window) { next(false) } else { next() } }) .catch(() => next(false)) } } else { next() } }) if (config.redirect_uri) { const vroutePath = '/' + getUrlPath(config.redirect_uri).substring( (router.options.history.base || '/').length ) router.addRoute({ path: vroutePath, name: `signinwin-${nameSlug}`, component: { render: () => h('div'), created() { mgr .signinRedirectCallback() .then(data => { Log.debug(`${authName} Window signin callback success`, data) // need to manually redirect for window type // goto original secure route or root const redirect = data.state ? data.state.to : null if (router) router.replace(redirect || '/') else window.location.href = appUrl }) .catch(err => { Log.error(`${authName} Window signin callback error`, err) if (router) router.replace('/') else window.location.href = appUrl }) } } }) } } }) function signInIfNecessary() { if (myRouter) { const current = myRouter.currentRoute.value if (current && current.meta.authName === authName) { Log.debug(`${authName} auth page re-signin with ${defaultSignInType}`) signInReal(defaultSignInType, { state: { current } }) .then(() => { // auth.myRouter() }) .catch(() => { setTimeout(signInIfNecessary, 5000) }) // window.location.reload(); // auth.myRouter.go(); //replace('/'); } } } function signInReal(type: SignInType, args?: any) { switch (type) { case SignInType.Popup: return mgr.signinPopup(args) // case SignInType.Silent: // return mgr.signinSilent(args) } return mgr.signinRedirect(args) } function redirectAfterSignout(router: Router | null) { if (router) { const current = router.currentRoute.value if (current && current.meta.authName === authName) { router.replace('/') return } } // window.location.reload(true); if (appUrl) window.location.href = appUrl } /** * Translates user manager events to vue events and perform default actions * if necessary. */ function handleManagerEvents() { mgr.events.addUserLoaded(newUser => { user.value = newUser }) mgr.events.addUserUnloaded(() => { user.value = null // redirect if on protected route (best method here?) Log.debug(`${authName} auth user unloaded`) signInIfNecessary() }) mgr.events.addAccessTokenExpired(() => { Log.debug( `${authName} auth token expired, user is authenticated=${authObj.isAuthenticated}` ) user.value = null signInIfNecessary() // if (auth.isAuthenticated) { // mgr // .signinSilent() // .then(() => { // Log.debug(`${authName} auth silent signin after token expiration`) // }) // .catch(() => { // Log.debug( // `${authName} auth silent signin error after token expiration` // ) // signInIfNecessary() // }) // } }) mgr.events.addSilentRenewError(e => { Log.debug(`${authName} auth silent renew error ${e}`) // TODO: need to restart renew manually? if (authObj.isAuthenticated) { setTimeout(() => { Log.debug(`${authName} auth silent renew retry`) mgr.signinSilent() }, 5000) } else { signInIfNecessary() } }) mgr.events.addUserSignedOut(() => { Log.debug(`${authName} auth user signed out`) user.value = null signInIfNecessary() }) } handleManagerEvents() return authObj } // general utilities /** * Gets the path portion of a url. * @param url - full url * @returns */ function getUrlPath(url: string) { const a = document.createElement('a') a.href = url let p = a.pathname if (p[0] !== '/') p = '/' + p return p } /** * Checks if current url's path matches given url's path. * @param {String} testUrl - url to test against. */ function matchesPath(testUrl: string) { return ( window.location.pathname.toLocaleLowerCase() === getUrlPath(testUrl).toLocaleLowerCase() ) } function slugify(str: string) { str = str.replace(/^\s+|\s+$/g, '') // trim str = str.toLowerCase() // remove accents, swap ñ for n, etc const from = 'ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;' const to = 'aaaaaeeeeeiiiiooooouuuunc------' for (let i = 0, l = from.length; i < l; i++) { str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i)) } str = str .replace(/[^a-z0-9 -]/g, '') // remove invalid chars .replace(/\s+/g, '-') // collapse whitespace and replace by - .replace(/-+/g, '-') // collapse dashes return str }
the_stack
import Database from 'better-sqlite3'; import {exit} from 'process.js'; import {assert} from 'console.js'; import {Dictionary, NumberDictionary} from '../../utils/lib-utils.js'; // Note that the types below match SQL tables in our data representation, and the // snake_case_named fields in each case match SQL fields. This match has to be exact // so that the type lines up with the output of better-sqlite3. type Entity = { storage_key_id: number; entity_id: string; // A "cleaned-up" entity_id, with random sections replaced with minimal representations. // Useful for quick comparisons with other entity IDs. clean_entity_id: string; storageKey: StorageKey; }; type StorageKey = { id: number, storage_key: string; data_type: number; value_id: number; // A "cleaned-up" storage_key, with random sections replaced with minimal representations. // Useful for quick comparisons with other storage keys. clean_storage_key: string; } type Type = { id: number, name: string, is_primitive: number, // A list of fields that have this type. fields?: Field[], // A list of fields that are fields of this type (only populated when this type is an Entity) subFields?: Field[] } type Field = { id: number, type_id: number, parent_type_id: number, name: string, is_collection: number, subFields?: Field[] } type FieldValue = { entity_storage_key_id: number, field_id: number, value_id: number } type TextPrimitiveValue = { id: number, value: string } type CollectionEntries = { collection_id: number, value_id: number, version_map: string } type EntityRef = { id: number, entity_id: string, creation_timestamp: number, expiration_timestamp: number, backing_storage_key: string, version_map: string, entity_storage_key: string } const expected = [ 'types', 'storage_keys', 'entities', 'entity_refs', 'collections', 'collection_entries', 'fields', 'field_values', 'text_primitive_values', 'number_primitive_values' ]; const TEXT_FIELDS = ['Text', 'BigInt', 'Instant']; const SINGLETON = 0; const COLLECTION = 1; const LIST = 2; const INLINE_ENTITY = 3; const INLINE_ENTITY_COLLECTION = 4; const INLINE_ENTITY_LIST = 5; export class DbDumpDataModel { db: Database.Database; entities: Dictionary<Entity>; storageKeys: Dictionary<StorageKey>; types: Dictionary<Type>; fields: Dictionary<Field>; fieldValues: Dictionary<FieldValue>; textPrimitiveValues: Dictionary<TextPrimitiveValue>; collectionEntries: Dictionary<CollectionEntries[]>; entityRefs: Dictionary<EntityRef>; fieldsByType: Dictionary<Field[]>; fieldsByParentType: Dictionary<Field[]>; constructor(fileName: string) { this.db = new Database(fileName, {readonly: true}); const tableNames = this.tables(); expected.forEach(e => { if (!tableNames.includes(e)) { console.error(`Missing table ${e} - this may not be an arcs DB!`); exit(1); } }); this.entities = this.mkTable('entities', 'storage_key_id'); this.storageKeys = this.mkTable('storage_keys', 'id'); this.types = this.mkTable('types', 'id'); this.adjustTypes(); this.fields = this.mkTable('fields', 'id'); this.fieldsByType = this.index(this.fields, 'type_id'); this.fieldsByParentType = this.index(this.fields, 'parent_type_id'); this.fieldValues = this.mkTable('field_values', ['entity_storage_key_id', 'field_id']); this.textPrimitiveValues = this.mkTable('text_primitive_values', 'id'); this.collectionEntries = this.mkSummaryTable('collection_entries', 'collection_id'); this.entityRefs = this.mkTable('entity_refs', 'id'); this.markupDictionary(this.entities, 'entity_id', 'clean_entity_id', processEntityId); this.markupDictionary(this.storageKeys, 'storage_key', 'clean_storage_key', processStorageKey); this.resolveForeignKeys(this.entities, 'storage_key_id', 'storageKey', this.storageKeys); Object.values(this.types).forEach(type => this.populateType(type)); } printEntities(prettyIds: boolean, toplevel: boolean) { for (const entity of Object.values(this.entities)) { const entityId = prettyIds ? entity.clean_entity_id : entity.entity_id; const storageKey = prettyIds ? entity.storageKey.clean_storage_key : entity.storageKey.storage_key; if (toplevel && storageKey.startsWith('inline')) { continue; } let entityString = `EntityId: ${entityId} StorageKey: ${storageKey} ${entity.storageKey.data_type} ${entity.storageKey.value_id}`; const type = this.types[entity.storageKey.value_id]; if (type.subFields) { const values = type.subFields.map(field => this.fieldValues[`${entity.storage_key_id}.${field.id}`]); if ((values.filter(value => value !== undefined)).length === 0) { entityString += ' ' + bold('<deleted>'); } else { for (let i = 0; i < values.length; i++) { const fieldName = type.subFields[i].name; const fieldType = this.types[type.subFields[i].type_id]; const fieldTypeName = fieldType.is_primitive === 1 ? fieldType.name : bold(fieldType.id + ''); const valueSpec = values[i]; let value; if (valueSpec == undefined) { value = bold('null'); } else if (fieldType.is_primitive && TEXT_FIELDS.includes(fieldType.name)) { const textPrimitive = this.textPrimitiveValues[valueSpec.value_id]; value = textPrimitive ? `'${textPrimitive.value}'` : bold(`ERR: ${valueSpec.value_id} not in text_primitive_values`); } else if (fieldType.is_primitive === 0 && type.subFields[i].is_collection === INLINE_ENTITY) { const storageKey = this.storageKeys[valueSpec.value_id]; if (storageKey == undefined) { value = blink(`ERR: no storageKey for inline entity ${valueSpec.value_id}`); } else { value = storageKey.clean_storage_key; } } else if (fieldType.is_primitive === 0 && type.subFields[i].is_collection === INLINE_ENTITY_COLLECTION || type.subFields[i].is_collection === INLINE_ENTITY_LIST) { const valueEntries = this.collectionEntries[valueSpec.value_id] || []; const values = valueEntries.map(entry => entry.value_id); value = values.map(id => { const storageKey = this.storageKeys[id]; if (storageKey == undefined) { return blink(`ERR: no storageKey for inline entity ${id}`); } const entity = this.entities[id]; if (entity == undefined) { return blink(`ERR: no entity table entry for inline entity ${id}`); } return storageKey.clean_storage_key; }).join(','); value = `[${value}]`; } else { value = valueSpec.value_id; } entityString += `\n ${fieldName}(${fieldTypeName}): ${value}`; } } } console.log(entityString); } } printTypes() { const usedTypeIds = new Set<number>(); Object.values(this.entities).forEach(entity => usedTypeIds.add(entity.storageKey.value_id)); const usedTypes = [...usedTypeIds.values()].map(idx => this.types[idx]); const reachable = new Set<Type>(); const addFieldsToReachable = (t: {subFields?: Field[]}) => t.subFields && t.subFields.forEach(field => { reachable.add(this.types[field.type_id]); addFieldsToReachable(field); }); usedTypes.forEach(addFieldsToReachable); usedTypes.forEach(type => { if (type.is_primitive === 1) { return; } if (reachable.has(type)) { return; } console.log(`\n${bold(type.id + '')}(${type.name}):`); type.subFields.forEach(field => this.printField(field, ' ')); }); } printStorageKeys(prettyIds: boolean, toplevel: boolean) { Object.values(this.storageKeys).forEach(key => { if (toplevel && key.storage_key.startsWith('inline')) { return; } const dataType = ['Entity', 'Singleton', 'Collection'][key.data_type]; console.log(`${key.id}: ${prettyIds ? key.clean_storage_key : key.storage_key} (${dataType} of ${bold(key.value_id + '')})`); }); } printCollections() { Object.values(this.storageKeys).forEach(key => { if (key.data_type === 0) { return; } const collection = this.collectionEntries[key.value_id] || []; console.log(key.clean_storage_key); console.log(collection.map(entry => entry.value_id)); }); } printEntityRefs() { Object.values(this.entityRefs).forEach(entityRef => { console.log(`${entityRef.id}: ${entityRef.entity_id} ${entityRef.entity_storage_key}`); }); } private printField(field: Field, indent: string) { const type = this.types[field.type_id]; let name = type.name; if (type.is_primitive === 0) { name = `${bold(type.id + '')}(${name})`; } switch (field.is_collection) { case SINGLETON: break; case COLLECTION: name = `[${name}]`; break; case LIST: name = `List<${name}>`; break; case INLINE_ENTITY: name = `inline ${name}`; break; case INLINE_ENTITY_COLLECTION: name = `[inline ${name}]`; break; case INLINE_ENTITY_LIST: name = `List<inline ${name}>`; break; } console.log(`${indent}${field.name}: ${name}`); field.subFields && field.subFields.forEach(field => this.printField(field, indent + ' ')); } // Generate fake entries for primitive Types because this is what we used to have. private adjustTypes() { if (!this.types[0]) { const primitives = ['Boolean', 'Number', 'Text', 'Byte', 'Short', 'Int', 'Long', 'Char', 'Float', 'Double', 'BigInt', 'Instant']; for (let i = 0; i < primitives.length; i++) { assert(!this.types[i]); this.types[i] = {id: i, name: primitives[i], is_primitive: 1}; } // b/170674301 Back when we were adding primitive types to the DB, they sometimes got left out (b/170674301). If that has happened // then the sentinel type needs to be reconstructed. if (!this.types[1000000]) { console.warn(`sentinel type record missing! This suggests that this is an older DB that has had b/170674301 happen.`); } this.types[1000000] = {id: 1000000, name: 'SENTINEL TYPE FOR REFERENCES', is_primitive: 1}; } } private resolveForeignKeys(dict: {}, field: string, reference: string, foreigns: {}) { Object.values(dict).forEach(item => item[reference] = foreigns[item[field]]); } private markupDictionary<T, U extends keyof T, V extends keyof T>(dict: Dictionary<T>, inField: U, outField: V, update: (i: T[U]) => T[V]) { Object.values(dict).forEach(item => this.markup(item, inField, outField, update)); } private markup<T, U extends keyof T, V extends keyof T>(element: T, inField: U, outField: V, update: (i: T[U]) => T[V]) { element[outField] = update(element[inField]); } private populateType(type: Type) { type.fields = []; type.subFields = []; if (this.fieldsByType[type.id]) { this.fieldsByType[type.id].forEach(field => { type.fields.push(field); if (field.subFields == null) { this.populateField(field); } }); } if (this.fieldsByParentType[type.id]) { this.fieldsByParentType[type.id].forEach(field => { type.subFields.push(field); if (field.subFields == null) { this.populateField(field); } }); } } private populateField(field: Field) { const t = this.types[field.type_id]; if (t.is_primitive === 1) { return; } field.subFields = []; this.fieldsByParentType[t.id].forEach(child => { field.subFields.push(child); if (child.subFields == null) { this.populateField(child); } }); } private mkTable<T>(table: string, keyName: string | string[]): Dictionary<T> { const result: Dictionary<T> = {}; this.get(`select * from ${table}`).forEach(item => { let key; if (typeof(keyName) === 'string') { key = item[keyName]; } else { key = keyName.map(component => item[component]).join('.'); } result[key] = item; }); return result; } private mkSummaryTable<T>(table: string, keyName: string): Dictionary<T[]> { const result: Dictionary<T[]> = {}; this.get(`select * from ${table}`).forEach(item => { const key = item[keyName]; if (result[key] == undefined) { result[key] = []; } result[key].push(item); }); return result; } private index<T>(table: Dictionary<T>, field: string): Dictionary<T[]> { const index: Dictionary<T[]> = {}; Object.values(table).forEach(entry => { const key = entry[field]; if (index[key] == undefined) { index[key] = []; } index[key].push(entry); }); return index; } private tables(): string[] { return this.get(`select name from sqlite_master where type='table'`).map(row => row.name); } private get(query: string) { return this.db.prepare(query).all(); } } const firstBit = {parts: {}, next: 0, id: '#'}; const secondBit = {parts: {}, next: 0, id: '@'}; const thirdBit = {parts: {}, next: 0, id: '$'}; const hexBit = {parts: {}, next: 0, id: '0x'}; const entityIdParts = {0: firstBit, 2: firstBit, 4: secondBit}; const postAmbleParts = {0: thirdBit}; const dbParts = {0: hexBit, 3: firstBit, 5: firstBit, 7: secondBit}; const collectionParts = {0: hexBit}; function processStorageKey(key: string): string { if (key.startsWith('inline://{')) { let innerKey = key.substring(10, key.lastIndexOf('}')); while (innerKey.startsWith('{')) { innerKey = innerKey.substring(1, innerKey.length - 1); } innerKey = processStorageKey(innerKey); const postAmble = key.substring(key.lastIndexOf('}') + 1); const parts = postAmble.split('/'); const id0 = processPart(postAmbleParts, parts, 0); return `inline-{${innerKey}}/${id0}/${bold(parts[1])}`; } else if (key.startsWith('db://')) { const hexBit = key.substring(5, key.indexOf('@')); const rest = key.substring(key.indexOf('@') + 1); let parts = rest.split(':'); parts = [hexBit, ...parts[0].split('/'), ...parts.slice(1)]; if (parts[2] === '!') { // this is a collection key parts = [parts[0], parts[1], ...parts[3].split('/')]; const ids = mapParts(collectionParts, parts); return `db-${ids[0]}@${ids[1]}/!:${ids[2]}/${ids[3]}/${ids[4]}`; } else { const ids = mapParts(dbParts, parts); return `db-${ids[0]}@${ids[1]}/${ids[2]}:${ids[3]}:${ids[4]}:${ids[5]}:${ids[6]}:${ids[7]}:${ids[8]}`; } } return key; } function processEntityId(id: string): string { const parts = id.split(':'); if (parts.length === 0) { // inline hash or "NO REFERENCE ID" return id; } if (parts.length !== 6) { // ??? return id; } const ids = mapParts(entityIdParts, parts); return `${ids[0]}:${ids[1]}:${ids[2]}:${ids[3]}:${ids[4]}:${ids[5]}`; } function mapParts(partSpec: NumberDictionary<{parts: Dictionary<string>, next: number, id: string}>, parts: string[]) { const result = []; for (let i = 0; i < parts.length; i++) { if (i in partSpec) { result.push(processPart(partSpec, parts, i)); } else { result.push(bold(parts[i])); } } return result; } function processPart(idParts: NumberDictionary<{parts: Dictionary<string>, next: number, id: string}>, parts: string[], id: number) { if (!idParts[id].parts[parts[id]]) { idParts[id].parts[parts[id]] = color(idParts[id].id + (idParts[id].next++), idParts[id].next); } return idParts[id].parts[parts[id]]; } function color(st: string, id: number) { return `\x1b[${30 + id % 8}m${st}\x1b[0m`; } function bold(st: string) { return `\x1b[1m${st}\x1b[0m`; } function blink(st: string) { return `\x1b[1;6;31m${st}\x1b[0m`; }
the_stack
import * as path from 'path' import * as core from '@actions/core' import {URL} from 'url' import {getDownloadSpecification} from '../src/internal/download-specification' import {ContainerEntry} from '../src/internal/contracts' const artifact1Name = 'my-artifact' const artifact2Name = 'my-artifact-extra' // Populating with only the information that is necessary function getPartialContainerEntry(): ContainerEntry { return { containerId: 10, scopeIdentifier: '00000000-0000-0000-0000-000000000000', path: 'ADD_INFORMATION', itemType: 'ADD_INFORMATION', status: 'created', dateCreated: '2020-02-06T22:13:35.373Z', dateLastModified: '2020-02-06T22:13:35.453Z', createdBy: '82f0bf89-6e55-4e5a-b8b6-f75eb992578c', lastModifiedBy: '82f0bf89-6e55-4e5a-b8b6-f75eb992578c', itemLocation: 'ADD_INFORMATION', contentLocation: 'ADD_INFORMATION', contentId: '', fileLength: 100 } } function createFileEntry(entryPath: string): ContainerEntry { const newFileEntry = getPartialContainerEntry() newFileEntry.path = entryPath newFileEntry.itemType = 'file' newFileEntry.itemLocation = createItemLocation(entryPath) newFileEntry.contentLocation = createContentLocation(entryPath) return newFileEntry } function createDirectoryEntry(directoryPath: string): ContainerEntry { const newDirectoryEntry = getPartialContainerEntry() newDirectoryEntry.path = directoryPath newDirectoryEntry.itemType = 'folder' newDirectoryEntry.itemLocation = createItemLocation(directoryPath) newDirectoryEntry.contentLocation = createContentLocation(directoryPath) return newDirectoryEntry } function createItemLocation(relativePath: string): string { const itemLocation = new URL( 'https://testing/_apis/resources/Containers/10000' ) itemLocation.searchParams.append('itemPath', relativePath) itemLocation.searchParams.append('metadata', 'true') return itemLocation.toString() } function createContentLocation(relativePath: string): string { const itemLocation = new URL( 'https://testing/_apis/resources/Containers/10000' ) itemLocation.searchParams.append('itemPath', relativePath) return itemLocation.toString() } /* Represents a set of container entries for two artifacts with the following directory structure /my-artifact /file1.txt /file2.txt /dir1 /file3.txt /dir2 /dir3 /dir4 file4.txt file5.txt (no length property) file6.txt (empty file) /my-artifact-extra /file1.txt */ // main artifact const file1Path = path.join(artifact1Name, 'file1.txt') const file2Path = path.join(artifact1Name, 'file2.txt') const dir1Path = path.join(artifact1Name, 'dir1') const file3Path = path.join(dir1Path, 'file3.txt') const dir2Path = path.join(dir1Path, 'dir2') const dir3Path = path.join(dir2Path, 'dir3') const dir4Path = path.join(dir3Path, 'dir4') const file4Path = path.join(dir4Path, 'file4.txt') const file5Path = path.join(dir4Path, 'file5.txt') const file6Path = path.join(dir4Path, 'file6.txt') const rootDirectoryEntry = createDirectoryEntry(artifact1Name) const directoryEntry1 = createDirectoryEntry(dir1Path) const directoryEntry2 = createDirectoryEntry(dir2Path) const directoryEntry3 = createDirectoryEntry(dir3Path) const directoryEntry4 = createDirectoryEntry(dir4Path) const fileEntry1 = createFileEntry(file1Path) const fileEntry2 = createFileEntry(file2Path) const fileEntry3 = createFileEntry(file3Path) const fileEntry4 = createFileEntry(file4Path) const missingLengthFileEntry = createFileEntry(file5Path) missingLengthFileEntry.fileLength = undefined // one file does not have a fileLength const emptyLengthFileEntry = createFileEntry(file6Path) emptyLengthFileEntry.fileLength = 0 // empty file path // extra artifact const artifact2File1Path = path.join(artifact2Name, 'file1.txt') const rootDirectoryEntry2 = createDirectoryEntry(artifact2Name) const extraFileEntry = createFileEntry(artifact2File1Path) const artifactContainerEntries: ContainerEntry[] = [ rootDirectoryEntry, fileEntry1, fileEntry2, directoryEntry1, fileEntry3, directoryEntry2, directoryEntry3, directoryEntry4, fileEntry4, missingLengthFileEntry, emptyLengthFileEntry, rootDirectoryEntry2, extraFileEntry ] describe('Search', () => { beforeAll(async () => { // mock all output so that there is less noise when running tests jest.spyOn(console, 'log').mockImplementation(() => {}) jest.spyOn(core, 'debug').mockImplementation(() => {}) jest.spyOn(core, 'info').mockImplementation(() => {}) jest.spyOn(core, 'warning').mockImplementation(() => {}) }) it('Download Specification - Absolute Path with no root directory', () => { const testDownloadPath = path.join( __dirname, 'some', 'destination', 'folder' ) const specification = getDownloadSpecification( artifact1Name, artifactContainerEntries, testDownloadPath, false ) expect(specification.rootDownloadLocation).toEqual(testDownloadPath) expect(specification.filesToDownload.length).toEqual(5) const item1ExpectedTargetPath = path.join(testDownloadPath, 'file1.txt') const item2ExpectedTargetPath = path.join(testDownloadPath, 'file2.txt') const item3ExpectedTargetPath = path.join( testDownloadPath, 'dir1', 'file3.txt' ) const item4ExpectedTargetPath = path.join( testDownloadPath, 'dir1', 'dir2', 'dir3', 'dir4', 'file4.txt' ) const item5ExpectedTargetPath = path.join( testDownloadPath, 'dir1', 'dir2', 'dir3', 'dir4', 'file5.txt' ) const item6ExpectedTargetPath = path.join( testDownloadPath, 'dir1', 'dir2', 'dir3', 'dir4', 'file6.txt' ) const targetLocations = specification.filesToDownload.map( item => item.targetPath ) expect(targetLocations).toContain(item1ExpectedTargetPath) expect(targetLocations).toContain(item2ExpectedTargetPath) expect(targetLocations).toContain(item3ExpectedTargetPath) expect(targetLocations).toContain(item4ExpectedTargetPath) expect(targetLocations).toContain(item5ExpectedTargetPath) for (const downloadItem of specification.filesToDownload) { if (downloadItem.targetPath === item1ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file1Path) ) } else if (downloadItem.targetPath === item2ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file2Path) ) } else if (downloadItem.targetPath === item3ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file3Path) ) } else if (downloadItem.targetPath === item4ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file4Path) ) } else if (downloadItem.targetPath === item5ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file5Path) ) } else { throw new Error('this should never be reached') } } expect(specification.directoryStructure.length).toEqual(3) expect(specification.directoryStructure).toContain(testDownloadPath) expect(specification.directoryStructure).toContain( path.join(testDownloadPath, 'dir1') ) expect(specification.directoryStructure).toContain( path.join(testDownloadPath, 'dir1', 'dir2', 'dir3', 'dir4') ) expect(specification.emptyFilesToCreate.length).toEqual(1) expect(specification.emptyFilesToCreate).toContain(item6ExpectedTargetPath) }) it('Download Specification - Relative Path with no root directory', () => { const testDownloadPath = path.join('some', 'destination', 'folder') const specification = getDownloadSpecification( artifact1Name, artifactContainerEntries, testDownloadPath, false ) expect(specification.rootDownloadLocation).toEqual(testDownloadPath) expect(specification.filesToDownload.length).toEqual(5) const item1ExpectedTargetPath = path.join(testDownloadPath, 'file1.txt') const item2ExpectedTargetPath = path.join(testDownloadPath, 'file2.txt') const item3ExpectedTargetPath = path.join( testDownloadPath, 'dir1', 'file3.txt' ) const item4ExpectedTargetPath = path.join( testDownloadPath, 'dir1', 'dir2', 'dir3', 'dir4', 'file4.txt' ) const item5ExpectedTargetPath = path.join( testDownloadPath, 'dir1', 'dir2', 'dir3', 'dir4', 'file5.txt' ) const item6ExpectedTargetPath = path.join( testDownloadPath, 'dir1', 'dir2', 'dir3', 'dir4', 'file6.txt' ) const targetLocations = specification.filesToDownload.map( item => item.targetPath ) expect(targetLocations).toContain(item1ExpectedTargetPath) expect(targetLocations).toContain(item2ExpectedTargetPath) expect(targetLocations).toContain(item3ExpectedTargetPath) expect(targetLocations).toContain(item4ExpectedTargetPath) expect(targetLocations).toContain(item5ExpectedTargetPath) for (const downloadItem of specification.filesToDownload) { if (downloadItem.targetPath === item1ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file1Path) ) } else if (downloadItem.targetPath === item2ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file2Path) ) } else if (downloadItem.targetPath === item3ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file3Path) ) } else if (downloadItem.targetPath === item4ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file4Path) ) } else if (downloadItem.targetPath === item5ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file5Path) ) } else { throw new Error('this should never be reached') } } expect(specification.directoryStructure.length).toEqual(3) expect(specification.directoryStructure).toContain(testDownloadPath) expect(specification.directoryStructure).toContain( path.join(testDownloadPath, 'dir1') ) expect(specification.directoryStructure).toContain( path.join(testDownloadPath, 'dir1', 'dir2', 'dir3', 'dir4') ) expect(specification.emptyFilesToCreate.length).toEqual(1) expect(specification.emptyFilesToCreate).toContain(item6ExpectedTargetPath) }) it('Download Specification - Absolute Path with root directory', () => { const testDownloadPath = path.join( __dirname, 'some', 'destination', 'folder' ) const specification = getDownloadSpecification( artifact1Name, artifactContainerEntries, testDownloadPath, true ) expect(specification.rootDownloadLocation).toEqual( path.join(testDownloadPath, artifact1Name) ) expect(specification.filesToDownload.length).toEqual(5) const item1ExpectedTargetPath = path.join( testDownloadPath, artifact1Name, 'file1.txt' ) const item2ExpectedTargetPath = path.join( testDownloadPath, artifact1Name, 'file2.txt' ) const item3ExpectedTargetPath = path.join( testDownloadPath, artifact1Name, 'dir1', 'file3.txt' ) const item4ExpectedTargetPath = path.join( testDownloadPath, artifact1Name, 'dir1', 'dir2', 'dir3', 'dir4', 'file4.txt' ) const item5ExpectedTargetPath = path.join( testDownloadPath, artifact1Name, 'dir1', 'dir2', 'dir3', 'dir4', 'file5.txt' ) const item6ExpectedTargetPath = path.join( testDownloadPath, artifact1Name, 'dir1', 'dir2', 'dir3', 'dir4', 'file6.txt' ) const targetLocations = specification.filesToDownload.map( item => item.targetPath ) expect(targetLocations).toContain(item1ExpectedTargetPath) expect(targetLocations).toContain(item2ExpectedTargetPath) expect(targetLocations).toContain(item3ExpectedTargetPath) expect(targetLocations).toContain(item4ExpectedTargetPath) expect(targetLocations).toContain(item5ExpectedTargetPath) for (const downloadItem of specification.filesToDownload) { if (downloadItem.targetPath === item1ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file1Path) ) } else if (downloadItem.targetPath === item2ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file2Path) ) } else if (downloadItem.targetPath === item3ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file3Path) ) } else if (downloadItem.targetPath === item4ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file4Path) ) } else if (downloadItem.targetPath === item5ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file5Path) ) } else { throw new Error('this should never be reached') } } expect(specification.directoryStructure.length).toEqual(3) expect(specification.directoryStructure).toContain( path.join(testDownloadPath, artifact1Name) ) expect(specification.directoryStructure).toContain( path.join(testDownloadPath, dir1Path) ) expect(specification.directoryStructure).toContain( path.join(testDownloadPath, dir4Path) ) expect(specification.emptyFilesToCreate.length).toEqual(1) expect(specification.emptyFilesToCreate).toContain(item6ExpectedTargetPath) }) it('Download Specification - Relative Path with root directory', () => { const testDownloadPath = path.join('some', 'destination', 'folder') const specification = getDownloadSpecification( artifact1Name, artifactContainerEntries, testDownloadPath, true ) expect(specification.rootDownloadLocation).toEqual( path.join(testDownloadPath, artifact1Name) ) expect(specification.filesToDownload.length).toEqual(5) const item1ExpectedTargetPath = path.join( testDownloadPath, artifact1Name, 'file1.txt' ) const item2ExpectedTargetPath = path.join( testDownloadPath, artifact1Name, 'file2.txt' ) const item3ExpectedTargetPath = path.join( testDownloadPath, artifact1Name, 'dir1', 'file3.txt' ) const item4ExpectedTargetPath = path.join( testDownloadPath, artifact1Name, 'dir1', 'dir2', 'dir3', 'dir4', 'file4.txt' ) const item5ExpectedTargetPath = path.join( testDownloadPath, artifact1Name, 'dir1', 'dir2', 'dir3', 'dir4', 'file5.txt' ) const item6ExpectedTargetPath = path.join( testDownloadPath, artifact1Name, 'dir1', 'dir2', 'dir3', 'dir4', 'file6.txt' ) const targetLocations = specification.filesToDownload.map( item => item.targetPath ) expect(targetLocations).toContain(item1ExpectedTargetPath) expect(targetLocations).toContain(item2ExpectedTargetPath) expect(targetLocations).toContain(item3ExpectedTargetPath) expect(targetLocations).toContain(item4ExpectedTargetPath) expect(targetLocations).toContain(item5ExpectedTargetPath) for (const downloadItem of specification.filesToDownload) { if (downloadItem.targetPath === item1ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file1Path) ) } else if (downloadItem.targetPath === item2ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file2Path) ) } else if (downloadItem.targetPath === item3ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file3Path) ) } else if (downloadItem.targetPath === item4ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file4Path) ) } else if (downloadItem.targetPath === item5ExpectedTargetPath) { expect(downloadItem.sourceLocation).toEqual( createContentLocation(file5Path) ) } else { throw new Error('this should never be reached') } } expect(specification.directoryStructure.length).toEqual(3) expect(specification.directoryStructure).toContain( path.join(testDownloadPath, artifact1Name) ) expect(specification.directoryStructure).toContain( path.join(testDownloadPath, dir1Path) ) expect(specification.directoryStructure).toContain( path.join(testDownloadPath, dir4Path) ) expect(specification.emptyFilesToCreate.length).toEqual(1) expect(specification.emptyFilesToCreate).toContain(item6ExpectedTargetPath) }) })
the_stack
import { loadFromPath } from '../../src/fhirdefs/load'; import { FHIRDefinitions } from '../../src/fhirdefs/FHIRDefinitions'; import path from 'path'; import { Type } from '../../src/utils/Fishable'; import { TestFisher, loggerSpy } from '../testhelpers'; describe('FHIRDefinitions', () => { let defs: FHIRDefinitions; beforeAll(() => { defs = new FHIRDefinitions(); loadFromPath(path.join(__dirname, '..', 'testhelpers', 'testdefs'), 'r4-definitions', defs); // Supplemental R3 defs needed to test fishing for implied extensions const r3Defs = new FHIRDefinitions(true); loadFromPath(path.join(__dirname, '..', 'testhelpers', 'testdefs'), 'r3-definitions', r3Defs); defs.addSupplementalFHIRDefinitions('hl7.fhir.r3.core#3.0.2', r3Defs); // Run the dependency resources through TestFisher to force them into the testhelpers cache const fisher = new TestFisher().withFHIR(defs); fisher.fishForFHIR('Condition'); fisher.fishForFHIR('eLTSSServiceModel'); fisher.fishForFHIR('boolean'); fisher.fishForFHIR('Address'); fisher.fishForFHIR('vitalsigns'); fisher.fishForFHIR('patient-mothersMaidenName'); fisher.fishForFHIR('allergyintolerance-clinical', Type.ValueSet); fisher.fishForFHIR('allergyintolerance-clinical', Type.CodeSystem); fisher.fishForFHIR('w3c-provenance-activity-type'); }); beforeEach(() => { defs.resetPredefinedResources(); loggerSpy.reset(); }); describe('#fishForFHIR()', () => { it('should find base FHIR resources', () => { const conditionByID = defs.fishForFHIR('Condition', Type.Resource); expect(conditionByID.url).toBe('http://hl7.org/fhir/StructureDefinition/Condition'); expect(conditionByID.fhirVersion).toBe('4.0.1'); expect( defs.fishForFHIR('http://hl7.org/fhir/StructureDefinition/Condition', Type.Resource) ).toEqual(conditionByID); }); it('should find base FHIR logical models', () => { const eLTSSServiceModelByID = defs.fishForFHIR('eLTSSServiceModel', Type.Logical); expect(eLTSSServiceModelByID.url).toBe( 'http://hl7.org/fhir/us/eltss/StructureDefinition/eLTSSServiceModel' ); expect(eLTSSServiceModelByID.version).toBe('0.1.0'); expect( defs.fishForFHIR( 'http://hl7.org/fhir/us/eltss/StructureDefinition/eLTSSServiceModel', Type.Logical ) ).toEqual(eLTSSServiceModelByID); }); it('should find base FHIR primitive types', () => { const booleanByID = defs.fishForFHIR('boolean', Type.Type); expect(booleanByID.url).toBe('http://hl7.org/fhir/StructureDefinition/boolean'); expect(booleanByID.fhirVersion).toBe('4.0.1'); expect( defs.fishForFHIR('http://hl7.org/fhir/StructureDefinition/boolean', Type.Type) ).toEqual(booleanByID); }); it('should find base FHIR complex types', () => { const addressByID = defs.fishForFHIR('Address', Type.Type); expect(addressByID.url).toBe('http://hl7.org/fhir/StructureDefinition/Address'); expect(addressByID.fhirVersion).toBe('4.0.1'); expect( defs.fishForFHIR('http://hl7.org/fhir/StructureDefinition/Address', Type.Type) ).toEqual(addressByID); }); it('should find base FHIR profiles', () => { const vitalSignsByID = defs.fishForFHIR('vitalsigns', Type.Profile); expect(vitalSignsByID.url).toBe('http://hl7.org/fhir/StructureDefinition/vitalsigns'); expect(vitalSignsByID.fhirVersion).toBe('4.0.1'); expect(defs.fishForFHIR('observation-vitalsigns', Type.Profile)).toEqual(vitalSignsByID); expect( defs.fishForFHIR('http://hl7.org/fhir/StructureDefinition/vitalsigns', Type.Profile) ).toEqual(vitalSignsByID); }); it('should find base FHIR profiles of logical models', () => { const serviceProfileByID = defs.fishForFHIR('service-profile', Type.Profile); expect(serviceProfileByID.url).toBe( 'http://hl7.org/fhir/some/example/StructureDefinition/ServiceProfile' ); expect(serviceProfileByID.fhirVersion).toBe('4.0.1'); expect(defs.fishForFHIR('ServiceProfile', Type.Profile)).toEqual(serviceProfileByID); expect( defs.fishForFHIR( 'http://hl7.org/fhir/some/example/StructureDefinition/ServiceProfile', Type.Profile ) ).toEqual(serviceProfileByID); }); it('should find base FHIR extensions', () => { const maidenNameExtensionByID = defs.fishForFHIR('patient-mothersMaidenName', Type.Extension); expect(maidenNameExtensionByID.url).toBe( 'http://hl7.org/fhir/StructureDefinition/patient-mothersMaidenName' ); expect(maidenNameExtensionByID.fhirVersion).toBe('4.0.1'); expect(defs.fishForFHIR('mothersMaidenName', Type.Extension)).toEqual( maidenNameExtensionByID ); expect( defs.fishForFHIR( 'http://hl7.org/fhir/StructureDefinition/patient-mothersMaidenName', Type.Extension ) ).toEqual(maidenNameExtensionByID); }); it('should find implied extensions from other versions of FHIR', () => { // See: http://hl7.org/fhir/versions.html#extensions const patientAnimalExtensionSTU3 = defs.fishForFHIR( 'http://hl7.org/fhir/3.0/StructureDefinition/extension-Patient.animal', Type.Extension ); // Just do a spot check as the detailed behavior is tested in the implied extension tests. expect(patientAnimalExtensionSTU3).toMatchObject({ resourceType: 'StructureDefinition', id: 'extension-Patient.animal', url: 'http://hl7.org/fhir/3.0/StructureDefinition/extension-Patient.animal', version: '3.0.2', name: 'Extension_Patient_animal', title: 'Implied extension for Patient.animal', description: 'Implied extension for Patient.animal', fhirVersion: '4.0.1' }); const diffRoot = patientAnimalExtensionSTU3.differential?.element?.[0]; expect(diffRoot.short).toEqual('This patient is known to be an animal (non-human)'); }); it('should not find implied extensions for versions of FHIR that are not loaded', () => { const patientAnimalExtensionDSTU2 = defs.fishForFHIR( 'http://hl7.org/fhir/1.0/StructureDefinition/extension-Patient.animal', Type.Extension ); expect(patientAnimalExtensionDSTU2).toBeUndefined(); expect(loggerSpy.getLastMessage('error')).toMatch( /The extension http:\/\/hl7\.org\/fhir\/1\.0\/StructureDefinition\/extension-Patient\.animal requires/ ); }); it('should find base FHIR value sets', () => { const allergyStatusValueSetByID = defs.fishForFHIR( 'allergyintolerance-clinical', Type.ValueSet ); expect(allergyStatusValueSetByID.url).toBe( 'http://hl7.org/fhir/ValueSet/allergyintolerance-clinical' ); // For some reason, value sets don't specify a fhirVersion, but in this case the business // version is the FHIR version, so we'll verify that instead expect(allergyStatusValueSetByID.version).toBe('4.0.1'); expect(defs.fishForFHIR('AllergyIntoleranceClinicalStatusCodes', Type.ValueSet)).toEqual( allergyStatusValueSetByID ); expect( defs.fishForFHIR('http://hl7.org/fhir/ValueSet/allergyintolerance-clinical', Type.ValueSet) ).toEqual(allergyStatusValueSetByID); }); it('should find base FHIR code sytems', () => { // Surprise! It turns out that the AllergyIntolerance status value set and code system // have the same ID! const allergyStatusCodeSystemByID = defs.fishForFHIR( 'allergyintolerance-clinical', Type.CodeSystem ); expect(allergyStatusCodeSystemByID.url).toBe( 'http://terminology.hl7.org/CodeSystem/allergyintolerance-clinical' ); // For some reason, code systems don't specify a fhirVersion, but in this case the business // version is the FHIR version, so we'll verify that instead expect(allergyStatusCodeSystemByID.version).toBe('4.0.1'); expect(defs.fishForFHIR('AllergyIntoleranceClinicalStatusCodes', Type.CodeSystem)).toEqual( allergyStatusCodeSystemByID ); expect( defs.fishForFHIR( 'http://terminology.hl7.org/CodeSystem/allergyintolerance-clinical', Type.CodeSystem ) ).toEqual(allergyStatusCodeSystemByID); }); it('should find definitions by the type order supplied', () => { // NOTE: There are two things with id allergyintolerance-clinical (the ValueSet and CodeSystem) const allergyStatusValueSetByID = defs.fishForFHIR( 'allergyintolerance-clinical', Type.ValueSet, Type.CodeSystem ); expect(allergyStatusValueSetByID.resourceType).toBe('ValueSet'); const allergyStatusCodeSystemByID = defs.fishForFHIR( 'allergyintolerance-clinical', Type.CodeSystem, Type.ValueSet ); expect(allergyStatusCodeSystemByID.resourceType).toBe('CodeSystem'); }); it('should not find the definition when the type is not requested', () => { const conditionByID = defs.fishForFHIR( 'Condition', Type.Logical, Type.Type, Type.Profile, Type.Extension, Type.ValueSet, Type.CodeSystem, Type.Instance ); expect(conditionByID).toBeUndefined(); const booleanByID = defs.fishForFHIR( 'boolean', Type.Resource, Type.Logical, Type.Profile, Type.Extension, Type.ValueSet, Type.CodeSystem, Type.Instance ); expect(booleanByID).toBeUndefined(); const addressByID = defs.fishForFHIR( 'Address', Type.Resource, Type.Logical, Type.Profile, Type.Extension, Type.ValueSet, Type.CodeSystem, Type.Instance ); expect(addressByID).toBeUndefined(); const vitalSignsProfileByID = defs.fishForFHIR( 'vitalsigns', Type.Resource, Type.Logical, Type.Type, Type.Extension, Type.ValueSet, Type.CodeSystem, Type.Instance ); expect(vitalSignsProfileByID).toBeUndefined(); const maidenNameExtensionByID = defs.fishForFHIR( 'patient-mothersMaidenName', Type.Resource, Type.Logical, Type.Type, Type.Profile, Type.ValueSet, Type.CodeSystem, Type.Instance ); expect(maidenNameExtensionByID).toBeUndefined(); // NOTE: There are two things with id allergyintolerance-clinical (the ValueSet and CodeSystem) const allergyStatusValueSetByID = defs.fishForFHIR( 'allergyintolerance-clinical', Type.Resource, Type.Logical, Type.Type, Type.Profile, Type.Extension, Type.Instance ); expect(allergyStatusValueSetByID).toBeUndefined(); const w3cProvenanceCodeSystemByID = defs.fishForFHIR( 'w3c-provenance-activity-type', Type.Resource, Type.Logical, Type.Type, Type.Profile, Type.Extension, Type.ValueSet, Type.Instance ); expect(w3cProvenanceCodeSystemByID).toBeUndefined(); const eLTSSServiceModelByID = defs.fishForFHIR( 'eLTSSServiceModel', Type.Resource, Type.Type, Type.Profile, Type.Extension, Type.ValueSet, Type.Instance ); expect(eLTSSServiceModelByID).toBeUndefined(); }); it('should globally find any definition', () => { const conditionByID = defs.fishForFHIR('Condition'); expect(conditionByID.kind).toBe('resource'); expect(conditionByID.fhirVersion).toBe('4.0.1'); expect(defs.fishForFHIR('http://hl7.org/fhir/StructureDefinition/Condition')).toEqual( conditionByID ); const booleanByID = defs.fishForFHIR('boolean'); expect(booleanByID.kind).toBe('primitive-type'); expect(booleanByID.fhirVersion).toBe('4.0.1'); expect(defs.fishForFHIR('http://hl7.org/fhir/StructureDefinition/boolean')).toEqual( booleanByID ); const addressByID = defs.fishForFHIR('Address'); expect(addressByID.kind).toBe('complex-type'); expect(addressByID.fhirVersion).toBe('4.0.1'); expect(defs.fishForFHIR('http://hl7.org/fhir/StructureDefinition/Address')).toEqual( addressByID ); const vitalSignsProfileByID = defs.fishForFHIR('vitalsigns'); expect(vitalSignsProfileByID.type).toBe('Observation'); expect(vitalSignsProfileByID.kind).toBe('resource'); expect(vitalSignsProfileByID.derivation).toBe('constraint'); expect(vitalSignsProfileByID.fhirVersion).toBe('4.0.1'); expect(defs.fishForFHIR('observation-vitalsigns')).toEqual(vitalSignsProfileByID); expect(defs.fishForFHIR('http://hl7.org/fhir/StructureDefinition/vitalsigns')).toEqual( vitalSignsProfileByID ); const maidenNameExtensionByID = defs.fishForFHIR('patient-mothersMaidenName'); expect(maidenNameExtensionByID.type).toBe('Extension'); expect(maidenNameExtensionByID.fhirVersion).toBe('4.0.1'); expect(defs.fishForFHIR('mothersMaidenName')).toEqual(maidenNameExtensionByID); expect( defs.fishForFHIR('http://hl7.org/fhir/StructureDefinition/patient-mothersMaidenName') ).toEqual(maidenNameExtensionByID); // NOTE: There are two things with id allergyintolerance-clinical (the ValueSet and CodeSystem) // When doing a non-type-specific search, we favor the ValueSet const allergyStatusValueSetByID = defs.fishForFHIR('allergyintolerance-clinical'); expect(allergyStatusValueSetByID.resourceType).toBe('ValueSet'); // For some reason, value sets don't specify a fhirVersion, but in this case the business // version is the FHIR version, so we'll verify that instead expect(allergyStatusValueSetByID.version).toBe('4.0.1'); expect(defs.fishForFHIR('AllergyIntoleranceClinicalStatusCodes')).toEqual( allergyStatusValueSetByID ); expect(defs.fishForFHIR('http://hl7.org/fhir/ValueSet/allergyintolerance-clinical')).toEqual( allergyStatusValueSetByID ); const w3cProvenanceCodeSystemByID = defs.fishForFHIR('w3c-provenance-activity-type'); expect(w3cProvenanceCodeSystemByID.resourceType).toBe('CodeSystem'); // For some reason, code systems don't specify a fhirVersion, but in this case the business // version is the FHIR version, so we'll verify that instead expect(w3cProvenanceCodeSystemByID.version).toBe('4.0.1'); expect(defs.fishForFHIR('W3cProvenanceActivityType')).toEqual(w3cProvenanceCodeSystemByID); expect(defs.fishForFHIR('http://hl7.org/fhir/w3c-provenance-activity-type')).toEqual( w3cProvenanceCodeSystemByID ); const eLTSSServiceModelByID = defs.fishForFHIR('eLTSSServiceModel'); expect(eLTSSServiceModelByID.kind).toBe('logical'); expect(eLTSSServiceModelByID.derivation).toBe('specialization'); expect( defs.fishForFHIR('http://hl7.org/fhir/us/eltss/StructureDefinition/eLTSSServiceModel') ).toEqual(eLTSSServiceModelByID); }); }); describe('#fishForMetadata()', () => { it('should find base FHIR resources', () => { const conditionByID = defs.fishForMetadata('Condition', Type.Resource); expect(conditionByID).toEqual({ abstract: false, id: 'Condition', name: 'Condition', sdType: 'Condition', url: 'http://hl7.org/fhir/StructureDefinition/Condition', parent: 'http://hl7.org/fhir/StructureDefinition/DomainResource', resourceType: 'StructureDefinition' }); expect( defs.fishForMetadata('http://hl7.org/fhir/StructureDefinition/Condition', Type.Resource) ).toEqual(conditionByID); }); it('should find base FHIR logical models', () => { const eLTSSServiceModelByID = defs.fishForMetadata('eLTSSServiceModel', Type.Logical); expect(eLTSSServiceModelByID).toEqual({ abstract: false, id: 'eLTSSServiceModel', name: 'ELTSSServiceModel', sdType: 'eLTSSServiceModel', url: 'http://hl7.org/fhir/us/eltss/StructureDefinition/eLTSSServiceModel', parent: 'http://hl7.org/fhir/StructureDefinition/Element', resourceType: 'StructureDefinition' }); expect( defs.fishForMetadata( 'http://hl7.org/fhir/us/eltss/StructureDefinition/eLTSSServiceModel', Type.Logical ) ).toEqual(eLTSSServiceModelByID); }); it('should find base FHIR primitive types', () => { const booleanByID = defs.fishForMetadata('boolean', Type.Type); expect(booleanByID).toEqual({ abstract: false, id: 'boolean', name: 'boolean', sdType: 'boolean', url: 'http://hl7.org/fhir/StructureDefinition/boolean', parent: 'http://hl7.org/fhir/StructureDefinition/Element', resourceType: 'StructureDefinition' }); expect( defs.fishForMetadata('http://hl7.org/fhir/StructureDefinition/boolean', Type.Type) ).toEqual(booleanByID); }); it('should find base FHIR complex types', () => { const addressByID = defs.fishForMetadata('Address', Type.Type); expect(addressByID).toEqual({ abstract: false, id: 'Address', name: 'Address', sdType: 'Address', url: 'http://hl7.org/fhir/StructureDefinition/Address', parent: 'http://hl7.org/fhir/StructureDefinition/Element', resourceType: 'StructureDefinition' }); expect( defs.fishForMetadata('http://hl7.org/fhir/StructureDefinition/Address', Type.Type) ).toEqual(addressByID); }); it('should find base FHIR profiles', () => { const vitalSignsByID = defs.fishForMetadata('vitalsigns', Type.Profile); expect(vitalSignsByID).toEqual({ abstract: false, id: 'vitalsigns', name: 'observation-vitalsigns', sdType: 'Observation', url: 'http://hl7.org/fhir/StructureDefinition/vitalsigns', parent: 'http://hl7.org/fhir/StructureDefinition/Observation', resourceType: 'StructureDefinition' }); expect(defs.fishForMetadata('observation-vitalsigns', Type.Profile)).toEqual(vitalSignsByID); expect( defs.fishForMetadata('http://hl7.org/fhir/StructureDefinition/vitalsigns', Type.Profile) ).toEqual(vitalSignsByID); }); it('should find base FHIR extensions', () => { const maidenNameExtensionByID = defs.fishForMetadata( 'patient-mothersMaidenName', Type.Extension ); expect(maidenNameExtensionByID).toEqual({ abstract: false, id: 'patient-mothersMaidenName', name: 'mothersMaidenName', sdType: 'Extension', url: 'http://hl7.org/fhir/StructureDefinition/patient-mothersMaidenName', parent: 'http://hl7.org/fhir/StructureDefinition/Extension', resourceType: 'StructureDefinition' }); expect(defs.fishForMetadata('mothersMaidenName', Type.Extension)).toEqual( maidenNameExtensionByID ); expect( defs.fishForMetadata( 'http://hl7.org/fhir/StructureDefinition/patient-mothersMaidenName', Type.Extension ) ).toEqual(maidenNameExtensionByID); }); it('should find base FHIR value sets', () => { const allergyStatusValueSetByID = defs.fishForMetadata( 'allergyintolerance-clinical', Type.ValueSet ); expect(allergyStatusValueSetByID).toEqual({ id: 'allergyintolerance-clinical', name: 'AllergyIntoleranceClinicalStatusCodes', url: 'http://hl7.org/fhir/ValueSet/allergyintolerance-clinical', resourceType: 'ValueSet' }); expect(defs.fishForMetadata('AllergyIntoleranceClinicalStatusCodes', Type.ValueSet)).toEqual( allergyStatusValueSetByID ); expect( defs.fishForMetadata( 'http://hl7.org/fhir/ValueSet/allergyintolerance-clinical', Type.ValueSet ) ).toEqual(allergyStatusValueSetByID); }); it('should find base FHIR code sytems', () => { const allergyStatusCodeSystemByID = defs.fishForMetadata( 'allergyintolerance-clinical', Type.CodeSystem ); expect(allergyStatusCodeSystemByID).toEqual({ id: 'allergyintolerance-clinical', name: 'AllergyIntoleranceClinicalStatusCodes', url: 'http://terminology.hl7.org/CodeSystem/allergyintolerance-clinical', resourceType: 'CodeSystem' }); expect( defs.fishForMetadata('AllergyIntoleranceClinicalStatusCodes', Type.CodeSystem) ).toEqual(allergyStatusCodeSystemByID); expect( defs.fishForMetadata( 'http://terminology.hl7.org/CodeSystem/allergyintolerance-clinical', Type.CodeSystem ) ).toEqual(allergyStatusCodeSystemByID); }); it('should find definitions by the type order supplied', () => { // NOTE: There are two things with id allergyintolerance-clinical (the ValueSet and CodeSystem) const allergyStatusValueSetByID = defs.fishForMetadata( 'allergyintolerance-clinical', Type.ValueSet, Type.CodeSystem ); expect(allergyStatusValueSetByID.url).toBe( 'http://hl7.org/fhir/ValueSet/allergyintolerance-clinical' ); const allergyStatusCodeSystemByID = defs.fishForMetadata( 'allergyintolerance-clinical', Type.CodeSystem, Type.ValueSet ); expect(allergyStatusCodeSystemByID.url).toBe( 'http://terminology.hl7.org/CodeSystem/allergyintolerance-clinical' ); }); it('should not find the definition when the type is not requested', () => { const conditionByID = defs.fishForMetadata( 'Condition', Type.Logical, Type.Type, Type.Profile, Type.Extension, Type.ValueSet, Type.CodeSystem, Type.Instance ); expect(conditionByID).toBeUndefined(); const booleanByID = defs.fishForMetadata( 'boolean', Type.Resource, Type.Logical, Type.Profile, Type.Extension, Type.ValueSet, Type.CodeSystem, Type.Instance ); expect(booleanByID).toBeUndefined(); const addressByID = defs.fishForMetadata( 'Address', Type.Resource, Type.Logical, Type.Profile, Type.Extension, Type.ValueSet, Type.CodeSystem, Type.Instance ); expect(addressByID).toBeUndefined(); const vitalSignsProfileByID = defs.fishForMetadata( 'vitalsigns', Type.Resource, Type.Logical, Type.Type, Type.Extension, Type.ValueSet, Type.CodeSystem, Type.Instance ); expect(vitalSignsProfileByID).toBeUndefined(); const maidenNameExtensionByID = defs.fishForMetadata( 'patient-mothersMaidenName', Type.Resource, Type.Logical, Type.Type, Type.Profile, Type.ValueSet, Type.CodeSystem, Type.Instance ); expect(maidenNameExtensionByID).toBeUndefined(); // NOTE: There are two things with id allergyintolerance-clinical (the ValueSet and CodeSystem) const allergyStatusValueSetByID = defs.fishForMetadata( 'allergyintolerance-clinical', Type.Resource, Type.Logical, Type.Type, Type.Profile, Type.Extension, Type.Instance ); expect(allergyStatusValueSetByID).toBeUndefined(); const w3cProvenanceCodeSystemByID = defs.fishForMetadata( 'w3c-provenance-activity-type', Type.Resource, Type.Logical, Type.Type, Type.Profile, Type.Extension, Type.ValueSet, Type.Instance ); expect(w3cProvenanceCodeSystemByID).toBeUndefined(); const eLTSSServiceModelByID = defs.fishForMetadata( 'eLTSSServiceModel', Type.Resource, Type.Type, Type.Profile, Type.Extension, Type.ValueSet, Type.Instance ); expect(eLTSSServiceModelByID).toBeUndefined(); }); it('should globally find any definition', () => { const conditionByID = defs.fishForMetadata('Condition'); expect(conditionByID).toEqual({ abstract: false, id: 'Condition', name: 'Condition', sdType: 'Condition', url: 'http://hl7.org/fhir/StructureDefinition/Condition', parent: 'http://hl7.org/fhir/StructureDefinition/DomainResource', resourceType: 'StructureDefinition' }); expect(defs.fishForMetadata('http://hl7.org/fhir/StructureDefinition/Condition')).toEqual( conditionByID ); const booleanByID = defs.fishForMetadata('boolean'); expect(booleanByID).toEqual({ abstract: false, id: 'boolean', name: 'boolean', sdType: 'boolean', url: 'http://hl7.org/fhir/StructureDefinition/boolean', parent: 'http://hl7.org/fhir/StructureDefinition/Element', resourceType: 'StructureDefinition' }); expect(defs.fishForMetadata('http://hl7.org/fhir/StructureDefinition/boolean')).toEqual( booleanByID ); const addressByID = defs.fishForMetadata('Address'); expect(addressByID).toEqual({ abstract: false, id: 'Address', name: 'Address', sdType: 'Address', url: 'http://hl7.org/fhir/StructureDefinition/Address', parent: 'http://hl7.org/fhir/StructureDefinition/Element', resourceType: 'StructureDefinition' }); expect(defs.fishForMetadata('http://hl7.org/fhir/StructureDefinition/Address')).toEqual( addressByID ); const vitalSignsProfileByID = defs.fishForMetadata('vitalsigns'); expect(vitalSignsProfileByID).toEqual({ abstract: false, id: 'vitalsigns', name: 'observation-vitalsigns', sdType: 'Observation', url: 'http://hl7.org/fhir/StructureDefinition/vitalsigns', parent: 'http://hl7.org/fhir/StructureDefinition/Observation', resourceType: 'StructureDefinition' }); expect(defs.fishForMetadata('observation-vitalsigns')).toEqual(vitalSignsProfileByID); expect(defs.fishForMetadata('http://hl7.org/fhir/StructureDefinition/vitalsigns')).toEqual( vitalSignsProfileByID ); const maidenNameExtensionByID = defs.fishForMetadata('patient-mothersMaidenName'); expect(maidenNameExtensionByID).toEqual({ abstract: false, id: 'patient-mothersMaidenName', name: 'mothersMaidenName', sdType: 'Extension', url: 'http://hl7.org/fhir/StructureDefinition/patient-mothersMaidenName', parent: 'http://hl7.org/fhir/StructureDefinition/Extension', resourceType: 'StructureDefinition' }); expect(defs.fishForMetadata('mothersMaidenName')).toEqual(maidenNameExtensionByID); expect( defs.fishForMetadata('http://hl7.org/fhir/StructureDefinition/patient-mothersMaidenName') ).toEqual(maidenNameExtensionByID); // NOTE: There are two things with id allergyintolerance-clinical (the ValueSet and CodeSystem) // When doing a non-type-specific search, we favor the ValueSet const allergyStatusValueSetByID = defs.fishForMetadata('allergyintolerance-clinical'); expect(allergyStatusValueSetByID).toEqual({ id: 'allergyintolerance-clinical', name: 'AllergyIntoleranceClinicalStatusCodes', url: 'http://hl7.org/fhir/ValueSet/allergyintolerance-clinical', resourceType: 'ValueSet' }); expect(defs.fishForMetadata('AllergyIntoleranceClinicalStatusCodes')).toEqual( allergyStatusValueSetByID ); expect( defs.fishForMetadata('http://hl7.org/fhir/ValueSet/allergyintolerance-clinical') ).toEqual(allergyStatusValueSetByID); const w3cProvenanceCodeSystemByID = defs.fishForMetadata('w3c-provenance-activity-type'); expect(w3cProvenanceCodeSystemByID).toEqual({ id: 'w3c-provenance-activity-type', name: 'W3cProvenanceActivityType', url: 'http://hl7.org/fhir/w3c-provenance-activity-type', resourceType: 'CodeSystem' }); expect(defs.fishForMetadata('W3cProvenanceActivityType')).toEqual( w3cProvenanceCodeSystemByID ); expect(defs.fishForMetadata('http://hl7.org/fhir/w3c-provenance-activity-type')).toEqual( w3cProvenanceCodeSystemByID ); const eLTSSServiceModelByID = defs.fishForMetadata('eLTSSServiceModel'); expect(eLTSSServiceModelByID).toEqual({ abstract: false, id: 'eLTSSServiceModel', name: 'ELTSSServiceModel', parent: 'http://hl7.org/fhir/StructureDefinition/Element', sdType: 'eLTSSServiceModel', url: 'http://hl7.org/fhir/us/eltss/StructureDefinition/eLTSSServiceModel', resourceType: 'StructureDefinition' }); expect(defs.fishForMetadata('ELTSSServiceModel')).toEqual(eLTSSServiceModelByID); expect( defs.fishForMetadata('http://hl7.org/fhir/us/eltss/StructureDefinition/eLTSSServiceModel') ).toEqual(eLTSSServiceModelByID); }); }); describe('#fishForPredefinedResource', () => { it('should not find resources that are not predefined', () => { const condition = defs.fishForFHIR('Condition'); expect(condition.id).toBe('Condition'); const predefinedCondition = defs.fishForPredefinedResource('Condition'); expect(predefinedCondition).toBeUndefined(); }); it('should not find resources that are predefined with different resourceTypes', () => { const condition = defs.fishForFHIR('Condition'); expect(condition.id).toBe('Condition'); defs.addPredefinedResource('', { resourceType: 'foo', id: condition.id, url: condition.url }); const predefinedCondition = defs.fishForPredefinedResource('Condition'); expect(predefinedCondition).toBeUndefined(); }); it('should not find resources that are predefined with different ids', () => { const condition = defs.fishForFHIR('Condition'); expect(condition.id).toBe('Condition'); defs.addPredefinedResource('', { resourceType: condition.resourceType, id: 'foo', url: condition.url }); const predefinedCondition = defs.fishForPredefinedResource('Condition'); expect(predefinedCondition).toBeUndefined(); }); it('should not find resources that are predefined with different urls', () => { const condition = defs.fishForFHIR('Condition'); expect(condition.id).toBe('Condition'); defs.addPredefinedResource('', { resourceType: condition.resourceType, id: condition.id, url: 'foo' }); const predefinedCondition = defs.fishForPredefinedResource('Condition'); expect(predefinedCondition).toBeUndefined(); }); it('should find resources that are predefined', () => { const condition = defs.fishForFHIR('Condition'); expect(condition.id).toBe('Condition'); defs.addPredefinedResource('', { resourceType: condition.resourceType, id: condition.id, url: condition.url }); const predefinedCondition = defs.fishForPredefinedResource('Condition'); expect(predefinedCondition.id).toBe('Condition'); }); }); describe('#fishForPredefinedResourceMetadata', () => { it('should not find resources that are not predefined', () => { const condition = defs.fishForFHIR('Condition'); expect(condition.id).toBe('Condition'); const predefinedCondition = defs.fishForPredefinedResourceMetadata('Condition'); expect(predefinedCondition).toBeUndefined(); }); it('should not find resources that are predefined with different resourceTypes', () => { const condition = defs.fishForFHIR('Condition'); expect(condition.id).toBe('Condition'); defs.addPredefinedResource('', { resourceType: 'foo', id: condition.id, url: condition.url }); const predefinedCondition = defs.fishForPredefinedResourceMetadata('Condition'); expect(predefinedCondition).toBeUndefined(); }); it('should not find resources that are predefined with different ids', () => { const condition = defs.fishForFHIR('Condition'); expect(condition.id).toBe('Condition'); defs.addPredefinedResource('', { resourceType: condition.resourceType, id: 'foo', url: condition.url }); const predefinedCondition = defs.fishForPredefinedResourceMetadata('Condition'); expect(predefinedCondition).toBeUndefined(); }); it('should not find resources that are predefined with different urls', () => { const condition = defs.fishForFHIR('Condition'); expect(condition.id).toBe('Condition'); defs.addPredefinedResource('', { resourceType: condition.resourceType, id: condition.id, url: 'foo' }); const predefinedCondition = defs.fishForPredefinedResourceMetadata('Condition'); expect(predefinedCondition).toBeUndefined(); }); it('should find resources that are predefined', () => { const condition = defs.fishForFHIR('Condition'); expect(condition.id).toBe('Condition'); defs.addPredefinedResource('', { resourceType: condition.resourceType, id: condition.id, url: condition.url }); const predefinedCondition = defs.fishForPredefinedResourceMetadata('Condition'); expect(predefinedCondition.id).toBe('Condition'); }); }); describe('#supplementalFHIRPackages', () => { it('should list no supplemental FHIR packages when none have been loaded', () => { const defs = new FHIRDefinitions(); expect(defs.supplementalFHIRPackages).toEqual([]); }); it('should list loaded supplemental FHIR packages', () => { const defs = new FHIRDefinitions(); // normally the loader would maintain the package array, but since we're not using the loader, we need to populate it here const r3 = new FHIRDefinitions(true); r3.packages.push('hl7.fhir.r3.core#3.0.2'); const r5 = new FHIRDefinitions(true); r5.packages.push('hl7.fhir.r5.core#current'); defs.addSupplementalFHIRDefinitions('hl7.fhir.r3.core#3.0.2', r3); defs.addSupplementalFHIRDefinitions('hl7.fhir.r5.core#current', r5); expect(defs.supplementalFHIRPackages).toEqual([ 'hl7.fhir.r3.core#3.0.2', 'hl7.fhir.r5.core#current' ]); }); }); });
the_stack
import { TypeAssertion, ObjectAssertion, AdditionalPropsMember, ValidationContext } from '../types'; import { validate, getType } from '../validator'; import { compile } from '../compiler'; import { serialize, deserialize } from '../serializer'; describe("compiler-6", function() { it("compiler-error-reporting-1", function() { const schema = compile(` @msgId('MSG_A') interface A { @msgId('MSG_A.a1') a1: string; @msgId('MSG_A.a2') a2?: number; /** Comment A.a3 */ @msgId('MSG_A.a3') a3: string[]; /** Comment A.a4 */ @msgId('MSG_A.a4') [propNames: string]: any; } /** Comment B */ @msgId('MSG_B') interface B { @msgId('MSG_B.b1') b1: boolean; /** Comment B.b2 */ @msgId('MSG_B.b2') b2: A; } @msgId('MSG_C') interface C extends A { @msgId('MSG_C.c1') c1: string; } /** Comment D */ @msgId('MSG_D') type D = string; /** Comment E */ @msgId('MSG_E') enum E { P, Q, R, } `); { expect(Array.from(schema.keys())).toEqual([ 'A', 'B', 'C', 'D', 'E', ]); } { // const ty = getType(schema, 'A'); for (const ty of [getType(deserialize(serialize(schema)), 'A'), getType(schema, 'A')]) { expect(false).toEqual(schema.get('A')?.exported as any); const rhs: TypeAssertion = { name: 'A', typeName: 'A', kind: 'object', members: [ ['a1', { name: 'a1', kind: 'primitive', primitiveName: 'string', messageId: 'MSG_A.a1', }], ['a2', { name: 'a2', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'number', messageId: 'MSG_A.a2', }, messageId: 'MSG_A.a2', }], ['a3', { name: 'a3', kind: 'repeated', min: null, max: null, repeated: { kind: 'primitive', primitiveName: 'string', }, messageId: 'MSG_A.a3', }, false, 'Comment A.a3'], ], additionalProps: [ [['string'], { kind: 'any', messageId: 'MSG_A.a4', }, false, 'Comment A.a4'], ], messageId: 'MSG_A', }; expect(ty).toEqual(rhs); } } { // const ty = getType(schema, 'B'); for (const ty of [getType(deserialize(serialize(schema)), 'B'), getType(schema, 'B')]) { expect(false).toEqual(schema.get('B')?.exported as any); const rhs: TypeAssertion = { name: 'B', typeName: 'B', kind: 'object', members: [ ['b1', { name: 'b1', kind: 'primitive', primitiveName: 'boolean', messageId: 'MSG_B.b1', }], ['b2', { name: 'b2', typeName: 'A', kind: 'object', members: [...(getType(schema, 'A') as ObjectAssertion).members], additionalProps: [...((getType(schema, 'A') as ObjectAssertion).additionalProps as AdditionalPropsMember[])], messageId: 'MSG_B.b2', }, false, 'Comment B.b2'], ], messageId: 'MSG_B', docComment: 'Comment B', }; expect(ty).toEqual(rhs); } } { // const ty = getType(schema, 'C'); for (const ty of [getType(deserialize(serialize(schema)), 'C'), getType(schema, 'C')]) { expect(false).toEqual(schema.get('C')?.exported as any); const rhs: TypeAssertion = { name: 'C', typeName: 'C', kind: 'object', members: [ ['c1', { name: 'c1', kind: 'primitive', primitiveName: 'string', messageId: 'MSG_C.c1', }], ['a1', { name: 'a1', kind: 'primitive', primitiveName: 'string', messageId: 'MSG_A.a1', }, true], ['a2', { name: 'a2', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'number', messageId: 'MSG_A.a2', }, messageId: 'MSG_A.a2', }, true], ['a3', { name: 'a3', kind: 'repeated', min: null, max: null, repeated: { kind: 'primitive', primitiveName: 'string', }, messageId: 'MSG_A.a3', }, true, 'Comment A.a3'], ], baseTypes: [ getType(schema, 'A') as any, ], additionalProps: [ [['string'], { kind: 'any', messageId: 'MSG_A.a4', }, true, 'Comment A.a4'] ], messageId: 'MSG_C', }; expect(ty).toEqual(rhs); } } { // const ty = getType(schema, 'D'); for (const ty of [getType(deserialize(serialize(schema)), 'D'), getType(schema, 'D')]) { expect(false).toEqual(schema.get('D')?.exported as any); const rhs: TypeAssertion = { name: 'D', typeName: 'D', kind: 'primitive', primitiveName: 'string', messageId: 'MSG_D', docComment: 'Comment D', }; expect(ty).toEqual(rhs); } } { // const ty = getType(schema, 'E'); for (const ty of [getType(deserialize(serialize(schema)), 'E'), getType(schema, 'E')]) { expect(false).toEqual(schema.get('E')?.exported as any); const rhs: TypeAssertion = { name: 'E', typeName: 'E', kind: 'enum', values: [ ['P', 0], ['Q', 1], ['R', 2], ], messageId: 'MSG_E', docComment: 'Comment E', }; expect(ty).toEqual(rhs); } } }); it("compiler-error-reporting-2", function() { const schema = compile(` @msgId('MSG_A') export interface A { @msgId('MSG_A.a1') a1: string; @msgId('MSG_A.a2') a2?: number; /** Comment A.a3 */ @msgId('MSG_A.a3') a3: string[]; /** Comment A.a4 */ @msgId('MSG_A.a4') [propNames: string]: any; } /** Comment B */ @msgId('MSG_B') export interface B { @msgId('MSG_B.b1') b1: boolean; /** Comment B.b2 */ @msgId('MSG_B.b2') b2: A; } @msgId('MSG_C') export interface C extends A { @msgId('MSG_C.c1') c1: string; } /** Comment D */ @msgId('MSG_D') export type D = string; /** Comment E */ @msgId('MSG_E') export enum E { P, Q, R, } `); { expect(Array.from(schema.keys())).toEqual([ 'A', 'B', 'C', 'D', 'E', ]); } { // const ty = getType(schema, 'A'); for (const ty of [getType(deserialize(serialize(schema)), 'A'), getType(schema, 'A')]) { expect(true).toEqual(schema.get('A')?.exported as any); const rhs: TypeAssertion = { name: 'A', typeName: 'A', kind: 'object', members: [ ['a1', { name: 'a1', kind: 'primitive', primitiveName: 'string', messageId: 'MSG_A.a1', }], ['a2', { name: 'a2', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'number', messageId: 'MSG_A.a2', }, messageId: 'MSG_A.a2', }], ['a3', { name: 'a3', kind: 'repeated', min: null, max: null, repeated: { kind: 'primitive', primitiveName: 'string', }, messageId: 'MSG_A.a3', }, false, 'Comment A.a3'], ], additionalProps: [ [['string'], { kind: 'any', messageId: 'MSG_A.a4', }, false, 'Comment A.a4'], ], messageId: 'MSG_A', }; expect(ty).toEqual(rhs); } } { // const ty = getType(schema, 'B'); for (const ty of [getType(deserialize(serialize(schema)), 'B'), getType(schema, 'B')]) { expect(true).toEqual(schema.get('B')?.exported as any); const rhs: TypeAssertion = { name: 'B', typeName: 'B', kind: 'object', members: [ ['b1', { name: 'b1', kind: 'primitive', primitiveName: 'boolean', messageId: 'MSG_B.b1', }], ['b2', { name: 'b2', typeName: 'A', kind: 'object', members: [...(getType(schema, 'A') as ObjectAssertion).members], additionalProps: [...((getType(schema, 'A') as ObjectAssertion).additionalProps as AdditionalPropsMember[])], messageId: 'MSG_B.b2', }, false, 'Comment B.b2'], ], messageId: 'MSG_B', docComment: 'Comment B', }; expect(ty).toEqual(rhs); } } { // const ty = getType(schema, 'C'); for (const ty of [getType(deserialize(serialize(schema)), 'C'), getType(schema, 'C')]) { expect(true).toEqual(schema.get('C')?.exported as any); const rhs: TypeAssertion = { name: 'C', typeName: 'C', kind: 'object', members: [ ['c1', { name: 'c1', kind: 'primitive', primitiveName: 'string', messageId: 'MSG_C.c1', }], ['a1', { name: 'a1', kind: 'primitive', primitiveName: 'string', messageId: 'MSG_A.a1', }, true], ['a2', { name: 'a2', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'number', messageId: 'MSG_A.a2', }, messageId: 'MSG_A.a2', }, true], ['a3', { name: 'a3', kind: 'repeated', min: null, max: null, repeated: { kind: 'primitive', primitiveName: 'string', }, messageId: 'MSG_A.a3', }, true, 'Comment A.a3'], ], baseTypes: [ getType(schema, 'A') as any, ], additionalProps: [ [['string'], { kind: 'any', messageId: 'MSG_A.a4', }, true, 'Comment A.a4'] ], messageId: 'MSG_C', }; expect(ty).toEqual(rhs); } } { // const ty = getType(schema, 'D'); for (const ty of [getType(deserialize(serialize(schema)), 'D'), getType(schema, 'D')]) { expect(true).toEqual(schema.get('D')?.exported as any); const rhs: TypeAssertion = { name: 'D', typeName: 'D', kind: 'primitive', primitiveName: 'string', messageId: 'MSG_D', docComment: 'Comment D', }; expect(ty).toEqual(rhs); } } { // const ty = getType(schema, 'E'); for (const ty of [getType(deserialize(serialize(schema)), 'E'), getType(schema, 'E')]) { expect(true).toEqual(schema.get('E')?.exported as any); const rhs: TypeAssertion = { name: 'E', typeName: 'E', kind: 'enum', values: [ ['P', 0], ['Q', 1], ['R', 2], ], messageId: 'MSG_E', docComment: 'Comment E', }; expect(ty).toEqual(rhs); } } }); it("compiler-error-reporting-3", function() { const schema = compile(` @msg('MSG_A') interface A { @msg('MSG_A.a1') a1: string; @msg('MSG_A.a2') a2?: number; /** Comment A.a3 */ @msg('MSG_A.a3') a3: string[]; /** Comment A.a4 */ @msg('MSG_A.a4') [propNames: string]: any; } /** Comment B */ @msg('MSG_B') interface B { @msg('MSG_B.b1') b1: boolean; /** Comment B.b2 */ @msg('MSG_B.b2') b2: A; } @msg('MSG_C') interface C extends A { @msg('MSG_C.c1') c1: string; } /** Comment D */ @msg('MSG_D') type D = string; /** Comment E */ @msg('MSG_E') enum E { P, Q, R, } `); { expect(Array.from(schema.keys())).toEqual([ 'A', 'B', 'C', 'D', 'E', ]); } { // const ty = getType(schema, 'A'); for (const ty of [getType(deserialize(serialize(schema)), 'A'), getType(schema, 'A')]) { expect(false).toEqual(schema.get('A')?.exported as any); const rhs: TypeAssertion = { name: 'A', typeName: 'A', kind: 'object', members: [ ['a1', { name: 'a1', kind: 'primitive', primitiveName: 'string', message: 'MSG_A.a1', }], ['a2', { name: 'a2', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'number', message: 'MSG_A.a2', }, message: 'MSG_A.a2', }], ['a3', { name: 'a3', kind: 'repeated', min: null, max: null, repeated: { kind: 'primitive', primitiveName: 'string', }, message: 'MSG_A.a3', }, false, 'Comment A.a3'], ], additionalProps: [ [['string'], { kind: 'any', message: 'MSG_A.a4', }, false, 'Comment A.a4'], ], message: 'MSG_A', }; expect(ty).toEqual(rhs); } } { // const ty = getType(schema, 'B'); for (const ty of [getType(deserialize(serialize(schema)), 'B'), getType(schema, 'B')]) { expect(false).toEqual(schema.get('B')?.exported as any); const rhs: TypeAssertion = { name: 'B', typeName: 'B', kind: 'object', members: [ ['b1', { name: 'b1', kind: 'primitive', primitiveName: 'boolean', message: 'MSG_B.b1', }], ['b2', { name: 'b2', typeName: 'A', kind: 'object', members: [...(getType(schema, 'A') as ObjectAssertion).members], additionalProps: [...((getType(schema, 'A') as ObjectAssertion).additionalProps as AdditionalPropsMember[])], message: 'MSG_B.b2', }, false, 'Comment B.b2'], ], message: 'MSG_B', docComment: 'Comment B', }; expect(ty).toEqual(rhs); } } { // const ty = getType(schema, 'C'); for (const ty of [getType(deserialize(serialize(schema)), 'C'), getType(schema, 'C')]) { expect(false).toEqual(schema.get('C')?.exported as any); const rhs: TypeAssertion = { name: 'C', typeName: 'C', kind: 'object', members: [ ['c1', { name: 'c1', kind: 'primitive', primitiveName: 'string', message: 'MSG_C.c1', }], ['a1', { name: 'a1', kind: 'primitive', primitiveName: 'string', message: 'MSG_A.a1', }, true], ['a2', { name: 'a2', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'number', message: 'MSG_A.a2', }, message: 'MSG_A.a2', }, true], ['a3', { name: 'a3', kind: 'repeated', min: null, max: null, repeated: { kind: 'primitive', primitiveName: 'string', }, message: 'MSG_A.a3', }, true, 'Comment A.a3'], ], baseTypes: [ getType(schema, 'A') as any, ], additionalProps: [ [['string'], { kind: 'any', message: 'MSG_A.a4', }, true, 'Comment A.a4'] ], message: 'MSG_C', }; expect(ty).toEqual(rhs); } } { // const ty = getType(schema, 'D'); for (const ty of [getType(deserialize(serialize(schema)), 'D'), getType(schema, 'D')]) { expect(false).toEqual(schema.get('D')?.exported as any); const rhs: TypeAssertion = { name: 'D', typeName: 'D', kind: 'primitive', primitiveName: 'string', message: 'MSG_D', docComment: 'Comment D', }; expect(ty).toEqual(rhs); } } { // const ty = getType(schema, 'E'); for (const ty of [getType(deserialize(serialize(schema)), 'E'), getType(schema, 'E')]) { expect(false).toEqual(schema.get('E')?.exported as any); const rhs: TypeAssertion = { name: 'E', typeName: 'E', kind: 'enum', values: [ ['P', 0], ['Q', 1], ['R', 2], ], message: 'MSG_E', docComment: 'Comment E', }; expect(ty).toEqual(rhs); } } }); it("compiler-error-reporting-4", function() { const schema = compile(` @msg('MSG_A') export interface A { @msg('MSG_A.a1') a1: string; @msg('MSG_A.a2') a2?: number; /** Comment A.a3 */ @msg('MSG_A.a3') a3: string[]; /** Comment A.a4 */ @msg('MSG_A.a4') [propNames: string]: any; } /** Comment B */ @msg('MSG_B') export interface B { @msg('MSG_B.b1') b1: boolean; /** Comment B.b2 */ @msg('MSG_B.b2') b2: A; } @msg('MSG_C') export interface C extends A { @msg('MSG_C.c1') c1: string; } /** Comment D */ @msg('MSG_D') export type D = string; /** Comment E */ @msg('MSG_E') export enum E { P, Q, R, } `); { expect(Array.from(schema.keys())).toEqual([ 'A', 'B', 'C', 'D', 'E', ]); } { // const ty = getType(schema, 'A'); for (const ty of [getType(deserialize(serialize(schema)), 'A'), getType(schema, 'A')]) { expect(true).toEqual(schema.get('A')?.exported as any); const rhs: TypeAssertion = { name: 'A', typeName: 'A', kind: 'object', members: [ ['a1', { name: 'a1', kind: 'primitive', primitiveName: 'string', message: 'MSG_A.a1', }], ['a2', { name: 'a2', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'number', message: 'MSG_A.a2', }, message: 'MSG_A.a2', }], ['a3', { name: 'a3', kind: 'repeated', min: null, max: null, repeated: { kind: 'primitive', primitiveName: 'string', }, message: 'MSG_A.a3', }, false, 'Comment A.a3'], ], additionalProps: [ [['string'], { kind: 'any', message: 'MSG_A.a4', }, false, 'Comment A.a4'], ], message: 'MSG_A', }; expect(ty).toEqual(rhs); } } { // const ty = getType(schema, 'B'); for (const ty of [getType(deserialize(serialize(schema)), 'B'), getType(schema, 'B')]) { expect(true).toEqual(schema.get('B')?.exported as any); const rhs: TypeAssertion = { name: 'B', typeName: 'B', kind: 'object', members: [ ['b1', { name: 'b1', kind: 'primitive', primitiveName: 'boolean', message: 'MSG_B.b1', }], ['b2', { name: 'b2', typeName: 'A', kind: 'object', members: [...(getType(schema, 'A') as ObjectAssertion).members], additionalProps: [...((getType(schema, 'A') as ObjectAssertion).additionalProps as AdditionalPropsMember[])], message: 'MSG_B.b2', }, false, 'Comment B.b2'], ], message: 'MSG_B', docComment: 'Comment B', }; expect(ty).toEqual(rhs); } } { // const ty = getType(schema, 'C'); for (const ty of [getType(deserialize(serialize(schema)), 'C'), getType(schema, 'C')]) { expect(true).toEqual(schema.get('C')?.exported as any); const rhs: TypeAssertion = { name: 'C', typeName: 'C', kind: 'object', members: [ ['c1', { name: 'c1', kind: 'primitive', primitiveName: 'string', message: 'MSG_C.c1', }], ['a1', { name: 'a1', kind: 'primitive', primitiveName: 'string', message: 'MSG_A.a1', }, true], ['a2', { name: 'a2', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'number', message: 'MSG_A.a2', }, message: 'MSG_A.a2', }, true], ['a3', { name: 'a3', kind: 'repeated', min: null, max: null, repeated: { kind: 'primitive', primitiveName: 'string', }, message: 'MSG_A.a3', }, true, 'Comment A.a3'], ], baseTypes: [ getType(schema, 'A') as any, ], additionalProps: [ [['string'], { kind: 'any', message: 'MSG_A.a4', }, true, 'Comment A.a4'] ], message: 'MSG_C', }; expect(ty).toEqual(rhs); } } { // const ty = getType(schema, 'D'); for (const ty of [getType(deserialize(serialize(schema)), 'D'), getType(schema, 'D')]) { expect(true).toEqual(schema.get('D')?.exported as any); const rhs: TypeAssertion = { name: 'D', typeName: 'D', kind: 'primitive', primitiveName: 'string', message: 'MSG_D', docComment: 'Comment D', }; expect(ty).toEqual(rhs); } } { // const ty = getType(schema, 'E'); for (const ty of [getType(deserialize(serialize(schema)), 'E'), getType(schema, 'E')]) { expect(true).toEqual(schema.get('E')?.exported as any); const rhs: TypeAssertion = { name: 'E', typeName: 'E', kind: 'enum', values: [ ['P', 0], ['Q', 1], ['R', 2], ], message: 'MSG_E', docComment: 'Comment E', }; expect(ty).toEqual(rhs); } } }); });
the_stack
* @module OrbitGT */ //package orbitgt.spatial.geom; type int8 = number; type int16 = number; type int32 = number; type float32 = number; type float64 = number; import { Bounds } from "./Bounds"; import { Coordinate } from "./Coordinate"; /** * Class Transform defines a generic 3D transformation. * * @version 1.0 November 2015 */ /** @internal */ export class Transform { /** The 16 elements (row major order) */ private _elements: Float64Array; /** * Create a new (identity) transform. */ public constructor() { this._elements = new Float64Array(16); this._elements[0] = 1.0; // m00 this._elements[1] = 0.0; // m01 this._elements[2] = 0.0; // m02 this._elements[3] = 0.0; // m03 this._elements[4] = 0.0; // m10 this._elements[5] = 1.0; // m11 this._elements[6] = 0.0; // m12 this._elements[7] = 0.0; // m13 this._elements[8] = 0.0; // m20 this._elements[9] = 0.0; // m21 this._elements[10] = 1.0; // m22 this._elements[11] = 0.0; // m23 this._elements[12] = 0.0; // m30 this._elements[13] = 0.0; // m31 this._elements[14] = 0.0; // m32 this._elements[15] = 1.0; // m33 } /** * Create a new (identity) transform. */ public static create(): Transform { return new Transform(); } /** * Create a transformation from elements. * @param elements the 16 matrix elements (row major order). * @return the transformation. */ public static fromRowMajor(elements: Float64Array): Transform { if (elements == null) return null; if (elements.length == 0) return null; let transform: Transform = new Transform(); let index: int32 = 0; for (let r: number = 0; r < 4; r++) for (let c: number = 0; c < 4; c++) transform.setElement(r, c, elements[index++]); return transform; } /** * Create a transformation from elements. * @param elements the 16 matrix elements (column major order). * @return the transformation. */ public static fromColumnMajor(elements: Float64Array): Transform { if (elements == null) return null; if (elements.length == 0) return null; let transform: Transform = new Transform(); let index: int32 = 0; for (let c: number = 0; c < 4; c++) for (let r: number = 0; r < 4; r++) transform.setElement(r, c, elements[index++]); return transform; } /** * Create a transformation from elements. * @param elements the 9 matrix elements (row major order). * @return the transformation. */ public static fromRotationElements(m00: float64, m01: float64, m02: float64, m10: float64, m11: float64, m12: float64, m20: float64, m21: float64, m22: float64): Transform { let transform: Transform = new Transform(); transform.setElement(0, 0, m00); transform.setElement(0, 1, m01); transform.setElement(0, 2, m02); transform.setElement(1, 0, m10); transform.setElement(1, 1, m11); transform.setElement(1, 2, m12); transform.setElement(2, 0, m20); transform.setElement(2, 1, m21); transform.setElement(2, 2, m22); return transform; } /** * Create a transformation from elements. * @param elements the 16 matrix elements (row major order). * @return the transformation. */ public static fromElements(m00: float64, m01: float64, m02: float64, m03: float64, m10: float64, m11: float64, m12: float64, m13: float64, m20: float64, m21: float64, m22: float64, m23: float64): Transform { let transform: Transform = Transform.fromRotationElements(m00, m01, m02, m10, m11, m12, m20, m21, m22); transform.setElement(0, 3, m03); transform.setElement(1, 3, m13); transform.setElement(2, 3, m23); return transform; } /** * Get an element. * @param index the index of the element. * @return the element. */ public get(index: int32): float64 { return this._elements[index]; } /** * Set an element. * @param index the index of the element. * @param value the value. */ public set(index: int32, value: float64): void { this._elements[index] = value; } /** * Get an element. * @param row the row index. * @param col the column index. * @return the element. */ public getElement(row: int32, col: int32): float64 { return this._elements[row * 4 + col]; } /** * Set an element. * @param row the row index. * @param col the column index. * @param value the value. */ public setElement(row: int32, col: int32, value: float64): void { this._elements[row * 4 + col] = value; } /** * Get the elements. * @return the elements (row major order). */ public getElements(): Float64Array { return this._elements; } /** * Set the elements. * @param elements the elements (row major order). */ public setElements(elements: Float64Array): void { for (let i: number = 0; i < this._elements.length; i++) this._elements[i] = elements[i]; } /** * Get the X column. * @return the X column. */ public getColumnX(): Coordinate { return new Coordinate(this.getElement(0, 0), this.getElement(1, 0), this.getElement(2, 0)); } /** * Get the Y column. * @return the Y column. */ public getColumnY(): Coordinate { return new Coordinate(this.getElement(0, 1), this.getElement(1, 1), this.getElement(2, 1)); } /** * Get the Z column. * @return the Z column. */ public getColumnZ(): Coordinate { return new Coordinate(this.getElement(0, 2), this.getElement(1, 2), this.getElement(2, 2)); } /** * Get the translation column. * @return the translation column. */ public getTranslation(): Coordinate { return new Coordinate(this.getElement(0, 3), this.getElement(1, 3), this.getElement(2, 3)); } /** * Set the translation. * @param tx the x position of the translation. * @param ty the y position of the translation. * @param tz the z position of the translation. * @return the tranformation. */ public setTranslation(tx: float64, ty: float64, tz: float64): Transform { this.setElement(0, 3, tx); this.setElement(1, 3, ty); this.setElement(2, 3, tz); return this; } /** * Clear the translation. * @return the tranformation. */ public clearTranslation(): Transform { this.setElement(0, 3, 0.0); this.setElement(1, 3, 0.0); this.setElement(2, 3, 0.0); return this; } /** * Swap two rows. * @param row1 the first row. * @param row2 the second row. */ public swapRows(row1: int32, row2: int32): void { for (let i: number = 0; i < 4; i++) { let e1: float64 = this.getElement(row1, i); let e2: float64 = this.getElement(row2, i); this.setElement(row1, i, e2); this.setElement(row2, i, e1); } } /** * Swap two columns. * @param col1 the first column. * @param col2 the second column. */ public swapColumns(col1: int32, col2: int32): void { for (let i: number = 0; i < 4; i++) { let e1: float64 = this.getElement(i, col1); let e2: float64 = this.getElement(i, col2); this.setElement(i, col1, e2); this.setElement(i, col2, e1); } } /** * Swap the YZ coordinates. */ public swapYZ(): void { let result: Transform = Transform.multiply2(this, Transform.createSwapYZ()); this.setElements(result.getElements()); } /** * Calculate the cosine of an angle. * @param angle the angle (in degrees). * @return the cosine. */ public static cos(angle: float64): float64 { /* One? */ if (angle == 0.0) return 1.0; if (angle == 360.0) return 1.0; /* Minus one? */ if (angle == 180.0) return -1.0; if (angle == -180.0) return -1.0; /* Zero? */ if (angle == 90.0) return 0.0; if (angle == -90.0) return 0.0; if (angle == 270.0) return 0.0; /* Calculate */ return Math.cos(angle / 180.0 * Math.PI); } /** * Calculate the sine of an angle. * @param angle the angle (in degrees). * @return the sine. */ public static sin(angle: float64): float64 { /* One? */ if (angle == 90.0) return 1.0; /* Minus one? */ if (angle == -90.0) return -1.0; if (angle == 270.0) return -1.0; /* Zero? */ if (angle == 0.0) return 0.0; if (angle == 360.0) return 0.0; if (angle == 180.0) return 0.0; if (angle == -180.0) return 0.0; /* Calculate */ return Math.sin(angle / 180.0 * Math.PI); } /** * Rotate around the X axis. * @param angle the rotation angle (degree). */ public rotateX(angle: float64): void { if (angle == 0.0) return; let result: Transform = Transform.multiply2(this, Transform.createRotationX(angle)); this.setElements(result.getElements()); } /** * Apply a rotation around X axis. * @param point the (mutable) point to rotate. * @param rotation the (Y->Z,counterclockwise) rotation (degrees). */ public static rotatePointX(point: Coordinate, rotation: float64): void { if (rotation == 0.0) return; let a: float64 = rotation; let dcos: float64 = Transform.cos(a); let dsin: float64 = Transform.sin(a); let ny: float64 = dcos * point.getY() - dsin * point.getZ(); let nz: float64 = dsin * point.getY() + dcos * point.getZ(); point.setXYZ(point.getX(), ny, nz); } /** * Rotate around the Y axis. * @param angle the rotation angle (degree). */ public rotateY(angle: float64): void { if (angle == 0.0) return; let result: Transform = Transform.multiply2(this, Transform.createRotationY(angle)); this.setElements(result.getElements()); } /** * Apply a rotation around Y axis. * @param point the (mutable) point to rotate. * @param rotation the (Z->X,counterclockwise) rotation (degrees). */ public static rotatePointY(point: Coordinate, rotation: float64): void { if (rotation == 0.0) return; let a: float64 = -rotation; // swapped orientation to CCW on 09/03/2012 let dcos: float64 = Transform.cos(a); let dsin: float64 = Transform.sin(a); let nx: float64 = dcos * point.getX() - dsin * point.getZ(); let nz: float64 = dsin * point.getX() + dcos * point.getZ(); point.setXYZ(nx, point.getY(), nz); } /** * Rotate around the Z axis. * @param angle the rotation angle (degree). */ public rotateZ(angle: float64): void { if (angle == 0.0) return; let result: Transform = Transform.multiply2(this, Transform.createRotationZ(angle)); this.setElements(result.getElements()); } /** * Apply a rotation around Z axis. * @param point the (mutable) point to rotate. * @param rotation the (X->Y,counterclockwise) rotation (degrees). */ public static rotatePointZ(point: Coordinate, rotation: float64): void { if (rotation == 0.0) return; let a: float64 = rotation; let dcos: float64 = Transform.cos(a); let dsin: float64 = Transform.sin(a); let nx: float64 = dcos * point.getX() - dsin * point.getY(); let ny: float64 = dsin * point.getX() + dcos * point.getY(); point.setXYZ(nx, ny, point.getZ()); } /** * Multiply two matrices. * @param a the first transform. * @param b the second transform. * @return the result transform (a x b). */ public static multiply2(a: Transform, b: Transform): Transform { /* Allow nulls */ if (a == null) a = new Transform(); if (b == null) b = new Transform(); /* Fill the destination transform "d" */ let d: Transform = new Transform(); for (let i: number = 0; i < 4; i++) { /* Get the next row from "a" */ let ai0: float64 = a.getElement(i, 0); let ai1: float64 = a.getElement(i, 1); let ai2: float64 = a.getElement(i, 2); let ai3: float64 = a.getElement(i, 3); /* Set the target row in "d" */ d.setElement(i, 0, ai0 * b.getElement(0, 0) + ai1 * b.getElement(1, 0) + ai2 * b.getElement(2, 0) + ai3 * b.getElement(3, 0)); // multiply by column(0) of "b" d.setElement(i, 1, ai0 * b.getElement(0, 1) + ai1 * b.getElement(1, 1) + ai2 * b.getElement(2, 1) + ai3 * b.getElement(3, 1)); // multiply by column(1) of "b" d.setElement(i, 2, ai0 * b.getElement(0, 2) + ai1 * b.getElement(1, 2) + ai2 * b.getElement(2, 2) + ai3 * b.getElement(3, 2)); // multiply by column(2) of "b" d.setElement(i, 3, ai0 * b.getElement(0, 3) + ai1 * b.getElement(1, 3) + ai2 * b.getElement(2, 3) + ai3 * b.getElement(3, 3)); // multiply by column(3) of "b" } /* Return the transform */ return d; } /** * Concatenate a transform. * @param transform the transform to concatenate. * @return the combined transformation. */ public concat(transform: Transform): Transform { return Transform.multiply2(this, transform); } /** * Multiply. * @param transform the transform to multiply with. */ public multiply(transform: Transform): void { let result: Transform = Transform.multiply2(this, transform); this.setElements(result.getElements()); } /** * Translate. * @param tx the x translation. * @param ty the y translation. * @param tz the z translation. */ public translate(tx: float64, ty: float64, tz: float64): void { let result: Transform = Transform.multiply2(this, Transform.createTranslation(tx, ty, tz)); this.setElements(result.getElements()); } /** * Translate. * @param point the xyz translation. */ public translatePoint(point: Coordinate): void { this.translate(point.getX(), point.getY(), point.getZ()); } /** * Scale. * @param sx the x scale. * @param sy the y scale. * @param sz the z scale. */ public scale(sx: float64, sy: float64, sz: float64): void { let result: Transform = Transform.multiply2(this, Transform.createScale(sx, sy, sz)); this.setElements(result.getElements()); } /** * Scale XYZ. * @param s the scale. */ public scale3(s: float64): void { this.scale(s, s, s); } /** * Create the inverse transform. * @return the inverse transform. */ public createInverse(): Transform { /* Get the 3x3 elements */ let a: float64 = this.getElement(0, 0); let b: float64 = this.getElement(0, 1); let c: float64 = this.getElement(0, 2); let d: float64 = this.getElement(1, 0); let e: float64 = this.getElement(1, 1); let f: float64 = this.getElement(1, 2); let g: float64 = this.getElement(2, 0); let h: float64 = this.getElement(2, 1); let i: float64 = this.getElement(2, 2); /* Invert the 3x3 matrix */ let idet: float64 = 1.0 / (a * (e * i - h * f) - b * (d * i - g * f) + c * (d * h - g * e)); let inverse: Transform = new Transform(); inverse.setElement(0, 0, (e * i - f * h) * idet); inverse.setElement(0, 1, -(b * i - c * h) * idet); inverse.setElement(0, 2, (b * f - c * e) * idet); inverse.setElement(1, 0, -(d * i - f * g) * idet); inverse.setElement(1, 1, (a * i - c * g) * idet); inverse.setElement(1, 2, -(a * f - c * d) * idet); inverse.setElement(2, 0, (d * h - e * g) * idet); inverse.setElement(2, 1, -(a * h - b * g) * idet); inverse.setElement(2, 2, (a * e - b * d) * idet); /* Invert the translation */ let t: Coordinate = new Coordinate(this.getElement(0, 3), this.getElement(1, 3), this.getElement(2, 3)); inverse.transformTo(t, t); inverse.setElement(0, 3, -t.getX()); inverse.setElement(1, 3, -t.getY()); inverse.setElement(2, 3, -t.getZ()); /* Done */ return inverse; } /** * Invert. */ public invert(): void { let result: Transform = this.createInverse(); this.setElements(result.getElements()); } /** * Create a copy. * @return a copy. */ public copy(): Transform { let copy: Transform = new Transform(); for (let i: number = 0; i < 16; i++) copy._elements[i] = this._elements[i]; return copy; } /** * Create an identity transform. * @return the transform. */ public static createIdentity(): Transform { return new Transform(); } /** * Create a translation transform. * @param tx the x translation. * @param ty the y translation. * @param tz the z translation. * @return the transform. */ public static createTranslation(tx: float64, ty: float64, tz: float64): Transform { let transform: Transform = Transform.createIdentity(); transform.setElement(0, 3, tx); transform.setElement(1, 3, ty); transform.setElement(2, 3, tz); return transform; } /** * Create a translation transform. * @param position the translation. * @return the transform. */ public static createTranslation2(position: Coordinate): Transform { return Transform.createTranslation(position.getX(), position.getY(), position.getZ()); } /** * Create a scale transform. * @param sx the x translation. * @param sy the y translation. * @param sz the z translation. * @return the transform. */ public static createScale(sx: float64, sy: float64, sz: float64): Transform { let transform: Transform = Transform.createIdentity(); transform.setElement(0, 0, sx); transform.setElement(1, 1, sy); transform.setElement(2, 2, sz); return transform; } /** * Create a rotation-round-X transform. * @param angle the rotation angle (degree). * @return the transform. */ public static createRotationX(angle: float64): Transform { let rad: float64 = (angle / 180.0 * Math.PI); let sin: float64 = (angle == 90.0) ? 1.0 : Math.sin(rad); let cos: float64 = (angle == 90.0) ? 0.0 : Math.cos(rad); let transform: Transform = Transform.createIdentity(); transform.setElement(1, 1, cos); transform.setElement(2, 1, sin); transform.setElement(1, 2, -sin); transform.setElement(2, 2, cos); return transform; } /** * Create a rotation-round-Y transform. * @param angle the rotation angle (degree). * @return the transform. */ public static createRotationY(angle: float64): Transform { let rad: float64 = (angle / 180.0 * Math.PI); let sin: float64 = Math.sin(rad); let cos: float64 = Math.cos(rad); let transform: Transform = Transform.createIdentity(); transform.setElement(0, 0, cos); transform.setElement(2, 0, -sin); transform.setElement(0, 2, sin); transform.setElement(2, 2, cos); return transform; } /** * Create a rotation-round-Z transform. * @param angle the rotation angle (degree). * @return the transform. */ public static createRotationZ(angle: float64): Transform { let rad: float64 = (angle / 180.0 * Math.PI); let sin: float64 = Math.sin(rad); let cos: float64 = Math.cos(rad); let transform: Transform = Transform.createIdentity(); transform.setElement(0, 0, cos); transform.setElement(1, 0, sin); transform.setElement(0, 1, -sin); transform.setElement(1, 1, cos); return transform; } /** * Create a swap YZ transform. * @return the transform. */ public static createSwapYZ(): Transform { let transform: Transform = Transform.createIdentity(); transform.setElement(1, 1, 0.0); transform.setElement(1, 2, 1.0); transform.setElement(2, 1, 1.0); transform.setElement(2, 2, 0.0); return transform; } /** * Create a transformation from elements. * @param elements the elements (row major order) * @return the transformation. */ public static createWithElements(elements: Float64Array): Transform { let transform: Transform = Transform.createIdentity(); transform.setElements(elements); return transform; } /** * Create a transformation from columns. * @param col0 the first column. * @param col1 the second column. * @param col2 the third column. * @param col3 the fourth column (considered zero if null). * @return the transformation. */ public static createWithColumns(col0: Coordinate, col1: Coordinate, col2: Coordinate, col3: Coordinate): Transform { let transform: Transform = Transform.createIdentity(); transform.setElement(0, 0, col0.getX()); transform.setElement(1, 0, col0.getY()); transform.setElement(2, 0, col0.getZ()); transform.setElement(0, 1, col1.getX()); transform.setElement(1, 1, col1.getY()); transform.setElement(2, 1, col1.getZ()); transform.setElement(0, 2, col2.getX()); transform.setElement(1, 2, col2.getY()); transform.setElement(2, 2, col2.getZ()); if (col3 != null) { transform.setElement(0, 3, col3.getX()); transform.setElement(1, 3, col3.getY()); transform.setElement(2, 3, col3.getZ()); } return transform; } /** * Create an orthogonal rotation from a quaternion. * @param a the first quaternion element (q1). * @param b the second quaternion element (q2). * @param c the third quaternion element (q3). * @param d the fourth quaternion element (q4). * @return the rotation matrix. */ public static fromQuaternion(a: float64, b: float64, c: float64, d: float64): Transform { // See "Quaternions and spatial rotation" section "From a quaternion to an orthogonal matrix" // at https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation // /* We should have a unit quaternion */ let len: float64 = (a * a + b * b + c * c + d * d); /* First row */ let m00: float64 = a * a + b * b - c * c - d * d; let m01: float64 = 2.0 * b * c - 2.0 * a * d; let m02: float64 = 2.0 * b * d + 2.0 * a * c; /* Second row */ let m10: float64 = 2.0 * b * c + 2.0 * a * d; let m11: float64 = a * a - b * b + c * c - d * d; let m12: float64 = 2.0 * c * d - 2.0 * a * b; /* Third row */ let m20: float64 = 2.0 * b * d - 2.0 * a * c; let m21: float64 = 2.0 * c * d + 2.0 * a * b; let m22: float64 = a * a - b * b - c * c + d * d; /* Return the rotation */ let transform: Transform = new Transform(); transform.setElement(0, 0, m00); transform.setElement(0, 1, m01); transform.setElement(0, 2, m02); transform.setElement(1, 0, m10); transform.setElement(1, 1, m11); transform.setElement(1, 2, m12); transform.setElement(2, 0, m20); transform.setElement(2, 1, m21); transform.setElement(2, 2, m22); return transform; } /** * Transform a point. * @param source the source point. * @param target the target point (can be same as source). * @return the target point. */ public transformTo(source: Coordinate, target: Coordinate): Coordinate { let sx: float64 = source.getX(); let sy: float64 = source.getY(); let sz: float64 = source.getZ(); target.x = this._elements[0] * sx + this._elements[1] * sy + this._elements[2] * sz + this._elements[3]; target.y = this._elements[4] * sx + this._elements[5] * sy + this._elements[6] * sz + this._elements[7]; target.z = this._elements[8] * sx + this._elements[9] * sy + this._elements[10] * sz + this._elements[11]; return target; } /** * Transform a point. * @param source the source point. * @return the target point. */ public transform(source: Coordinate): Coordinate { return this.transformTo(source, Coordinate.create()); } /** * Transform bounds. * @param bounds the bounds. * @return the transformed bounds. */ public transformBounds(bounds: Bounds): Bounds { /* Not valid? */ if (bounds.isValid() == false) return bounds; /* Transform all corners */ let nbounds: Bounds = new Bounds(); let point: Coordinate = Coordinate.create(); for (let i: number = 0; i < 8; i++) { /* Transform the next corner */ bounds.getCorner(i, point); this.transformTo(point, point); nbounds.add(point); } /* Return the new bounds */ return nbounds; } /** * Check if the transform matches another transform. * @param other the other transform. * @return true if same. */ public same(other: Transform): boolean { for (let i: number = 0; i < 16; i++) if (this._elements[i] != other._elements[i]) return false; return true; } /** * The standard toString method. * @see Object#toString */ public toString(): string { return "[Transform:m00=" + this._elements[0] + ",m10=" + this._elements[4] + ",m20=" + this._elements[8] + ",m01=" + this._elements[1] + ",m11=" + this._elements[5] + ",m21=" + this._elements[9] + ",m02=" + this._elements[2] + ",m12=" + this._elements[6] + ",m22=" + this._elements[10] + ",m03=" + this._elements[3] + ",m13=" + this._elements[7] + ",m23=" + this._elements[11] + "]"; } }
the_stack
import { Sequence } from "../src/source-resolver"; import { createElement } from "../src/util"; import { TextView } from "../src/text-view"; import { RangeView } from "../src/range-view"; export class SequenceView extends TextView { sequence: Sequence; searchInfo: Array<any>; phaseSelect: HTMLSelectElement; numInstructions: number; currentPhaseIndex: number; phaseIndexes: Set<number>; isShown: boolean; rangeView: RangeView; showRangeView: boolean; toggleRangeViewEl: HTMLElement; createViewElement() { const pane = document.createElement('div'); pane.setAttribute('id', "sequence"); pane.classList.add("scrollable"); pane.setAttribute("tabindex", "0"); return pane; } constructor(parentId, broker) { super(parentId, broker); this.numInstructions = 0; this.phaseIndexes = new Set<number>(); this.isShown = false; this.showRangeView = false; this.rangeView = null; this.toggleRangeViewEl = this.elementForToggleRangeView(); } attachSelection(s) { const view = this; if (!(s instanceof Set)) return; view.selectionHandler.clear(); view.blockSelectionHandler.clear(); const selected = new Array(); for (const key of s) selected.push(key); view.selectionHandler.select(selected, true); } detachSelection() { this.blockSelection.clear(); return this.selection.detachSelection(); } show() { this.currentPhaseIndex = this.phaseSelect.selectedIndex; if (!this.isShown) { this.isShown = true; this.phaseIndexes.add(this.currentPhaseIndex); this.container.appendChild(this.divNode); this.container.getElementsByClassName("graph-toolbox")[0].appendChild(this.toggleRangeViewEl); } if (this.showRangeView) this.rangeView.show(); } hide() { // A single SequenceView object is used for two phases (i.e before and after // register allocation), tracking the indexes lets the redundant hides and // shows be avoided when switching between the two. this.currentPhaseIndex = this.phaseSelect.selectedIndex; if (!this.phaseIndexes.has(this.currentPhaseIndex)) { this.isShown = false; this.container.removeChild(this.divNode); this.container.getElementsByClassName("graph-toolbox")[0].removeChild(this.toggleRangeViewEl); if (this.showRangeView) this.rangeView.hide(); } } onresize() { if (this.showRangeView) this.rangeView.onresize(); } initializeContent(data, rememberedSelection) { this.divNode.innerHTML = ''; this.sequence = data.sequence; this.searchInfo = []; this.divNode.onclick = (e: MouseEvent) => { if (!(e.target instanceof HTMLElement)) return; const instructionId = Number.parseInt(e.target.dataset.instructionId, 10); if (!instructionId) return; if (!e.shiftKey) this.broker.broadcastClear(null); this.broker.broadcastInstructionSelect(null, [instructionId], true); }; this.phaseSelect = (document.getElementById('phase-select') as HTMLSelectElement); this.currentPhaseIndex = this.phaseSelect.selectedIndex; this.addBlocks(this.sequence.blocks); const lastBlock = this.sequence.blocks[this.sequence.blocks.length - 1]; this.numInstructions = lastBlock.instructions[lastBlock.instructions.length - 1].id + 1; this.addRangeView(); this.attachSelection(rememberedSelection); this.show(); } elementForBlock(block) { const view = this; function mkLinkHandler(id, handler) { return function (e) { e.stopPropagation(); if (!e.shiftKey) { handler.clear(); } handler.select(["" + id], true); }; } function mkBlockLinkHandler(blockId) { return mkLinkHandler(blockId, view.blockSelectionHandler); } function mkOperandLinkHandler(text) { return mkLinkHandler(text, view.selectionHandler); } function elementForOperandWithSpan(span, text, searchInfo, isVirtual) { const selectionText = isVirtual ? "virt_" + text : text; span.onclick = mkOperandLinkHandler(selectionText); searchInfo.push(text); view.addHtmlElementForNodeId(selectionText, span); const container = createElement("div", ""); container.appendChild(span); return container; } function elementForOperand(operand, searchInfo) { let isVirtual = false; let className = "parameter tag clickable " + operand.type; if (operand.text[0] == 'v' && !(operand.tooltip && operand.tooltip.includes("Float"))) { isVirtual = true; className += " virtual-reg"; } const span = createElement("span", className, operand.text); if (operand.tooltip) { span.setAttribute("title", operand.tooltip); } return elementForOperandWithSpan(span, operand.text, searchInfo, isVirtual); } function elementForPhiOperand(text, searchInfo) { const span = createElement("span", "parameter tag clickable virtual-reg", text); return elementForOperandWithSpan(span, text, searchInfo, true); } function elementForInstruction(instruction, searchInfo) { const instNodeEl = createElement("div", "instruction-node"); const instId = createElement("div", "instruction-id", instruction.id); const offsets = view.sourceResolver.instructionToPcOffsets(instruction.id); instId.classList.add("clickable"); instId.dataset.instructionId = instruction.id; if (offsets) { instId.setAttribute("title", `This instruction generated gap code at pc-offset 0x${offsets.gap.toString(16)}, code at pc-offset 0x${offsets.arch.toString(16)}, condition handling at pc-offset 0x${offsets.condition.toString(16)}.`); } instNodeEl.appendChild(instId); const instContentsEl = createElement("div", "instruction-contents"); instNodeEl.appendChild(instContentsEl); // Print gap moves. const gapEl = createElement("div", "gap", "gap"); let hasGaps = false; for (const gap of instruction.gaps) { const moves = createElement("div", "comma-sep-list gap-move"); for (const move of gap) { hasGaps = true; const moveEl = createElement("div", "move"); const destinationEl = elementForOperand(move[0], searchInfo); moveEl.appendChild(destinationEl); const assignEl = createElement("div", "assign", "="); moveEl.appendChild(assignEl); const sourceEl = elementForOperand(move[1], searchInfo); moveEl.appendChild(sourceEl); moves.appendChild(moveEl); } gapEl.appendChild(moves); } if (hasGaps) { instContentsEl.appendChild(gapEl); } const instEl = createElement("div", "instruction"); instContentsEl.appendChild(instEl); if (instruction.outputs.length > 0) { const outputs = createElement("div", "comma-sep-list input-output-list"); for (const output of instruction.outputs) { const outputEl = elementForOperand(output, searchInfo); outputs.appendChild(outputEl); } instEl.appendChild(outputs); const assignEl = createElement("div", "assign", "="); instEl.appendChild(assignEl); } const text = instruction.opcode + instruction.flags; const instLabel = createElement("div", "node-label", text); if (instruction.opcode == "ArchNop" && instruction.outputs.length == 1 && instruction.outputs[0].tooltip) { instLabel.innerText = instruction.outputs[0].tooltip; } searchInfo.push(text); view.addHtmlElementForNodeId(text, instLabel); instEl.appendChild(instLabel); if (instruction.inputs.length > 0) { const inputs = createElement("div", "comma-sep-list input-output-list"); for (const input of instruction.inputs) { const inputEl = elementForOperand(input, searchInfo); inputs.appendChild(inputEl); } instEl.appendChild(inputs); } if (instruction.temps.length > 0) { const temps = createElement("div", "comma-sep-list input-output-list temps"); for (const temp of instruction.temps) { const tempEl = elementForOperand(temp, searchInfo); temps.appendChild(tempEl); } instEl.appendChild(temps); } return instNodeEl; } const sequenceBlock = createElement("div", "schedule-block"); sequenceBlock.classList.toggle("deferred", block.deferred); const blockId = createElement("div", "block-id com clickable", block.id); blockId.onclick = mkBlockLinkHandler(block.id); sequenceBlock.appendChild(blockId); const blockPred = createElement("div", "predecessor-list block-list comma-sep-list"); for (const pred of block.predecessors) { const predEl = createElement("div", "block-id com clickable", pred); predEl.onclick = mkBlockLinkHandler(pred); blockPred.appendChild(predEl); } if (block.predecessors.length > 0) sequenceBlock.appendChild(blockPred); const phis = createElement("div", "phis"); sequenceBlock.appendChild(phis); const phiLabel = createElement("div", "phi-label", "phi:"); phis.appendChild(phiLabel); const phiContents = createElement("div", "phi-contents"); phis.appendChild(phiContents); for (const phi of block.phis) { const phiEl = createElement("div", "phi"); phiContents.appendChild(phiEl); const outputEl = elementForOperand(phi.output, this.searchInfo); phiEl.appendChild(outputEl); const assignEl = createElement("div", "assign", "="); phiEl.appendChild(assignEl); for (const input of phi.operands) { const inputEl = elementForPhiOperand(input, this.searchInfo); phiEl.appendChild(inputEl); } } const instructions = createElement("div", "instructions"); for (const instruction of block.instructions) { instructions.appendChild(elementForInstruction(instruction, this.searchInfo)); } sequenceBlock.appendChild(instructions); const blockSucc = createElement("div", "successor-list block-list comma-sep-list"); for (const succ of block.successors) { const succEl = createElement("div", "block-id com clickable", succ); succEl.onclick = mkBlockLinkHandler(succ); blockSucc.appendChild(succEl); } if (block.successors.length > 0) sequenceBlock.appendChild(blockSucc); this.addHtmlElementForBlockId(block.id, sequenceBlock); return sequenceBlock; } addBlocks(blocks) { for (const block of blocks) { const blockEl = this.elementForBlock(block); this.divNode.appendChild(blockEl); } } addRangeView() { const preventRangeView = reason => { const toggleRangesInput = this.toggleRangeViewEl.firstChild as HTMLInputElement; if (this.rangeView) { toggleRangesInput.checked = false; this.toggleRangeView(toggleRangesInput); } toggleRangesInput.disabled = true; this.toggleRangeViewEl.style.textDecoration = "line-through"; this.toggleRangeViewEl.setAttribute("title", reason); }; if (this.sequence.register_allocation) { if (!this.rangeView) { this.rangeView = new RangeView(this); } const source = this.sequence.register_allocation; if (source.fixedLiveRanges.size == 0 && source.liveRanges.size == 0) { preventRangeView("No live ranges to show"); } else if (this.numInstructions >= 249) { // This is due to the css grid-column being limited to 1000 columns. // Performance issues would otherwise impose some limit. // TODO(george.wort@arm.com): Allow the user to specify an instruction range // to display that spans less than 249 instructions. preventRangeView( "Live range display is only supported for sequences with less than 249 instructions"); } if (this.showRangeView) { this.rangeView.initializeContent(this.sequence.blocks); } } else { preventRangeView("No live range data provided"); } } elementForToggleRangeView() { const toggleRangeViewEl = createElement("label", "", "show live ranges"); const toggleRangesInput = createElement("input", "range-toggle-show") as HTMLInputElement; toggleRangesInput.setAttribute("type", "checkbox"); toggleRangesInput.oninput = () => this.toggleRangeView(toggleRangesInput); toggleRangeViewEl.insertBefore(toggleRangesInput, toggleRangeViewEl.firstChild); return toggleRangeViewEl; } toggleRangeView(toggleRangesInput: HTMLInputElement) { toggleRangesInput.disabled = true; this.showRangeView = toggleRangesInput.checked; if (this.showRangeView) { this.rangeView.initializeContent(this.sequence.blocks); this.rangeView.show(); } else { this.rangeView.hide(); } window.dispatchEvent(new Event('resize')); toggleRangesInput.disabled = false; } searchInputAction(searchBar, e) { e.stopPropagation(); this.selectionHandler.clear(); const query = searchBar.value; if (query.length == 0) return; const select = []; window.sessionStorage.setItem("lastSearch", query); const reg = new RegExp(query); for (const item of this.searchInfo) { if (reg.exec(item) != null) { select.push(item); } } this.selectionHandler.select(select, true); } }
the_stack
import { mat3, mat4, vec2, vec3 } from 'gl-matrix'; import { auxiliaries } from 'webgl-operate'; import { AccumulatePass, AntiAliasingKernel, BlitPass, Camera, Canvas, Context, DefaultFramebuffer, EventProvider, ForwardSceneRenderPass, Framebuffer, Geometry, GLTFAlphaMode, GLTFLoader, GLTFPbrMaterial, GLTFPrimitive, Invalidate, Material, Navigation, NdcFillingTriangle, Program, Renderbuffer, Renderer, Shader, ShadowPass, Texture2D, TextureCube, Wizard, } from 'webgl-operate'; import { PostProcessingPass } from './postprocessingpass'; import { Scene } from './scene'; import { Demo } from '../demo'; import { DiskLight } from './arealight'; import { DepthOfFieldKernel } from './depthoffieldkernel'; import { DiffuseEnvironmentSample, LightSample, SampleManager, SpecularEnvironmentSample } from './samplemanager'; // tslint:disable:max-classes-per-file /** * @todo comment */ export class ProgressiveLightingRenderer extends Renderer { static URL = 'https://p-otto.waduhek.de'; protected _loader: GLTFLoader; protected _navigation: Navigation; protected _forwardPass: ForwardSceneRenderPass; protected _accumulatePass: AccumulatePass; protected _blitPass: BlitPass; protected _postProcessingPass: PostProcessingPass; protected _shadowPass: ShadowPass; protected _camera: Camera; protected _depthOfFieldRange: number; protected _sampleManager: SampleManager; protected _currentScene: Scene; protected _datsunScene: Scene; protected _kitchenScene: Scene; protected _skylineScene: Scene; protected _cornellScene: Scene; protected _intermediateFBO: Framebuffer; protected _colorRenderTexture: Texture2D; protected _depthRenderbuffer: Renderbuffer; protected _preDepthFBO: Framebuffer; protected _normalDepthTexture: Texture2D; protected _preDepthRenderbuffer: Renderbuffer; protected _depthProgram: Program; protected _defaultFramebuffer: Framebuffer; protected _ndcTriangle: NdcFillingTriangle; protected _program: Program; protected _shadowProgram: Program; protected _emptyTexture: Texture2D; protected _diffuseEnvironment: TextureCube; protected _specularEnvironment: TextureCube; protected _brdfLUT: Texture2D; protected _uLightSampleIndex: WebGLUniformLocation; protected _uLightFactor: WebGLUniformLocation; protected _uNumDiffuseEnvironmentSamples: WebGLUniformLocation; protected _uDiffuseEnvironmentFactor: WebGLUniformLocation; protected _uNumSpecularEnvironmentSamples: WebGLUniformLocation; protected _uSpecularEnvironmentFactor: WebGLUniformLocation; protected _uViewProjection: WebGLUniformLocation; protected _uView: WebGLUniformLocation; protected _uProjection: WebGLUniformLocation; protected _uModel: WebGLUniformLocation; protected _uNormalMatrix: WebGLUniformLocation; protected _uViewNormalMatrix: WebGLUniformLocation; protected _uCameraNearFar: WebGLUniformLocation; protected _ndcOffsetKernel: AntiAliasingKernel; protected _uNdcOffset: WebGLUniformLocation; protected _depthOfFieldKernel: DepthOfFieldKernel; protected _uCocPoint: WebGLUniformLocation; protected _uFrameNumber: WebGLUniformLocation; protected _uBaseColor: WebGLUniformLocation; protected _uBaseColorTexCoord: WebGLUniformLocation; protected _uMetallicRoughness: WebGLUniformLocation; protected _uMetallicRoughnessTexCoord: WebGLUniformLocation; protected _uNormal: WebGLUniformLocation; protected _uNormalTexCoord: WebGLUniformLocation; protected _uEmissive: WebGLUniformLocation; protected _uEmissiveTexCoord: WebGLUniformLocation; protected _uOcclusion: WebGLUniformLocation; protected _uOcclusionTexCoord: WebGLUniformLocation; protected _uEye: WebGLUniformLocation; protected _uGeometryFlags: WebGLUniformLocation; protected _uPbrFlags: WebGLUniformLocation; protected _uBaseColorFactor: WebGLUniformLocation; protected _uMetallicFactor: WebGLUniformLocation; protected _uRoughnessFactor: WebGLUniformLocation; protected _uEmissiveFactor: WebGLUniformLocation; protected _uNormalScale: WebGLUniformLocation; protected _uBlendMode: WebGLUniformLocation; protected _uBlendCutoff: WebGLUniformLocation; protected _uDiffuseEnvironment: WebGLUniformLocation; protected _uSpecularEnvironment: WebGLUniformLocation; protected _uBRDFLookupTable: WebGLUniformLocation; protected _uShadowMap: WebGLUniformLocation; protected _uLastFrame: WebGLUniformLocation; protected _uNormalDepth: WebGLUniformLocation; protected _uOcclusionRange: WebGLUniformLocation; protected _uExposure: WebGLUniformLocation; protected _uIBLStrength: WebGLUniformLocation; protected _uLightView: WebGLUniformLocation; protected _uLightProjection: WebGLUniformLocation; protected _uLightNearFar: WebGLUniformLocation; protected _uModelS: WebGLUniformLocation; protected _uViewS: WebGLUniformLocation; protected _uProjectionS: WebGLUniformLocation; protected _uLightNearFarS: WebGLUniformLocation; protected _uLightPositionS: WebGLUniformLocation; protected _uModelD: WebGLUniformLocation; protected _uProjectionD: WebGLUniformLocation; protected _uViewD: WebGLUniformLocation; protected _uCameraNearFarD: WebGLUniformLocation; /** * Initializes and sets up rendering passes, navigation, loads a font face and links shaders with program. * @param context - valid context to create the object for. * @param identifier - meaningful name for identification of this instance. * @param mouseEventProvider - required for mouse interaction * @returns - whether initialization was successful */ protected onInitialize(context: Context, callback: Invalidate, eventProvider: EventProvider): boolean { const gl = this._context.gl; const gl2facade = this._context.gl2facade; context.enable(['OES_standard_derivatives', 'WEBGL_color_buffer_float', 'OES_texture_float', 'OES_texture_float_linear']); this._loader = new GLTFLoader(this._context); this._cornellScene = new Scene(`${ProgressiveLightingRenderer.URL}/models/cornell.glb`, new Camera(vec3.fromValues(-0.255, 3.09, -8.0), vec3.fromValues(0.135, 1.192, -0.46)), 0.2, 20); this._cornellScene.addDiskLight(new DiskLight( vec3.fromValues(0.13, 2.32, -0.23), 0.15, vec3.fromValues(303, 303, 303), vec3.fromValues(0, -1, 0), 90.0)); this._skylineScene = new Scene( `${ProgressiveLightingRenderer.URL}/models/skyline.glb`, new Camera(vec3.fromValues(-4.0645, 2.816, 6.2326), vec3.fromValues(0.342, -0.42328, 0.1032)), // new Camera(vec3.fromValues(1.7162, 0.6412, 4.2596), vec3.fromValues(-0.7943, -0.17933, -0.7432)), 0.2, 20); this._skylineScene.addDiskLight(new DiskLight( vec3.fromValues(1.827, 2.5, -1.11), 0.25, vec3.fromValues(501, 501, 501), vec3.fromValues(-0.5554236173629761, -0.7600213289260864, 0.33744949102401733), 110.0)); this._skylineScene.addDiskLight(new DiskLight( vec3.fromValues(-2.03, 2.5, -1.205), 0.25, vec3.fromValues(501, 501, 501), vec3.fromValues(0.5903826355934143, -0.7270721793174744, 0.3504488170146942), 110.0)); this._skylineScene.addDiskLight(new DiskLight( vec3.fromValues(1.418, 2.5, 2.17), 0.25, vec3.fromValues(501, 501, 501), vec3.fromValues(-0.39374271035194397, -0.6941867470741272, -0.6025540828704834), 110.0)); this._skylineScene.addDiskLight(new DiskLight( vec3.fromValues(-1.642, 2.5, 1.9708), 0.25, vec3.fromValues(501, 501, 501), vec3.fromValues(0.45841217041015625, -0.6979479193687439, -0.5502063035964966), 110.0)); this._datsunScene = new Scene( `${ProgressiveLightingRenderer.URL}/models/datsun.glb`, new Camera(vec3.fromValues(-1.9631, 1.89, 6.548), vec3.fromValues(0.292, -0.327, -0.13)), 0.2, 30); this._datsunScene.addDiskLight(new DiskLight( vec3.fromValues(-3.04, 3.0, -1.4), 0.15, vec3.fromValues(901, 901, 901), vec3.fromValues(0.67636, -0.66746, 0.31148), 110.0)); this._datsunScene.addDiskLight(new DiskLight( vec3.fromValues(2.62, 3.0, -1.4), 0.15, vec3.fromValues(901, 901, 901), vec3.fromValues(-0.62057, -0.71058, 0.33160), 110.0)); this._datsunScene.addDiskLight(new DiskLight( vec3.fromValues(-2.12, 3.0, 2.1), 0.15, vec3.fromValues(901, 901, 901), vec3.fromValues(0.50102, -0.70899, -0.49629), 110.0)); this._datsunScene.addDiskLight(new DiskLight( vec3.fromValues(2.14, 3.0, 2.1), 0.15, vec3.fromValues(901, 901, 901), vec3.fromValues(-0.50454, -0.70731, -0.49511), 110.0)); this._kitchenScene = new Scene( `${ProgressiveLightingRenderer.URL}/models/kitchen.glb`, new Camera(vec3.fromValues(-0.65597, 2.2284, 6.2853), vec3.fromValues(0.24971, 1.1144, -0.7265)), // new Camera(vec3.fromValues(-3.479, 1.604, -0.5713), vec3.fromValues(0.0, 1.0673, -0.8168)), 0.1, 10); this._kitchenScene.addDiskLight(new DiskLight( vec3.fromValues(-0.54, 1.6, -1.17), 0.025, vec3.fromValues(5001, 5001, 5001), vec3.fromValues(0, -1, 0), 160.0)); this._kitchenScene.addDiskLight(new DiskLight( vec3.fromValues(0.88, 1.6, -1.17), 0.025, vec3.fromValues(5001, 5001, 5001), vec3.fromValues(0, -1, 0), 160.0)); this._kitchenScene.addDiskLight(new DiskLight( vec3.fromValues(1.62, 1.6, -1.17), 0.025, vec3.fromValues(5001, 5001, 5001), vec3.fromValues(0, -1, 0), 160.0)); this._kitchenScene.addDiskLight(new DiskLight( vec3.fromValues(0.16, 1.6, -1.17), 0.025, vec3.fromValues(5001, 5001, 5001), vec3.fromValues(0, -1, 0), 160.0)); this._kitchenScene.addDiskLight(new DiskLight( vec3.fromValues(1.92, 1.6, -0.86), 0.025, vec3.fromValues(5001, 5001, 5001), vec3.fromValues(0, -1, 0), 160.0)); this._kitchenScene.addDiskLight(new DiskLight( vec3.fromValues(1.92, 1.6, -0.22), 0.025, vec3.fromValues(5001, 5001, 5001), vec3.fromValues(0, -1, 0), 160.0)); this._emptyTexture = new Texture2D(this._context, 'EmptyTexture'); this._emptyTexture.initialize(1, 1, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE); this._defaultFramebuffer = new DefaultFramebuffer(this._context, 'DefaultFBO'); this._defaultFramebuffer.initialize(); this._ndcTriangle = new NdcFillingTriangle(this._context); this._ndcTriangle.initialize(); /* Initialize program, we do not use the default gltf shader here */ const vert = new Shader(this._context, gl.VERTEX_SHADER, 'mesh.vert'); vert.initialize(require('./data/mesh.vert')); const frag = new Shader(this._context, gl.FRAGMENT_SHADER, 'progressive_lighting.frag'); frag.initialize(require('./data/progressive_lighting.frag')); this._program = new Program(this._context, 'ProgressiveLightingProgram'); this._program.initialize([vert, frag]); this._uViewProjection = this._program.uniform('u_viewProjection'); this._uView = this._program.uniform('u_view'); this._uProjection = this._program.uniform('u_projection'); this._uModel = this._program.uniform('u_model'); this._uNormalMatrix = this._program.uniform('u_normalMatrix'); this._uViewNormalMatrix = this._program.uniform('u_viewNormalMatrix'); this._uCameraNearFar = this._program.uniform('u_cameraNearFar'); this._uBaseColor = this._program.uniform('u_baseColor'); this._uBaseColorTexCoord = this._program.uniform('u_baseColorTexCoord'); this._uMetallicRoughness = this._program.uniform('u_metallicRoughness'); this._uMetallicRoughnessTexCoord = this._program.uniform('u_metallicRoughnessTexCoord'); this._uNormal = this._program.uniform('u_normal'); this._uNormalTexCoord = this._program.uniform('u_normalTexCoord'); this._uEmissive = this._program.uniform('u_emissive'); this._uEmissiveTexCoord = this._program.uniform('u_emissiveTexCoord'); this._uOcclusion = this._program.uniform('u_occlusion'); this._uOcclusionTexCoord = this._program.uniform('u_occlusionTexCoord'); this._uNdcOffset = this._program.uniform('u_ndcOffset'); this._uFrameNumber = this._program.uniform('u_frameNumber'); this._uCocPoint = this._program.uniform('u_cocPoint'); this._uEye = this._program.uniform('u_eye'); this._uGeometryFlags = this._program.uniform('u_geometryFlags'); this._uPbrFlags = this._program.uniform('u_pbrFlags'); this._uBaseColorFactor = this._program.uniform('u_baseColorFactor'); this._uMetallicFactor = this._program.uniform('u_metallicFactor'); this._uRoughnessFactor = this._program.uniform('u_roughnessFactor'); this._uEmissiveFactor = this._program.uniform('u_emissiveFactor'); this._uNormalScale = this._program.uniform('u_normalScale'); this._uBlendMode = this._program.uniform('u_blendMode'); this._uBlendCutoff = this._program.uniform('u_blendCutoff'); this._uLightSampleIndex = this._program.uniform('u_lightSampleIndex'); this._uLightFactor = this._program.uniform('u_lightFactor'); this._uNumDiffuseEnvironmentSamples = this._program.uniform('u_numDiffuseEnvironmentSamples'); this._uDiffuseEnvironmentFactor = this._program.uniform('u_diffuseEnvironmentFactor'); this._uNumSpecularEnvironmentSamples = this._program.uniform('u_numSpecularEnvironmentSamples'); this._uSpecularEnvironmentFactor = this._program.uniform('u_specularEnvironmentFactor'); this._uDiffuseEnvironment = this._program.uniform('u_diffuseEnvironment'); this._uSpecularEnvironment = this._program.uniform('u_specularEnvironment'); this._uBRDFLookupTable = this._program.uniform('u_brdfLUT'); this._uLastFrame = this._program.uniform('u_lastFrame'); this._uShadowMap = this._program.uniform('u_shadowMap'); this._uNormalDepth = this._program.uniform('u_normalDepth'); this._uLightView = this._program.uniform('u_lightView'); this._uLightProjection = this._program.uniform('u_lightProjection'); this._uLightNearFar = this._program.uniform('u_lightNearFar'); this._uOcclusionRange = this._program.uniform('u_occlusionRange'); this._uIBLStrength = this._program.uniform('u_iblStrength'); /* Initialize shadow program */ const shadowVert = new Shader(this._context, gl.VERTEX_SHADER, 'mesh.vert'); shadowVert.initialize(require('./data/mesh.vert')); const shadowFrag = new Shader(this._context, gl.FRAGMENT_SHADER, 'shadow.frag'); shadowFrag.initialize(require('./data/shadow.frag')); this._shadowProgram = new Program(this._context, 'ShadowProgram'); this._shadowProgram.initialize([shadowVert, shadowFrag]); this._uModelS = this._shadowProgram.uniform('u_model'); this._uViewS = this._shadowProgram.uniform('u_view'); this._uProjectionS = this._shadowProgram.uniform('u_projection'); this._uLightNearFarS = this._shadowProgram.uniform('u_lightNearFar'); this._uLightPositionS = this._shadowProgram.uniform('u_lightPosition'); /* Initialize pre depth program */ const depthVert = new Shader(this._context, gl.VERTEX_SHADER, 'mesh.vert'); depthVert.initialize(require('./data/mesh.vert')); const depthFrag = new Shader(this._context, gl.FRAGMENT_SHADER, 'normal_depth.frag'); depthFrag.initialize(require('./data/normal_depth.frag')); this._depthProgram = new Program(this._context, 'NormalDepthProgram'); this._depthProgram.initialize([depthVert, depthFrag]); this._uViewD = this._depthProgram.uniform('u_view'); this._uProjectionD = this._depthProgram.uniform('u_projection'); this._uCameraNearFarD = this._depthProgram.uniform('u_cameraNearFar'); this._uModelD = this._depthProgram.uniform('u_model'); /* Camera will be setup by the scenes */ this._camera = new Camera(); /* Create and configure navigation */ this._navigation = new Navigation(callback, eventProvider); this._navigation.camera = this._camera; /** * Setup intermediate FBO and textures */ this._colorRenderTexture = new Texture2D(this._context, 'ColorRenderTexture'); this._depthRenderbuffer = new Renderbuffer(this._context, 'DepthRenderbuffer'); this._intermediateFBO = new Framebuffer(this._context, 'IntermediateFBO'); /** * Setup pre depth FBO */ this._preDepthFBO = new Framebuffer(this._context, 'PreDepthFBO'); this._normalDepthTexture = new Texture2D(this._context, 'NormalDepthTexture'); this._preDepthRenderbuffer = new Renderbuffer(this._context, 'PreDepthRenderbuffer'); /* Create and configure forward pass. */ this._forwardPass = new ForwardSceneRenderPass(context); this._forwardPass.initialize(); this._forwardPass.camera = this._camera; this._forwardPass.target = this._intermediateFBO; this._forwardPass.program = this._program; this._forwardPass.updateViewProjectionTransform = (matrix: mat4) => { gl.uniformMatrix4fv(this._uViewProjection, gl.FALSE, matrix); }; this._accumulatePass = new AccumulatePass(context); this._accumulatePass.initialize(this._ndcTriangle); this._accumulatePass.precision = Wizard.Precision.float; this._accumulatePass.texture = this._colorRenderTexture; this._postProcessingPass = new PostProcessingPass(context); this._postProcessingPass.initialize(this._ndcTriangle); this._shadowPass = new ShadowPass(context); this._shadowPass.initialize(ShadowPass.ShadowMappingType.HardLinear, [2048, 2048]); this._blitPass = new BlitPass(this._context); this._blitPass.initialize(this._ndcTriangle); this._blitPass.framebuffer = this._postProcessingPass.framebuffer; this._blitPass.readBuffer = gl2facade.COLOR_ATTACHMENT0; this._blitPass.target = this._defaultFramebuffer; this._blitPass.drawBuffer = gl.BACK; /** * Start loading environment. */ this.loadEnvironmentMap(); /** * Setup debugging widgets. */ const assetSelect = window.document.getElementById('asset-select')! as HTMLSelectElement; assetSelect.onchange = (_) => { this.loadAsset(); }; const environmentSelect = window.document.getElementById('environment-select')! as HTMLSelectElement; environmentSelect.onchange = (_) => { this.loadEnvironmentMap(); this._invalidate(true); }; const debugSelect = window.document.getElementById('debug-select')! as HTMLSelectElement; debugSelect.onchange = (_) => { this.setDebugMode(); this._invalidate(true); }; const exposureRange = window.document.getElementById('exposure-range')! as HTMLInputElement; exposureRange.onchange = (_) => { this._postProcessingPass.exposure = parseFloat(exposureRange.value) / 10.0; this._invalidate(true); }; const iblRange = window.document.getElementById('ibl-range')! as HTMLInputElement; iblRange.onchange = (_) => { this._program.bind(); gl.uniform1f(this._uIBLStrength, parseFloat(iblRange.value) / 20.0); this._program.unbind(); this._invalidate(true); }; iblRange.onchange(new Event('')); const occlusionRange = window.document.getElementById('occlusion-range')! as HTMLInputElement; occlusionRange.onchange = (_) => { this._program.bind(); gl.uniform1f(this._uOcclusionRange, parseFloat(occlusionRange.value) / 300.0); this._program.unbind(); this._invalidate(true); }; occlusionRange.onchange(new Event('')); const dofRange = window.document.getElementById('dof-range')! as HTMLInputElement; dofRange.onchange = (_) => { this._depthOfFieldRange = parseFloat(dofRange.value) / 1000.0; this._invalidate(true); }; dofRange.onchange(new Event('')); return true; } /** * Uninitializes Buffers, Textures, and Program. */ protected onUninitialize(): void { super.uninitialize(); // TODO: make sure that all meshes and programs inside of the scene get cleaned // this._mesh.uninitialize(); // this._meshProgram.uninitialize(); } protected onDiscarded(): void { this._altered.alter('canvasSize'); this._altered.alter('clearColor'); this._altered.alter('frameSize'); this._altered.alter('multiFrameNumber'); } /** * This is invoked in order to check if rendering of a frame is required by means of implementation specific * evaluation (e.g., lazy non continuous rendering). Regardless of the return value a new frame (preparation, * frame, swap) might be invoked anyway, e.g., when update is forced or canvas or context properties have * changed or the renderer was invalidated @see{@link invalidate}. * Updates the navigaten and the AntiAliasingKernel. * @returns whether to redraw */ protected onUpdate(): boolean { if (this._altered.frameSize || this._camera.altered) { this._camera.viewport = [this._frameSize[0], this._frameSize[1]]; } if (this._altered.canvasSize || this._camera.altered) { this._camera.aspect = this._canvasSize[0] / this._canvasSize[1]; } this._navigation.update(); this._forwardPass.update(); return this._altered.any || this._camera.altered; } /** * This is invoked in order to prepare rendering of one or more frames, regarding multi-frame rendering and * camera-updates. */ protected onPrepare(): void { const gl = this._context.gl; const gl2facade = this._context.gl2facade; if (this._forwardPass.scene === undefined) { this.loadAsset(); } const lightSampleCount = Math.round(this._multiFrameNumber / this._currentScene.diskLights.length / 4.0); const environmentSampleCount = Math.round(this._multiFrameNumber); this._sampleManager = new SampleManager( this._currentScene, this._multiFrameNumber, lightSampleCount, environmentSampleCount); if (!this._intermediateFBO.initialized) { this._colorRenderTexture.initialize(this._frameSize[0], this._frameSize[1], this._context.isWebGL2 ? gl.RGBA32F : gl.RGBA, gl.RGBA, gl.FLOAT); this._depthRenderbuffer.initialize(this._frameSize[0], this._frameSize[1], gl.DEPTH_COMPONENT16); this._intermediateFBO.initialize([[gl2facade.COLOR_ATTACHMENT0, this._colorRenderTexture] , [gl.DEPTH_ATTACHMENT, this._depthRenderbuffer]]); } if (!this._preDepthFBO.initialized) { this._normalDepthTexture.initialize(this._frameSize[0], this._frameSize[1], this._context.isWebGL2 ? gl.RGBA32F : gl.RGBA, this._context.isWebGL2 ? gl.RGBA : gl.RGBA, gl.FLOAT); this._preDepthRenderbuffer.initialize(this._frameSize[0], this._frameSize[1], gl.DEPTH_COMPONENT16); this._preDepthFBO.initialize([[gl2facade.COLOR_ATTACHMENT0, this._normalDepthTexture] , [gl.DEPTH_ATTACHMENT, this._preDepthRenderbuffer]]); } if (this._altered.multiFrameNumber) { this._ndcOffsetKernel = new AntiAliasingKernel(this._multiFrameNumber); this._depthOfFieldKernel = new DepthOfFieldKernel(this._multiFrameNumber); } if (this._altered.frameSize) { this._intermediateFBO.resize(this._frameSize[0], this._frameSize[1]); this._camera.viewport = [this._frameSize[0], this._frameSize[1]]; } if (this._altered.clearColor) { this._intermediateFBO.clearColor(this._clearColor); this._forwardPass.clearColor = this._clearColor; } this._forwardPass.prepare(); this._accumulatePass.update(); this._postProcessingPass.texture = this._accumulatePass.framebuffer!.texture(gl2facade.COLOR_ATTACHMENT0)!; this._postProcessingPass.normalDepthTexture = this._normalDepthTexture; this._postProcessingPass.update(); this.bindMultiframeUniforms(); this._altered.reset(); this._camera.altered = false; } protected preDepthPass(): void { const gl = this._context.gl; this._preDepthFBO.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT, true, false); gl.viewport(0, 0, this._preDepthFBO.width, this._preDepthFBO.height); this._depthProgram.bind(); this._forwardPass.program = this._depthProgram; this._forwardPass.target = this._preDepthFBO; this._forwardPass.bindMaterial = (_: Material) => { }; this._forwardPass.bindGeometry = (_: Geometry) => { }; this._forwardPass.updateModelTransform = (matrix: mat4) => { gl.uniformMatrix4fv(this._uModelD, gl.FALSE, matrix); }; this._forwardPass.drawCalls(false); } protected shadowPass(lightIndex: number, eye: vec3): void { const gl = this._context.gl; const light = this._currentScene.diskLights[lightIndex]; const center = vec3.add(vec3.create(), eye, light.direction); const lightCamera = new Camera(); lightCamera.eye = eye; lightCamera.center = center; lightCamera.up = vec3.fromValues(1.0, 0.0, 0.0); lightCamera.near = 0.1; lightCamera.far = 30.0; lightCamera.fovy = light.fovy; const lightNearFar = vec2.fromValues(lightCamera.near, lightCamera.far); this._shadowPass.frame(() => { this._shadowProgram.bind(); gl.uniformMatrix4fv(this._uProjectionS, gl.FALSE, lightCamera.projection); gl.uniformMatrix4fv(this._uViewS, gl.FALSE, lightCamera.view); gl.uniform2fv(this._uLightNearFarS, lightNearFar); gl.uniform3fv(this._uLightPositionS, eye); this._forwardPass.bindMaterial = (_: Material) => { }; this._forwardPass.bindGeometry = (_: Geometry) => { }; this._forwardPass.updateModelTransform = (matrix: mat4) => { gl.uniformMatrix4fv(this._uModelS, gl.FALSE, matrix); }; this._forwardPass.drawCalls(false); this._shadowProgram.unbind(); }); // Update mesh programs values for shadow map application this._program.bind(); gl.uniformMatrix4fv(this._uLightView, gl.FALSE, lightCamera.view); gl.uniformMatrix4fv(this._uLightProjection, gl.FALSE, lightCamera.projection); gl.uniform2fv(this._uLightNearFar, lightNearFar); this._program.unbind(); } protected onFrame(frameNumber: number): void { if (this.isLoading) { return; } auxiliaries.assert(this._forwardPass.scene !== undefined, `Scene undefined in onFrame.`); const gl = this._context.gl; const gl2facade = this._context.gl2facade; this.prepareFrame(frameNumber); this._forwardPass.program = this._program; this._forwardPass.target = this._intermediateFBO; this._forwardPass.bindMaterial = (material: Material) => { const pbrMaterial = material as GLTFPbrMaterial; auxiliaries.assert(pbrMaterial !== undefined, `Material ${material.name} is not a PBR material.`); /** * Base color texture */ if (pbrMaterial.baseColorTexture !== undefined) { pbrMaterial.baseColorTexture.bind(gl.TEXTURE0); gl.uniform1i(this._uBaseColorTexCoord, pbrMaterial.baseColorTexCoord); } else { this._emptyTexture.bind(gl.TEXTURE0); } /** * Metallic Roughness texture */ if (pbrMaterial.metallicRoughnessTexture !== undefined) { pbrMaterial.metallicRoughnessTexture.bind(gl.TEXTURE1); gl.uniform1i(this._uMetallicRoughnessTexCoord, pbrMaterial.metallicRoughnessTexCoord); } else { this._emptyTexture.bind(gl.TEXTURE1); } /** * Normal texture */ if (pbrMaterial.normalTexture !== undefined) { pbrMaterial.normalTexture.bind(gl.TEXTURE2); gl.uniform1i(this._uNormalTexCoord, pbrMaterial.normalTexCoord); } else { this._emptyTexture.bind(gl.TEXTURE2); } /** * Occlusion texture */ if (pbrMaterial.occlusionTexture !== undefined) { pbrMaterial.occlusionTexture.bind(gl.TEXTURE3); gl.uniform1i(this._uOcclusionTexCoord, pbrMaterial.occlusionTexCoord); } else { this._emptyTexture.bind(gl.TEXTURE3); } /** * Emission texture */ if (pbrMaterial.emissiveTexture !== undefined) { pbrMaterial.emissiveTexture.bind(gl.TEXTURE4); gl.uniform1i(this._uEmissiveTexCoord, pbrMaterial.emissiveTexCoord); } else { this._emptyTexture.bind(gl.TEXTURE4); } /** * Material properties */ gl.uniform4fv(this._uBaseColorFactor, pbrMaterial.baseColorFactor); gl.uniform3fv(this._uEmissiveFactor, pbrMaterial.emissiveFactor); gl.uniform1f(this._uMetallicFactor, pbrMaterial.metallicFactor); gl.uniform1f(this._uRoughnessFactor, pbrMaterial.roughnessFactor); gl.uniform1f(this._uNormalScale, pbrMaterial.normalScale); gl.uniform1i(this._uPbrFlags, pbrMaterial.flags); if (pbrMaterial.alphaMode === GLTFAlphaMode.OPAQUE) { gl.disable(gl.BLEND); gl.uniform1i(this._uBlendMode, 0); } else if (pbrMaterial.alphaMode === GLTFAlphaMode.MASK) { gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.uniform1i(this._uBlendMode, 1); gl.uniform1f(this._uBlendCutoff, pbrMaterial.alphaCutoff); } else if (pbrMaterial.alphaMode === GLTFAlphaMode.BLEND) { gl.enable(gl.BLEND); gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.uniform1i(this._uBlendMode, 2); } else { auxiliaries.log(auxiliaries.LogLevel.Warning, 'Unknown blend mode encountered.'); } }; this._forwardPass.bindGeometry = (geometry: Geometry) => { const primitive = geometry as GLTFPrimitive; gl.uniform1i(this._uGeometryFlags, primitive.flags); }; this._forwardPass.updateModelTransform = (matrix: mat4) => { gl.uniformMatrix4fv(this._uModel, gl.FALSE, matrix); const normalMatrix = mat3.create(); mat3.normalFromMat4(normalMatrix, matrix); gl.uniformMatrix3fv(this._uNormalMatrix, gl.FALSE, normalMatrix); }; this._forwardPass.frame(); this._accumulatePass.frame(frameNumber); this._postProcessingPass.texture = this._accumulatePass.framebuffer!.texture(gl2facade.COLOR_ATTACHMENT0)!; this._postProcessingPass.frame(); } protected onSwap(): void { this._blitPass.frame(); } /** * Bind all uniforms that do not change within a multi-frame. * This avoids unnecessary calls in each individual frame. */ protected bindMultiframeUniforms(): void { const gl = this._context.gl; /** * Prepare main program uniforms */ this._program.bind(); gl.uniformMatrix4fv(this._uView, gl.FALSE, this._camera.view); gl.uniformMatrix4fv(this._uProjection, gl.FALSE, this._camera.projection); gl.uniform2fv(this._uCameraNearFar, vec2.fromValues(this._camera.near, this._camera.far)); const viewNormalMatrix = mat3.create(); mat3.normalFromMat4(viewNormalMatrix, this._camera.view); gl.uniformMatrix3fv(this._uViewNormalMatrix, gl.FALSE, viewNormalMatrix); gl.uniform3fv(this._uEye, this._camera.eye); gl.uniform1i(this._uBaseColor, 0); gl.uniform1i(this._uMetallicRoughness, 1); gl.uniform1i(this._uNormal, 2); gl.uniform1i(this._uOcclusion, 3); gl.uniform1i(this._uEmissive, 4); gl.uniform1i(this._uDiffuseEnvironment, 10); gl.uniform1i(this._uSpecularEnvironment, 5); gl.uniform1i(this._uBRDFLookupTable, 6); gl.uniform1i(this._uShadowMap, 7); gl.uniform1i(this._uNormalDepth, 8); gl.uniform1i(this._uLastFrame, 9); this._specularEnvironment.bind(gl.TEXTURE5); this._diffuseEnvironment.bind(gl.TEXTURE10); this._brdfLUT.bind(gl.TEXTURE6); this._shadowPass.shadowMapTexture.bind(gl.TEXTURE7); this._normalDepthTexture.bind(gl.TEXTURE8); /** * Prepare depth program uniforms */ this._depthProgram.bind(); gl.uniform2fv(this._uCameraNearFarD, vec2.fromValues(this._camera.near, this._camera.far)); gl.uniformMatrix4fv(this._uViewD, gl.FALSE, this._camera.view); gl.uniformMatrix4fv(this._uProjectionD, gl.FALSE, this._camera.projection); this._depthProgram.unbind(); } /** * Bind all uniforms that change each frame and perform shadow and depth prepass if necessary. */ protected prepareFrame(frameNumber: number): void { const gl = this._context.gl; const gl2facade = this._context.gl2facade; const samples = this._sampleManager.getNextFrameSamples(); let numDiffuseEnvironmentSamples = 0; let diffuseEnvironmentFactor = 1.0; let numSpecularEnvironmentSamples = 0; let specularEnvironmentFactor = 1.0; let currentLightIndex = -1; let lightEye = vec3.create(); let lightFactor = 1.0; for (const sample of samples) { if (sample instanceof DiffuseEnvironmentSample) { numDiffuseEnvironmentSamples++; diffuseEnvironmentFactor = sample.factor; } if (sample instanceof SpecularEnvironmentSample) { numSpecularEnvironmentSamples++; specularEnvironmentFactor = sample.factor; } if (sample instanceof LightSample) { currentLightIndex = sample.lightIndex; lightEye = sample.eye; lightFactor = sample.factor; } } if (frameNumber === 1) { this.preDepthPass(); } if (currentLightIndex >= 0) { this.shadowPass(currentLightIndex, lightEye); } this._program.bind(); gl.uniform1i(this._uFrameNumber, frameNumber); const ndcOffset = this._ndcOffsetKernel.get(frameNumber); ndcOffset[0] = 2.0 * ndcOffset[0] / this._frameSize[0]; ndcOffset[1] = 2.0 * ndcOffset[1] / this._frameSize[1]; gl.uniform2fv(this._uNdcOffset, ndcOffset); const cocPoint = this._depthOfFieldKernel.get(frameNumber); cocPoint[0] *= this._depthOfFieldRange; cocPoint[1] *= this._depthOfFieldRange; gl.uniform2fv(this._uCocPoint, cocPoint); /** * Update samples that should be handled in this frame. */ gl.uniform1i(this._uLightSampleIndex, currentLightIndex); gl.uniform1f(this._uLightFactor, lightFactor); gl.uniform1i(this._uNumDiffuseEnvironmentSamples, numDiffuseEnvironmentSamples); gl.uniform1f(this._uDiffuseEnvironmentFactor, diffuseEnvironmentFactor); gl.uniform1i(this._uNumSpecularEnvironmentSamples, numSpecularEnvironmentSamples); gl.uniform1f(this._uSpecularEnvironmentFactor, specularEnvironmentFactor); const lastFrame = this._accumulatePass.framebuffer!.texture(gl2facade.COLOR_ATTACHMENT0)!; lastFrame.bind(gl.TEXTURE9); } /** * Load asset from URI specified by the HTML select */ protected loadAsset(): void { const assetSelect = window.document.getElementById('asset-select')! as HTMLSelectElement; let scene: Scene | undefined; if (assetSelect.value === 'Datsun') { scene = this._datsunScene; } else if (assetSelect.value === 'Kitchen') { scene = this._kitchenScene; } else if (assetSelect.value === 'Cornell') { scene = this._cornellScene; } else if (assetSelect.value === 'Skyline') { scene = this._skylineScene; } auxiliaries.assert(scene !== undefined, `Unknown scene ${assetSelect.value}.`); if (scene === undefined) { auxiliaries.log(auxiliaries.LogLevel.Error, `Scene ${assetSelect.value} could not be loaded.`); return; } // Show loading spinner and clear background this.startLoading(); this._postProcessingPass.clear(); this._currentScene = scene; this._camera = scene!.camera; this.updateCamera(); this.updateLights(scene!); this._loader.uninitialize(); this._loader.loadAsset(scene!.uri) .then(() => { this._forwardPass.scene = this._loader.defaultScene; this._invalidate(true); this.finishLoading(); }); } protected setDebugMode(): void { const gl = this._context.gl; const debugSelect = window.document.getElementById('debug-select')! as HTMLSelectElement; let debugMode = 0; if (debugSelect.value === 'Final') { debugMode = 0; } else if (debugSelect.value === 'Flat') { debugMode = 1; } else if (debugSelect.value === 'IBL') { debugMode = 2; } else if (debugSelect.value === 'Light sources') { debugMode = 3; } else if (debugSelect.value === 'Illuminance') { debugMode = 4; } this._program.bind(); gl.uniform1i(this._program.uniform('u_debugMode'), debugMode); this._program.unbind(); } protected updateLights(scene: Scene): void { const gl = this._context.gl; this._program.bind(); gl.uniform1i(this._program.uniform('u_numDiskLights'), scene.diskLights.length); let i = 0; for (const diskLight of scene.diskLights) { gl.uniform3fv(this._program.uniform(`u_diskLights[${i}].center`), diskLight.center); gl.uniform1f(this._program.uniform(`u_diskLights[${i}].radius`), diskLight.radius); gl.uniform3fv(this._program.uniform(`u_diskLights[${i}].luminance`), diskLight.luminance); gl.uniform3fv(this._program.uniform(`u_diskLights[${i}].direction`), diskLight.direction); i++; } this._program.unbind(); } protected updateCamera(): void { // focal length of 50mm this._camera.viewport = [this._frameSize[0], this._frameSize[1]]; this._camera.aspect = this._canvasSize[0] / this._canvasSize[1]; // Convert from horizontal to vertical FOV const horizontalFOV = 39.6 * auxiliaries.DEG2RAD; const verticalFOV = 2.0 * Math.atan(Math.tan(horizontalFOV / 2.0) * (1.0 / this._camera.aspect)); this._camera.fovy = verticalFOV * auxiliaries.RAD2DEG; this._forwardPass.camera = this._camera; this._navigation.camera = this._camera; this._camera.altered = true; } /** * Setup environment lighting */ protected loadEnvironmentMap(): void { const environmentSelect = window.document.getElementById('environment-select')! as HTMLSelectElement; const environmentName = environmentSelect.value; const gl = this._context.gl; this._brdfLUT = new Texture2D(this._context, 'BRDFLookUpTable'); this._brdfLUT.initialize(1, 1, gl.RG16F, gl.RG, gl.FLOAT); this._brdfLUT.wrap(gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE); this._brdfLUT.filter(gl.LINEAR, gl.LINEAR); this._brdfLUT.fetch('/examples/data/imagebasedlighting/brdfLUT.png'); const internalFormatAndType = Wizard.queryInternalTextureFormat( this._context, gl.RGBA, Wizard.Precision.byte); this._diffuseEnvironment = new TextureCube(this._context, 'DiffuseEnvironment'); this._diffuseEnvironment.initialize(64, internalFormatAndType[0], gl.RGBA, internalFormatAndType[1]); this._diffuseEnvironment.fetch({ positiveX: `${ProgressiveLightingRenderer.URL}/${environmentName}/preprocessed-map-px-diffuse.png`, negativeX: `${ProgressiveLightingRenderer.URL}/${environmentName}/preprocessed-map-nx-diffuse.png`, positiveY: `${ProgressiveLightingRenderer.URL}/${environmentName}/preprocessed-map-py-diffuse.png`, negativeY: `${ProgressiveLightingRenderer.URL}/${environmentName}/preprocessed-map-ny-diffuse.png`, positiveZ: `${ProgressiveLightingRenderer.URL}/${environmentName}/preprocessed-map-pz-diffuse.png`, negativeZ: `${ProgressiveLightingRenderer.URL}/${environmentName}/preprocessed-map-nz-diffuse.png`, }, true); this._specularEnvironment = new TextureCube(this._context, 'SpecularEnvironment'); this._specularEnvironment.initialize(512, internalFormatAndType[0], gl.RGBA, internalFormatAndType[1]); const MIPMAP_LEVELS = 9; this._specularEnvironment.filter(gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR); this._specularEnvironment.levels(0, MIPMAP_LEVELS - 1); for (let mipLevel = 0; mipLevel < MIPMAP_LEVELS; ++mipLevel) { this._specularEnvironment.fetch({ positiveX: `${ProgressiveLightingRenderer.URL}/${environmentName}/preprocessed-map-px-${mipLevel}.png`, negativeX: `${ProgressiveLightingRenderer.URL}/${environmentName}/preprocessed-map-nx-${mipLevel}.png`, positiveY: `${ProgressiveLightingRenderer.URL}/${environmentName}/preprocessed-map-py-${mipLevel}.png`, negativeY: `${ProgressiveLightingRenderer.URL}/${environmentName}/preprocessed-map-ny-${mipLevel}.png`, positiveZ: `${ProgressiveLightingRenderer.URL}/${environmentName}/preprocessed-map-pz-${mipLevel}.png`, negativeZ: `${ProgressiveLightingRenderer.URL}/${environmentName}/preprocessed-map-nz-${mipLevel}.png`, }, true, mipLevel); } } } export class ProgressiveLightingDemo extends Demo { private _canvas: Canvas; private _renderer: ProgressiveLightingRenderer; onInitialize(element: HTMLCanvasElement | string): boolean { this._canvas = new Canvas(element); this._canvas.controller.multiFrameNumber = 128; this._canvas.framePrecision = Wizard.Precision.float; this._canvas.frameScale = [1.0, 1.0]; this._renderer = new ProgressiveLightingRenderer(); this._canvas.renderer = this._renderer; const frameScale = window.document.getElementById('frame-scale')! as HTMLInputElement; frameScale.onchange = (_) => { const scale = parseFloat(frameScale.value) / 100.0; this._canvas.frameScale = [scale, scale]; }; const multiFrameCount = window.document.getElementById('multiframe-count')! as HTMLInputElement; multiFrameCount.onchange = (_) => { this._canvas.controller.multiFrameNumber = parseInt(multiFrameCount.value, 10); }; return true; } onUninitialize(): void { this._canvas.dispose(); (this._renderer as Renderer).uninitialize(); } get canvas(): Canvas { return this._canvas; } get renderer(): ProgressiveLightingRenderer { return this._renderer; } }
the_stack
import * as geom from "../format/geom"; import * as dbft from "../format/dragonBonesFormat"; import * as l2ft from "../format/live2DFormat"; const rotateMatrixA = geom.helpMatrixA; const rotateMatrixB = geom.helpMatrixB; let modelConfig: l2ft.ModelConfig; let result: dbft.DragonBones; let armature: dbft.Armature; let defaultSkin: dbft.Skin; /** * Convert Live2D format to DragonBones format. */ export default function (data: l2ft.ModelConfig): dbft.DragonBones | null { modelConfig = data; const l2Displays = modelConfig.modelImpl.displays; // Create dragonBones. result = new dbft.DragonBones(); result.frameRate = 30; // result.name = modelConfig.name; result.version = dbft.DATA_VERSION_5_6; result.compatibleVersion = dbft.DATA_VERSION_5_5; // Create textureAtlas. let textureIndex = 0; for (const l2Texture of modelConfig.textures) { if (typeof l2Texture === "string") { continue; } const textureAtlas = new dbft.TextureAtlas(); textureAtlas.name = result.name; textureAtlas.width = l2Texture.width; textureAtlas.height = l2Texture.height; textureAtlas.imagePath = l2Texture.file; result.textureAtlas.push(textureAtlas); const subTexture = new dbft.Texture(); subTexture.name = result.name + "_" + textureIndex.toString().padStart(2, "0"); subTexture.x = 0; subTexture.y = 0; subTexture.width = textureAtlas.width; subTexture.height = textureAtlas.height; textureAtlas.SubTexture.push(subTexture); textureIndex++; } // Create armature. armature = new dbft.Armature(); armature.name = data.name; armature.aabb.x = -modelConfig.modelImpl.stageWidth * 0.5; armature.aabb.y = -modelConfig.modelImpl.stageHeight; armature.aabb.width = modelConfig.modelImpl.stageWidth; armature.aabb.height = modelConfig.modelImpl.stageHeight; armature.canvas = new dbft.Canvas(); armature.canvas.x = 0.0; armature.canvas.y = -modelConfig.modelImpl.stageHeight * 0.5; armature.canvas.width = modelConfig.modelImpl.stageWidth; armature.canvas.height = modelConfig.modelImpl.stageHeight; result.armature.push(armature); // Create root bone. const rootBone = new dbft.Bone(); rootBone.name = "DST_BASE"; rootBone.length = 150.0; armature.bone.push(rootBone); // Modify bone rotate. rotateMatrixA.identity(); rotateMatrixA.rotate(Math.PI * 0.5); rotateMatrixB.identity(); rotateMatrixB.rotate(-Math.PI * 0.5); for (const l2Part of modelConfig.modelImpl.parts) { for (const l2Bone of l2Part.bones) { const l2Parent = modelConfig.modelImpl.getBone(l2Bone.parent); const isSurfaceParent = l2Parent && l2Parent instanceof l2ft.Surface; const l2Timelines = l2Bone.animation.timelines; if (l2Bone instanceof l2ft.Bone) { const bone = new dbft.Bone(); bone.length = 150.0; if (l2Bone.alphaFrames) { bone.alpha = getPose(l2Timelines, l2Bone.alphaFrames, (a, b, t) => { if (b) { return a + (b - a) * t; } return a; }); } bone.name = l2Bone.name; bone.parent = l2Parent ? (l2Parent.name === rootBone.name ? "" : l2Parent.name) : ""; armature.bone.push(bone); // const poseTransform = getPose(l2Timelines, l2Bone.transformFrames, (a, b, t) => { const result = new l2ft.Transform(); if (b) { result.interpolation(a, b, t); } else { result.copyFrom(a); } return result; }); if (isSurfaceParent) { // Scale and rotate. bone.transform.x = (poseTransform.x - 0.5) * 400.0; bone.transform.y = (poseTransform.y - 0.5) * 400.0; if (poseTransform.reflectX !== poseTransform.reflectY) { bone.transform.skY = poseTransform.rotate + 90.0; bone.transform.skX = poseTransform.rotate + 90.0; } else { bone.transform.skY = poseTransform.rotate - 90.0; bone.transform.skX = poseTransform.rotate - 90.0; } bone.transform.scX = poseTransform.scaleX * (poseTransform.reflectX ? -1.0 : 1.0); bone.transform.scY = poseTransform.scaleY * (poseTransform.reflectY ? -1.0 : 1.0); } else if (bone.parent) { // Rotate. rotateMatrixA.transformPoint(poseTransform.x, poseTransform.y, bone.transform); // const parentTransform = (l2Parent as l2ft.Bone).transformFrames[0]; if (parentTransform.reflectX !== parentTransform.reflectY) { bone.transform.skY = poseTransform.rotate; bone.transform.skX = poseTransform.rotate; if (poseTransform.reflectX !== poseTransform.reflectY) { } else { bone.transform.scX = poseTransform.scaleX * (parentTransform.reflectY ? -1.0 : 1.0); bone.transform.scY = poseTransform.scaleY * (parentTransform.reflectX ? -1.0 : 1.0); } } else { if (poseTransform.reflectX !== poseTransform.reflectY) { bone.transform.skY = poseTransform.rotate + 180.0; bone.transform.skX = poseTransform.rotate + 180.0; } else { bone.transform.skY = poseTransform.rotate; bone.transform.skX = poseTransform.rotate; } bone.transform.scX = poseTransform.scaleX * (poseTransform.reflectX ? -1.0 : 1.0); bone.transform.scY = poseTransform.scaleY * (poseTransform.reflectY ? -1.0 : 1.0); } } else { // Rotate and offset. bone.transform.x = poseTransform.x + armature.aabb.x; bone.transform.y = poseTransform.y + armature.aabb.y; if (poseTransform.reflectX !== poseTransform.reflectY) { bone.transform.skY = poseTransform.rotate + 90.0; bone.transform.skX = poseTransform.rotate + 90.0; } else { bone.transform.skY = poseTransform.rotate - 90.0; bone.transform.skX = poseTransform.rotate - 90.0; } bone.transform.scX = poseTransform.scaleX * (poseTransform.reflectX ? -1.0 : 1.0); bone.transform.scY = poseTransform.scaleY * (poseTransform.reflectY ? -1.0 : 1.0); } if (!bone.transform.scX) { bone.transform.scX = 0.000001; } if (!bone.transform.scY) { bone.transform.scY = 0.000001; } } else if (l2Bone instanceof l2ft.Surface) { const surface = new dbft.Surface(); surface.segmentX = l2Bone.segmentX; surface.segmentY = l2Bone.segmentY; surface.name = l2Bone.name; surface.parent = l2Parent ? (l2Parent.name === rootBone.name ? "" : l2Parent.name) : ""; armature.bone.push(surface); // const poseVertices = getPose(l2Timelines, l2Bone.deformFrames, (a, b, t) => { const result = new Array<number>(); if (b) { vertivesInterpolation(result, a, b, t); } else { vertivesCopyFrom(result, a); } return result; }); for (let i = 0, l = poseVertices.length; i < l; i += 2) { if (isSurfaceParent) { // Scale. surface.vertices[i] = (poseVertices[i] - 0.5) * 400.0; surface.vertices[i + 1] = (poseVertices[i + 1] - 0.5) * 400.0; } else if (surface.parent) { // Rotate. rotateMatrixA.transformPoint(poseVertices[i], poseVertices[i + 1], geom.helpPointA); surface.vertices[i] = geom.helpPointA.x; surface.vertices[i + 1] = geom.helpPointA.y; } else { // Offset. surface.vertices[i] = poseVertices[i] + armature.aabb.x; surface.vertices[i + 1] = poseVertices[i + 1] + armature.aabb.y; } } } } } // Sort bones. armature.sortBones(); // armature.localToGlobal(); // Create slots and skins. defaultSkin = new dbft.Skin(); armature.skin.push(defaultSkin); for (const l2Display of l2Displays) { const l2Parent = modelConfig.modelImpl.getBone(l2Display.parent); const isSurfaceParent = l2Parent !== null && l2Parent instanceof l2ft.Surface; const l2Timelines = l2Display.animation.timelines; if (l2Display instanceof l2ft.Mesh) { // Create slot. const slot = new dbft.Slot(); slot.name = l2Display.name; slot.parent = l2Parent ? l2Parent.name : rootBone.name; slot.alpha = getPose(l2Timelines, l2Display.alphaFrames, (a, b, t) => { if (b) { return a + (b - a) * t; } return a; }); slot.zIndex = getPose(l2Timelines, l2Display.zIndexFrames, (a, _b, _t) => { return a; }); slot._zOrder = slot.zIndex * 1000 + l2Display.zOrder; // slot.color; armature.slot.push(slot); // Create displays. const display = new dbft.MeshDisplay(); display.name = l2Display.name; display.path = result.name + "_" + (l2Display.textureIndex >= 0 ? l2Display.textureIndex : 0).toString().padStart(2, "0"); // UVs. for (const value of l2Display.uvs) { display.uvs.push(value); } // Triangles. for (const index of l2Display.indices) { display.triangles.push(index); } // Vertices. const poseVertices = getPose(l2Timelines, l2Display.deformFrames, (a, b, t) => { const result = new Array<number>(); if (b) { vertivesInterpolation(result, a, b, t); } else { vertivesCopyFrom(result, a); } return result; }); for (let i = 0, l = poseVertices.length; i < l; i += 2) { if (isSurfaceParent) { // Scale. display.vertices[i] = (poseVertices[i] - 0.5) * 400.0; display.vertices[i + 1] = (poseVertices[i + 1] - 0.5) * 400.0; } else if (slot.parent !== rootBone.name) { // Rotate. rotateMatrixA.transformPoint(poseVertices[i], poseVertices[i + 1], geom.helpPointA); display.vertices[i] = geom.helpPointA.x; display.vertices[i + 1] = geom.helpPointA.y; } else { // Offset. display.vertices[i] = poseVertices[i] + armature.aabb.x; display.vertices[i + 1] = poseVertices[i + 1] + armature.aabb.y; } } // const edges = dbft.getEdgeFormTriangles(display.triangles); // for (const value of edges) { // display.edges.push(value); // } // Create skinSlot. const skinSlot = new dbft.SkinSlot(); skinSlot.name = l2Display.name; skinSlot.display.push(display); defaultSkin.slot.push(skinSlot); } } armature.sortSlots(); // Create animations. if (modelConfig.modelImpl.animations.timelines.length > 0) { for (const l2Part of modelConfig.modelImpl.parts) { // Create bone timelines. for (const l2Bone of l2Part.bones) { const l2Timelines = l2Bone.animation.timelines; const bone = armature.getBone(l2Bone.name); if (l2Timelines.length === 0 || !bone) { continue; } const l2Parent = modelConfig.modelImpl.getBone(l2Bone.parent); const isSurfaceParent = l2Parent !== null && l2Parent instanceof l2ft.Surface; if (l2Bone.alphaFrames) { let hasAlpha = false; for (const alpha of l2Bone.alphaFrames) { if (alpha !== bone.alpha) { hasAlpha = true; break; } } if (hasAlpha) { createAnimation(l2Timelines, l2Bone.alphaFrames, bone, (l2Timeline, l2Frames, target, offset, blendAnimation) => { const l2TimelineInfo = modelConfig.modelImpl.getTimelineInfo(l2Timeline.name) as l2ft.TimelineInfo; const totalValue = l2TimelineInfo.maximum - l2TimelineInfo.minimum; const timeline = new dbft.TypeTimeline(); timeline.type = dbft.TimelineType.BoneAlpha; timeline.name = target.name; for (let i = 0; i < l2Timeline.frameCount; ++i) { const progress = (l2Timeline.frames[i] - l2TimelineInfo.minimum) / totalValue; const l2Frame = l2Frames[offset + i]; const frame = new dbft.SingleValueFrame1(); frame._position = Math.floor(progress * blendAnimation.duration); frame.tweenEasing = i === l2Timeline.frameCount - 1 ? NaN : 0.0; frame.value = l2Frame; timeline.frame.push(frame); } dbft.modifyFramesByPosition(timeline.frame); blendAnimation.timeline.push(timeline); }); } } if (l2Bone instanceof l2ft.Bone) { createAnimation(l2Timelines, l2Bone.transformFrames, bone, (l2Timeline, l2Frames, target, offset, blendAnimation) => { const l2TimelineInfo = modelConfig.modelImpl.getTimelineInfo(l2Timeline.name) as l2ft.TimelineInfo; const totalValue = l2TimelineInfo.maximum - l2TimelineInfo.minimum; const translateTimeline = new dbft.TypeTimeline(); const rotateTimeline = new dbft.TypeTimeline(); const scaleTimeline = new dbft.TypeTimeline(); translateTimeline.type = dbft.TimelineType.BoneTranslate; rotateTimeline.type = dbft.TimelineType.BoneRotate; scaleTimeline.type = dbft.TimelineType.BoneScale; translateTimeline.name = target.name; rotateTimeline.name = target.name; scaleTimeline.name = target.name; for (let i = 0; i < l2Timeline.frameCount; ++i) { const progress = (l2Timeline.frames[i] - l2TimelineInfo.minimum) / totalValue; const l2Frame = l2Frames[offset + i]; const translateFrame = new dbft.DoubleValueFrame0(); const rotateFrame = new dbft.DoubleValueFrame0(); const scaleFrame = new dbft.DoubleValueFrame1(); let x = 0.0; let y = 0.0; translateFrame._position = rotateFrame._position = scaleFrame._position = Math.floor(progress * blendAnimation.duration); translateFrame.tweenEasing = rotateFrame.tweenEasing = scaleFrame.tweenEasing = i === l2Timeline.frameCount - 1 ? NaN : 0.0; if (isSurfaceParent) { x = (l2Frame.x - 0.5) * 400.0; y = (l2Frame.y - 0.5) * 400.0; } else { x = l2Frame.x; y = l2Frame.y; } if (!target.parent || isSurfaceParent) { if (target.parent) { translateFrame.x = x - target.transform.x; translateFrame.y = y - target.transform.y; if (l2Frame.reflectX !== l2Frame.reflectY) { rotateFrame.x = l2Frame.rotate + 90.0 - target.transform.skY; } else { rotateFrame.x = l2Frame.rotate - 90.0 - target.transform.skY; } } else { translateFrame.x = x - target.transform.x + armature.aabb.x; translateFrame.y = y - target.transform.y + armature.aabb.y; if (l2Frame.reflectX !== l2Frame.reflectY) { rotateFrame.x = l2Frame.rotate + 90.0 - target.transform.skY; } else { rotateFrame.x = l2Frame.rotate - 90.0 - target.transform.skY; } } scaleFrame.x = l2Frame.scaleX * (l2Frame.reflectX ? -1.0 : 1.0) / target.transform.scX; scaleFrame.y = l2Frame.scaleY * (l2Frame.reflectY ? -1.0 : 1.0) / target.transform.scY; } else { rotateMatrixA.transformPoint(x, y, translateFrame); translateFrame.x -= target.transform.x; translateFrame.y -= target.transform.y; // const parentTransform = (l2Parent as l2ft.Bone).transformFrames[0]; if (parentTransform.reflectX !== parentTransform.reflectY) { rotateFrame.x = l2Frame.rotate - target.transform.skY; if (l2Frame.reflectX !== l2Frame.reflectY) { } else { scaleFrame.x = l2Frame.scaleX * (parentTransform.reflectY ? -1.0 : 1.0) / target.transform.scX; scaleFrame.y = l2Frame.scaleY * (parentTransform.reflectX ? -1.0 : 1.0) / target.transform.scY; } } else { if (l2Frame.reflectX !== l2Frame.reflectY) { rotateFrame.x = l2Frame.rotate + 180 - target.transform.skY; } else { rotateFrame.x = l2Frame.rotate - target.transform.skY; } scaleFrame.x = l2Frame.scaleX * (l2Frame.reflectX ? -1.0 : 1.0) / target.transform.scX; scaleFrame.y = l2Frame.scaleY * (l2Frame.reflectY ? -1.0 : 1.0) / target.transform.scY; } } translateTimeline.frame.push(translateFrame); rotateTimeline.frame.push(rotateFrame); scaleTimeline.frame.push(scaleFrame); } dbft.modifyFramesByPosition(translateTimeline.frame); dbft.modifyFramesByPosition(rotateTimeline.frame); dbft.modifyFramesByPosition(scaleTimeline.frame); blendAnimation.timeline.push(translateTimeline); blendAnimation.timeline.push(rotateTimeline); blendAnimation.timeline.push(scaleTimeline); }); } else if (l2Bone instanceof l2ft.Surface) { createAnimation(l2Timelines, l2Bone.deformFrames, bone as dbft.Surface, (l2Timeline, l2Frames, target, offset, blendAnimation) => { const l2TimelineInfo = modelConfig.modelImpl.getTimelineInfo(l2Timeline.name) as l2ft.TimelineInfo; const totalValue = l2TimelineInfo.maximum - l2TimelineInfo.minimum; const timeline = new dbft.TypeTimeline(); timeline.type = dbft.TimelineType.Surface; timeline.name = target.name; for (let i = 0; i < l2Timeline.frameCount; ++i) { const progress = (l2Timeline.frames[i] - l2TimelineInfo.minimum) / totalValue; const l2Frame = l2Frames[offset + i]; const frame = new dbft.MutilpleValueFrame(); frame._position = Math.floor(progress * blendAnimation.duration); frame.tweenEasing = i === l2Timeline.frameCount - 1 ? NaN : 0.0; createDeformFrame( frame, l2Frame, target.vertices, isSurfaceParent, target.parent.length > 0 ); timeline.frame.push(frame); } dbft.modifyFramesByPosition(timeline.frame); blendAnimation.timeline.push(timeline); }); } } // Create slot timeines. for (const l2Display of l2Part.displays) { const l2Timelines = l2Display.animation.timelines; const slot = armature.getSlot(l2Display.name); if (l2Timelines.length === 0 || !slot) { continue; } const l2Parent = modelConfig.modelImpl.getBone(l2Display.parent); const isSurfaceParent = l2Parent !== null && l2Parent instanceof l2ft.Surface; if (l2Display instanceof l2ft.Mesh) { const meshDisplay = armature.getDisplay(defaultSkin.name, l2Display.name, l2Display.name) as dbft.MeshDisplay | null; if (!meshDisplay) { continue; } let hasZIndex = false; let prevZIndex = NaN; for (const zIndex of l2Display.zIndexFrames) { if (prevZIndex === prevZIndex && zIndex !== prevZIndex) { hasZIndex = true; break; } prevZIndex = zIndex; } if (hasZIndex) { createAnimation(l2Timelines, l2Display.zIndexFrames, meshDisplay, (l2Timeline, l2Frames, target, offset, blendAnimation) => { const l2TimelineInfo = modelConfig.modelImpl.getTimelineInfo(l2Timeline.name) as l2ft.TimelineInfo; const totalValue = l2TimelineInfo.maximum - l2TimelineInfo.minimum; const timeline = new dbft.TypeTimeline(); timeline.type = dbft.TimelineType.SlotZIndex; timeline.name = target.name; for (let i = 0; i < l2Timeline.frameCount; ++i) { const progress = (l2Timeline.frames[i] - l2TimelineInfo.minimum) / totalValue; const l2Frame = l2Frames[offset + i]; const frame = new dbft.SingleValueFrame0(); frame._position = Math.floor(progress * blendAnimation.duration); frame.value = l2Frame; timeline.frame.push(frame); } dbft.modifyFramesByPosition(timeline.frame); blendAnimation.timeline.push(timeline); }); } let hasAlpha = false; for (const alpha of l2Display.alphaFrames) { if (alpha !== slot.alpha) { hasAlpha = true; break; } } if (hasAlpha) { createAnimation(l2Timelines, l2Display.alphaFrames, meshDisplay, (l2Timeline, l2Frames, target, offset, blendAnimation) => { const l2TimelineInfo = modelConfig.modelImpl.getTimelineInfo(l2Timeline.name) as l2ft.TimelineInfo; const totalValue = l2TimelineInfo.maximum - l2TimelineInfo.minimum; const timeline = new dbft.TypeTimeline(); timeline.type = dbft.TimelineType.SlotAlpha; timeline.name = target.name; for (let i = 0; i < l2Timeline.frameCount; ++i) { const progress = (l2Timeline.frames[i] - l2TimelineInfo.minimum) / totalValue; const l2Frame = l2Frames[offset + i]; const frame = new dbft.SingleValueFrame1(); frame._position = Math.floor(progress * blendAnimation.duration); frame.tweenEasing = i === l2Timeline.frameCount - 1 ? NaN : 0.0; frame.value = l2Frame; timeline.frame.push(frame); } dbft.modifyFramesByPosition(timeline.frame); blendAnimation.timeline.push(timeline); }); } // createAnimation(l2Timelines, l2Display.deformFrames, meshDisplay, (l2Timeline, l2Frames, target, offset, blendAnimation) => { const l2TimelineInfo = modelConfig.modelImpl.getTimelineInfo(l2Timeline.name) as l2ft.TimelineInfo; const totalValue = l2TimelineInfo.maximum - l2TimelineInfo.minimum; const timeline = new dbft.TypeTimeline(); timeline.type = dbft.TimelineType.SlotDeform; timeline.name = target.name; for (let i = 0; i < l2Timeline.frameCount; ++i) { const progress = (l2Timeline.frames[i] - l2TimelineInfo.minimum) / totalValue; const l2Frame = l2Frames[offset + i]; const frame = new dbft.MutilpleValueFrame(); frame._position = Math.floor(progress * blendAnimation.duration); frame.tweenEasing = i === l2Timeline.frameCount - 1 ? NaN : 0.0; createDeformFrame( frame, l2Frame, target.vertices, isSurfaceParent, slot.parent !== rootBone.name ); timeline.frame.push(frame); } dbft.modifyFramesByPosition(timeline.frame); blendAnimation.timeline.push(timeline); }); } } } } const paramBackupAnimations = armature.animation.map(animation => animation.name); if (modelConfig.motions) { // Create motion animations. for (const motionName in modelConfig.motions) { let index = 0; const motionConfigs = modelConfig.motions[motionName]; for (const motionConfig of motionConfigs) { if (!motionConfig.motion) { continue; } const paramAnimations = paramBackupAnimations.concat(); const animationName = motionConfigs.length > 1 ? (motionName + "_" + index.toString().padStart(2, "0")) : motionName; const animation = new dbft.Animation(); animation.playTimes = 0; animation.fadeInTime = motionConfig.fade_in ? motionConfig.fade_in * 0.001 : (motionConfig.motion.fade_in ? motionConfig.motion.fade_in * 0.001 : 0.3); animation.name = animationName; animation.type = dbft.AnimationType.Tree; for (const timelineName in motionConfig.motion.values) { const l2TimelineInfo = modelConfig.modelImpl.getTimelineInfo(timelineName); if (!l2TimelineInfo) { continue; } if (!paramAnimations.includes(timelineName)) { continue; } paramAnimations.splice(paramAnimations.indexOf(timelineName), 1); let duration = 0; const values = motionConfig.motion.values[timelineName]; let [min, max] = getMinAndMax(values); const timeline = new dbft.TypeTimeline(); let prevFrame: dbft.SingleValueFrame0 | null = null; timeline.type = dbft.TimelineType.AnimationProgress; timeline.name = timelineName; min = (min - l2TimelineInfo.minimum) / (l2TimelineInfo.maximum - l2TimelineInfo.minimum); max = (max - l2TimelineInfo.minimum) / (l2TimelineInfo.maximum - l2TimelineInfo.minimum); for (let i = 0, l = values.length; i < l; ++i) { const value = values[i]; const frame = new dbft.SingleValueFrame0(); frame.tweenEasing = 0.0; frame.value = (value - l2TimelineInfo.minimum) / (l2TimelineInfo.maximum - l2TimelineInfo.minimum); timeline.frame.push(frame); duration += frame.duration; if ( i > 1 && prevFrame && ( (Math.abs(prevFrame.value - min) < 0.1 || Math.abs(prevFrame.value - max) < 0.1) && (Math.abs(frame.value - min) < 0.1 || Math.abs(frame.value - max) < 0.1) ) && Math.abs(prevFrame.value - frame.value) > Math.abs(max - min) * 0.7 ) { prevFrame.tweenEasing = NaN; } prevFrame = frame; } const firstVaule = (timeline.frame[0] as dbft.SingleValueFrame0).value; if ( prevFrame && ( (Math.abs(prevFrame.value - min) < 0.1 || Math.abs(prevFrame.value - max) < 0.1) && (Math.abs(firstVaule - min) < 0.1 || Math.abs(firstVaule - max) < 0.1) ) && Math.abs(prevFrame.value - firstVaule) > Math.abs(max - min) * 0.7 ) { prevFrame.tweenEasing = NaN; } animation.duration = Math.max(duration, animation.duration); animation.timeline.push(timeline); } // for (const timelineName of paramAnimations) { // const l2TimelineInfo = modelConfig.modelImpl.getTimelineInfo(timelineName); // if (!l2TimelineInfo) { // continue; // } // const timeline = new dbft.TypeTimeline(); // timeline.type = dbft.TimelineType.AnimationProgress; // timeline.name = timelineName; // // // const frame = new dbft.SingleValueFrame0(); // frame.value = l2TimelineInfo.default; // timeline.frame.push(frame); // animation.timeline.push(timeline); // } for (const timelineName in motionConfig.motion.alphas) { const part = modelConfig.modelImpl.getPart(timelineName); if (!part) { continue; } let duration = 0; const alphas = motionConfig.motion.alphas[timelineName]; for (const l2Display of part.displays) { if (l2Display instanceof l2ft.Mesh) { const timeline = new dbft.TypeTimeline(); timeline.type = dbft.TimelineType.SlotColor; timeline.name = l2Display.name; for (let i = 0, l = alphas.length; i < l; ++i) { const alpha = alphas[i]; const frame = new dbft.SlotColorFrame(); if (i !== l - 1) { frame.tweenEasing = 0; duration += frame.duration; } frame.value.aM = alpha * 100.0; timeline.frame.push(frame); } animation.timeline.push(timeline); } } animation.duration = Math.max(duration, animation.duration); } armature.animation.unshift(animation); index++; } } } if (modelConfig.expressions) { // Create expression animations. for (const expressionConfig of modelConfig.expressions) { const expression = expressionConfig.expression; if (!expression || !expression.params || expression.params.length === 0) { continue; } const animation = new dbft.Animation(); animation.playTimes = 1; animation.fadeInTime = expression.fade_in ? expression.fade_in * 0.001 : 0.3; animation.name = expressionConfig.name; animation.type = dbft.AnimationType.Tree; for (const timelineConfig of expression.params) { const l2TimelineInfo = modelConfig.modelImpl.getTimelineInfo(timelineConfig.id); if (!l2TimelineInfo) { continue; } const timeline = new dbft.TypeTimeline(); timeline.type = dbft.TimelineType.AnimationProgress; timeline.name = l2TimelineInfo.name; // const frame = new dbft.SingleValueFrame0(); frame.value = (timelineConfig.val - l2TimelineInfo.minimum) / (l2TimelineInfo.maximum - l2TimelineInfo.minimum); timeline.frame.push(frame); if (timelineConfig.def) { // TODO } animation.duration = 0; animation.timeline.push(timeline); } armature.animation.unshift(animation); } } return result; } function getPose<T>( l2Timelines: l2ft.Timeline[], frames: T[], action: (a: T, b: T | null, t: number) => T, level: number = -1, offset: number = -1 ): T { if (level < 0) { if (l2Timelines.length > 0) { level = l2Timelines.length - 1; offset = 0; } else { return frames[0]; } } const l2Timeline = l2Timelines[level]; const l2TimelineInfo = modelConfig.modelImpl.getTimelineInfo(l2Timeline.name) as l2ft.TimelineInfo; let index = l2Timeline.frames.indexOf(l2TimelineInfo.default); let count = 1; if (index < 0) { if (l2TimelineInfo.default <= l2Timeline.frames[0]) { index = 0; } else if (l2TimelineInfo.default >= l2Timeline.frames[l2Timeline.frames.length - 1]) { index = l2Timeline.frames.length - 1; } } for (let i = 0; i < level; ++i) { count *= l2Timelines[i].frameCount; } if (index < 0) { for (const value of l2Timeline.frames) { index++; if (value > l2TimelineInfo.default) { const prevValue = l2Timeline.frames[index - 1]; const progress = (l2TimelineInfo.default - prevValue) / (value - prevValue); if (level === 0) { return action( frames[offset + index - 1], frames[offset + index], progress ); } return action( getPose(l2Timelines, frames, action, level - 1, offset + (index - 1) * count), getPose(l2Timelines, frames, action, level - 1, offset + index * count), progress ); } } throw new Error(); } else { if (level === 0) { return frames[offset + index]; } offset += index * count; return getPose(l2Timelines, frames, action, level - 1, offset); } } function createAnimation<F, T extends { name: string }>( l2Timelines: l2ft.Timeline[], frames: F[], target: T, action: (l2Timeline: l2ft.Timeline, frames: F[], target: T, offset: number, blendAnimation: dbft.Animation) => void, indices: number[] = [0], parentAnimation: dbft.Animation | null = null ): void { const level = l2Timelines.length - indices.length; const index = indices[indices.length - 1]; const l2Timeline = l2Timelines[level]; let blendName = target.name; let animation = armature.getAnimation(l2Timeline.name) as dbft.Animation | null; if (!animation) { animation = new dbft.Animation(); animation.playTimes = 0; animation.duration = modelConfig.modelImpl.frameCount; animation.name = l2Timeline.name; animation.type = dbft.AnimationType.Tree; armature.animation.unshift(animation); } if (l2Timelines.length === 1) { action(l2Timeline, frames, target, 0, animation); return; } else if (level === 0 && !animation.getAnimationTimeline(blendName, dbft.TimelineType.AnimationProgress)) { const blendTimeline = new dbft.TypeTimeline(); const frameBegin = new dbft.SingleValueFrame0(); const frameEnd = new dbft.SingleValueFrame0(); frameBegin._position = 0; frameBegin.value = 0.0; frameBegin.tweenEasing = 0.0; frameEnd._position = animation.duration; frameEnd.value = 1.0; blendTimeline.type = dbft.TimelineType.AnimationProgress; blendTimeline.name = blendName; blendTimeline.frame.push(frameBegin, frameEnd); dbft.modifyFramesByPosition(blendTimeline.frame); animation.timeline.push(blendTimeline); } if (parentAnimation) { let i = 0; for (const value of indices) { if (i > 0) { blendName += "_" + (value).toString().padStart(2, "0"); } i++; } if (!parentAnimation.getAnimationTimeline(blendName, dbft.TimelineType.AnimationProgress)) { const parentL2Timleine = l2Timelines[level + 1]; const parentL2TimelineInfo = modelConfig.modelImpl.getTimelineInfo(parentL2Timleine.name) as l2ft.TimelineInfo; const totalValue = parentL2TimelineInfo.maximum - parentL2TimelineInfo.minimum; const childTimeline = new dbft.AnimationTimeline(); const frameBegin = new dbft.SingleValueFrame0(); const frameEnd = new dbft.SingleValueFrame0(); childTimeline.type = dbft.TimelineType.AnimationProgress; childTimeline.x = (parentL2Timleine.frames[index] - parentL2TimelineInfo.minimum) / totalValue * 2.0 - 1.0; childTimeline.name = blendName; frameBegin._position = 0; frameBegin.value = 0; frameBegin.tweenEasing = 0.0; frameEnd._position = parentAnimation.duration; frameEnd.value = 1.0; childTimeline.frame.push(frameBegin, frameEnd); dbft.modifyFramesByPosition(childTimeline.frame); parentAnimation.timeline.push(childTimeline); } } let blendAnimation = armature.getAnimation(blendName) as dbft.Animation | null; if (!blendAnimation) { blendAnimation = new dbft.Animation(); blendAnimation.playTimes = 0; blendAnimation.duration = animation.duration; blendAnimation.type = dbft.AnimationType.Node; blendAnimation.blendType = level !== 0 ? dbft.AnimationBlendType.E1D : dbft.AnimationBlendType.None; blendAnimation.name = blendName; armature.animation.push(blendAnimation); if (level !== 0) { const blendTimeline = new dbft.TypeTimeline(); const frameBegin = new dbft.DoubleValueFrame0(); const frameEnd = new dbft.DoubleValueFrame0(); frameBegin._position = 0; frameBegin.x = -1.0; frameBegin.tweenEasing = 0.0; frameEnd._position = blendAnimation.duration; frameEnd.x = 1.0; blendTimeline.type = dbft.TimelineType.AnimationParameter; blendTimeline.name = blendAnimation.name; blendTimeline.frame.push(frameBegin, frameEnd); dbft.modifyFramesByPosition(blendTimeline.frame); animation.timeline.push(blendTimeline); } } if (level === 0) { let offset = 0; for (let i = 0, l = indices.length; i < l; ++i) { const value = indices[i]; let count = 1; for (let j = 0; j < l2Timelines.length - i; ++j) { count *= l2Timelines[j].frameCount; } offset += value * count; } action(l2Timeline, frames, target, offset, blendAnimation); } else { for (let i = 0, l = l2Timeline.frameCount; i < l; ++i) { const childIndices = indices.concat(); childIndices.push(i); createAnimation(l2Timelines, frames, target, action, childIndices, blendAnimation); } } } function createDeformFrame( deformFrame: dbft.MutilpleValueFrame, l2DeformFrame: number[], pose: number[], isSurfaceParent: boolean, isRotatedParent: boolean ): void { for (let j = 0, lJ = l2DeformFrame.length; j < lJ; j += 2) { if (isSurfaceParent) { // Scale. deformFrame.value[j] = (l2DeformFrame[j] - 0.5) * 400.0 - pose[j]; deformFrame.value[j + 1] = (l2DeformFrame[j + 1] - 0.5) * 400.0 - pose[j + 1]; } else if (isRotatedParent) { // Rotate. rotateMatrixA.transformPoint(l2DeformFrame[j], l2DeformFrame[j + 1], geom.helpPointA); deformFrame.value[j] = geom.helpPointA.x - pose[j]; deformFrame.value[j + 1] = geom.helpPointA.y - pose[j + 1]; } else { // Offset. deformFrame.value[j] = l2DeformFrame[j] - pose[j] + armature.aabb.x; deformFrame.value[j + 1] = l2DeformFrame[j + 1] - pose[j + 1] + armature.aabb.y; } } } function vertivesCopyFrom(result: number[], target: number[]): void { result.length = target.length; for (let i = 0, l = target.length; i < l; ++i) { result[i] = target[i]; } } function vertivesAdd(result: number[], target: number[]): void { result.length = target.length; for (let i = 0, l = target.length; i < l; ++i) { result[i] += target[i]; } } function vertivesMinus(result: number[], target: number[]): void { result.length = target.length; for (let i = 0, l = target.length; i < l; ++i) { result[i] -= target[i]; } } function vertivesInterpolation(result: number[], a: number[], b: number[], t: number): void { result.length = a.length; const helper: number[] = []; vertivesCopyFrom(helper, b); vertivesMinus(helper, a); for (let i = 0, l = helper.length; i < l; ++i) { helper[i] *= t; } vertivesCopyFrom(result, a); vertivesAdd(result, helper); } function getMinAndMax(values: number[]) { let min = 999999.0; let max = -999999.0; for (const value of values) { if (value < min) { min = value; } if (value > max) { max = value; } } return [min, max]; }
the_stack
import { AsyncHierarchyIterable, AsyncOrderedHierarchyIterable } from '@esfx/async-iter-hierarchy'; import { AsyncOrderedIterable } from '@esfx/async-iter-ordered'; import { HashMap } from '@esfx/collections-hashmap'; import { HashSet } from '@esfx/collections-hashset'; import { Equaler } from '@esfx/equatable'; import { T } from '@esfx/fn'; import * as assert from "@esfx/internal-assert"; import { isAsyncIterable, isIterable, isPrimitive } from '@esfx/internal-guards'; import { Index } from '@esfx/interval'; import { Hierarchical, HierarchyIterable, HierarchyProvider } from "@esfx/iter-hierarchy"; import { Axis } from '@esfx/iter-hierarchy/axis'; import { OrderedIterable } from '@esfx/iter-ordered'; import { toArrayAsync } from './scalars'; function isHierarchyElement<T>(provider: HierarchyProvider<T>, value: T) { return value !== undefined && (provider.owns === undefined || provider.owns(value)); } function createAsyncHierarchyIterable(tag: string, axis: <TNode>(provider: HierarchyProvider<TNode>, element: TNode) => Iterable<TNode>) { return { [tag]: class <TNode> implements AsyncHierarchyIterable<TNode> { private _source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>; private _predicate: (element: TNode) => PromiseLike<boolean> | boolean; private _axis: (provider: HierarchyProvider<TNode>, element: TNode) => Iterable<TNode>; constructor(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => PromiseLike<boolean> | boolean) { this._source = source; this._predicate = predicate; this._axis = axis; } async *[Symbol.asyncIterator](): AsyncIterator<TNode> { const source = this._source; const hierarchy = source[Hierarchical.hierarchy](); const predicate = this._predicate; const axis = this._axis; for await (const element of source) { if (isHierarchyElement(hierarchy, element)) { for (const related of axis(hierarchy, element)) { let result = predicate(related); if (!isPrimitive(result)) result = await result; if (result) { yield related; } } } } } [Hierarchical.hierarchy]() { return this._source[Hierarchical.hierarchy](); } } }[tag]; } const AsyncRootHierarchyIterable = createAsyncHierarchyIterable("AsyncRootHierarchyIterable", 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 rootAsync<TNode, U extends TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): AsyncHierarchyIterable<TNode, U>; export function rootAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode>; export function rootAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => PromiseLike<boolean> | boolean = T): AsyncHierarchyIterable<TNode> { assert.assertType((isAsyncIterable(source) || isIterable(source)) && Hierarchical.hasInstance(source), "source"); assert.mustBeFunctionOrUndefined(predicate, "predicate"); return new AsyncRootHierarchyIterable(source, predicate); } const AsyncAncestorsHierarchyIterable = createAsyncHierarchyIterable("AsyncAncestorsHierarchyIterable", Axis.ancestors); /** * Selects the ancestors of each node in the iterable. This is equivalent to the `ancestor::*` selector in XPath. * @category Hierarchy */ export function ancestorsAsync<TNode, U extends TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): AsyncHierarchyIterable<TNode, U>; export function ancestorsAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode>; export function ancestorsAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => PromiseLike<boolean> | boolean = T): AsyncHierarchyIterable<TNode> { assert.assertType((isAsyncIterable(source) || isIterable(source)) && Hierarchical.hasInstance(source), "source"); assert.mustBeFunctionOrUndefined(predicate, "predicate"); return new AsyncAncestorsHierarchyIterable(source, predicate); } const AsyncAncestorsAndSelfHierarchyIterable = createAsyncHierarchyIterable("AsyncAncestorsAndSelfHierarchyIterable", 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 ancestorsAndSelfAsync<TNode, U extends TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): AsyncHierarchyIterable<TNode, U>; export function ancestorsAndSelfAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode>; export function ancestorsAndSelfAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => PromiseLike<boolean> | boolean = T): AsyncHierarchyIterable<TNode> { assert.assertType((isAsyncIterable(source) || isIterable(source)) && Hierarchical.hasInstance(source), "source"); assert.mustBeFunctionOrUndefined(predicate, "predicate"); return new AsyncAncestorsAndSelfHierarchyIterable(source, predicate); } const AsyncDescendantsHierarchyIterable = createAsyncHierarchyIterable("AsyncDescendantsHierarchyIterable", 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 descendantsAsync<TNode, U extends TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): AsyncHierarchyIterable<TNode, U>; export function descendantsAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode>; export function descendantsAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => PromiseLike<boolean> | boolean = T): AsyncHierarchyIterable<TNode> { assert.assertType((isAsyncIterable(source) || isIterable(source)) && Hierarchical.hasInstance(source), "source"); assert.mustBeFunctionOrUndefined(predicate, "predicate"); return new AsyncDescendantsHierarchyIterable(source, predicate); } const AsyncDescendantsAndSelfHierarchyIterable = createAsyncHierarchyIterable("AsyncDescendantsAndSelfHierarchyIterable", 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 descendantsAndSelfAsync<TNode, U extends TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): AsyncHierarchyIterable<TNode, U>; export function descendantsAndSelfAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode>; export function descendantsAndSelfAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => PromiseLike<boolean> | boolean = T): AsyncHierarchyIterable<TNode> { assert.assertType((isAsyncIterable(source) || isIterable(source)) && Hierarchical.hasInstance(source), "source"); assert.mustBeFunctionOrUndefined(predicate, "predicate"); return new AsyncDescendantsAndSelfHierarchyIterable(source, predicate); } const AsyncParentsHierarchyIterable = createAsyncHierarchyIterable("AsyncParentsHierarchyIterable", 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 parentsAsync<TNode, U extends TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): AsyncHierarchyIterable<TNode, U>; export function parentsAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode>; export function parentsAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => PromiseLike<boolean> | boolean = T): AsyncHierarchyIterable<TNode> { assert.assertType((isAsyncIterable(source) || isIterable(source)) && Hierarchical.hasInstance(source), "source"); assert.mustBeFunctionOrUndefined(predicate, "predicate"); return new AsyncParentsHierarchyIterable(source, predicate); } const AsyncSelfHierarchyIterable = createAsyncHierarchyIterable("AsyncSelfHierarchyIterable", Axis.self); /** * Selects each node in the iterable. This is equivalent to the `self::*` or `.` selectors in XPath. * @category Hierarchy */ export function selfAsync<TNode, T extends TNode, U extends T>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (element: T) => element is U): AsyncHierarchyIterable<TNode, U>; export function selfAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate?: (element: T) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode, T>; export function selfAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => PromiseLike<boolean> | boolean = T): AsyncHierarchyIterable<TNode> { assert.assertType((isAsyncIterable(source) || isIterable(source)) && Hierarchical.hasInstance(source), "source"); assert.mustBeFunctionOrUndefined(predicate, "predicate"); return new AsyncSelfHierarchyIterable(source, predicate); } const AsyncSiblingsHierarchyIterable = createAsyncHierarchyIterable("AsyncSiblingsHierarchyIterable", Axis.siblings); /** * Selects the siblings of each node in the iterable, excluding the node itself. * @category Hierarchy */ export function siblingsAsync<TNode, U extends TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): AsyncHierarchyIterable<TNode, U>; export function siblingsAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode>; export function siblingsAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => PromiseLike<boolean> | boolean = T): AsyncHierarchyIterable<TNode> { assert.assertType((isAsyncIterable(source) || isIterable(source)) && Hierarchical.hasInstance(source), "source"); assert.mustBeFunctionOrUndefined(predicate, "predicate"); return new AsyncSiblingsHierarchyIterable(source, predicate); } const AsyncSiblingsAndSelfHierarchyIterable = createAsyncHierarchyIterable("AsyncSiblingsAndSelfHierarchyIterable", 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 siblingsAndSelfAsync<TNode, U extends TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): AsyncHierarchyIterable<TNode, U>; export function siblingsAndSelfAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode>; export function siblingsAndSelfAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => PromiseLike<boolean> | boolean = T): AsyncHierarchyIterable<TNode> { assert.assertType((isAsyncIterable(source) || isIterable(source)) && Hierarchical.hasInstance(source), "source"); assert.mustBeFunctionOrUndefined(predicate, "predicate"); return new AsyncSiblingsAndSelfHierarchyIterable(source, predicate); } const AsyncPrecedingSiblingsHierarchyIterable = createAsyncHierarchyIterable("AsyncPrecedingSiblingsHierarchyIterable", 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 precedingSiblingsAsync<TNode, U extends TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): AsyncHierarchyIterable<TNode, U>; export function precedingSiblingsAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode>; export function precedingSiblingsAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => PromiseLike<boolean> | boolean = T): AsyncHierarchyIterable<TNode> { assert.assertType((isAsyncIterable(source) || isIterable(source)) && Hierarchical.hasInstance(source), "source"); assert.mustBeFunctionOrUndefined(predicate, "predicate"); return new AsyncPrecedingSiblingsHierarchyIterable(source, predicate); } export { precedingSiblingsAsync as siblingsBeforeSelfAsync }; export { followingSiblingsAsync as siblingsAfterSelfAsync }; const AsyncFollowingSiblingsHierarchyIterable = createAsyncHierarchyIterable("AsyncFollowingSiblingsHierarchyIterable", 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 followingSiblingsAsync<TNode, U extends TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): AsyncHierarchyIterable<TNode, U>; export function followingSiblingsAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode>; export function followingSiblingsAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => PromiseLike<boolean> | boolean = T): AsyncHierarchyIterable<TNode> { assert.assertType((isAsyncIterable(source) || isIterable(source)) && Hierarchical.hasInstance(source), "source"); assert.mustBeFunctionOrUndefined(predicate, "predicate"); return new AsyncFollowingSiblingsHierarchyIterable(source, predicate); } const AsyncPrecedingHierarchyIterable = createAsyncHierarchyIterable("AsyncPrecedingHierarchyIterable", 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 precedingAsync<TNode, U extends TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): AsyncHierarchyIterable<TNode, U>; export function precedingAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode>; export function precedingAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => PromiseLike<boolean> | boolean = T): AsyncHierarchyIterable<TNode> { assert.assertType((isAsyncIterable(source) || isIterable(source)) && Hierarchical.hasInstance(source), "source"); assert.mustBeFunctionOrUndefined(predicate, "predicate"); return new AsyncPrecedingHierarchyIterable(source, predicate); } const AsyncFollowingHierarchyIterable = createAsyncHierarchyIterable("AsyncFollowingHierarchyIterable", 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 followingAsync<TNode, U extends TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): AsyncHierarchyIterable<TNode, U>; export function followingAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode>; export function followingAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => PromiseLike<boolean> | boolean = T): AsyncHierarchyIterable<TNode> { assert.assertType((isAsyncIterable(source) || isIterable(source)) && Hierarchical.hasInstance(source), "source"); assert.mustBeFunctionOrUndefined(predicate, "predicate"); return new AsyncFollowingHierarchyIterable(source, predicate); } const AsyncChildrenHierarchyIterable = createAsyncHierarchyIterable("AsyncChildrenHierarchyIterable", 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 childrenAsync<TNode, U extends TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): AsyncHierarchyIterable<TNode, U>; export function childrenAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode>; export function childrenAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => PromiseLike<boolean> | boolean = T): AsyncHierarchyIterable<TNode> { assert.assertType((isAsyncIterable(source) || isIterable(source)) && Hierarchical.hasInstance(source), "source"); assert.mustBeFunctionOrUndefined(predicate, "predicate"); return new AsyncChildrenHierarchyIterable(source, predicate); } const AsyncFirstChildHierarchyIterable = createAsyncHierarchyIterable("AsyncFirstChildHierarchyIterable", 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 firstChildAsync<TNode, U extends TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): AsyncHierarchyIterable<TNode, U>; export function firstChildAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode>; export function firstChildAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => PromiseLike<boolean> | boolean = T): AsyncHierarchyIterable<TNode> { assert.assertType((isAsyncIterable(source) || isIterable(source)) && Hierarchical.hasInstance(source), "source"); assert.mustBeFunction(predicate, "predicate"); return new AsyncFirstChildHierarchyIterable(source, predicate); } const AsyncLastChildHierarchyIterable = createAsyncHierarchyIterable("AsyncLastChildHierarchyIterable", 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 lastChildAsync<TNode, U extends TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => element is U): AsyncHierarchyIterable<TNode, U>; export function lastChildAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode>; export function lastChildAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, predicate: (element: TNode) => PromiseLike<boolean> | boolean = T): AsyncHierarchyIterable<TNode> { assert.assertType((isAsyncIterable(source) || isIterable(source)) && Hierarchical.hasInstance(source), "source"); assert.mustBeFunction(predicate, "predicate"); return new AsyncLastChildHierarchyIterable(source, predicate); } class AsyncNthChildIterable<TNode, T extends TNode> implements AsyncIterable<TNode> { private _source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>; private _predicate: (element: TNode) => PromiseLike<boolean> | boolean; private _offset: number | Index; constructor(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, offset: number | Index, predicate: (element: TNode) => PromiseLike<boolean> | boolean) { this._source = source; this._offset = offset; this._predicate = predicate; } async *[Symbol.asyncIterator](): AsyncIterator<TNode> { const source = this._source; const provider = source[Hierarchical.hierarchy](); const offset = this._offset; const predicate = this._predicate; for await (const element of source) { if (isHierarchyElement(provider, element)) { for (const child of Axis.nthChild(provider, element, offset)) { let result = predicate(child); if (!isPrimitive(result)) result = await result; if (result) { yield child; } } } } } [Hierarchical.hierarchy]() { return this._source[Hierarchical.hierarchy](); } } /** * Creates an `AsyncHierarchyIterable` for the child of each element at the specified offset. A negative offset * starts from the last child. * * @param source An `AsyncHierarchyIterable` or `HierarchyIterable` object. * @param offset The offset for the child. * @param predicate An optional callback used to filter the results. * @category Hierarchy */ export function nthChildAsync<TNode, U extends TNode>(source: AsyncHierarchyIterable<TNode, U> | HierarchyIterable<TNode, U>, offset: number | Index, predicate: (element: TNode) => element is U): AsyncHierarchyIterable<TNode, U>; /** * Creates an `AsyncHierarchyIterable` for the child of each element at the specified offset. A negative offset * starts from the last child. * * @param source An `AsyncHierarchyIterable` or `HierarchyIterable` object. * @param offset The offset for the child. * @param predicate An optional callback used to filter the results. * @category Hierarchy */ export function nthChildAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, offset: number | Index, predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode>; export function nthChildAsync<TNode>(source: AsyncHierarchyIterable<TNode> | HierarchyIterable<TNode>, offset: number | Index, predicate: (element: TNode) => PromiseLike<boolean> | boolean = T): AsyncHierarchyIterable<TNode> { assert.assertType((isAsyncIterable(source) || isIterable(source)) && Hierarchical.hasInstance(source), "source"); assert.mustBeInteger(offset, "offset"); assert.mustBeFunction(predicate, "predicate"); return new AsyncNthChildIterable(source, offset, predicate); } class AsyncTopMostIterable<TNode, T extends TNode> implements AsyncHierarchyIterable<TNode, T> { private _source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>; private _predicate: (value: T) => PromiseLike<boolean> | boolean; private _equaler: Equaler<TNode> | undefined; constructor(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (value: T) => PromiseLike<boolean> | boolean, equaler: Equaler<TNode> | undefined) { this._source = source; this._predicate = predicate; this._equaler = equaler; } async *[Symbol.asyncIterator](): AsyncIterator<T> { const source = this._source; const predicate = this._predicate; const equaler = this._equaler; const hierarchy = source[Hierarchical.hierarchy](); const topMostNodes = await toArrayAsync(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--; } } } if (predicate === T) { yield* topMostNodes; } else { for (const node of topMostNodes) { if (await predicate(node)) yield node; } } } [Hierarchical.hierarchy]() { return this._source[Hierarchical.hierarchy](); } } /** * Creates an `AsyncHierarchyIterable` for the top-most elements. Elements of `source` that are a descendant of any other * element of `source` are removed. * * @param source An `AsyncHierarchyIterable` or `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 topMostAsync<TNode, T extends TNode, U extends T>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (element: T) => element is U, equaler?: Equaler<TNode>): AsyncHierarchyIterable<TNode, U>; /** * Creates an `AsyncHierarchyIterable` for the top-most elements. Elements of `source` that are a descendant of any other * element of `source` are removed. * * @param source An `AsyncHierarchyIterable` or `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 topMostAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate?: (element: T) => PromiseLike<boolean> | boolean, equaler?: Equaler<TNode>): AsyncHierarchyIterable<TNode, T>; export function topMostAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (element: T) => PromiseLike<boolean> | boolean = T, equaler: Equaler<TNode> = Equaler.defaultEqualer): AsyncHierarchyIterable<TNode, T> { assert.assertType((isAsyncIterable(source) || isIterable(source)) && Hierarchical.hasInstance(source), "source"); assert.mustBeFunction(predicate, "predicate"); assert.mustBeType(Equaler.hasInstance, equaler, "equaler"); return new AsyncTopMostIterable<TNode, T>(source, predicate, equaler); } class AsyncBottomMostIterable<TNode, T extends TNode> implements AsyncHierarchyIterable<TNode, T> { private _source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>; private _predicate: (value: T) => PromiseLike<boolean> | boolean; private _equaler: Equaler<TNode> | undefined; constructor(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (value: T) => PromiseLike<boolean> | boolean, equaler: Equaler<TNode> | undefined) { this._source = source; this._predicate = predicate; this._equaler = equaler; } async *[Symbol.asyncIterator](): AsyncIterator<T> { const source = this._source; const predicate = this._predicate; const equaler = this._equaler; const hierarchy = source[Hierarchical.hierarchy](); const bottomMostNodes = await toArrayAsync(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--; } } } if (predicate === T) { yield* bottomMostNodes; return; } for (const node of bottomMostNodes) { if (await predicate(node)) yield node; } } [Hierarchical.hierarchy]() { return this._source[Hierarchical.hierarchy](); } } /** * Creates an `AsyncHierarchyIterable` for the bottom-most elements. Elements of `source` that are an ancestor of any other * element of `source` are removed. * * @param source An `AsyncHierarchyIterable` or `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 bottomMostAsync<TNode, T extends TNode, U extends T>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (element: T) => element is U, equaler?: Equaler<TNode>): AsyncHierarchyIterable<TNode, U>; /** * Creates an `AsyncHierarchyIterable` for the bottom-most elements. Elements of `source` that are an ancestor of any other * element of `source` are removed. * * @param source An `AsyncHierarchyIterable` or `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 bottomMostAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate?: (element: T) => PromiseLike<boolean> | boolean, equaler?: Equaler<TNode>): AsyncHierarchyIterable<TNode, T>; export function bottomMostAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (element: T) => PromiseLike<boolean> | boolean = T, equaler: Equaler<TNode> = Equaler.defaultEqualer): AsyncHierarchyIterable<TNode, T> { assert.assertType((isAsyncIterable(source) || isIterable(source)) && Hierarchical.hasInstance(source), "source"); assert.mustBeFunction(predicate, "predicate"); assert.mustBeType(Equaler.hasInstance, equaler, "equaler"); return new AsyncBottomMostIterable<TNode, T>(source, predicate, equaler); } /** * Creates an `AsyncHierarchyIterable` using the provided `HierarchyProvider`. * * @param source An `AsyncIterable` or `Iterable` object. * @param hierarchy A `HierarchyProvider`. * @category Hierarchy */ export function toHierarchyAsync<TNode, T extends TNode = TNode>(source: AsyncOrderedIterable<T> | OrderedIterable<T>, hierarchy: HierarchyProvider<TNode>): AsyncOrderedHierarchyIterable<TNode, T>; /** * Creates an `AsyncHierarchyIterable` using the provided `HierarchyProvider`. * * @param source An `AsyncIterable` or `Iterable` object. * @param hierarchy A `HierarchyProvider`. * @category Hierarchy */ export function toHierarchyAsync<TNode, T extends TNode = TNode>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, hierarchy: HierarchyProvider<TNode>): AsyncHierarchyIterable<TNode, T>; export function toHierarchyAsync<TNode, T extends TNode = TNode>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, hierarchy: HierarchyProvider<TNode>): AsyncHierarchyIterable<TNode, T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeType(HierarchyProvider.hasInstance, hierarchy, "hierarchy"); return AsyncHierarchyIterable.create(source, hierarchy); }
the_stack
import { parse, parseExpression } from '@babel/parser' import { Expression, File, Identifier, isArrayPattern, isAssignmentPattern, isCallExpression, isClassDeclaration, isDeclaration, isDeclareClass, isDeclareFunction, isDeclareVariable, isEnumDeclaration, isExpression, isFile, isFunction, isFunctionDeclaration, isIdentifier, isImportDeclaration, isImportSpecifier, isMemberExpression, isObjectMember, isObjectPattern, isOptionalMemberExpression, isPrivateName, isRestElement, isVariableDeclaration, LVal, Node as BabelNode, ObjectMember, PatternLike, traverse as traverseBabel, } from '@babel/types' import { isSimpleIdentifier, Node, RootNode } from '@vue/compiler-core' import { flatten, isCamelCase, isPascalCase } from '@vuedx/shared' import { isDirectiveNode, isElementNode, isSimpleExpressionNode, traverse, } from '@vuedx/template-ast-types' import { forAliasRE } from './transforms/transformFor' export class Scope { public readonly bindings: Record<string, Node | null> = {} public constructor(public readonly parent: Scope | null = null) {} public get identifiers(): string[] { return Array.from(Object.keys(this.bindings)) } public get globals(): string[] { return this.identifiers.filter( (identifier) => this.getBinding(identifier) === null, ) } public getBinding(identifier: string): null | Node { if (identifier in this.bindings) return this.bindings[identifier] ?? null if (this.parent != null) { return (this.bindings[identifier] = this.parent.getBinding(identifier)) } else { this.bindings[identifier] = null } return null } public setBinding(identifer: string, node: Node): void { this.bindings[identifer] = node } } export function withScope(ast: RootNode): RootNode { ast.scope = new Scope(null) traverse(ast, (node, ancestors) => { const parent = (ancestors[ancestors.length - 1]?.node ?? ast) as any const scope = (node.scope = node.scope ?? new Scope(parent.scope)) if (isSimpleExpressionNode(node) && !node.isStatic) { if ( parent != null || !( isDirectiveNode(parent) && ['slot', 'for'].includes(parent.name) && parent.exp === node ) ) { getIdentifiers(node.content).forEach((identifier) => scope.getBinding(identifier), ) } } else if (isElementNode(node)) { node.props.forEach((prop) => { if (isDirectiveNode(prop)) { const directiveScope = (prop.scope = prop.scope ?? new Scope(scope)) if (prop.name === 'slot') { if (isSimpleExpressionNode(prop.exp)) { const localScope = (prop.exp.scope = new Scope(directiveScope)) const content = prop.exp.content.trim() getIdentifiers(`(${content}) => {}`).forEach((identifier) => { scope.setBinding(identifier, node) localScope.getBinding(identifier) }) } } else if (prop.name === 'for') { if (isSimpleExpressionNode(prop.exp)) { const localScope = (prop.exp.scope = new Scope(directiveScope)) const match = forAliasRE.exec(prop.exp.content) if (match != null) { const LHS = match[1]! const RHS = match[2]! getIdentifiers(RHS).forEach((identifier) => { localScope.getBinding(identifier) }) getIdentifiers(`${LHS ?? '()'} => {}`).forEach((identifier) => { scope.setBinding(identifier, node) localScope.getBinding(identifier) }) } } } // TODO: Handle scope in v-on // If block statement and uses `$event`, add to scope. } }) } }) return ast } /** * @internal */ export function getTopLevelIdentifiers( source: string, ignoreImportsFrom: string[], ): { identifiers: Set<string> components: Set<string> directives: Set<string> propsIdentifier: string | undefined emitIdentifier: string | undefined } { const identifiers = new Set<string>() const components = new Set<string>() const directives = new Set<string>() let propsIdentifier: string | undefined let emitIdentifier: string | undefined let definePropsIdentifierFn: string | undefined let defineEmitIdentifierFn: string | undefined const ignoredSources = new Set(ignoreImportsFrom) try { const ast = parseUsingBabel(source, true) const getIdentifiers = (node: LVal): string[] => { if (isIdentifier(node)) return [node.name] else if (isMemberExpression(node)) { if (isIdentifier(node.property)) { return [node.property.name] } else if (isExpression(node.property)) { return [] } else if (isPrivateName(node.property)) { return [node.property.id.name] } else { return [] } } else if (isRestElement(node)) { return getIdentifiers(node.argument) } else if (isAssignmentPattern(node)) { return getIdentifiers(node.left) } else if (isArrayPattern(node)) { return flatten( node.elements .filter((element): element is PatternLike => element != null) .map((element) => getIdentifiers(element)), ) } else if (isObjectPattern(node)) { return flatten( node.properties.map((property) => { if (isRestElement(property) || isIdentifier(property)) { return getIdentifiers(property) } else { return [] } }), ) } else { return [] } } if (isFile(ast)) { ast.program.body.forEach((node) => { if (!isDeclaration(node)) return if (isVariableDeclaration(node)) { node.declarations.forEach((declaration) => { getIdentifiers(declaration.id).forEach((name) => identifiers.add(name), ) if ( isIdentifier(declaration.id) && isCallExpression(declaration.init) ) { if (isIdentifier(declaration.init.callee)) { if (declaration.init.callee.name === definePropsIdentifierFn) { propsIdentifier = declaration.id.name } else if ( declaration.init.callee.name === defineEmitIdentifierFn ) { emitIdentifier = declaration.id.name } } } }) } else if (isFunctionDeclaration(node)) { if (node.id != null) identifiers.add(node.id.name) } else if (isImportDeclaration(node)) { const isVue = node.source.value === 'vue' node.specifiers.forEach((specifier) => { if (isVue && isImportSpecifier(specifier)) { const name = isIdentifier(specifier.imported) ? specifier.imported.name : specifier.imported.value if (name === 'defineProps') { definePropsIdentifierFn = specifier.local.name return // - } else if (name === 'defineEmit') { defineEmitIdentifierFn = specifier.local.name return // - } } if (!ignoredSources.has(node.source.value)) { identifiers.add(specifier.local.name) if ( isCamelCase(specifier.local.name) && /^v[A-Z]/.test(specifier.local.name) ) { directives.add(specifier.local.name) } else if (isPascalCase(specifier.local.name)) { components.add(specifier.local.name) } } }) } else if (isClassDeclaration(node)) { identifiers.add(node.id.name) } else if (isDeclareClass(node)) { identifiers.add(node.id.name) } else if (isDeclareFunction(node)) { identifiers.add(node.id.name) } else if (isDeclareVariable(node)) { identifiers.add(node.id.name) } else if (isEnumDeclaration(node)) { identifiers.add(node.id.name) } }) } } catch { // FIXME: Handle errors } return { identifiers, components, directives, emitIdentifier, propsIdentifier, } } function getIdentifiers(source: string): Set<string> { source = source .trim() // Common errors when user is typing. .replace(/(\.|\[\]?)\s*$/, '') const identifiers = new Set<string>() const add = (id: string): void => { if (isValidIdentifier(id)) identifiers.add(id) } if (isSimpleIdentifier(source.trim())) { add(source) } else { try { const ast = parseUsingBabel(source, false) traverseBabel(ast, (node, ancestors) => { if (isIdentifier(node)) { if (ancestors.length > 0) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion if (shouldTrack(node, ancestors[ancestors.length - 1]!.node)) { add(node.name) } } else { add(node.name) } } }) } catch { const RE = /\b[a-z$_][a-z0-9$_]+\b/gi let match: RegExpMatchArray | null while ((match = RE.exec(source)) != null) { add(match[0] ?? '') } } } return identifiers } function isValidIdentifier(id: string): boolean { return ( id.trim().length > 0 && !/^(of|in|for|while|function|class|const|let|var)$/.test(id) ) } function parseUsingBabel(source: string, withTS = false): File | Expression { try { return parse(source, { plugins: withTS ? ['bigInt', 'optionalChaining', 'typescript'] : ['bigInt', 'optionalChaining'], // @ts-expect-error errorRecovery: true, }) } catch { return parseExpression(source, { plugins: withTS ? ['bigInt', 'optionalChaining', 'typescript'] : ['bigInt', 'optionalChaining'], // @ts-expect-error errorRecovery: true, }) } } // TODO: This misses destructured arguments function shouldTrack(identifier: Identifier, parent: BabelNode): boolean { if ( !( isFunction(parent) && // not id of a FunctionDeclaration (parent as any).id === identifier ) && // not a key of Property !isStaticPropertyKey(identifier, parent) && // not a property of a MemberExpression !( (isMemberExpression(parent) || isOptionalMemberExpression(parent)) && parent.property === identifier && !parent.computed ) && // skip allowed globals !isKnownIdentifier(identifier.name) && // special case for webpack compilation identifier.name !== `require` && // is a special keyword but parsed as identifier identifier.name !== `arguments` ) { return true } return false } const KNOWN_IDENTIFIERS = new Set( ( 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' + 'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' + 'Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt' ).split(','), ) function isKnownIdentifier(value: string): boolean { return KNOWN_IDENTIFIERS.has(value) || /^(true|false|null|this)$/.test(value) } function isStaticProperty(node: BabelNode): node is ObjectMember { return isObjectMember(node) && !node.computed } function isStaticPropertyKey(node: BabelNode, parent: BabelNode): boolean { return isStaticProperty(parent) && parent.key === node }
the_stack
import { LokiEventEmitter } from "./event_emitter"; import { ResultSet } from "./result_set"; import { Collection } from "./collection"; import { Doc } from "../../common/types"; import { Scorer } from "../../full-text-search/src/scorer"; /** * DynamicView class is a versatile 'live' view class which can have filters and sorts applied. * Collection.addDynamicView(name) instantiates this DynamicView object and notifies it * whenever documents are add/updated/removed so it can remain up-to-date. (chainable) * * @example * let mydv = mycollection.addDynamicView('test'); // default is non-persistent * mydv.applyFind({ 'doors' : 4 }); * mydv.applyWhere(function(obj) { return obj.name === 'Toyota'; }); * let results = mydv.data(); * * @extends LokiEventEmitter * @see {@link Collection#addDynamicView} to construct instances of DynamicView * * @param <TData> - the data type * @param <TNested> - nested properties of data type */ export class DynamicView<T extends object = object> extends LokiEventEmitter { public readonly name: string; private _collection: Collection<T>; private _persistent: boolean; private _sortPriority: DynamicView.SortPriority; private _minRebuildInterval: number; private _rebuildPending: boolean = false; private _resultSet: ResultSet<T>; private _resultData: Doc<T>[] = []; private _resultDirty: boolean = false; private _cachedResultSet: ResultSet<T> = null; // keep ordered filter pipeline private _filterPipeline: DynamicView.Filter<T>[] = []; // sorting member variables // we only support one active search, applied using applySort() or applySimpleSort() private _sortFunction: (lhs: Doc<T>, rhs: Doc<T>) => number = null; private _sortCriteria: (keyof T | [keyof T, boolean])[] = null; private _sortCriteriaSimple: { field: keyof T, options: boolean | ResultSet.SimpleSortOptions } = null; private _sortByScoring: boolean = null; private _sortDirty: boolean = false; /** * Constructor. * @param {Collection} collection - a reference to the collection to work agains * @param {string} name - the name of this dynamic view * @param {object} options - the options * @param {boolean} [options.persistent=false] - indicates if view is to main internal results array in 'resultdata' * @param {string} [options.sortPriority="passive"] - the sort priority * @param {number} [options.minRebuildInterval=1] - minimum rebuild interval (need clarification to docs here) */ constructor(collection: Collection<T>, name: string, options: DynamicView.Options = {}) { super(); ( { persistent: this._persistent = false, // 'passive' will defer the sort phase until they call data(). (most efficient overall) // 'active' will sort async whenever next idle. (prioritizes read speeds) sortPriority: this._sortPriority = "passive", minRebuildInterval: this._minRebuildInterval = 1 } = options ); this._collection = collection; this.name = name; this._resultSet = new ResultSet(collection); // for now just have 1 event for when we finally rebuilt lazy view // once we refactor transactions, i will tie in certain transactional events this._events = { "rebuild": [] }; } /** * Internally used immediately after deserialization (loading) * This will clear out and reapply filterPipeline ops, recreating the view. * Since where filters do not persist correctly, this method allows * restoring the view to state where user can re-apply those where filters. * * @param removeWhereFilters * @returns {DynamicView} This dynamic view for further chained ops. * @fires DynamicView.rebuild */ private _rematerialize({removeWhereFilters = false}): this { this._resultData = []; this._resultDirty = true; this._resultSet = new ResultSet(this._collection); if (this._sortFunction || this._sortCriteria || this._sortCriteriaSimple || this._sortByScoring !== null) { this._sortDirty = true; } if (removeWhereFilters) { // for each view see if it had any where filters applied... since they don't // serialize those functions lets remove those invalid filters let fpi = this._filterPipeline.length; while (fpi--) { if (this._filterPipeline[fpi].type === "where") { if (fpi !== this._filterPipeline.length - 1) { this._filterPipeline[fpi] = this._filterPipeline[this._filterPipeline.length - 1]; } this._filterPipeline.length--; } } } // back up old filter pipeline, clear filter pipeline, and reapply pipeline ops const ofp = this._filterPipeline; this._filterPipeline = []; // now re-apply 'find' filterPipeline ops for (let idx = 0; idx < ofp.length; idx++) { this.applyFind(ofp[idx].val); } // during creation of unit tests, i will remove this forced refresh and leave lazy this.data(); // emit rebuild event in case user wants to be notified this.emit("rebuild", this); return this; } /** * Makes a copy of the internal ResultSet for branched queries. * Unlike this dynamic view, the branched ResultSet will not be 'live' updated, * so your branched query should be immediately resolved and not held for future evaluation. * @param {(string|array=)} transform - Optional name of collection transform, or an array of transform steps * @param {object} parameters - optional parameters (if optional transform requires them) * @returns {ResultSet} A copy of the internal ResultSet for branched queries. */ public branchResultSet(transform?: string | Collection.Transform<T>[], parameters?: object): ResultSet<T> { const rs = this._resultSet.copy(); if (transform === undefined) { return rs; } return rs.transform(transform, parameters); } /** * Override of toJSON to avoid circular references. */ public toJSON(): DynamicView.Serialized { return { name: this.name, _persistent: this._persistent, _sortPriority: this._sortPriority, _minRebuildInterval: this._minRebuildInterval, _resultSet: this._resultSet, _filterPipeline: this._filterPipeline, _sortCriteria: this._sortCriteria, _sortCriteriaSimple: this._sortCriteriaSimple, _sortByScoring: this._sortByScoring, _sortDirty: this._sortDirty, }; } public static fromJSONObject(collection: Collection, obj: DynamicView.Serialized): DynamicView { let dv = new DynamicView(collection, obj.name); dv._resultDirty = true; dv._filterPipeline = obj._filterPipeline; dv._resultData = []; dv._sortCriteria = obj._sortCriteria as any; dv._sortCriteriaSimple = obj._sortCriteriaSimple as any; dv._sortByScoring = obj._sortByScoring; dv._sortDirty = obj._sortDirty; dv._resultSet._filteredRows = obj._resultSet._filteredRows; dv._resultSet._filterInitialized = obj._resultSet._filterInitialized; dv._rematerialize({ removeWhereFilters: true }); return dv; } /** * Used to clear pipeline and reset dynamic view to initial state. * Existing options should be retained. * @param {boolean} queueSortPhase - (default: false) if true we will async rebuild view (maybe set default to true in future?) */ public removeFilters({queueSortPhase = false} = {}): void { this._rebuildPending = false; this._resultSet.reset(); this._resultData = []; this._resultDirty = true; this._cachedResultSet = null; // keep ordered filter pipeline this._filterPipeline = []; // sorting member variables // we only support one active search, applied using applySort() or applySimpleSort() this._sortFunction = null; this._sortCriteria = null; this._sortCriteriaSimple = null; this._sortByScoring = null; this._sortDirty = false; if (queueSortPhase === true) { this._queueSortPhase(); } } /** * Used to apply a sort to the dynamic view * @example * dv.applySort(function(obj1, obj2) { * if (obj1.name === obj2.name) return 0; * if (obj1.name > obj2.name) return 1; * if (obj1.name < obj2.name) return -1; * }); * @param {function} comparefun - a javascript compare function used for sorting * @returns {DynamicView} this DynamicView object, for further chain ops. */ public applySort(comparefun: (lhs: Doc<T>, rhs: Doc<T>) => number): this { this._sortFunction = comparefun; this._sortCriteria = null; this._sortCriteriaSimple = null; this._sortByScoring = null; this._queueSortPhase(); return this; } /** * Used to specify a property used for view translation. * @param {string} field - the field name * @param {boolean|object=} options - boolean for sort descending or options object * @param {boolean} [options.desc=false] - whether we should sort descending. * @param {boolean} [options.disableIndexIntersect=false] - whether we should explicity not use array intersection. * @param {boolean} [options.forceIndexIntersect=false] - force array intersection (if binary index exists). * @param {boolean} [options.useJavascriptSorting=false] - whether results are sorted via basic javascript sort. * @returns {DynamicView} this DynamicView object, for further chain ops. * @example * dv.applySimpleSort("name"); */ public applySimpleSort(field: keyof T, options: boolean | ResultSet.SimpleSortOptions = false): this { this._sortCriteriaSimple = {field, options}; this._sortFunction = null; this._sortCriteria = null; this._sortByScoring = null; this._queueSortPhase(); return this; } /** * Allows sorting a ResultSet based on multiple columns. * @param {Array} criteria - array of property names or subarray of [propertyname, isdesc] used evaluate sort order * @returns {DynamicView} Reference to this DynamicView, sorted, for future chain operations. * @example * // to sort by age and then name (both ascending) * dv.applySortCriteria(['age', 'name']); * // to sort by age (ascending) and then by name (descending) * dv.applySortCriteria(['age', ['name', true]]); * // to sort by age (descending) and then by name (descending) * dv.applySortCriteria([['age', true], ['name', true]]); */ public applySortCriteria(criteria: (keyof T | [keyof T, boolean])[]): this { this._sortCriteria = criteria; this._sortCriteriaSimple = null; this._sortFunction = null; this._sortByScoring = null; this._queueSortPhase(); return this; } /** * Used to apply a sort by the latest full-text-search scoring. * @param {boolean} [ascending=false] - sort ascending */ public applySortByScoring(ascending = false): this { this._sortFunction = null; this._sortCriteria = null; this._sortCriteriaSimple = null; this._sortByScoring = ascending; this._queueSortPhase(); return this; } /** * Returns the scoring of the last full-text-search. * @returns {ScoreResult[]} */ public getScoring(): Scorer.ScoreResult[] { return this._resultSet.getScoring(); } /** * Marks the beginning of a transaction. * @returns {DynamicView} this DynamicView object, for further chain ops. */ public startTransaction(): this { this._cachedResultSet = this._resultSet.copy(); return this; } /** * Commits a transaction. * @returns {DynamicView} this DynamicView object, for further chain ops. */ public commit(): this { this._cachedResultSet = null; return this; } /** * Rolls back a transaction. * @returns {DynamicView} this DynamicView object, for further chain ops. */ public rollback(): this { this._resultSet = this._cachedResultSet; if (this._persistent) { // for now just rebuild the persistent dynamic view data in this worst case scenario // (a persistent view utilizing transactions which get rolled back), we already know the filter so not too bad. this._resultData = this._resultSet.data(); this.emit("rebuild", this); } return this; } /** * Find the index of a filter in the pipeline, by that filter's ID. * @param {(string|number)} uid - The unique ID of the filter. * @returns {number}: index of the referenced filter in the pipeline; -1 if not found. */ private _indexOfFilterWithId(uid: string | number): number { if (typeof uid === "string" || typeof uid === "number") { for (let idx = 0, len = this._filterPipeline.length; idx < len; idx++) { if (uid === this._filterPipeline[idx].uid) { return idx; } } } return -1; } /** * Add the filter object to the end of view's filter pipeline and apply the filter to the ResultSet. * @param {object} filter - The filter object. Refer to applyFilter() for extra details. */ private _addFilter(filter: DynamicView.Filter<T>): void { this._filterPipeline.push(filter); this._resultSet[filter.type as string](filter.val); } /** * Reapply all the filters in the current pipeline. * * @returns {DynamicView} this DynamicView object, for further chain ops. */ public reapplyFilters(): this { this._resultSet.reset(); this._cachedResultSet = null; if (this._persistent) { this._resultData = []; this._resultDirty = true; } const filters = this._filterPipeline; this._filterPipeline = []; for (let idx = 0, len = filters.length; idx < len; idx++) { this._addFilter(filters[idx]); } if (this._sortFunction || this._sortCriteria || this._sortCriteriaSimple || this._sortByScoring !== null) { this._queueSortPhase(); } else { this._queueRebuildEvent(); } return this; } /** * Adds or updates a filter in the DynamicView filter pipeline * @param {object} filter - A filter object to add to the pipeline. * The object is in the format { 'type': filter_type, 'val', filter_param, 'uid', optional_filter_id } * @returns {DynamicView} this DynamicView object, for further chain ops. */ public applyFilter(filter: DynamicView.Filter<T>): this { const idx = this._indexOfFilterWithId(filter.uid); if (idx >= 0) { this._filterPipeline[idx] = filter; return this.reapplyFilters(); } this._cachedResultSet = null; if (this._persistent) { this._resultData = []; this._resultDirty = true; } this._addFilter(filter); if (this._sortFunction || this._sortCriteria || this._sortCriteriaSimple || this._sortByScoring !== null) { this._queueSortPhase(); } else { this._queueRebuildEvent(); } return this; } /** * applyFind() - Adds or updates a mongo-style query option in the DynamicView filter pipeline * * @param {object} query - A mongo-style query object to apply to pipeline * @param {(string|number)} uid - Optional: The unique ID of this filter, to reference it in the future. * @returns {DynamicView} this DynamicView object, for further chain ops. */ public applyFind(query: object, uid: string | number = ""): this { this.applyFilter({ type: "find", val: query, uid }); return this; } /** * Adds or updates a javascript filter function in the DynamicView filter pipeline * @param {function} fun - A javascript filter function to apply to pipeline * @param {(string|number)} uid - Optional: The unique ID of this filter, to reference it in the future. * @returns {DynamicView} this DynamicView object, for further chain ops. */ public applyWhere(fun: (obj: Doc<T>) => boolean, uid?: string | number): this { this.applyFilter({ type: "where", val: fun, uid }); return this; } /** * Remove the specified filter from the DynamicView filter pipeline * @param {(string|number)} uid - The unique ID of the filter to be removed. * @returns {DynamicView} this DynamicView object, for further chain ops. */ public removeFilter(uid: string | number): this { const idx = this._indexOfFilterWithId(uid); if (idx < 0) { throw new Error("Dynamic view does not contain a filter with ID: " + uid); } this._filterPipeline.splice(idx, 1); this.reapplyFilters(); return this; } /** * Returns the number of documents representing the current DynamicView contents. * @returns {number} The number of documents representing the current DynamicView contents. */ public count(): number { // in order to be accurate we will pay the minimum cost (and not alter dv state management) // recurring ResultSet data resolutions should know internally its already up to date. // for persistent data this will not update resultdata nor fire rebuild event. if (this._resultDirty) { this._resultData = this._resultSet.data(); } return this._resultSet.count(); } /** * Resolves and pending filtering and sorting, then returns document array as result. * @param {object} options - optional parameters to pass to ResultSet.data() if non-persistent * @param {boolean} [options.forceClones] - Allows forcing the return of cloned objects even when * the collection is not configured for clone object. * @param {string} [options.forceCloneMethod] - Allows overriding the default or collection specified cloning method. * Possible values include 'parse-stringify', 'jquery-extend-deep', 'shallow', 'shallow-assign' * @param {boolean} [options.removeMeta] - will force clones and strip $loki and meta properties from documents * * @returns {Array} An array of documents representing the current DynamicView contents. */ public data(options: ResultSet.DataOptions = {}): Doc<T>[] { // using final sort phase as 'catch all' for a few use cases which require full rebuild if (this._sortDirty || this._resultDirty) { this._performSortPhase({ suppressRebuildEvent: true }); } return (this._persistent) ? (this._resultData) : (this._resultSet.data(options)); } /** * When the view is not sorted we may still wish to be notified of rebuild events. * This event will throttle and queue a single rebuild event when batches of updates affect the view. */ private _queueRebuildEvent(): void { if (this._rebuildPending) { return; } this._rebuildPending = true; setTimeout(() => { if (this._rebuildPending) { this._rebuildPending = false; this.emit("rebuild", this); } }, this._minRebuildInterval); } /** * If the view is sorted we will throttle sorting to either : * (1) passive - when the user calls data(), or * (2) active - once they stop updating and yield js thread control */ private _queueSortPhase(): void { // already queued? exit without queuing again if (this._sortDirty) { return; } this._sortDirty = true; if (this._sortPriority === "active") { // active sorting... once they are done and yield js thread, run async performSortPhase() setTimeout(() => { this._performSortPhase(); }, this._minRebuildInterval); } else { // must be passive sorting... since not calling performSortPhase (until data call), lets use queueRebuildEvent to // potentially notify user that data has changed. this._queueRebuildEvent(); } } /** * Invoked synchronously or asynchronously to perform final sort phase (if needed) */ private _performSortPhase(options: { suppressRebuildEvent?: boolean } = {}): void { // async call to this may have been pre-empted by synchronous call to data before async could fire if (!this._sortDirty && !this._resultDirty) { return; } if (this._sortDirty) { if (this._sortFunction) { this._resultSet.sort(this._sortFunction); } else if (this._sortCriteria) { this._resultSet.compoundsort(this._sortCriteria); } else if (this._sortCriteriaSimple) { this._resultSet.simplesort(this._sortCriteriaSimple.field, this._sortCriteriaSimple.options); } else if (this._sortByScoring !== null) { this._resultSet.sortByScoring(this._sortByScoring); } this._sortDirty = false; } if (this._persistent) { // persistent view, rebuild local resultdata array this._resultData = this._resultSet.data(); this._resultDirty = false; } if (!options.suppressRebuildEvent) { this.emit("rebuild", this); } } /** * (Re)evaluating document inclusion. * Called by : collection.insert() and collection.update(). * @param {int} objIndex - index of document to (re)run through filter pipeline. * @param {boolean} isNew - true if the document was just added to the collection. * @hidden */ _evaluateDocument(objIndex: number, isNew: boolean): void { // if no filter applied yet, the result 'set' should remain 'everything' if (!this._resultSet._filterInitialized) { if (this._persistent) { this._resultData = this._resultSet.data(); } // need to re-sort to sort new document if (this._sortFunction || this._sortCriteria || this._sortCriteriaSimple) { this._queueSortPhase(); } else { this._queueRebuildEvent(); } return; } const ofr = this._resultSet._filteredRows; const oldPos = (isNew) ? (-1) : (ofr.indexOf(+objIndex)); const oldlen = ofr.length; // creating a 1-element ResultSet to run filter chain ops on to see if that doc passes filters; // mostly efficient algorithm, slight stack overhead price (this function is called on inserts and updates) const evalResultSet = new ResultSet(this._collection); evalResultSet._filteredRows = [objIndex]; evalResultSet._filterInitialized = true; let filter; for (let idx = 0, len = this._filterPipeline.length; idx < len; idx++) { filter = this._filterPipeline[idx]; evalResultSet[filter.type as string](filter.val); } // not a true position, but -1 if not pass our filter(s), 0 if passed filter(s) const newPos = (evalResultSet._filteredRows.length === 0) ? -1 : 0; // wasn't in old, shouldn't be now... do nothing if (oldPos === -1 && newPos === -1) return; // wasn't in ResultSet, should be now... add if (oldPos === -1 && newPos !== -1) { ofr.push(objIndex); if (this._persistent) { this._resultData.push(this._collection._data[objIndex]); } // need to re-sort to sort new document if (this._sortFunction || this._sortCriteria || this._sortCriteriaSimple) { this._queueSortPhase(); } else { this._queueRebuildEvent(); } return; } // was in ResultSet, shouldn't be now... delete if (oldPos !== -1 && newPos === -1) { if (oldPos < oldlen - 1) { ofr.splice(oldPos, 1); if (this._persistent) { this._resultData.splice(oldPos, 1); } } else { ofr.length = oldlen - 1; if (this._persistent) { this._resultData.length = oldlen - 1; } } // in case changes to data altered a sort column if (this._sortFunction || this._sortCriteria || this._sortCriteriaSimple) { this._queueSortPhase(); } else { this._queueRebuildEvent(); } return; } // was in ResultSet, should still be now... (update persistent only?) if (oldPos !== -1 && newPos !== -1) { if (this._persistent) { // in case document changed, replace persistent view data with the latest collection._data document this._resultData[oldPos] = this._collection._data[objIndex]; } // in case changes to data altered a sort column if (this._sortFunction || this._sortCriteria || this._sortCriteriaSimple) { this._queueSortPhase(); } else { this._queueRebuildEvent(); } } } /** * Internal function called on collection.delete(). * @hidden */ _removeDocument(objIndex: number): void { // if no filter applied yet, the result 'set' should remain 'everything' if (!this._resultSet._filterInitialized) { if (this._persistent) { this._resultData = this._resultSet.data(); } // in case changes to data altered a sort column if (this._sortFunction || this._sortCriteria || this._sortCriteriaSimple) { this._queueSortPhase(); } else { this._queueRebuildEvent(); } return; } const ofr = this._resultSet._filteredRows; const oldPos = ofr.indexOf(+objIndex); let oldlen = ofr.length; if (oldPos !== -1) { // if not last row in resultdata, swap last to hole and truncate last row if (oldPos < oldlen - 1) { ofr[oldPos] = ofr[oldlen - 1]; ofr.length = oldlen - 1; if (this._persistent) { this._resultData[oldPos] = this._resultData[oldlen - 1]; this._resultData.length = oldlen - 1; } } // last row, so just truncate last row else { ofr.length = oldlen - 1; if (this._persistent) { this._resultData.length = oldlen - 1; } } // in case changes to data altered a sort column if (this._sortFunction || this._sortCriteria || this._sortCriteriaSimple) { this._queueSortPhase(); } else { this._queueRebuildEvent(); } } // since we are using filteredRows to store data array positions // if they remove a document (whether in our view or not), // we need to adjust array positions -1 for all document array references after that position oldlen = ofr.length; for (let idx = 0; idx < oldlen; idx++) { if (ofr[idx] > objIndex) { ofr[idx]--; } } } /** * Data transformation via user supplied functions * @param {function} mapFunction - this function accepts a single document for you to transform and return * @param {function} reduceFunction - this function accepts many (array of map outputs) and returns single value * @returns The output of your reduceFunction */ public mapReduce<U1, U2>(mapFunction: (item: T, index: number, array: T[]) => U1, reduceFunction: (array: U1[]) => U2): U2 { try { return reduceFunction(this.data().map(mapFunction)); } catch (err) { throw err; } } } export namespace DynamicView { export interface Options { persistent?: boolean; sortPriority?: SortPriority; minRebuildInterval?: number; } export type SortPriority = "passive" | "active"; export interface Serialized { name: string; _persistent: boolean; _sortPriority: SortPriority; _minRebuildInterval: number; _resultSet: ResultSet<any>; _filterPipeline: Filter<any>[]; _sortCriteria: (string | [string, boolean])[]; _sortCriteriaSimple: { field: string, options: boolean | ResultSet.SimpleSortOptions }; _sortByScoring: boolean; _sortDirty: boolean; } export type Filter<T extends object = object> = { type: "find"; val: ResultSet.Query<Doc<T>>; uid: number | string; } | { type: "where"; val: (obj: Doc<T>) => boolean; uid: number | string; }; }
the_stack
import GL from '@luma.gl/constants'; import {getWebGL2Context, assertWebGL2Context, log} from '@luma.gl/gltools'; import Resource, {ResourceProps} from './resource'; import Texture2D from './texture-2d'; import Renderbuffer from './renderbuffer'; import {clear, clearBuffer} from './clear'; import {copyToDataUrl} from './copy-and-blit'; import {getLumaContextData} from '../context/luma-context-data'; import {getFeatures} from '../features'; import {getKey} from '../webgl-utils'; import {assert} from '../utils'; const ERR_MULTIPLE_RENDERTARGETS = 'Multiple render targets not supported'; type TextureAttachment = { texture: Texture2D; layer?: number; // = 0 level?: number; // = 0 }; type Attachment = Renderbuffer | Texture2D | TextureAttachment; export type ImmutableFramebufferProps = ResourceProps & { attachments?: Record<string, Attachment>; readBuffer?: number; drawBuffers?: number[]; check?: boolean; }; export type FramebufferProps = ImmutableFramebufferProps & { width?: number; height?: number; color?: boolean; depth?: boolean; stencil?: boolean; }; type colorBufferFloatOptions = {colorBufferFloat?: boolean; colorBufferHalfFloat?: boolean}; export class ImmutableFramebuffer extends Resource { constructor(gl: WebGLRenderingContext, props?: ImmutableFramebufferProps) { super(gl, props); this._initialize({ attachments: props?.attachments || {}, readBuffer: props?.readBuffer, drawBuffers: props?.drawBuffers }); } checkStatus(): this { const {gl} = this; const status = this.getStatus(); if (status !== gl.FRAMEBUFFER_COMPLETE) { throw new Error(_getFrameBufferStatus(status)); } return this; } getStatus(): number { const {gl} = this; const prevHandle = gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle); const status = gl.checkFramebufferStatus(GL.FRAMEBUFFER); // @ts-ignore gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null); return status; } // DEBUG // Note: Will only work when called in an event handler show() { if (typeof window !== 'undefined') { window.open(copyToDataUrl(this), 'luma-debug-texture'); } return this; } log(logLevel = 0, message = '') { if (logLevel > log.level || typeof window === 'undefined') { return this; } message = message || `Framebuffer ${this.id}`; const image = copyToDataUrl(this, {targetMaxHeight: 100}); log.image({logLevel, message, image}, message)(); return this; } // WEBGL INTERFACE bind({target = GL.FRAMEBUFFER} = {}) { this.gl.bindFramebuffer(target, this.handle); return this; } unbind({target = GL.FRAMEBUFFER} = {}) { this.gl.bindFramebuffer(target, null); return this; } // PRIVATE _initialize(options: {attachments: Record<string, Attachment>; readBuffer?: number; drawBuffers?: number[]}): this { const {attachments = {}, readBuffer, drawBuffers} = options; this._attach(attachments); // Multiple render target support, set read buffer and draw buffers const prevHandle = this.gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle); if (readBuffer) { this._setReadBuffer(readBuffer); } if (drawBuffers) { this._setDrawBuffers(drawBuffers); } // @ts-ignore this.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null); return this; } /** Attach from a map of attachments */ _attach(attachments: Record<string, Attachment>) { const prevHandle = this.gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle); // Walk the attachments for (const key in attachments) { // Ensure key is not undefined assert(key !== undefined, 'Misspelled framebuffer binding point?'); const attachmentPoint = Number(key) as GL; const attachment = attachments[attachmentPoint]; this._attachOne(attachmentPoint, attachment); } // @ts-ignore this.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null); } /** Attach one attachment */ _attachOne(attachmentPoint: GL, attachment: Attachment): Renderbuffer | Texture2D { if (attachment instanceof Renderbuffer) { this._attachRenderbuffer(attachmentPoint, attachment); return attachment; } else if (Array.isArray(attachment)) { const [texture, layer = 0, level = 0] = attachment; this._attachTexture(attachmentPoint, texture, layer, level); return texture; } else if (attachment instanceof Texture2D) { this._attachTexture(attachmentPoint, attachment, 0, 0); return attachment; } } _attachRenderbuffer(attachment: GL, renderbuffer: Renderbuffer): void { this.gl.framebufferRenderbuffer(GL.FRAMEBUFFER, attachment, GL.RENDERBUFFER, renderbuffer.handle); } /** * @param attachment * @param texture * @param layer = 0 - index into Texture2DArray and Texture3D or face for `TextureCubeMap` * @param level = 0 - mipmapLevel (must be 0 in WebGL1) */ _attachTexture(attachment: GL, texture: Texture2D, layer: number, level: number): void { const {gl} = this; gl.bindTexture(texture.target, texture.handle); switch (texture.target) { case GL.TEXTURE_2D_ARRAY: case GL.TEXTURE_3D: const gl2 = assertWebGL2Context(gl); gl2.framebufferTextureLayer(GL.FRAMEBUFFER, attachment, texture.target, level, layer); break; case GL.TEXTURE_CUBE_MAP: // layer must be a cubemap face (or if index, converted to cube map face) const face = mapIndexToCubeMapFace(layer); gl.framebufferTexture2D(GL.FRAMEBUFFER, attachment, face, texture.handle, level); break; case GL.TEXTURE_2D: gl.framebufferTexture2D(GL.FRAMEBUFFER, attachment, GL.TEXTURE_2D, texture.handle, level); break; default: assert(false, 'Illegal texture type'); } gl.bindTexture(texture.target, null); } /** @note Expects framebuffer to be bound */ _setReadBuffer(readBuffer: number): void { const gl2 = getWebGL2Context(this.gl); if (gl2) { gl2.readBuffer(readBuffer); } else { // Setting to color attachment 0 is a noop, so allow it in WebGL1 assert( readBuffer === GL.COLOR_ATTACHMENT0 || readBuffer === GL.BACK, ERR_MULTIPLE_RENDERTARGETS ); } } /** @note Expects framebuffer to be bound */ _setDrawBuffers(drawBuffers: number[]) { const {gl} = this; const gl2 = assertWebGL2Context(gl); if (gl2) { gl2.drawBuffers(drawBuffers); } else { // TODO - is this not handled by polyfills? const ext = gl.getExtension('WEBGL_draw_buffers'); if (ext) { ext.drawBuffersWEBGL(drawBuffers); } else { // Setting a single draw buffer to color attachment 0 is a noop, allow in WebGL1 assert( drawBuffers.length === 1 && (drawBuffers[0] === GL.COLOR_ATTACHMENT0 || drawBuffers[0] === GL.BACK), ERR_MULTIPLE_RENDERTARGETS ); } } } // RESOURCE METHODS _createHandle() { return this.gl.createFramebuffer(); } _deleteHandle() { this.gl.deleteFramebuffer(this.handle); } _bindHandle(handle) { return this.gl.bindFramebuffer(GL.FRAMEBUFFER, handle); } } export default class Framebuffer extends ImmutableFramebuffer { width = null; height = null; attachments = {}; readBuffer = GL.COLOR_ATTACHMENT0; drawBuffers = [GL.COLOR_ATTACHMENT0]; ownResources = []; static readonly FRAMEBUFFER_ATTACHMENT_PARAMETERS = [ GL.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, // WebGLRenderbuffer or WebGLTexture GL.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, // GL.RENDERBUFFER, GL.TEXTURE, GL.NONE // GL.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, // GL.TEXTURE_CUBE_MAP_POSITIVE_X, etc. // GL.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, // GLint // EXT_sRGB or WebGL2 GL.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, // GL.LINEAR, GL.SRBG // WebGL2 // GL.FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER, // GLint GL.FRAMEBUFFER_ATTACHMENT_RED_SIZE, // GLint GL.FRAMEBUFFER_ATTACHMENT_GREEN_SIZE, // GLint GL.FRAMEBUFFER_ATTACHMENT_BLUE_SIZE, // GLint GL.FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, // GLint GL.FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, // GLint GL.FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE // GLint // GL.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE // GL.FLOAT, GL.INT, GL.UNSIGNED_INT, GL.SIGNED_NORMALIZED, OR GL.UNSIGNED_NORMALIZED. ]; /** * Check color buffer float support * @param options.colorBufferFloat Whether floating point textures can be rendered and read * @param options.colorBufferHalfFloat Whether half float textures can be rendered and read */ static isSupported(gl: WebGLRenderingContext, options: colorBufferFloatOptions): boolean { return isFloatColorBufferSupported(gl, options); } /** * returns the default Framebuffer * Creates a Framebuffer object wrapper for the default WebGL framebuffer (target === null) */ static getDefaultFramebuffer(gl: WebGLRenderingContext): Framebuffer { const lumaContextData = getLumaContextData(gl); lumaContextData.defaultFramebuffer = lumaContextData.defaultFramebuffer || new Framebuffer(gl, { id: 'default-framebuffer', handle: null, attachments: {} }); // TODO - can we query for and get a handle to the GL.FRONT renderbuffer? return lumaContextData.defaultFramebuffer; } get MAX_COLOR_ATTACHMENTS(): number { const gl2 = assertWebGL2Context(this.gl); return gl2.getParameter(gl2.MAX_COLOR_ATTACHMENTS); } get MAX_DRAW_BUFFERS(): number { const gl2 = assertWebGL2Context(this.gl); return gl2.getParameter(gl2.MAX_DRAW_BUFFERS); } constructor(gl: WebGLRenderingContext, props?: FramebufferProps) { super(gl, props); this.initialize(props); Object.seal(this); } get color() { return this.attachments[GL.COLOR_ATTACHMENT0] || null; } get texture() { return this.attachments[GL.COLOR_ATTACHMENT0] || null; } get depth() { return ( this.attachments[GL.DEPTH_ATTACHMENT] || this.attachments[GL.DEPTH_STENCIL_ATTACHMENT] || null ); } get stencil() { return ( this.attachments[GL.STENCIL_ATTACHMENT] || this.attachments[GL.DEPTH_STENCIL_ATTACHMENT] || null ); } // initialize(props?: FramebufferProps): this; initialize(props: FramebufferProps) { let {attachments = null} = props || {}; const { width = 1, height = 1, color = true, depth = true, stencil = false, check = true, readBuffer = undefined, drawBuffers = undefined } = props || {}; assert(width >= 0 && height >= 0, 'Width and height need to be integers'); // Store actual width and height for diffing this.width = width; this.height = height; // Resize any provided attachments - note that resize only resizes if needed // Note: A framebuffer has no separate size, it is defined by its attachments (which must agree) if (attachments) { for (const attachment in attachments) { const target = attachments[attachment]; const object = Array.isArray(target) ? target[0] : target; object.resize({width, height}); } } else { // Create any requested default attachments attachments = this._createDefaultAttachments(color, depth, stencil, width, height); } this.update({clearAttachments: true, attachments, readBuffer, drawBuffers}); // Checks that framebuffer was properly set up, if not, throws an explanatory error if (attachments && check) { this.checkStatus(); } } delete(): this { for (const resource of this.ownResources) { resource.delete(); } super.delete(); return this; } update(options: { attachments: Record<string, Attachment>, readBuffer?: number, drawBuffers?, clearAttachments?: boolean, resizeAttachments?: boolean }): this { const { attachments = {}, readBuffer, drawBuffers, clearAttachments = false, resizeAttachments = true } = options; this.attach(attachments, {clearAttachments, resizeAttachments}); const {gl} = this; // Multiple render target support, set read buffer and draw buffers const prevHandle = gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle); if (readBuffer) { this._setReadBuffer(readBuffer); this.readBuffer = readBuffer; } if (drawBuffers) { this._setDrawBuffers(drawBuffers); this.drawBuffers = drawBuffers; } // @ts-ignore gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null); return this; } // Attachment resize is expected to be a noop if size is same resize(size?: {width?: number; height?: number}): this { let {width, height} = size || {}; // for default framebuffer, just update the stored size if (this.handle === null) { assert(width === undefined && height === undefined); this.width = this.gl.drawingBufferWidth; this.height = this.gl.drawingBufferHeight; return this; } if (width === undefined) { width = this.gl.drawingBufferWidth; } if (height === undefined) { height = this.gl.drawingBufferHeight; } if (width !== this.width && height !== this.height) { log.log(2, `Resizing framebuffer ${this.id} to ${width}x${height}`)(); } for (const attachmentPoint in this.attachments) { this.attachments[attachmentPoint].resize({width, height}); } this.width = width; this.height = height; return this; } // Attach from a map of attachments attach(attachments, {clearAttachments = false, resizeAttachments = true} = {}) { const newAttachments = {}; // Any current attachments need to be removed, add null values to map if (clearAttachments) { Object.keys(this.attachments).forEach((key) => { newAttachments[key] = null; }); } // Overlay the new attachments Object.assign(newAttachments, attachments); const prevHandle = this.gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle); // Walk the attachments for (const key in newAttachments) { // Ensure key is not undefined assert(key !== undefined, 'Misspelled framebuffer binding point?'); const attachment = Number(key); const descriptor = newAttachments[attachment]; let object = descriptor; if (!object) { this._unattach(attachment); } else { object = this._attachOne(attachment, object); this.attachments[attachment] = object; } // Resize objects if (resizeAttachments && object) { object.resize({width: this.width, height: this.height}); } } // @ts-ignore this.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null); // Assign to attachments and remove any nulls to get a clean attachment map Object.assign(this.attachments, attachments); Object.keys(this.attachments) .filter((key) => !this.attachments[key]) .forEach((key) => { delete this.attachments[key]; }); } clear(options?: {color?: any; depth?: any; stencil?: any; drawBuffers?: any[]}): this { const {color, depth, stencil, drawBuffers = []} = options; // Bind framebuffer and delegate to global clear functions const prevHandle = this.gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle); if (color || depth || stencil) { clear(this.gl, {color, depth, stencil}); } drawBuffers.forEach((value, drawBuffer) => { clearBuffer(this.gl, {drawBuffer, value}); }); // @ts-ignore this.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null); return this; } // WEBGL2 INTERFACE // Copies a rectangle of pixels between framebuffers // eslint-disable-next-line complexity blit(opts = {}) { log.error('Framebuffer.blit({...}) is no logner supported, use blit(source, target, opts)')(); return null; } // signals to the GL that it need not preserve all pixels of a specified region of the framebuffer invalidate(options: {attachments: []; x?: number; y?: number; width: number; height: number}) { const {attachments = [], x = 0, y = 0, width, height} = options; const gl2 = assertWebGL2Context(this.gl); const prevHandle = gl2.bindFramebuffer(GL.READ_FRAMEBUFFER, this.handle); const invalidateAll = x === 0 && y === 0 && width === undefined && height === undefined; if (invalidateAll) { gl2.invalidateFramebuffer(GL.READ_FRAMEBUFFER, attachments); } else { // TODO - why does type checking fail on this line // @ts-ignore gl2.invalidateFramebuffer(GL.READ_FRAMEBUFFER, attachments, x, y, width, height); } // @ts-ignore gl2.bindFramebuffer(GL.READ_FRAMEBUFFER, prevHandle); return this; } // Return the value for `pname` of the specified attachment. // The type returned is the type of the requested pname getAttachmentParameter(attachment, pname, keys) { let value = this._getAttachmentParameterFallback(pname); if (value === null) { this.gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle); value = this.gl.getFramebufferAttachmentParameter(GL.FRAMEBUFFER, attachment, pname); this.gl.bindFramebuffer(GL.FRAMEBUFFER, null); } if (keys && value > 1000) { // @ts-ignore value = getKey(this.gl, value); } return value; } getAttachmentParameters( attachment = GL.COLOR_ATTACHMENT0, keys, // @ts-ignore parameters = this.constructor.ATTACHMENT_PARAMETERS || [] ) { const values = {}; for (const pname of parameters) { const key = keys ? getKey(this.gl, pname) : pname; values[key] = this.getAttachmentParameter(attachment, pname, keys); } return values; } // @ts-expect-error getParameters(keys = true) { const attachments = Object.keys(this.attachments); // if (this === this.gl.luma.defaultFramebuffer) { // attachments = [GL.COLOR_ATTACHMENT0, GL.DEPTH_STENCIL_ATTACHMENT]; // } const parameters = {}; for (const attachmentName of attachments) { const attachment = Number(attachmentName); const key = keys ? getKey(this.gl, attachment) : attachment; parameters[key] = this.getAttachmentParameters(attachment, keys); } return parameters; } // PRIVATE METHODS _createDefaultAttachments(color, depth, stencil, width, height) { let defaultAttachments = null; // Add a color buffer if requested and not supplied if (color) { defaultAttachments = defaultAttachments || {}; defaultAttachments[GL.COLOR_ATTACHMENT0] = new Texture2D(this.gl, { id: `${this.id}-color0`, pixels: null, // reserves texture memory, but texels are undefined format: GL.RGBA, type: GL.UNSIGNED_BYTE, width, height, // Note: Mipmapping can be disabled by texture resource when we resize the texture // to a non-power-of-two dimenstion (NPOT texture) under WebGL1. To have consistant // behavior we always disable mipmaps. mipmaps: false, // Set MIN and MAG filtering parameters so mipmaps are not used in sampling. // Use LINEAR so subpixel algos like fxaa work. // Set WRAP modes that support NPOT textures too. parameters: { [GL.TEXTURE_MIN_FILTER]: GL.LINEAR, [GL.TEXTURE_MAG_FILTER]: GL.LINEAR, [GL.TEXTURE_WRAP_S]: GL.CLAMP_TO_EDGE, [GL.TEXTURE_WRAP_T]: GL.CLAMP_TO_EDGE } }); // track to delete later this.ownResources.push(defaultAttachments[GL.COLOR_ATTACHMENT0]); } if (depth && stencil) { // TODO - handle separate stencil defaultAttachments = defaultAttachments || {}; defaultAttachments[GL.DEPTH_STENCIL_ATTACHMENT] = new Renderbuffer(this.gl, { id: `${this.id}-depth-stencil`, format: GL.DEPTH24_STENCIL8, width, height: 111 }); // track to delete later this.ownResources.push(defaultAttachments[GL.DEPTH_STENCIL_ATTACHMENT]); // TODO - optional texture // new Texture2D(this.gl, { // id: `${this.id}-depth-stencil`, // format: GL.DEPTH24_STENCIL8, // dataFormat: GL.DEPTH_STENCIL, // type: GL.UNSIGNED_INT_24_8, // width, // height, // mipmaps: false // }); } else if (depth) { // Add a depth buffer if requested and not supplied defaultAttachments = defaultAttachments || {}; defaultAttachments[GL.DEPTH_ATTACHMENT] = new Renderbuffer(this.gl, { id: `${this.id}-depth`, format: GL.DEPTH_COMPONENT16, width, height }); // track to delete later this.ownResources.push(defaultAttachments[GL.DEPTH_ATTACHMENT]); } else if (stencil) { // TODO - handle separate stencil assert(false); } return defaultAttachments; } _unattach(attachment) { const oldAttachment = this.attachments[attachment]; if (!oldAttachment) { return; } if (oldAttachment instanceof Renderbuffer) { // render buffer this.gl.framebufferRenderbuffer(GL.FRAMEBUFFER, attachment, GL.RENDERBUFFER, null); } else { // Must be a texture attachment this.gl.framebufferTexture2D(GL.FRAMEBUFFER, attachment, GL.TEXTURE_2D, null, 0); } delete this.attachments[attachment]; } // Attempt to provide workable defaults for WebGL2 symbols under WebGL1 // null means OK to query // TODO - move to webgl1 polyfills /* eslint-disable complexity */ _getAttachmentParameterFallback(pname) { const caps = getFeatures(this.gl); switch (pname) { case GL.FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER: // GLint return !caps.WEBGL2 ? 0 : null; case GL.FRAMEBUFFER_ATTACHMENT_RED_SIZE: // GLint case GL.FRAMEBUFFER_ATTACHMENT_GREEN_SIZE: // GLint case GL.FRAMEBUFFER_ATTACHMENT_BLUE_SIZE: // GLint case GL.FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE: // GLint case GL.FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE: // GLint case GL.FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE: // GLint return !caps.WEBGL2 ? 8 : null; case GL.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE: // GLenum return !caps.WEBGL2 ? GL.UNSIGNED_INT : null; case GL.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING: return !caps.WEBGL2 && !caps.EXT_sRGB ? GL.LINEAR : null; default: return null; } } /* eslint-enable complexity */ } // PUBLIC METHODS // Map an index to a cube map face constant function mapIndexToCubeMapFace(layer) { // TEXTURE_CUBE_MAP_POSITIVE_X is a big value (0x8515) // if smaller assume layer is index, otherwise assume it is already a cube map face constant return layer < GL.TEXTURE_CUBE_MAP_POSITIVE_X ? layer + GL.TEXTURE_CUBE_MAP_POSITIVE_X : layer; } // Helper METHODS // Get a string describing the framebuffer error if installed function _getFrameBufferStatus(status) { // Use error mapping if installed // @ts-ignore const STATUS = Framebuffer.STATUS || {}; return STATUS[status] || `Framebuffer error ${status}`; } /** * Support * @param gl * @param options.colorBufferFloat Whether floating point textures can be rendered and read * @param options.colorBufferHalfFloat Whether half float textures can be rendered and read */ function isFloatColorBufferSupported( gl: WebGLRenderingContext, options: {colorBufferFloat?: boolean; colorBufferHalfFloat?: boolean} ): boolean { const { colorBufferFloat, // Whether floating point textures can be rendered and read colorBufferHalfFloat // Whether half float textures can be rendered and read } = options; let supported = true; if (colorBufferFloat) { supported = Boolean( // WebGL 2 gl.getExtension('EXT_color_buffer_float') || // WebGL 1, not exposed on all platforms gl.getExtension('WEBGL_color_buffer_float') || // WebGL 1, implicitly enables float render targets https://www.khronos.org/registry/webgl/extensions/OES_texture_float/ gl.getExtension('OES_texture_float') ); } if (colorBufferHalfFloat) { supported = supported && Boolean( // WebGL 2 gl.getExtension('EXT_color_buffer_float') || // WebGL 1 gl.getExtension('EXT_color_buffer_half_float') ); } return supported; }
the_stack
import React, { Component } from "react"; import { connect } from "react-redux"; import { withRouter } from "react-router-dom"; import queryString from "query-string"; import getDateString from "helpers/getDateString"; import MarkdownViewer from "Components/Common/MarkdownViewer"; import { Small, Medium } from "Components/Common/Responsive"; import { retrieveLocalData, prependToLocalStorageArray, deleteFromLocalStorageArray } from "../../../storage/localStorage"; import "./SearchSuggestionBox.scss"; import recentSearchIcon from "assets/updated.svg"; import closeIcon from "assets/mobile-menu-close.svg"; import isEqual from "lodash/isEqual"; type SearchDataType = { name?: string; regionName?: string; data: any; }; const KEY_CODE_ARROW_DOWN = 40; const KEY_CODE_ARROW_LEFT = 37; const KEY_CODE_ARROW_UP = 38; const KEY_CODE_ARROW_RIGHT = 39; const KEY_CODE_ENTER = 13; const KEY_CODE_ESC = 27; /** * when no user input, the first `maxDefaultListItemNumber` items will be returned */ const maxDefaultListItemNumber = 5; /** * Max no.of items will be saved locally */ const maxSavedItemNumber = 5; function getRecentSearches() { const items = retrieveLocalData("recentSearches", []); if (!items || typeof items !== "object" || !items.length) { return []; } else { return items; } } type Props = { searchText: string; inputRef: any; isSearchInputFocus: boolean; history: any; location: any; datasetSearch: any; }; class SearchSuggestionBox extends Component<Props & any, any> { searchInputRef: HTMLInputElement | null; containerRef: HTMLDivElement | null; cacheImages: any[] = []; constructor(props) { super(props); this.state = { isMouseOver: false, recentSearches: getRecentSearches(), selectedItemIdx: null, manuallyHidden: false }; this.cacheImgs(); this.searchInputRef = null; this.onSearchInputKeyDown = this.onSearchInputKeyDown.bind(this); this.containerRef = null; this.saveRecentSearch(this.props); } cacheImgs() { const cacheImg = img => { const imgLoader = new Image(); imgLoader.src = img; this.cacheImages.push(imgLoader); }; this.cacheImages = []; cacheImg(recentSearchIcon); cacheImg(closeIcon); } createSearchDataFromProps(props): SearchDataType | null { if (!props || !props.location || !props.location.search) return null; const data = queryString.parse(props.location.search); if (!Object.keys(data).length) return null; const searchData = { data }; if (data.regionId) { if ( props.datasetSearch && props.datasetSearch.activeRegion && props.datasetSearch.activeRegion.regionName ) searchData["regionName"] = props.datasetSearch.activeRegion.regionName; else return null; //--- Only save searches when region name is available } return searchData; } createSearchOptionListTextFromArray(arr, lastSeparator = "or") { if (!arr) return null; if (typeof arr === "string") return `*${arr}*`; if (!arr.length) return null; const formatedItems = arr.map((item, idx) => `*${item}*`); if (formatedItems.length <= 1) return formatedItems[0]; const lastItem = formatedItems.pop(); let resultStr = formatedItems.join(", "); resultStr = `${resultStr} ${lastSeparator} ${lastItem}`; return resultStr; } createSearchItemLabelText(searchData: SearchDataType) { const data = searchData.data; const filters: string[] = []; if (data.regionId) filters.push(`in *${searchData.regionName}*`); if (data.format && data.format.length) filters.push( "in " + this.createSearchOptionListTextFromArray(data.format) + " format" ); if (data.organisation) filters.push( "from organisation " + this.createSearchOptionListTextFromArray(data.publisher) ); if (data.dateFrom) filters.push("from *" + getDateString(data.dateFrom) + "*"); if (data.dateFrom) filters.push("to *" + getDateString(data.dateFrom) + "*"); let qStr = data.q ? data.q.trim() : ""; if (qStr === "*") qStr = "\\*"; return qStr ? qStr + " " + filters.join("; ") : filters.join("; "); } saveRecentSearch(newProps, prevProps?) { const searchData = this.createSearchDataFromProps(newProps); if (!searchData) return; if ( !searchData.data.q || !searchData.data.q.trim() || searchData.data.q.trim() === "*" ) return; const currentSearchData = this.createSearchDataFromProps(prevProps); if (isEqual(currentSearchData, searchData)) return; const recentSearches = prependToLocalStorageArray( "recentSearches", searchData, maxSavedItemNumber, [] ); this.setState({ recentSearches }); } componentDidUpdate(prevProps, prevState) { this.saveRecentSearch(this.props, prevProps); this.setupSearchInputListener(this.props); if ( prevState.selectedItemIdx !== this.state.selectedItemIdx || prevState.deleteSelected !== this.state.deleteSelected ) { this.props.onSelectedIdChange && this.props.onSelectedIdChange( this.state.selectedItemIdx || this.state.selectedItemIdx === 0 ? this.buildOptionId( this.state.selectedItemIdx, this.state.deleteSelected ) : null ); } } executeSearchItem(item: SearchDataType) { const searchData = { ...item.data }; if (searchData.publisher) delete searchData.publisher; const qStr = queryString.stringify(searchData); this.props.history.push(`/search?${qStr}`); this.setState({ isMouseOver: false, selectedItemIdx: null }); this.searchInputRef && this.searchInputRef.blur(); } onSearchItemClick(e, item: SearchDataType) { e.preventDefault(); this.executeSearchItem(item); } onDeleteItemClick(e, idx) { e.preventDefault(); this.deleteItem(idx); } deleteItem(idx) { const recentSearches = deleteFromLocalStorageArray( "recentSearches", idx, [] ); this.setState({ recentSearches }); } onMouseOver() { this.setState({ isMouseOver: true }); } onMouseOut() { this.setState({ isMouseOver: false }); } getFilteredResult() { const recentSearches = this.state.recentSearches; if (!recentSearches || !recentSearches.length) return []; if (!this.props.searchText) return recentSearches.slice(0, maxDefaultListItemNumber); const inputText = this.props.searchText.trim().toLowerCase(); if (!inputText) return recentSearches.slice(0, maxDefaultListItemNumber); const filteredRecentSearches = recentSearches.filter(item => { if ( item.data.q && item.data.q.toLowerCase().indexOf(inputText) !== -1 ) return true; return false; }); return filteredRecentSearches; } shouldShow() { if (!this.props.isSearchInputFocus && !this.state.isMouseOver) { return false; } if (this.state.manuallyHidden) { return false; } const filteredRecentSearches = this.state.recentSearches; if (!filteredRecentSearches || !filteredRecentSearches.length) return false; return true; } setupSearchInputListener(newProps) { if (!newProps || !newProps.inputRef) return; const newInputRef = newProps.inputRef; if (this.searchInputRef) { if (this.searchInputRef === newInputRef) return; this.searchInputRef.removeEventListener( "keydown", this.onSearchInputKeyDown ); this.searchInputRef = null; } this.searchInputRef = newInputRef; this.searchInputRef && this.searchInputRef.addEventListener( "keydown", this.onSearchInputKeyDown ); } onSearchInputKeyDown(e) { const keyCode = e.which || e.keyCode || 0; this.setState({ manuallyHidden: false }); if (!this.shouldShow()) return; if (keyCode === KEY_CODE_ENTER && this.state.selectedItemIdx !== null) { e.preventDefault(); e.stopImmediatePropagation(); if (this.state.deleteSelected) { this.deleteItem(this.state.selectedItemIdx); } else { this.executeSearchItem( this.state.recentSearches[this.state.selectedItemIdx] ); } return; } if ( keyCode === KEY_CODE_ARROW_UP && this.state.selectedItemIdx !== null ) { e.preventDefault(); //--- stop cursor from moving to the beginning of the input text } switch (keyCode) { case KEY_CODE_ARROW_DOWN: this.selectNextItem(); break; case KEY_CODE_ARROW_UP: this.selectPrevItem(); break; case KEY_CODE_ARROW_LEFT: this.setState({ deleteSelected: false }); break; case KEY_CODE_ARROW_RIGHT: this.setState({ deleteSelected: true }); break; case KEY_CODE_ESC: this.setState({ manuallyHidden: true }); break; default: break; } } selectNextItem() { const maxNumber = this.getSavedSearchItemsNumber(); if (!maxNumber) return; let newIdx; if (this.state.selectedItemIdx === null) newIdx = 0; else newIdx = (this.state.selectedItemIdx + 1) % maxNumber; this.selectItem(newIdx); } selectPrevItem() { if (this.state.selectedItemIdx === null) return; let newIdx: number | null = this.state.selectedItemIdx - 1; if (newIdx < 0) newIdx = null; this.selectItem(newIdx); } selectItem(index) { this.setState({ selectedItemIdx: index }); } getSavedSearchItemsNumber() { const recentSearchItems = this.state.recentSearches; if (!recentSearchItems) return 0; return recentSearchItems.length; } buildOptionId(idx, deleteSelected = false) { return `search-history-item-${idx}${ deleteSelected ? "-delete-button" : "" }`; } render() { if (!this.shouldShow()) return null; const recentSearchItems = this.state.recentSearches; return ( <div className="search-suggestion-box" ref={el => (this.containerRef = el)} id="search-suggestion-box" > <div className="search-suggestion-box-position-adjust" /> <div className="search-suggestion-box-body" onMouseOver={() => this.onMouseOver()} onMouseOut={() => this.onMouseOut()} > <Medium> <h5 className="search-suggestion__heading"> Recent Searches </h5> </Medium> <ul id="search-history-items" role="listbox" className="search-history-items" > {recentSearchItems.map((item, idx: number) => ( <li key={idx} className={`search-item-container ${ this.state.selectedItemIdx === idx && !this.state.deleteSelected ? "selected" : "" }`} > <img className="recent-item-icon" src={recentSearchIcon} alt="recent search item" /> <button role="option" aria-selected={ this.state.selectedItemIdx === idx && !this.state.deleteSelected } id={this.buildOptionId(idx)} className="au-btn au-btn--tertiary search-item-main-button" onClick={e => this.onSearchItemClick(e, item) } tabIndex={-1} > <span className="sr-only"> Recent search item </span> <Medium> <MarkdownViewer markdown={this.createSearchItemLabelText( item )} truncate={false} /> </Medium> <Small> <div className="recent-item-content"> {item.data.q ? item.data.q.trim() : ""} </div> </Small> </button> <button id={this.buildOptionId(idx, true)} role="option" aria-selected={ this.state.deleteSelected && this.state.selectedItemIdx === idx } className={`au-btn au-btn--tertiary search-item-delete-button ${ this.state.deleteSelected && this.state.selectedItemIdx === idx ? "search-item-delete-button--selected" : "" }`} onClick={e => this.onDeleteItemClick(e, idx) } tabIndex={-1} > <img alt={`delete recent search item ${this.createSearchItemLabelText( item )}`} src={closeIcon} /> </button> </li> ))} </ul> </div> </div> ); } } const SearchSuggestionBoxWithRouter = withRouter(props => ( <SearchSuggestionBox {...props} /> )); const mapStateToProps = state => { return { datasetSearch: state.datasetSearch }; }; export default connect(mapStateToProps)(SearchSuggestionBoxWithRouter);
the_stack
* This is a fork of the Karpathy's TSNE.js (original license below). * * The MIT License (MIT) * * Copyright (c) 2015 Andrej Karpathy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * The algorithm was originally described in this paper: * * L.J.P. van der Maaten and G.E. Hinton. * Visualizing High-Dimensional Data Using t-SNE. Journal of Machine Learning Research * 9(Nov):2579-2605, 2008. * * You can find the PDF [here](http://jmlr.csail.mit.edu/papers/volume9/vandermaaten08a/vandermaaten08a.pdf). */ // cSpell:words Maaten Andrej Karpathy Karpathy's randn xtod premult dists gainid export type tSNEOptions = { perplexity?: number; epsilon?: number; dimension: number; }; class GaussRandom { private returnV = false; private vVal = 0.0; get value(): number { if (this.returnV) { this.returnV = false; return this.vVal; } const u = 2 * Math.random() - 1; const v = 2 * Math.random() - 1; const r = u * u + v * v; if (r === 0 || r > 1) { return this.value; } const c = Math.sqrt((-2 * Math.log(r)) / r); this.vVal = v * c; this.returnV = true; return u * c; } } export default class tSNE { readonly dimension: number; epsilon = 10; perplexity = 30; private Random = new GaussRandom(); private data = new Float32Array(); private P: Float32Array = new Float32Array(); private Y: number[][] = []; private gains: number[][] = []; private yStep: number[][] = []; private D = 0; private N = 0; private iter = 0; get solution() { return this.Y; } get step() { return this.iter; } constructor(options: tSNEOptions) { this.dimension = options.dimension; this.perplexity = options.perplexity ?? this.perplexity; this.epsilon = options.epsilon ?? this.epsilon; } private L2(x1: Float32Array, x2: Float32Array) { if (x1.length !== x2.length) { throw new Error('Cannot compare vectors with different length'); } const D = x1.length; let d = 0; for (let i = 0; i < D; i++) { const x1i = x1[i]; const x2i = x2[i]; d += (x1i - x2i) * (x1i - x2i); } return d; } private randn2d(s?: number) { const uses = s != null; const x: number[][] = []; for (let i = 0; i < this.N; i++) { const xHere: number[] = []; for (let j = 0; j < this.dimension; j++) { if (uses) { xHere.push(s as number); } else { xHere.push(this.Random.value * 1e-4); } } x.push(xHere); } return x; } private sliceDataRow(row: number) { return this.data.slice(row * this.D, (row + 1) * this.D); } private xtod() { const dist = new Float32Array(this.N * this.N); for (let i = 0; i < this.N; i++) { for (let j = 0; j < this.N; j++) { const d = this.L2(this.sliceDataRow(i), this.sliceDataRow(j)); dist[i * this.N + j] = d; dist[j * this.N + i] = d; } } return dist; } private d2p(D: Float32Array, tol = 1e-4) { const Nf = Math.sqrt(D.length); const N = Math.floor(Nf); if (Nf !== N) { throw new Error('Distance is not a square matrix'); } const hTarget = Math.log(this.perplexity); const P = new Float32Array(N * N); const pRow = new Float32Array(N); for (let i = 0; i < N; i++) { let betaMin = Number.NEGATIVE_INFINITY; let betaMax = Number.POSITIVE_INFINITY; let beta = 1; const maxTries = 50; let num = 0; while (num < maxTries) { let pSum = 0.0; for (let j = 0; j < N; j++) { let pj = Math.exp(-D[i * N + j] * beta); if (i === j) { pj = 0; } pRow[j] = pj; pSum += pj; } let hHere = 0.0; for (let j = 0; j < N; j++) { const pj = pSum === 0 ? 0 : pRow[j] / pSum; pRow[j] = pj; if (pj > 1e-7) { hHere -= pj * Math.log(pj); } } if (hHere > hTarget) { betaMin = beta; if (betaMax === Number.POSITIVE_INFINITY) { beta *= 2; } else { beta = (beta + betaMax) / 2; } } else { betaMax = beta; if (betaMin === Number.NEGATIVE_INFINITY) { beta /= 2; } else { beta = (beta + betaMin) / 2; } } num++; if (Math.abs(hHere - hTarget) < tol) { break; } } for (let j = 0; j < N; j++) { P[i * N + j] = pRow[j]; } } const pOut = new Float32Array(N * N); const N2 = N * 2; for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { pOut[i * N + j] = Math.max((P[i * N + j] + P[j * N + i]) / N2, Number.EPSILON); } } return pOut; } private costGrad() { const Y = this.Y; const N = this.N; const dim = this.dimension; const P = this.P; const NN = N * N; const pMul = this.iter < 100 ? 4 : 1; const Qu = new Float32Array(NN); let qSum = 0.0; for (let i = 0; i < N; i++) { for (let j = i + 1; j < N; j++) { let dSum = 0.0; for (let d = 0; d < dim; d++) { const dHere = Y[i][d] - Y[j][d]; dSum += dHere * dHere; } const qu = 1.0 / (1.0 + dSum); Qu[i * N + j] = qu; Qu[j * N + i] = qu; qSum += 2 * qu; } } const Q = new Float32Array(NN); for (let q = 0; q < NN; q++) { Q[q] = Math.max(Qu[q] / qSum, Number.EPSILON); } let cost = 0.0; const grad: number[][] = []; for (let i = 0; i < N; i++) { const gSum = Array.from<number>({length: dim}).fill(0.0); for (let j = 0; j < N; j++) { cost += -P[i * N + j] * Math.log(Q[i * N + j]); const premult = 4 * (pMul * P[i * N + j] - Q[i * N + j]) * Qu[i * N + j]; for (let d = 0; d < dim; d++) { gSum[d] += premult * (Y[i][d] - Y[j][d]); } } grad.push(gSum); } return {cost, grad}; } setData(data: Float32Array, dimension: number) { if (data.length && dimension && data.length % dimension !== 0) { throw Error('Wrong data shape'); } if (data.length === 0 || dimension === 0) { return; } this.data = data; this.D = dimension; this.N = data.length / dimension; const dists = this.xtod(); this.P = this.d2p(dists); this.Y = this.randn2d(); this.gains = this.randn2d(1.0); this.yStep = this.randn2d(0.0); this.iter = 0; } setPerplexity(perplexity: number) { this.perplexity = perplexity; } setEpsilon(epsilon: number) { this.epsilon = epsilon; } run() { this.iter++; const N = this.N; const {cost, grad} = this.costGrad(); const yMean = new Float32Array(this.dimension); for (let i = 0; i < N; i++) { for (let d = 0; d < this.dimension; d++) { const gid = grad[i][d]; const sid = this.yStep[i][d]; const gainid = this.gains[i][d]; let newGain = Math.sign(gid) === Math.sign(sid) ? gainid * 0.8 : gainid + 0.2; if (newGain < 0.01) { newGain = 0.01; } this.gains[i][d] = newGain; const momVal = this.iter < 250 ? 0.5 : 0.8; const newSid = momVal * sid - this.epsilon * newGain * grad[i][d]; this.yStep[i][d] = newSid; this.Y[i][d] += newSid; yMean[d] += this.Y[i][d]; } } for (let i = 0; i < N; i++) { for (let d = 0; d < this.dimension; d++) { this.Y[i][d] -= yMean[d] / N; } } return cost; } }
the_stack
import * as THREE from 'three'; const tmpOrigin = new THREE.Vector3(); const tmpU = new THREE.Vector3(); const tmpV = new THREE.Vector3(); const tmpNormal = new THREE.Vector3(); const tmpLookAt = new THREE.Vector3(); const tmpProbeBox = new THREE.Vector4(); const tmpPrevClearColor = new THREE.Color(); // used inside blending function const tmpNormalOther = new THREE.Vector3(); const PROBE_BG_ZERO = new THREE.Color('#000000'); const PROBE_BG_FULL = new THREE.Color('#ffffff'); export const PROBE_BATCH_COUNT = 8; export interface LightProbeSettings { targetSize: number; offset: number; near: number; far: number; } export const DEFAULT_LIGHT_PROBE_SETTINGS: LightProbeSettings = { targetSize: 16, offset: 0, near: 0.05, far: 50 }; export type ProbeDataReport = { rgbaData: Float32Array; rowPixelStride: number; probeBox: THREE.Vector4; originX: number; // device coordinates of lower-left corner of the viewbox originY: number; }; export interface ProbeTexel { texelIndex: number; // used by caller for correlation originalMesh: THREE.Mesh; originalBuffer: THREE.BufferGeometry; faceIndex: number; pU: number; pV: number; } export type ProbeBatcher = ( gl: THREE.WebGLRenderer, lightScene: THREE.Scene, texelIterator: Iterator<ProbeTexel | null> ) => Generator<{ texelIndex: number; rgba: THREE.Vector4; }>; // bilinear interpolation of normals in triangle, with normalization function setBlendedNormal( out: THREE.Vector3, origNormalArray: ArrayLike<number>, origIndexArray: ArrayLike<number>, faceVertexBase: number, pU: number, pV: number ) { // barycentric coordinate for origin point const pO = 1 - pU - pV; out.fromArray(origNormalArray, origIndexArray[faceVertexBase] * 3); out.multiplyScalar(pO); tmpNormalOther.fromArray( origNormalArray, origIndexArray[faceVertexBase + 1] * 3 ); out.addScaledVector(tmpNormalOther, pU); tmpNormalOther.fromArray( origNormalArray, origIndexArray[faceVertexBase + 2] * 3 ); out.addScaledVector(tmpNormalOther, pV); out.normalize(); } function setUpProbeUp( probeCam: THREE.Camera, mesh: THREE.Mesh, origin: THREE.Vector3, normal: THREE.Vector3, uDir: THREE.Vector3 ) { probeCam.position.copy(origin); probeCam.up.copy(uDir); // add normal to accumulator and look at it tmpLookAt.copy(normal); tmpLookAt.add(origin); probeCam.lookAt(tmpLookAt); probeCam.scale.set(1, 1, 1); // then, transform camera into world space probeCam.applyMatrix4(mesh.matrixWorld); } function setUpProbeSide( probeCam: THREE.Camera, mesh: THREE.Mesh, origin: THREE.Vector3, normal: THREE.Vector3, direction: THREE.Vector3, directionSign: number ) { probeCam.position.copy(origin); // up is the normal probeCam.up.copy(normal); // add normal to accumulator and look at it tmpLookAt.copy(origin); tmpLookAt.addScaledVector(direction, directionSign); probeCam.lookAt(tmpLookAt); probeCam.scale.set(1, 1, 1); // then, transform camera into world space probeCam.applyMatrix4(mesh.matrixWorld); } // for each pixel in the individual probe viewport, compute contribution to final tally // (edges are weaker because each pixel covers less of a view angle) // @todo perform weighted pixel averaging/etc all in this file export function generatePixelAreaLookup(probeTargetSize: number) { const probePixelCount = probeTargetSize * probeTargetSize; const lookup = new Array(probePixelCount) as number[]; const probePixelBias = 0.5 / probeTargetSize; for (let py = 0; py < probeTargetSize; py += 1) { // compute offset from center (with a bias for target pixel size) const dy = py / probeTargetSize - 0.5 + probePixelBias; for (let px = 0; px < probeTargetSize; px += 1) { // compute offset from center (with a bias for target pixel size) const dx = px / probeTargetSize - 0.5 + probePixelBias; // compute multiplier as affected by inclination of corresponding ray const span = Math.hypot(dx * 2, dy * 2); const hypo = Math.hypot(span, 1); const area = 1 / hypo; lookup[py * probeTargetSize + px] = area; } } return lookup; } // collect and combine pixel aggregate from rendered probe viewports // (this ignores the alpha channel from viewports) const tmpTexelRGBA = new THREE.Vector4(); function readTexel( readLightProbe: () => Generator<ProbeDataReport>, probePixelAreaLookup: number[] ) { let r = 0, g = 0, b = 0, totalDivider = 0; for (const { rgbaData: probeData, rowPixelStride, probeBox: box, originX, originY } of readLightProbe()) { const probeTargetSize = box.z; // assuming width is always full const rowStride = rowPixelStride * 4; let rowStart = box.y * rowStride + box.x * 4; const totalMax = (box.y + box.w) * rowStride; let py = originY; while (rowStart < totalMax) { const rowMax = rowStart + box.z * 4; let px = originX; for (let i = rowStart; i < rowMax; i += 4) { // compute multiplier as affected by inclination of corresponding ray const area = probePixelAreaLookup[py * probeTargetSize + px]; r += area * probeData[i]; g += area * probeData[i + 1]; b += area * probeData[i + 2]; totalDivider += area; px += 1; } rowStart += rowStride; py += 1; } } // alpha is set later tmpTexelRGBA.x = r / totalDivider; tmpTexelRGBA.y = g / totalDivider; tmpTexelRGBA.z = b / totalDivider; } // @todo use light sphere for AO (double-check that far-extent is radius + epsilon) export async function withLightProbe( aoMode: boolean, aoDistance: number, settings: LightProbeSettings, taskCallback: ( renderLightProbeBatch: ProbeBatcher, debugLightProbeTexture: THREE.Texture ) => Promise<void> ) { const probeTargetSize = settings.targetSize; const probeBgColor = aoMode ? PROBE_BG_FULL : PROBE_BG_ZERO; const halfSize = probeTargetSize / 2; const targetWidth = probeTargetSize * 4; // 4 tiles across const targetHeight = probeTargetSize * 2 * PROBE_BATCH_COUNT; // 2 tiles x batch count // @todo make this async? const probePixelAreaLookup = generatePixelAreaLookup(probeTargetSize); // set up simple rasterization for pure data consumption const probeTarget = new THREE.WebGLRenderTarget(targetWidth, targetHeight, { type: THREE.FloatType, magFilter: THREE.NearestFilter, minFilter: THREE.NearestFilter, generateMipmaps: false }); const rtFov = 90; // view cone must be quarter of the hemisphere const rtAspect = 1; // square render target const rtNear = settings.near; const rtFar = aoMode ? aoDistance : settings.far; // in AO mode, lock far-extent to requested distance const probeCam = new THREE.PerspectiveCamera(rtFov, rtAspect, rtNear, rtFar); const probeData = new Float32Array(targetWidth * targetHeight * 4); const batchTexels = new Array(PROBE_BATCH_COUNT) as (number | undefined)[]; // @todo ensure there is biasing to be in middle of texel physical square const renderLightProbeBatch: ProbeBatcher = function* renderLightProbeBatch( gl, lightScene, texelIterator ) { // save existing renderer state gl.getClearColor(tmpPrevClearColor); const prevClearAlpha = gl.getClearAlpha(); const prevAutoClear = gl.autoClear; const prevToneMapping = gl.toneMapping; // reset tone mapping output to linear because we are aggregating unprocessed luminance output gl.toneMapping = THREE.LinearToneMapping; // set up render target for overall clearing // (bypassing setViewport means that the renderer conveniently preserves previous state) probeTarget.scissorTest = true; probeTarget.scissor.set(0, 0, targetWidth, targetHeight); probeTarget.viewport.set(0, 0, targetWidth, targetHeight); gl.setRenderTarget(probeTarget); gl.autoClear = false; // clear entire area gl.setClearColor(probeBgColor, 1); gl.clear(true, true, false); for (let batchItem = 0; batchItem < PROBE_BATCH_COUNT; batchItem += 1) { const texelResult = texelIterator.next(); if (!texelResult.done && texelResult.value) { const { texelIndex, originalMesh, originalBuffer, faceIndex, pU, pV } = texelResult.value; // each batch is 2 tiles high const batchOffsetY = batchItem * probeTargetSize * 2; // save which texel is being rendered for later reporting batchTexels[batchItem] = texelIndex; if (!originalBuffer.index) { throw new Error('expected indexed mesh'); } // read vertex position for this face and interpolate along U and V axes const origIndexArray = originalBuffer.index.array; const origPosArray = originalBuffer.attributes.position.array; const origNormalArray = originalBuffer.attributes.normal.array; // get face vertex positions const faceVertexBase = faceIndex * 3; tmpOrigin.fromArray(origPosArray, origIndexArray[faceVertexBase] * 3); tmpU.fromArray(origPosArray, origIndexArray[faceVertexBase + 1] * 3); tmpV.fromArray(origPosArray, origIndexArray[faceVertexBase + 2] * 3); // compute face dimensions tmpU.sub(tmpOrigin); tmpV.sub(tmpOrigin); // set camera to match texel, first in mesh-local space tmpOrigin.addScaledVector(tmpU, pU); tmpOrigin.addScaledVector(tmpV, pV); // compute normal and cardinal directions // (done per texel for linear interpolation of normals) setBlendedNormal( tmpNormal, origNormalArray, origIndexArray, faceVertexBase, pU, pV ); // use consistent "left" and "up" directions based on just the normal if (tmpNormal.x === 0 && tmpNormal.y === 0) { tmpU.set(1, 0, 0); } else { tmpU.set(0, 0, 1); } tmpV.crossVectors(tmpNormal, tmpU); tmpV.normalize(); tmpU.crossVectors(tmpNormal, tmpV); tmpU.normalize(); // nudge the light probe position based on requested offset tmpOrigin.addScaledVector(tmpNormal, settings.offset); // proceed with the renders setUpProbeUp(probeCam, originalMesh, tmpOrigin, tmpNormal, tmpU); probeTarget.viewport.set( 0, batchOffsetY + probeTargetSize, probeTargetSize, probeTargetSize ); probeTarget.scissor.set( 0, batchOffsetY + probeTargetSize, probeTargetSize, probeTargetSize ); gl.setRenderTarget(probeTarget); // propagate latest target params gl.render(lightScene, probeCam); // sides only need the upper half of rendered view, so we set scissor accordingly setUpProbeSide(probeCam, originalMesh, tmpOrigin, tmpNormal, tmpU, 1); probeTarget.viewport.set( 0, batchOffsetY, probeTargetSize, probeTargetSize ); probeTarget.scissor.set( 0, batchOffsetY + halfSize, probeTargetSize, halfSize ); gl.setRenderTarget(probeTarget); // propagate latest target params gl.render(lightScene, probeCam); setUpProbeSide(probeCam, originalMesh, tmpOrigin, tmpNormal, tmpU, -1); probeTarget.viewport.set( probeTargetSize, batchOffsetY, probeTargetSize, probeTargetSize ); probeTarget.scissor.set( probeTargetSize, batchOffsetY + halfSize, probeTargetSize, halfSize ); gl.setRenderTarget(probeTarget); // propagate latest target params gl.render(lightScene, probeCam); setUpProbeSide(probeCam, originalMesh, tmpOrigin, tmpNormal, tmpV, 1); probeTarget.viewport.set( probeTargetSize * 2, batchOffsetY, probeTargetSize, probeTargetSize ); probeTarget.scissor.set( probeTargetSize * 2, batchOffsetY + halfSize, probeTargetSize, halfSize ); gl.setRenderTarget(probeTarget); // propagate latest target params gl.render(lightScene, probeCam); setUpProbeSide(probeCam, originalMesh, tmpOrigin, tmpNormal, tmpV, -1); probeTarget.viewport.set( probeTargetSize * 3, batchOffsetY, probeTargetSize, probeTargetSize ); probeTarget.scissor.set( probeTargetSize * 3, batchOffsetY + halfSize, probeTargetSize, halfSize ); gl.setRenderTarget(probeTarget); // propagate latest target params gl.render(lightScene, probeCam); } else { // if nothing else to render, mark the end of batch and finish batchTexels[batchItem] = undefined; break; } } // fetch rendered data in one go (this is very slow) gl.readRenderTargetPixels( probeTarget, 0, 0, targetWidth, targetHeight, probeData ); // restore renderer state gl.setRenderTarget(null); // this restores original scissor/viewport gl.setClearColor(tmpPrevClearColor, prevClearAlpha); gl.autoClear = prevAutoClear; gl.toneMapping = prevToneMapping; // if something was rendered, send off the data for consumption for (let batchItem = 0; batchItem < PROBE_BATCH_COUNT; batchItem += 1) { const renderedTexelIndex = batchTexels[batchItem]; // see if the batch ended early if (renderedTexelIndex === undefined) { break; } // each batch is 2 tiles high const probePartsReporter = function* () { const batchOffsetY = batchItem * probeTargetSize * 2; const rowPixelStride = probeTargetSize * 4; const probeDataReport: ProbeDataReport = { rgbaData: probeData, rowPixelStride, probeBox: tmpProbeBox, originX: 0, // filled in later originY: 0 }; tmpProbeBox.set( 0, batchOffsetY + probeTargetSize, probeTargetSize, probeTargetSize ); probeDataReport.originX = 0; probeDataReport.originY = 0; yield probeDataReport; tmpProbeBox.set(0, batchOffsetY + halfSize, probeTargetSize, halfSize); probeDataReport.originX = 0; probeDataReport.originX = halfSize; yield probeDataReport; tmpProbeBox.set( probeTargetSize, batchOffsetY + halfSize, probeTargetSize, halfSize ); probeDataReport.originX = 0; probeDataReport.originX = halfSize; yield probeDataReport; tmpProbeBox.set( probeTargetSize * 2, batchOffsetY + halfSize, probeTargetSize, halfSize ); probeDataReport.originX = 0; probeDataReport.originX = halfSize; yield probeDataReport; tmpProbeBox.set( probeTargetSize * 3, batchOffsetY + halfSize, probeTargetSize, halfSize ); probeDataReport.originX = 0; probeDataReport.originX = halfSize; yield probeDataReport; }; // aggregate the probe target pixels readTexel(probePartsReporter, probePixelAreaLookup); yield { texelIndex: renderedTexelIndex, rgba: tmpTexelRGBA }; } }; try { await taskCallback(renderLightProbeBatch, probeTarget.texture); } finally { // always clean up regardless of error state probeTarget.dispose(); } }
the_stack
import { satisfies } from 'satisfier' import * as T from '.' import { AllType } from './AllType' import { analyze } from './analyze' describe('non-strict', () => { const options = { strict: false, debug: false } describe('undefined', () => { test('only undefined passes', () => { const t = T.undefined assert(analyze(options, t, undefined), { type: 'undefined' }) analyzeFailsOtherThan(options, t, undefined) assert(analyze(options, t, true), { type: 'undefined', fail: true }) }) }) describe('null', () => { test('only null passes', () => { const t = T.null assert(analyze(options, t, null), { type: 'null' }) analyzeFailsOtherThan(options, t, null) assert(analyze(options, t, true), { type: 'null', fail: true }) }) test('optional', () => { const t = T.null.optional const pass = { type: 'union' as const, value: [ { type: 'null' }, { type: 'undefined' } ] } assert(analyze(options, t, null), pass) assert(analyze(options, t, undefined), pass) assert(analyze(options, t, true), { type: 'union' as const, value: [ { type: 'null', fail: true }, { type: 'undefined', fail: true } ], fail: true }) }) }) describe('boolean', () => { test('only true | false passes', () => { const t = T.boolean const pass = { type: 'boolean' as const } assert(analyze(options, t, true), pass) assert(analyze(options, t, false), pass) analyzeFailsOtherThan(options, t, true, false) assert(analyze(options, t, null), { type: 'boolean', fail: true }) }) test('true', () => { const t = T.boolean.true assert(analyze(options, t, true), { type: 'boolean', value: true }) assert(analyze(options, t, null), { type: 'boolean', value: true, fail: true }) }) test('false', () => { const t = T.boolean.false assert(analyze(options, t, false), { type: 'boolean', value: false }) assert(analyze(options, t, null), { type: 'boolean', value: false, fail: true }) }) test('optional', () => { const t = T.boolean.optional const pass = { type: 'union' as const, value: [ { type: 'boolean' }, { type: 'undefined' } ], } assert(analyze(options, t, undefined), pass) assert(analyze(options, t, true), pass) assert(analyze(options, t, false), pass) analyzeFailsOtherThan(options, t, true, false, undefined) assert(analyze(options, t, null), { type: 'union' as const, value: [ { type: 'boolean', fail: true }, { type: 'undefined', fail: true } ], fail: true }) }) test('optional create', () => { const t = T.boolean.optional.create(true) const pass = { type: 'union' as const, value: [ { type: 'boolean', value: true }, { type: 'undefined' } ], } assert(analyze(options, t, undefined), pass) assert(analyze(options, t, true), pass) assert(analyze(options, t, false), { type: 'union' as const, value: [ { type: 'boolean', value: true, fail: true }, { type: 'undefined', fail: true } ], fail: true }) }) test('optional true', () => { const t = T.boolean.optional.true const pass = { type: 'union' as const, value: [ { type: 'boolean', value: true }, { type: 'undefined' } ], } assert(analyze(options, t, undefined), pass) assert(analyze(options, t, true), pass) assert(analyze(options, t, false), { type: 'union' as const, value: [ { type: 'boolean', value: true, fail: true }, { type: 'undefined', fail: true } ], fail: true }) }) test('optional false', () => { const t = T.boolean.optional.false const pass = { type: 'union' as const, value: [ { type: 'boolean', value: false }, { type: 'undefined' } ], } assert(analyze(options, t, undefined), pass) assert(analyze(options, t, false), pass) assert(analyze(options, t, true), { type: 'union' as const, value: [ { type: 'boolean', value: false, fail: true }, { type: 'undefined', fail: true } ], fail: true }) }) }) describe('number', () => { test('only number passes', () => { const t = T.number const pass = { type: 'number' as const } assert(analyze(options, t, 0), pass) assert(analyze(options, t, 1), pass) assert(analyze(options, t, -1), pass) analyzeFailsOtherThan(options, t, -1, 0, 1) assert(analyze(options, t, null), { type: 'number', fail: true }) }) test('0', () => { const t = T.number.create(0) const pass = { type: 'number' as const, value: 0 } assert(analyze(options, t, 0), pass) analyzeFailsOtherThan(options, t, 0) assert(analyze(options, t, 1), { type: 'number', value: 0, fail: true }) }) test('1', () => { const t = T.number.create(1) const pass = { type: 'number' as const, value: 1 } assert(analyze(options, t, 1), pass) analyzeFailsOtherThan(options, t, 1) assert(analyze(options, t, 0), { type: 'number', value: 1, fail: true }) }) test('optional', () => { const t = T.number.optional const pass = { type: 'union' as const, value: [ { type: 'number' }, { type: 'undefined' } ] } assert(analyze(options, t, undefined), pass) assert(analyze(options, t, 0), pass) assert(analyze(options, t, 1), pass) assert(analyze(options, t, -1), pass) analyzeFailsOtherThan(options, t, -1, 0, 1, undefined) assert(analyze(options, t, null), { type: 'union' as const, value: [ { type: 'number', fail: true }, { type: 'undefined', fail: true } ], fail: true }) }) test('optional create', () => { const t = T.number.optional.create(1) const pass = { type: 'union' as const, value: [ { type: 'number', value: 1 }, { type: 'undefined' } ] } assert(analyze(options, t, undefined), pass) assert(analyze(options, t, 1), pass) assert(analyze(options, t, 0), { type: 'union' as const, value: [ { type: 'number', value: 1, fail: true }, { type: 'undefined', fail: true } ], fail: true }) }) test('list: single', () => { const t = T.number.list(1) const pass = { type: 'number' as const, value: 1 } assert(analyze(options, t, 1), pass) assert(analyze(options, t, 0), { type: 'number', value: 1, fail: true }) }) test('list: multiple', () => { const t = T.number.list(1, 2, 3) const pass = { type: 'union' as const, value: [ { type: 'number', value: 1 }, { type: 'number', value: 2 }, { type: 'number', value: 3 }, ] } assert(analyze(options, t, 1), pass) assert(analyze(options, t, 2), pass) assert(analyze(options, t, 3), pass) assert(analyze(options, t, 0), { type: 'union' as const, value: [ { type: 'number', value: 1, fail: true }, { type: 'number', value: 2, fail: true }, { type: 'number', value: 3, fail: true } ], fail: true }) }) test('optional.list: multiple', () => { const t = T.number.optional.list(1, 2, 3) const pass = { type: 'union' as const, value: [ { type: 'number', value: 1 }, { type: 'number', value: 2 }, { type: 'number', value: 3 }, { type: 'undefined' } ] } assert(analyze(options, t, undefined), pass) assert(analyze(options, t, 1), pass) assert(analyze(options, t, 2), pass) assert(analyze(options, t, 3), pass) assert(analyze(options, t, 0), { type: 'union' as const, value: [ { type: 'number', value: 1, fail: true }, { type: 'number', value: 2, fail: true }, { type: 'number', value: 3, fail: true }, { type: 'undefined', fail: true } ], fail: true }) }) }) describe('string', () => { test('only string passes', () => { const t = T.string const pass = { type: 'string' as const } assert(analyze(options, t, ''), pass) assert(analyze(options, t, 'a'), pass) analyzeFailsOtherThan(options, t, '', 'a') assert(analyze(options, t, null), { type: 'string', fail: true }) }) test("''", () => { const t = T.string.create('') const pass = { type: 'string' as const, value: '' } assert(analyze(options, t, ''), pass) analyzeFailsOtherThan(options, t, '') assert(analyze(options, t, 'a'), { type: 'string', value: '', fail: true }) }) test(`'a'`, () => { const t = T.string.create('a') const pass = { type: 'string' as const, value: 'a' } assert(analyze(options, t, 'a'), pass) analyzeFailsOtherThan(options, t, 'a') assert(analyze(options, t, ''), { type: 'string', value: 'a', fail: true }) }) test('optional', () => { const t = T.string.optional const pass = { type: 'union' as const, value: [ { type: 'string' }, { type: 'undefined' } ] } assert(analyze(options, t, undefined), pass) assert(analyze(options, t, ''), pass) assert(analyze(options, t, 'a'), pass) analyzeFailsOtherThan(options, t, '', 'a', undefined) assert(analyze(options, t, null), { type: 'union' as const, value: [ { type: 'string', fail: true }, { type: 'undefined', fail: true } ], fail: true }) }) test('optional create', () => { const t = T.string.optional.create('a') const pass = { type: 'union' as const, value: [ { type: 'string', value: 'a' }, { type: 'undefined' } ] } assert(analyze(options, t, undefined), pass) assert(analyze(options, t, 'a'), pass) assert(analyze(options, t, ''), { type: 'union' as const, value: [ { type: 'string', value: 'a', fail: true }, { type: 'undefined', fail: true } ], fail: true }) }) test('list: single', () => { const t = T.string.list('a') assert(analyze(options, t, 'a'), { type: 'string', value: 'a' }) assert(analyze(options, t, ''), { type: 'string', value: 'a', fail: true }) }) test('list: multiple', () => { const t = T.string.list('1', '2', '3') const pass = { type: 'union' as const, value: [ { type: 'string', value: '1' }, { type: 'string', value: '2' }, { type: 'string', value: '3' } ] } assert(analyze(options, t, '1'), pass) assert(analyze(options, t, '2'), pass) assert(analyze(options, t, '3'), pass) assert(analyze(options, t, 1), { type: 'union' as const, value: [ { type: 'string', value: '1', fail: true }, { type: 'string', value: '2', fail: true }, { type: 'string', value: '3', fail: true }, ], fail: true }) }) test('optional.list: multiple', () => { const t = T.string.optional.list('1', '2', '3') const pass = { type: 'union' as const, value: [ { type: 'string', value: '1' }, { type: 'string', value: '2' }, { type: 'string', value: '3' }, { type: 'undefined' } ] } assert(analyze(options, t, undefined), pass) assert(analyze(options, t, '1'), pass) assert(analyze(options, t, '2'), pass) assert(analyze(options, t, '3'), pass) assert(analyze(options, t, 1), { type: 'union' as const, value: [ { type: 'string', value: '1', fail: true }, { type: 'string', value: '2', fail: true }, { type: 'string', value: '3', fail: true }, { type: 'undefined', fail: true } ], fail: true }) }) }) describe('bigint', () => { // test('only number passes', () => { // const t = T.number // const pass = { type: 'number' } // assert(analyze(options, t, 0), pass) // assert(analyze(options, t, 1), pass) // assert(analyze(options, t, -1), pass) // analyzeFailsOtherThan(options, t, -1, 0, 1) // assert(analyze(options, t, null), { pass: false, type: 'number' }) // }) // test('0', () => { // const t = T.number.create(0) // const pass = { type: 'number', value: 0 } // assert(analyze(options, t, 0), pass) // analyzeFailsOtherThan(options, t, 0) // assert(analyze(options, t, 1), { pass: false, type: 'number', value: 0, actual: 1 }) // }) // test('1', () => { // const t = T.number.create(1) // const pass = { type: 'number', value: 1 } // assert(analyze(options, t, 1), pass) // analyzeFailsOtherThan(options, t, 1) // assert(analyze(options, t, 0), { pass: false, type: 'number', value: 1, actual: 0 }) // }) // test('optional', () => { // const t = T.number.optional // const pass = { // pass: true, // type: 'union', // value: [ // { type: 'number' }, // { type: 'undefined' } // ] // } // assert(analyze(options, t, undefined), pass) // assert(analyze(options, t, 0), pass) // assert(analyze(options, t, 1), pass) // assert(analyze(options, t, -1), pass) // analyzeFailsOtherThan(options, t, -1, 0, 1, undefined) // assert(analyze(options, t, null), { // pass: false, // type: 'union', // value: [ // { pass: false, type: 'number' }, // { pass: false, type: 'undefined' } // ], // actual: null // }) // }) // test('optional create', () => { // const t = T.number.optional.create(1) // const pass = { // pass: true, // type: 'union', // value: [ // { type: 'number', value: 1 }, // { type: 'undefined' } // ] // } // assert(analyze(options, t, undefined), pass) // assert(analyze(options, t, 1), pass) // assert(analyze(options, t, 0), { // pass: false, // type: 'union', // value: [ // { pass: false, type: 'number', value: 1, actual: 0 }, // { pass: false, type: 'undefined', actual: 0 } // ], // actual: 0 // }) // }) // test('list: single', () => { // const t = T.number.list(1) // const pass = { type: 'number', value: 1 } // assert(analyze(options, t, 1), pass) // assert(analyze(options, t, 0), { // pass: false, // type: 'number', // value: 1, // actual: 0 // }) // }) // test('list: multiple', () => { // const t = T.number.list(1, 2, 3) // const pass = { // pass: true, // type: 'union', // value: [ // { type: 'number', value: 1 }, // { type: 'number', value: 2 }, // { type: 'number', value: 3 }, // ] // } // assert(analyze(options, t, 1), pass) // assert(analyze(options, t, 2), pass) // assert(analyze(options, t, 3), pass) // assert(analyze(options, t, 0), { // pass: false, // type: 'union', // value: [ // { pass: false, type: 'number', value: 1, actual: 0 }, // { pass: false, type: 'number', value: 2, actual: 0 }, // { pass: false, type: 'number', value: 3, actual: 0 } // ], // actual: 0 // }) // }) // test('optional.list: multiple', () => { // const t = T.number.optional.list(1, 2, 3) // const pass = { // pass: true, // type: 'union', // value: [ // { type: 'number', value: 1 }, // { type: 'number', value: 2 }, // { type: 'number', value: 3 }, // { type: 'undefined' } // ] // } // assert(analyze(options, t, undefined), pass) // assert(analyze(options, t, 1), pass) // assert(analyze(options, t, 2), pass) // assert(analyze(options, t, 3), pass) // assert(analyze(options, t, 0), { // pass: false, // type: 'union', // value: [ // { pass: false, type: 'number', value: 1, actual: 0 }, // { pass: false, type: 'number', value: 2, actual: 0 }, // { pass: false, type: 'number', value: 3, actual: 0 }, // { pass: false, type: 'undefined', actual: 0 } // ], // actual: 0 // }) // }) }) describe('symbol', () => { test('only symbol passes', () => { const t = T.symbol const pass = { type: 'symbol' } as const assert(analyze(options, t, Symbol()), pass) assert(analyze(options, t, Symbol('abc')), pass) assert(analyze(options, t, Symbol.for('def')), pass) analyzeFailsOtherThan(options, t, Symbol.for('a')) assert(analyze(options, t, true), { type: 'symbol', fail: true }) }) test('optional', () => { const t = T.symbol.optional const pass = { type: 'union' as const, value: [ { type: 'symbol' }, { type: 'undefined' } ] } assert(analyze(options, t, Symbol()), pass) assert(analyze(options, t, Symbol('abc')), pass) assert(analyze(options, t, Symbol.for('def')), pass) assert(analyze(options, t, undefined), pass) assert(analyze(options, t, true), { type: 'union' as const, value: [ { type: 'symbol', fail: true }, { type: 'undefined', fail: true } ], fail: true }) }) }) describe('union', () => { test('on two types', () => { const t = T.union.create(T.boolean, T.number) const pass = { type: 'union' as const, value: [{ type: 'boolean' }, { type: 'number' }] } assert(analyze(options, t, 0), pass) assert(analyze(options, t, false), pass) }) test('on multiple primitive types', () => { const t = T.union.create(T.boolean, T.null, T.number) const pass = { type: 'union' as const, value: [ { type: 'boolean' }, { type: 'null' }, { type: 'number' } ] } assert(analyze(options, t, false), pass) assert(analyze(options, t, null), pass) assert(analyze(options, t, 0), pass) }) }) describe('array', () => { test('only array of any kind passes', () => { const t = T.array const pass = { type: 'array' as const } assert(analyze(options, t, []), pass) assert(analyze(options, t, ['a']), pass) analyzeFailsOtherThan(options, t, [], ['a']) assert(analyze(options, t, null), { type: 'array', fail: true }) }) test('array.unknown accepts only array of any kind', () => { const t = T.array.unknown const pass = { type: 'array', value: { type: 'unknown' } } as const assert(analyze(options, t, []), pass) assert(analyze(options, t, ['a']), pass) analyzeFailsOtherThan(options, t, [], ['a']) assert(analyze(options, t, null), { type: 'array', value: { type: 'unknown' }, fail: true }) }) test('specific type', () => { const t = T.array.create(T.number) const pass = { type: 'array', value: { type: 'number' } } as const assert(analyze(options, t, []), pass) assert(analyze(options, t, [0]), pass) assert(analyze(options, t, [1, 2]), pass) assert(analyze(options, t, ['a']), { type: 'array', value: { type: 'number', fail: true }, fail: true }) assert(analyze(options, t, [1, 'a']), { type: 'array', // value: { type: 'number' }, value: { type: 'number', fail: true }, fail: true }) assert(analyze(options, t, ['a', 1]), { type: 'array', value: { type: 'number', fail: true }, fail: true }) }) test('specific const type', () => { const t = T.array.create(T.number.create(2)) const pass = { type: 'array', value: { type: 'number', value: 2 } } as const assert(analyze(options, t, []), pass) assert(analyze(options, t, [2]), pass) assert(analyze(options, t, [0]), { type: 'array', value: { type: 'number', value: 2, fail: true }, fail: true }) }) test(`array's value type can be union type`, () => { const t = T.array.create(T.union.create(T.number, T.boolean)) const pass = { type: 'array', value: { type: 'union', value: [{ type: 'number' }, { type: 'boolean' }] } } as const assert(analyze(options, t, []), pass) assert(analyze(options, t, [0]), pass) assert(analyze(options, t, [false]), pass) assert(analyze(options, t, [false, 0]), pass) assert(analyze(options, t, [0, false, '']), { type: 'array', value: { type: 'union', value: [ { type: 'number', fail: true }, { type: 'boolean', fail: true } ], fail: true }, fail: true }) }) test('optional', () => { const t = T.array.optional const pass = { type: 'union' as const, value: [{ type: 'array' }, { type: 'undefined' }] } assert(analyze(options, t, []), pass) assert(analyze(options, t, [1]), pass) assert(analyze(options, t, ['a']), pass) assert(analyze(options, t, undefined), pass) }) test('optional create', () => { const t = T.array.optional.create(T.string) const pass = { type: 'union' as const, value: [ { type: 'array', value: { type: 'string' } }, { type: 'undefined' } ] } assert(analyze(options, t, ['']), pass) assert(analyze(options, t, ['a']), pass) assert(analyze(options, t, undefined), pass) }) }) describe('tuple', () => { test('single value', () => { const t = T.tuple.create(T.number) const pass = { type: 'tuple' as const, value: [{ type: 'number' as const }] } assert(analyze(options, t, [0]), pass) assert(analyze(options, t, [1]), pass) assert(analyze(options, t, true), { type: 'tuple', value: [{ type: 'number' }], fail: true }) assert(analyze(options, t, []), { type: 'tuple', value: [{ type: 'number', fail: true }], fail: true }) assert(analyze(options, t, ['a']), { type: 'tuple', value: [{ type: 'number', fail: true }], fail: true }) }) test('two values', () => { const t = T.tuple.create(T.number, T.string) const pass = { type: 'tuple' as const, value: [{ type: 'number' }, { type: 'string' }] } expect(T.satisfy(t, [0, ''])).toBe(true) expect(T.satisfy(t, [0])).toBe(false) assert(analyze(options, t, [0, '']), pass) assert(analyze(options, t, [1]), { type: 'tuple', value: [ { type: 'number' }, { type: 'string', fail: true } ], fail: true }) assert(analyze(options, t, [1, 2]), { type: 'tuple', value: [ { type: 'number' }, { type: 'string', fail: true } ], fail: true }) assert(analyze(options, t, ['a']), { type: 'tuple', value: [ { type: 'number', fail: true }, { type: 'string', fail: true } ], fail: true }) }) }) describe('object', () => { test('only object of any kind passes', () => { const t = T.object const pass = { type: 'object' as const } assert(analyze(options, t, {}), pass) assert(analyze(options, t, { a: 1 }), pass) assert(analyze(options, t, { 0: 0 }), pass) assert(analyze(options, t, []), { type: 'object', fail: true }) assert(analyze(options, t, null), { type: 'object', fail: true }) analyzeFailsOtherThan(options, t, {}, { a: 1 }) }) test('single prop', () => { const t = T.object.create({ a: T.number }) const pass = { type: 'object' as const, value: { a: { type: 'number' } } } assert(analyze(options, t, { a: 0 }), pass) assert(analyze(options, t, { a: 1 }), pass) assert(analyze(options, t, { a: 'a' }), { type: 'object', value: { a: { type: 'number', fail: true } }, fail: true }) assert(analyze(options, t, { a: { b: 'b' } }), { type: 'object', value: { a: { type: 'number', fail: true } }, fail: true }) }) test('two props', () => { const t = T.object.create({ a: T.number.create(1), b: T.string }) const pass = { type: 'object' as const, value: { a: { type: 'number', value: 1 }, b: { type: 'string' } } } assert(analyze(options, t, { a: 1, b: '' }), pass) assert(analyze(options, t, { a: 1, b: 'b' }), pass) assert(analyze(options, t, { a: 1, b: '' }), pass) assert(analyze(options, t, { a: 1, b: '', c: 3 }), pass) assert(analyze(options, t, { a: 2, b: '' }), { type: 'object', value: { a: { type: 'number', value: 1, fail: true }, b: { type: 'string' } }, fail: true }) }) test('props with union', () => { const t = T.object.create({ a: T.union.create(T.number.create(1), T.boolean.true), b: T.string }) const pass = { type: 'object' as const, value: { a: { type: 'union' as const, value: [{ type: 'number', value: 1 }, { type: 'boolean', value: true }] }, b: { type: 'string' } } } assert(analyze(options, t, { a: 1, b: '' }), pass) assert(analyze(options, t, { a: true, b: '' }), pass) assert(analyze(options, t, { a: false, b: '' }), { type: 'object', value: { a: { type: 'union', value: [ { type: 'number', value: 1, fail: true }, { type: 'boolean', value: true, fail: true } ], fail: true }, b: { type: 'string' } }, fail: true }) }) test('nested object', () => { const t = T.object.create({ a: T.object.create({ b: T.number }) }) const pass = { type: 'object' as const, value: { a: { type: 'object', value: { b: { type: 'number' } } } } } assert(analyze(options, t, { a: { b: 0 } }), pass) assert(analyze(options, t, { a: { b: 'b' } }), { type: 'object', value: { a: { type: 'object', value: { b: { type: 'number', fail: true } }, fail: true } }, fail: true }) }) test('optional', () => { const t = T.object.optional const pass = { type: 'union' as const, value: [{ type: 'object' }, { type: 'undefined' }] } assert(analyze(options, t, undefined), pass) assert(analyze(options, t, {}), pass) assert(analyze(options, t, { a: 0 }), pass) }) test('optional create', () => { const t = T.object.optional.create({ a: T.string }) const pass = { type: 'union' as const, value: [ { type: 'object', value: { a: { type: 'string' } } }, { type: 'undefined' } ] } assert(analyze(options, t, undefined), pass) assert(analyze(options, t, { a: '' }), pass) assert(analyze(options, t, {}), { type: 'union' as const, value: [ { type: 'object', value: { a: { type: 'string', fail: true } }, fail: true }, { type: 'undefined', fail: true } ], fail: true }) }) }) describe('record', () => { test('base type', () => { const t = T.record.create(T.number) const pass = { type: 'record' as const, value: { type: 'number' } } analyzeFailsOtherThan(options, T.record.create(T.null), {}, { a: 1 }) assert(analyze(options, t, { a: 1 }), pass) assert(analyze(options, t, { a: 'b' }), { type: 'record', value: { type: 'number', fail: true }, fail: true }) }) test('nested', () => { const t = T.record.optional.create(T.record.create(T.string)) const pass = { type: 'union' as const, value: [{ type: 'record', value: { type: 'record', value: { type: 'string' } } }, { type: 'undefined' } ] } assert(analyze(options, t, undefined), pass) assert(analyze(options, t, { a: { b: 'b' } }), pass) assert(analyze(options, t, { a: { b: true } }), { type: 'union' as const, value: [{ type: 'record', value: { type: 'record', value: { type: 'string', fail: true }, fail: true }, fail: true }, { type: 'undefined', fail: true }], fail: true }) }) }) }) describe('strict', () => { const options = { strict: true, debug: false } describe('tuple', () => { test('have more elements then specified will fail', () => { const t = T.tuple.create(T.string) assert(analyze(options, t, ['a', 'b', 'c', 'd']), { type: 'tuple', value: [{ type: 'string' }], fail: true }) }) }) describe('object', () => { test('have extra properties then specified will fail', () => { const t = T.object.create({ a: T.number }) assert(analyze(options, t, { a: 1, b: 2, c: 'c' }), { type: 'object', value: { a: { type: 'number' } }, fail: true }) }) }) }) function assert(result: analyze.Result, analysis: AllType.Analysis) { expect(result.analysis).toEqual(analysis) } function analyzeFailsOtherThan(options: analyze.Options, type: T.AllType, ...excepts: any[]) { const values = [undefined, null, true, false, -1, 0, 1, -1n, 0n, 1n, '', 'a', [], ['a'], {}, { a: 1 }, Symbol.for('a')] values.forEach(v => { if (!excepts.some(e => satisfies(v, e))) { expect(analyze(options, type, v).analysis.fail).toBe(true) } }) }
the_stack
import copyTo from 'copy-to-clipboard'; import Parser from './parser'; import { EditorInterface, EngineInterface, ClipboardInterface } from './types'; import { RangeInterface } from './types/range'; import { isEngine, isSafari } from './utils'; import { $ } from './node'; import Range from './range'; import { NodeInterface } from './types'; import { CARD_ELEMENT_KEY, CARD_KEY, DATA_ID } from './constants'; export const isDragEvent = ( event: DragEvent | ClipboardEvent, ): event is DragEvent => { return !!(<DragEvent>event).dataTransfer; }; export default class Clipboard implements ClipboardInterface { private editor: EditorInterface; constructor(editor: EditorInterface) { this.editor = editor; } getData(event: DragEvent | ClipboardEvent) { const transfer = isDragEvent(event) ? event.dataTransfer : event.clipboardData; let html = transfer?.getData('text/html'); let text = transfer?.getData('text'); let files: Array<File> = []; // Edge 处理 try { if (transfer?.items && transfer.items.length > 0) { Array.from(transfer.items).forEach((item) => { let file = item.kind === 'file' ? item.getAsFile() : null; if (file !== null) { if ( file.type && file.type.indexOf('image/png') > -1 && !file.lastModified ) { file = new File([file], 'image.png', { type: file.type, }); } file['ext'] = text?.split('.').pop(); } if (file) files.push(file); }); } else if (transfer?.files && transfer.files.length > 0) { files = Array.from(transfer.files); } } catch (err) { if (transfer?.files && transfer.files.length > 0) { files = Array.from(transfer.files); } } // 从 Mac OS Finder 复制文件 if (html === '' && text && /^.+\.\w+$/.test(text) && files.length > 0) { text = ''; // 在图片上,点击右键复制 } else if ( text === '' && html && /^(<meta.+?>)?<img.+?>$/.test(html) && files.length > 0 ) { html = ''; // 从 Excel、Numbers 复制 } else if ( (html || text) && files.length > 0 && !html?.startsWith('<img') && (html || !/^https(s)?:/.test(text || '')) ) { files = []; } return { html, text, files, }; } write( event: ClipboardEvent, range: RangeInterface | null = null, callback?: (data: { html: string; text: string }) => void, ) { if (!range) range = Range.from(this.editor); if (!range) throw 'Range is null'; range = range.cloneRange(); //.shrinkToElementNode(); let card = range.startNode.closest(`[${CARD_KEY}]`, (node) => { return $(node).isEditable() ? undefined : node.parentNode || undefined; }); if (card.length > 0 && !range.collapsed && range.endOffset === 0) { if (range.endContainer.previousSibling) { range.setEndAfter(range.endContainer.previousSibling); } if ( !range.collapsed && range.endOffset > 0 && range.endContainer.childNodes[range.endOffset - 1] === card[0] ) { const cardCenter = range.startNode.closest( `[${CARD_ELEMENT_KEY}="center"]`, (node) => { return $(node).isEditable() ? undefined : node.parentNode || undefined; }, ); if (cardCenter.length > 0) { range.setEnd( cardCenter[0], cardCenter[0].childNodes.length, ); } else { range.setEnd(card[0], card[0].childNodes.length); } } } let root = range.commonAncestorNode; card = root.closest(`[${CARD_KEY}]`, (node) => { return $(node).isEditable() ? undefined : node.parentNode || undefined; }); if (card.length > 0) { const cardCenter = root.closest( `[${CARD_ELEMENT_KEY}="center"]`, (node) => { return $(node).isEditable() ? undefined : node.parentNode || undefined; }, ); if (cardCenter.length === 0) { range.select(card); root = range.commonAncestorNode; } } const nodes: Array<Node> = root.name === '#text' ? [document.createElement('span')] : []; card = root.closest(`[${CARD_KEY}]`, (node) => { if ($(node).isEditable()) return; if (node.nodeType === Node.ELEMENT_NODE) { const display = window .getComputedStyle(node as Element) .getPropertyValue('display'); if (display === 'inline') { nodes.push(node.cloneNode()); } } return node.parentNode || undefined; }); const { node, list } = this.editor; const hasChildEngine = root.find('.am-engine-view').length > 0 || root.find('.am-engine').length > 0; const hasParentEngine = root.closest('.am-engine-view').length > 0 || root.closest('.am-engine').length > 0; if (card.length <= 0 && (hasChildEngine || hasParentEngine)) { event.preventDefault(); if (range.collapsed) { event.clipboardData?.setData('text/html', ''); event.clipboardData?.setData('text', ''); } else { // 修复自定义列表选择范围 let customizeStartItem: NodeInterface | undefined; const li = range.startNode.closest('li'); if (li && node.isCustomize(li)) { const endLi = range.endNode.closest('li'); if ( !li.equal(endLi) || (list.isLast(range) && list.isFirst(range)) ) { if (list.isFirst(range)) { const ul = li.parent(); const index = li.getIndex(); if (ul) range.setStart(ul, index < 0 ? 0 : index); } else { const ul = li.parent(); // 选在列表项靠后的节点,把剩余节点拼接成完成的列表项 const selection = range.createSelection(); const rightNode = selection.getNode( li, 'center', true, ); selection.anchor?.remove(); selection.focus?.remove(); if (isEngine(this.editor)) this.editor.change.combinText(); if (rightNode.length > 0) { let isRemove = false; rightNode.each((_, index) => { const item = rightNode.eq(index); if (!isRemove && item?.name === 'li') { isRemove = true; return; } if (isRemove) item?.remove(); }); const card = li.first(); const component = card ? this.editor.card.find(card) : undefined; if (component) { customizeStartItem = rightNode; this.editor.list.addCardToCustomize( customizeStartItem, component.name, component.getValue(), ); if (ul) node.wrap( customizeStartItem, ul?.clone(), ); } } } } } const contents = range .enlargeToElementNode(true) .cloneContents(); // if (customizeStartItem) { // contents.removeChild(contents.childNodes[0]); // contents.prepend(customizeStartItem[0]); // } const listMergeBlocks: NodeInterface[] = []; contents.querySelectorAll('li').forEach((child) => { const childElement = $(child); const dataId = childElement.attributes(DATA_ID); if (!dataId) return; const curentElement = this.editor.container .get<HTMLElement>() ?.querySelector(`[${DATA_ID}=${dataId}]`); // 补充自定义列表丢失的卡片 if ( node.isCustomize(childElement) && !childElement.first()?.isCard() && curentElement?.firstChild ) { childElement.prepend( node.clone( $(curentElement.firstChild), true, false, ), ); } let parent: NodeInterface | Node | null | undefined = curentElement?.parentElement; parent = parent ? $(parent.cloneNode(false)) : null; const childParent = child.parentElement; if ( curentElement && parent && node.isList(parent) && (!childParent || !node.isList(childParent)) ) { if (parent.name === 'ol') { // 设置复制位置的 start 属性,默认不设置 // let start = parseInt(parent.attributes('start') || '0', 10) // start = $(curentElement).index() + start // if(start === 0) start = 1 // parent.attributes('start', start); parent.removeAttributes('start'); } node.wrap(child, parent); listMergeBlocks.push(parent); } }); const { inner, outter } = this.setNodes(nodes); const listNodes: NodeInterface[] = []; contents.childNodes.forEach((child) => { const childNode = $(child); if (node.isList(childNode) || childNode.name === 'li') { listNodes.push(childNode); } }); this.editor.nodeId.generateAll($(contents), true); // 合并列表 this.editor.list.merge(listNodes); const parser = new Parser(contents, this.editor); let html = parser.toHTML(inner, outter); const text = new Parser(html, this.editor).toText( this.editor.schema, true, ); if (callback) { callback({ html, text }); } if (html) html = '<meta name="source" content="aomao" />' + html; event.clipboardData?.setData('text/html', html); event.clipboardData?.setData('text', text); } } } copy(data: Node | string, trigger: boolean = false) { if (typeof data === 'string') { return copyTo(data); } const editor = this.editor; const selection = window.getSelection(); const range = selection ? Range.from(editor, selection) || Range.create(editor) : Range.create(editor); const cloneRange = range.cloneRange(); const block = $('<div class="am-engine-view">&#8203;</div>'); block.css({ position: 'fixed', top: 0, clip: 'rect(0, 0, 0, 0)', }); const clera = () => { block.remove(); selection?.removeAllRanges(); selection?.addRange(cloneRange.toRange()); }; block.on('copy', (e: ClipboardEvent) => { e.stopPropagation(); this.write(e, range); clera(); }); $(document.body).append(block); block.append(editor.node.clone($(data), true)); if (trigger) { block.traverse((child) => { if (child.equal(block)) return; editor.trigger('copy', child); }); } block.append($('&#8203;', null)); const first = block.first()!; const end = block.last()!; range.select(block, true); range.setStartAfter(first); range.setEndBefore(end); selection?.removeAllRanges(); selection?.addRange(range.toRange()); let success = false; try { success = document.execCommand('copy'); if (!success) { throw 'Copy failed'; } } catch (err) { console.log('The copy command was not executed successfully ', err); clera(); } return success; } cut() { const range = Range.from(this.editor); if (!range) return; const root = range.commonAncestorNode; (this.editor as EngineInterface).change.delete(range); const listElements = this.editor.node.isList(root) ? root : root.find('ul,ol'); for (let i = 0; i < listElements.length; i++) { const list = $(listElements[i]); const childs = list.find('li'); childs.each((child) => { if ( '' === (child as HTMLElement).innerText || (isSafari && '\n' === (child as HTMLElement).innerText) ) { child.parentNode?.removeChild(child); } }); if (list.children().length === 0) { list.remove(); } } } private setNodes(nodes: Array<Node>) { if (0 === nodes.length) return {}; for (let i = nodes.length - 1; i > 0; i--) { const node = nodes[i]; node.appendChild(nodes[i - 1]); } return { inner: nodes[0], outter: nodes[nodes.length - 1], }; } }
the_stack
import * as React from 'react'; import styles from './MetadataNews.module.scss'; import { IMetadataNewsProps, IMetadataNewsState, IMetadataRefinerInfo, IMetadataNewsItem, ILookupInfo, ILoadNewsResult, IMetadataNewsPageCollectionInfo, unescapeHTML, IMetadataContextualMenuItemResult } from '../../../interfaces'; import MetadataNewsRefiners from './MetadataNewsRefiners'; import { escape } from '@microsoft/sp-lodash-subset'; import { sp, PagedItemCollection } from '@pnp/sp'; import { IContextualMenuItem, ActionButton, Label, Spinner, SpinnerSize, Dialog, DialogType, DialogFooter, PrimaryButton, Image, ImageFit } from '@microsoft/office-ui-fabric-react-bundle'; //'office-ui-fabric-react/lib'; import { DocumentCard, DocumentCardActivity, DocumentCardPreview, DocumentCardTitle, DocumentCardType } from '@microsoft/office-ui-fabric-react-bundle'; //'office-ui-fabric-react/lib/DocumentCard'; import Truncate from 'react-truncate'; // array.from shim for some versions of IE let from = require('array.from'); if (Array['from'] === undefined) { Array['from'] = from.shim(); } // Plugin used for neatly arranging news items in the multiple column mode import { CSSGrid, measureItems, layout } from 'react-stonecutter'; // measureItems is a higher order function that wraps CSSGrid component and returns another component (also grid, but that takes into account actual item image heights) const Grid = measureItems(CSSGrid, { measureImages: true }); // A simple wrapper used in the MetadataNews component - conditionally injects Grid if multi column mode is enabled class Wrapper extends React.Component<any,any> { constructor(props: any, state: any) { super(props); } public render() { return this.props.multiColumn ? <div style={{display: this.props.itemCount > 0 ? "block" : "none", margin: "0 auto"}}> <Grid component="div" columns={this.props.columns} gutterWidth={10} gutterHeight={10} columnWidth={this.props.columnWidth} layout={layout.pinterest} > {this.props.children} </Grid> </div> : <div style={{display: this.props.itemCount > 0 ? "block" : "none", margin: "0 auto"}}> {this.props.children} </div>; } } // Main component export default class MetadataNews extends React.Component<IMetadataNewsProps, IMetadataNewsState> { private containerElement: HTMLElement = null; private themeBackgroundColor: string = null; private wrapper: React.ClassicComponentClass<{}>; constructor(props: IMetadataNewsProps, state: IMetadataNewsState) { super(props); this.state = { currentNewsItems: [], currentRefiners: [], pagedCollectionInfos: null, currentPage: 1, loading: false, dialogItem: null, containerWidth: 0, containerHeight: 0 }; this.updateWindowDimensions = this.updateWindowDimensions.bind(this); sp.setup({ sp: { headers: { Accept: 'application/json;odata=verbose' }, baseUrl: this.props.webUrl } }); } public shouldComponentUpdate(nextProps: IMetadataNewsProps, nextState: IMetadataNewsState) { return JSON.stringify(this.props) != JSON.stringify(nextProps) || JSON.stringify(this.state) != JSON.stringify(nextState); } // To make component render quickly the actual data retrieval starts after initial render in componentDidMount event public componentDidMount() { this.updateWindowDimensions(); window.addEventListener('resize', this.updateWindowDimensions); // Waiting for __themeState__ variable to become available to correctly read the theme configuration (if present) and then loading the data let reTryCount = 10; let intervalId = setInterval(() => { if ((window["__themeState__"] !== null && window["__themeState__"].theme !== null) || reTryCount < 1) { this.themeBackgroundColor = window["__themeState__"].theme ? window["__themeState__"].theme.accent : "#0078d7"; clearInterval(intervalId); this.loadNews(); } reTryCount--; }, 200); } // Removing event handler public componentWillUnmount() { window.removeEventListener('resize', this.updateWindowDimensions); } // Rendering logic public render(): React.ReactElement<IMetadataNewsProps> { let startItemsPosition = (this.state.currentPage - 1) * this.props.ItemLimit; let endItemsPosition = startItemsPosition + parseInt(this.props.ItemLimit as any); let docType = DocumentCardType.compact; if (this.state.containerWidth < 600) { docType = DocumentCardType.normal; } let itemMaxWidthNumber = parseInt(this.props.ItemHeight) * 1.7; let itemMaxWidth = `inherit`; let columnCount = 1; if (this.props.multiColumn) { columnCount = Math.floor(this.state.containerWidth / itemMaxWidthNumber); docType = DocumentCardType.normal; itemMaxWidth = `${itemMaxWidthNumber}px`; } return ( <div className={styles.metadataNews}> <div className={styles.container} id={styles.newsContainer} style={{maxWidth: `${this.props.containerWidth}px`}}> <MetadataNewsRefiners {...this.props} themeBackgroundColor={this.themeBackgroundColor} onContextualItemClick={(filterNodes) => this.handleRefinerChange(filterNodes)} /> <div className={styles.row}> <div className={styles.column}> {/* Paging */} <div style={{margin: "0 auto", textAlign: "center"}}> { this.state.currentPage > 1 ? <ActionButton data-automation-id='pagePrev' iconProps={{iconName: 'PageLeft'}} onClick={() => { if (this.state.currentPage == 2) { this.setState({pagedCollectionInfos: null, currentPage: 1, currentNewsItems: []}, () => { this.loadNews(); }); } else { this.changePage(false); } }}></ActionButton> : null } <Label style={{display: "inline-block", lineHeight: "40px", padding: 0, color: "#908989"}}>Page {this.state.currentPage}</Label> { this.state.pagedCollectionInfos != null && this.state.pagedCollectionInfos.length > 0 && this.state.pagedCollectionInfos[0].collection.hasNext ? <ActionButton data-automation-id='pageNext' iconProps={{iconName: 'PageRight'}} onClick={() => this.changePage(true)}></ActionButton> : null } </div> {/* Shows the dialog component if user clicked on an item */} {this.state.dialogItem == null ? null : <Dialog isOpen={true} hidden={false} onDismiss={() => this.setState({dialogItem: null})} dialogContentProps={{ type: DialogType.largeHeader, title: this.state.dialogItem.title, responsiveMode: 5, //or ResponsiveMode.xxxLarge, showCloseButton: true, className: styles.dialogMainOverride }} modalProps={{ isBlocking: false, responsiveMode: 5, //or ResponsiveMode.xxxLarge, containerClassName: styles.dialogMainOverride, firstFocusableSelector: styles.dialogMainOverride }} > {this.state.dialogItem.bannerImg != null ? <Image alt="" src={this.state.dialogItem.bannerImg} style={{maxWidth: "100%", margin: "0 auto"}}/> : null} <div className={styles.dialogMainOverride} dangerouslySetInnerHTML={{__html: this.state.dialogItem.content}}></div> <DialogFooter><PrimaryButton onClick={() => this.setState({dialogItem: null})} text='Close' /></DialogFooter> </Dialog> } {this.state.loading ? <Spinner size={SpinnerSize.large} label='Loading...' ariaLive='assertive' /> : <Wrapper itemCount={this.state.currentNewsItems.length} columns={columnCount} multiColumn={this.props.multiColumn} columnWidth={itemMaxWidthNumber}> { this.state.currentNewsItems.map((n: IMetadataNewsItem, i) => { if (i < startItemsPosition || i >= endItemsPosition) { return null; } return ( /* Below is the template for each rendered news item */ <div style={{margin: "10px", minHeight: `${this.props.ItemHeight}px`, maxWidth: itemMaxWidth}} className={styles.docCards} > {/* Reusing... or rather brutally abusing the DocumentCard and related components to instead display news item content in them */} <DocumentCard type={docType} onClick={() => { this.onItemClick(n); }} > {/* Image rendering code */} {n.bannerImg == null || n.bannerImg == "" ? null : <div style={{maxWidth: `${parseInt(this.props.ItemHeight) * 1.7}px`}}> <DocumentCardPreview previewImages={[{ url: n.bannerImg, name: "...", previewImageSrc: n.bannerImg, height: parseInt(this.props.ItemHeight), imageFit: ImageFit.cover, errorImageSrc: "/_layouts/images/prvnews.gif" }]} /> </div> } {/* Title and news item body rendering code */} <div style={{width: `calc(100% - ${n.bannerImg == null || n.bannerImg == "" || docType == DocumentCardType.normal ? 0 : parseInt(this.props.ItemHeight) * 1.7}px)`}}> <DocumentCardTitle title={n.title} shouldTruncate={true} /> <div className={styles.docCardActivity}> <div className="docCardContents"> <Truncate lines={4} ellipsis={<span>...</span>}> <p dangerouslySetInnerHTML={{__html: this.extractContents(n.content)}}></p> </Truncate> </div> <DocumentCardActivity activity={n.lookupMetadata != null ? unescapeHTML(this.combinePostMetadata(n.lookupMetadata)) : ''} people={[{name: n.created.toString(), profileImageSrc: null}]} /> </div> </div> </DocumentCard> </div> ); }) } </Wrapper> } </div> </div> </div> </div> ); } // Join the titles of lookup field values from multiple lookup fields for a single item private combinePostMetadata(lookupInfos: ILookupInfo[]): string { let toReturn = ''; let combined = lookupInfos.map(ni => { let vals = ni.lookupValues.map(v => v.lookupValue); let res = []; for (let v of vals) { if (v != null) { res.push(v); } return res.length == 0 ? null : res.join('; '); } }); combined = combined.filter((n) => n != undefined ); toReturn = combined.join('; '); return toReturn; } // Make main container dimensions-aware private updateWindowDimensions() { this.containerElement = window.document.getElementById(styles.newsContainer); if (this.containerElement != null) { this.setState({ containerWidth: this.containerElement.offsetWidth, containerHeight: this.containerElement.offsetHeight }); } } private onItemClick(item: IMetadataNewsItem) { this.setState({dialogItem: item}); } // Paging logic - change page number and call the loadNews method when going forward private changePage(toNextPage: boolean) { if (toNextPage && this.state.currentNewsItems.length >= this.props.ItemLimit) { this.setState({currentPage: this.state.currentPage + 1}, () => { let itemsLimit = this.state.currentPage * this.props.ItemLimit; if (this.state.currentNewsItems.length < itemsLimit) { this.loadNews(); } }); } else if (this.state.currentPage > 1) { this.setState({currentPage: this.state.currentPage - 1}); } } // Compose SharePoint REST API filter string private getRestFilter() { let filter = "ContentType eq 'Site Page' and PromotedState eq 2"; filter += this.props.AdditionalFilter != null && this.props.AdditionalFilter.length > 0 ? ` and ${this.props.AdditionalFilter}` : ""; // sort the filters into { internalName, [values] } objects let sortedRefiners = []; for (let item of this.state.currentRefiners) { if (!sortedRefiners.some(val => val.internalName == item.data)) { sortedRefiners.push({ internalName: item.data, values: [item.name]}); } else { let info = sortedRefiners.filter(it => it.internalName == item.data); if (info != null && info.length > 0) { let itemInfo = info[0]; itemInfo.values.push(item.name); } } } for (let itemInfo of sortedRefiners) { for (let i = 0; i < itemInfo.values.length; i++) { let currentFilterPart = `${itemInfo.internalName}/Title eq '${encodeURIComponent(itemInfo.values[i]).replace("'",'%27%27')}'`; if (filter.length == 0) { filter = currentFilterPart; } else { filter += ` and ${currentFilterPart}`; } } } //console.log(`filter: ${filter}`); //filter = encodeURI(filter); //console.log(`filter encoded: ${filter}`); return filter; } // Build the pnp news request and return Promise object private constructNewsRequest(ris: IMetadataRefinerInfo[]) { let listName = "Site Pages"; let toSelect: string[] = ["ID", "CanvasContent1", "BannerImageUrl", "Created", "Title", "FileRef", "FileLeafRef", "Author/Name", "Editor/Name", "Author/Title", "Editor/Title"]; let toExpand: string[] = ["Author", "Editor"]; ris.forEach(ri => { toSelect.push(`${ri.InternalName}/Title`); toSelect.push(`${ri.InternalName}/Id`); toExpand.push(ri.InternalName); }); let promise: Promise<PagedItemCollection<any>> = sp.web.lists.getByTitle(listName).items.filter(this.getRestFilter()) .select(...toSelect).expand(...toExpand).orderBy("Created", false).top(this.props.ItemLimit).getPaged(); return promise; } // Main news getting request logic private processNewsRequest(promise: Promise<PagedItemCollection<any>>, ris: IMetadataRefinerInfo[], allNewsItems: IMetadataNewsItem[]) { let infosPromise: Promise<ILoadNewsResult> = new Promise<ILoadNewsResult>((resolve, reject) => { let toResolve: ILoadNewsResult = { infos: [], pagedItems: null }; promise.then((val: PagedItemCollection<any>) => { for (let item of val.results) { let newsItem = null; for (let ni of allNewsItems) { if (ni.id == item.ID) { newsItem = ni; break; } } // Build a JSON object holding relevant list item data if (newsItem == null) { newsItem = { id: item.ID, bannerImg: item.BannerImageUrl != null ? item.BannerImageUrl.Url : "", title: item.Title, url: item.FileRef, content: item.CanvasContent1.replace("data-sp-componentid", "style=\"display: none;\" data-sp-componentid"), created: item.Created.split('T')[0] } as IMetadataNewsItem; toResolve.infos.push(newsItem); } // Supplement ris.forEach(ri => { if (item[ri.InternalName] != null && ri.InternalName != this.props.HideRefinerFromItemCard) { if (newsItem.lookupMetadata == null) { newsItem.lookupMetadata = []; } let lookupMetadataItem: ILookupInfo; if (newsItem.lookupMetadata.some(lm => lm.lookupFieldInternalName == ri.InternalName)) { lookupMetadataItem = newsItem.lookupMetadata.filter(lm => lm.lookupFieldInternalName == ri.InternalName)[0]; } else { lookupMetadataItem = { lookupFieldInternalName: ri.InternalName, lookupFieldDisplayName: ri.DisplayName, lookupFieldIsMultiValue: ri.IsMultiValue, lookupFieldLookupList: null, lookupValues: [] }; newsItem.lookupMetadata.push(lookupMetadataItem); } lookupMetadataItem.lookupValues.push({ lookupId: item[ri.InternalName].Id, lookupValue: item[ri.InternalName].Title }); } }); } toResolve.pagedItems = val; resolve(toResolve); }).catch(err => { console.error(err); resolve(toResolve); }); }); return infosPromise; } // This method gets called when actual requests are needed private loadNews() { this.setState({loading: true}); let allItemInfos: IMetadataNewsItem[] = []; let pagedItemCollections: IMetadataNewsPageCollectionInfo[] = []; let loadPromises: Promise<PagedItemCollection<any>>[] = []; // This branch handles subsequent requests if (this.state.pagedCollectionInfos != null) { for (let pagePartInfo of this.state.pagedCollectionInfos) { let promise = pagePartInfo.collection.getNext(); loadPromises.push(promise); this.processNewsRequest(promise, pagePartInfo.relatedRefiners, allItemInfos).then(res => { allItemInfos.push(...res.infos); if (res.pagedItems != null) { pagedItemCollections.push({ collection: res.pagedItems, relatedRefiners: pagePartInfo.relatedRefiners }); } }); } } // Ths branch handles initial news item get request // In the event of lookup column count exceeding the throttling limit we need to make several requests to get all of lookup values else { const noOfLookupsBeforeThrottle = 6; let noOfRequests = Math.floor(this.props.RefinerInfos.length / noOfLookupsBeforeThrottle) + 1; for (let i = 0; i < noOfRequests; i++) { let numerOfRefinersToGet = noOfLookupsBeforeThrottle; if (numerOfRefinersToGet + i * noOfLookupsBeforeThrottle > this.props.RefinerInfos.length) { numerOfRefinersToGet = this.props.RefinerInfos.length % noOfLookupsBeforeThrottle; } let getFrom = 0; let getTo = (i + 1) * numerOfRefinersToGet; if (i > 0) { getFrom = i * noOfLookupsBeforeThrottle - 1; } let currentRefiners = this.props.RefinerInfos.slice(getFrom, getTo); let promise = this.constructNewsRequest(currentRefiners); loadPromises.push(promise); this.processNewsRequest(promise, currentRefiners, allItemInfos).then(res => { allItemInfos.push(...res.infos); if (res.pagedItems != null) { pagedItemCollections.push({ collection: res.pagedItems, relatedRefiners: currentRefiners }); } }); } } // When all requests are complete - set the state, making sure currentNewsItems are extended by newly received data Promise.all(loadPromises).then(() => { this.setState({ currentNewsItems: [...this.state.currentNewsItems, ...allItemInfos], loading: false, pagedCollectionInfos: pagedItemCollections.length > 0 ? pagedItemCollections : null }); }); } // React to refiner change in the MetadataNewsRefiners component private handleRefinerChange(incomingRefiners: IContextualMenuItem[]) { this.setState({ currentRefiners: incomingRefiners, currentPage: 1, pagedCollectionInfos: null, currentNewsItems: [] }, () => { this.loadNews(); }); } // Helper method that trims any unwanted information from body of the news item private extractContents(s: string | Element) { let el: Element = null; if (s instanceof Element) { el = s; } else { el = document.createElement('span'); el.innerHTML = s; } let res = null; if (el.hasAttribute('data-sp-rte')) { res = el.textContent || el.innerHTML; } else { for (let i = 0; i < el.children.length; i++) { let child = el.children.item(i); res = this.extractContents(child); if (res != null) { break; } } } return res; } }
the_stack
import { instantiateRipemd160, instantiateSecp256k1, instantiateSha1, instantiateSha256, instantiateSha512, Sha256, } from '../../crypto/crypto'; import { TransactionContextCommon } from '../../transaction/transaction-types'; import { generateSigningSerializationBCH, SigningSerializationFlag, } from '../../vm/instruction-sets/common/signing-serialization'; import { AuthenticationProgramStateBCH, createInstructionSetBCH, generateBytecodeMap, getFlagsForInstructionSetBCH, instructionSetBCHCurrentStrict, OpcodesBCH, } from '../../vm/instruction-sets/instruction-sets'; import { createAuthenticationVirtualMachine } from '../../vm/virtual-machine'; import { authenticationTemplateToCompilationEnvironment, createAuthenticationProgramEvaluationCommon, createCompiler, } from '../compiler'; import { attemptCompilerOperations, compilerOperationAttemptBytecodeResolution, compilerOperationHelperCompileScript, compilerOperationHelperDeriveHdKeyPrivate, compilerOperationHelperGenerateCoveredBytecode, compilerOperationRequires, } from '../compiler-operation-helpers'; import { compilerOperationsCommon } from '../compiler-operations'; import { AnyCompilationEnvironment, CompilationData, CompilationEnvironment, CompilerOperationResult, } from '../compiler-types'; import { AuthenticationTemplate } from '../template-types'; export type CompilerOperationsKeyBCH = | 'data_signature' | 'public_key' | 'schnorr_data_signature' | 'schnorr_signature' | 'signature'; export enum SigningSerializationAlgorithmIdentifier { /** * A.K.A. `SIGHASH_ALL` */ allOutputs = 'all_outputs', /** * A.K.A. `SIGHASH_ALL|ANYONE_CAN_PAY` */ allOutputsSingleInput = 'all_outputs_single_input', /** * A.K.A. `SIGHASH_SINGLE` */ correspondingOutput = 'corresponding_output', /** * A.K.A. `SIGHASH_SINGLE|ANYONE_CAN_PAY` */ correspondingOutputSingleInput = 'corresponding_output_single_input', /** * A.K.A `SIGHASH_NONE` */ noOutputs = 'no_outputs', /** * A.K.A `SIGHASH_NONE|ANYONE_CAN_PAY` */ noOutputsSingleInput = 'no_outputs_single_input', } // eslint-disable-next-line complexity const getSigningSerializationType = ( algorithmIdentifier: string, prefix = '' ) => { switch (algorithmIdentifier) { case `${prefix}${SigningSerializationAlgorithmIdentifier.allOutputs}`: return Uint8Array.of( // eslint-disable-next-line no-bitwise SigningSerializationFlag.allOutputs | SigningSerializationFlag.forkId ); case `${prefix}${SigningSerializationAlgorithmIdentifier.allOutputsSingleInput}`: return Uint8Array.of( // eslint-disable-next-line no-bitwise SigningSerializationFlag.allOutputs | SigningSerializationFlag.singleInput | SigningSerializationFlag.forkId ); case `${prefix}${SigningSerializationAlgorithmIdentifier.correspondingOutput}`: return Uint8Array.of( // eslint-disable-next-line no-bitwise SigningSerializationFlag.correspondingOutput | SigningSerializationFlag.forkId ); case `${prefix}${SigningSerializationAlgorithmIdentifier.correspondingOutputSingleInput}`: return Uint8Array.of( // eslint-disable-next-line no-bitwise SigningSerializationFlag.correspondingOutput | SigningSerializationFlag.singleInput | SigningSerializationFlag.forkId ); case `${prefix}${SigningSerializationAlgorithmIdentifier.noOutputs}`: return Uint8Array.of( // eslint-disable-next-line no-bitwise SigningSerializationFlag.noOutputs | SigningSerializationFlag.forkId ); case `${prefix}${SigningSerializationAlgorithmIdentifier.noOutputsSingleInput}`: return Uint8Array.of( // eslint-disable-next-line no-bitwise SigningSerializationFlag.noOutputs | SigningSerializationFlag.singleInput | SigningSerializationFlag.forkId ); default: return undefined; } }; export const compilerOperationHelperComputeSignatureBCH = ({ coveredBytecode, identifier, transactionContext, operationName, privateKey, sha256, sign, }: { coveredBytecode: Uint8Array; identifier: string; privateKey: Uint8Array; transactionContext: TransactionContextCommon; operationName: string; sign: (privateKey: Uint8Array, messageHash: Uint8Array) => Uint8Array; sha256: { hash: Sha256['hash'] }; }): CompilerOperationResult => { const [, , algorithm, unknown] = identifier.split('.') as ( | string | undefined )[]; if (unknown !== undefined) { return { error: `Unknown component in "${identifier}" – the fragment "${unknown}" is not recognized.`, status: 'error', }; } if (algorithm === undefined) { return { error: `Invalid signature identifier. Signatures must be of the form: "[variable_id].${operationName}.[signing_serialization_type]".`, status: 'error', }; } const signingSerializationType = getSigningSerializationType(algorithm); if (signingSerializationType === undefined) { return { error: `Unknown signing serialization algorithm, "${algorithm}".`, status: 'error', }; } const serialization = generateSigningSerializationBCH({ correspondingOutput: transactionContext.correspondingOutput, coveredBytecode, locktime: transactionContext.locktime, outpointIndex: transactionContext.outpointIndex, outpointTransactionHash: transactionContext.outpointTransactionHash, outputValue: transactionContext.outputValue, sequenceNumber: transactionContext.sequenceNumber, sha256, signingSerializationType, transactionOutpoints: transactionContext.transactionOutpoints, transactionOutputs: transactionContext.transactionOutputs, transactionSequenceNumbers: transactionContext.transactionSequenceNumbers, version: transactionContext.version, }); const digest = sha256.hash(sha256.hash(serialization)); const bitcoinEncodedSignature = Uint8Array.from([ ...sign(privateKey, digest), ...signingSerializationType, ]); return { bytecode: bitcoinEncodedSignature, signature: { serialization }, status: 'success', }; }; export const compilerOperationHelperHdKeySignatureBCH = ({ operationName, secp256k1Method, }: { operationName: string; secp256k1Method: keyof NonNullable<CompilationEnvironment['secp256k1']>; }) => attemptCompilerOperations( [compilerOperationAttemptBytecodeResolution], compilerOperationRequires({ canBeSkipped: false, dataProperties: ['hdKeys', 'transactionContext'], environmentProperties: [ 'entityOwnership', 'ripemd160', 'secp256k1', 'sha256', 'sha512', 'variables', 'sourceScriptIds', 'unlockingScripts', ], operation: (identifier, data, environment): CompilerOperationResult => { const { hdKeys, transactionContext } = data; const { secp256k1, sha256, sourceScriptIds, unlockingScripts, } = environment; const derivationResult = compilerOperationHelperDeriveHdKeyPrivate({ environment, hdKeys, identifier, }); if (derivationResult.status === 'error') return derivationResult; const result = compilerOperationHelperGenerateCoveredBytecode({ data, environment, identifier, sourceScriptIds, unlockingScripts, }); if ('error' in result) { return result; } return compilerOperationHelperComputeSignatureBCH({ coveredBytecode: result, identifier, operationName, privateKey: derivationResult.bytecode, sha256, sign: secp256k1[secp256k1Method], transactionContext, }); }, }) ); export const compilerOperationHdKeyEcdsaSignatureBCH = compilerOperationHelperHdKeySignatureBCH( { operationName: 'signature', secp256k1Method: 'signMessageHashDER', } ); export const compilerOperationHdKeySchnorrSignatureBCH = compilerOperationHelperHdKeySignatureBCH( { operationName: 'schnorr_signature', secp256k1Method: 'signMessageHashSchnorr', } ); export const compilerOperationHelperKeySignatureBCH = ({ operationName, secp256k1Method, }: { operationName: string; secp256k1Method: keyof NonNullable<CompilationEnvironment['secp256k1']>; }) => attemptCompilerOperations( [compilerOperationAttemptBytecodeResolution], compilerOperationRequires({ canBeSkipped: false, dataProperties: ['keys', 'transactionContext'], environmentProperties: [ 'sha256', 'secp256k1', 'unlockingScripts', 'sourceScriptIds', ], operation: (identifier, data, environment): CompilerOperationResult => { const { keys, transactionContext } = data; const { secp256k1, sha256, unlockingScripts, sourceScriptIds, } = environment; const { privateKeys } = keys; const [variableId] = identifier.split('.'); const privateKey = privateKeys === undefined ? undefined : privateKeys[variableId]; if (privateKey === undefined) { return { error: `Identifier "${identifier}" refers to a Key, but a private key for "${variableId}" (or an existing signature) was not provided in the compilation data.`, recoverable: true, status: 'error', }; } const result = compilerOperationHelperGenerateCoveredBytecode({ data, environment, identifier, sourceScriptIds, unlockingScripts, }); if ('error' in result) { return result; } return compilerOperationHelperComputeSignatureBCH({ coveredBytecode: result, identifier, operationName, privateKey, sha256, sign: secp256k1[secp256k1Method], transactionContext, }); }, }) ); export const compilerOperationKeyEcdsaSignatureBCH = compilerOperationHelperKeySignatureBCH( { operationName: 'signature', secp256k1Method: 'signMessageHashDER', } ); export const compilerOperationKeySchnorrSignatureBCH = compilerOperationHelperKeySignatureBCH( { operationName: 'schnorr_signature', secp256k1Method: 'signMessageHashSchnorr', } ); export const compilerOperationHelperComputeDataSignatureBCH = < Data extends CompilationData, Environment extends AnyCompilationEnvironment<TransactionContextCommon> >({ data, environment, identifier, operationName, privateKey, sha256, sign, }: { data: Data; environment: Environment; identifier: string; privateKey: Uint8Array; operationName: string; sign: (privateKey: Uint8Array, messageHash: Uint8Array) => Uint8Array; sha256: { hash: Sha256['hash'] }; }): CompilerOperationResult => { const [, , scriptId, unknown] = identifier.split('.') as [ string, string | undefined, string | undefined, string | undefined ]; if (unknown !== undefined) { return { error: `Unknown component in "${identifier}" – the fragment "${unknown}" is not recognized.`, status: 'error', }; } if (scriptId === undefined) { return { error: `Invalid data signature identifier. Data signatures must be of the form: "[variable_id].${operationName}.[target_script_id]".`, status: 'error', }; } const result = compilerOperationHelperCompileScript({ data, environment, targetScriptId: scriptId, }); if (result === false) { return { error: `Data signature tried to sign an unknown target script, "${scriptId}".`, status: 'error', }; } if ('error' in result) { return result; } const digest = sha256.hash(result); return { bytecode: sign(privateKey, digest), signature: { message: result }, status: 'success', }; }; export const compilerOperationHelperKeyDataSignatureBCH = ({ operationName, secp256k1Method, }: { operationName: string; secp256k1Method: keyof NonNullable<CompilationEnvironment['secp256k1']>; }) => attemptCompilerOperations( [compilerOperationAttemptBytecodeResolution], compilerOperationRequires({ canBeSkipped: false, dataProperties: ['keys'], environmentProperties: ['sha256', 'secp256k1'], operation: (identifier, data, environment): CompilerOperationResult => { const { keys } = data; const { secp256k1, sha256 } = environment; const { privateKeys } = keys; const [variableId] = identifier.split('.'); const privateKey = privateKeys === undefined ? undefined : privateKeys[variableId]; if (privateKey === undefined) { return { error: `Identifier "${identifier}" refers to a Key, but a private key for "${variableId}" (or an existing signature) was not provided in the compilation data.`, recoverable: true, status: 'error', }; } return compilerOperationHelperComputeDataSignatureBCH< typeof data, typeof environment >({ data, environment, identifier, operationName, privateKey, sha256, sign: secp256k1[secp256k1Method], }); }, }) ); export const compilerOperationKeyEcdsaDataSignatureBCH = compilerOperationHelperKeyDataSignatureBCH( { operationName: 'data_signature', secp256k1Method: 'signMessageHashDER', } ); export const compilerOperationKeySchnorrDataSignatureBCH = compilerOperationHelperKeyDataSignatureBCH( { operationName: 'schnorr_data_signature', secp256k1Method: 'signMessageHashSchnorr', } ); export const compilerOperationHelperHdKeyDataSignatureBCH = ({ operationName, secp256k1Method, }: { operationName: string; secp256k1Method: keyof NonNullable<CompilationEnvironment['secp256k1']>; }) => attemptCompilerOperations( [compilerOperationAttemptBytecodeResolution], compilerOperationRequires({ canBeSkipped: false, dataProperties: ['hdKeys'], environmentProperties: [ 'entityOwnership', 'ripemd160', 'secp256k1', 'sha256', 'sha512', 'variables', ], operation: (identifier, data, environment) => { const { hdKeys } = data; const { secp256k1, sha256 } = environment; const derivationResult = compilerOperationHelperDeriveHdKeyPrivate({ environment, hdKeys, identifier, }); if (derivationResult.status === 'error') return derivationResult; return compilerOperationHelperComputeDataSignatureBCH< typeof data, typeof environment >({ data, environment, identifier, operationName, privateKey: derivationResult.bytecode, sha256, sign: secp256k1[secp256k1Method], }); }, }) ); export const compilerOperationHdKeyEcdsaDataSignatureBCH = compilerOperationHelperHdKeyDataSignatureBCH( { operationName: 'data_signature', secp256k1Method: 'signMessageHashDER', } ); export const compilerOperationHdKeySchnorrDataSignatureBCH = compilerOperationHelperHdKeyDataSignatureBCH( { operationName: 'schnorr_data_signature', secp256k1Method: 'signMessageHashSchnorr', } ); export const compilerOperationSigningSerializationFullBCH = compilerOperationRequires( { canBeSkipped: false, dataProperties: ['transactionContext'], environmentProperties: ['sha256', 'sourceScriptIds', 'unlockingScripts'], operation: (identifier, data, environment): CompilerOperationResult => { const [, algorithmOrComponent, unknownPart] = identifier.split('.') as ( | string | undefined )[]; if (algorithmOrComponent === undefined) { return { error: `Invalid signing serialization operation. Include the desired component or algorithm, e.g. "signing_serialization.version".`, status: 'error', }; } if (unknownPart !== undefined) { return { error: `Unknown component in "${identifier}" – the fragment "${unknownPart}" is not recognized.`, status: 'error', }; } const signingSerializationType = getSigningSerializationType( algorithmOrComponent, 'full_' ); if (signingSerializationType === undefined) { return { error: `Unknown signing serialization algorithm, "${algorithmOrComponent}".`, status: 'error', }; } const { sha256, sourceScriptIds, unlockingScripts } = environment; const result = compilerOperationHelperGenerateCoveredBytecode({ data, environment, identifier, sourceScriptIds, unlockingScripts, }); if ('error' in result) { return result; } const { transactionContext } = data; return { bytecode: generateSigningSerializationBCH({ correspondingOutput: transactionContext.correspondingOutput, coveredBytecode: result, locktime: transactionContext.locktime, outpointIndex: transactionContext.outpointIndex, outpointTransactionHash: transactionContext.outpointTransactionHash, outputValue: transactionContext.outputValue, sequenceNumber: transactionContext.sequenceNumber, sha256, signingSerializationType, transactionOutpoints: transactionContext.transactionOutpoints, transactionOutputs: transactionContext.transactionOutputs, transactionSequenceNumbers: transactionContext.transactionSequenceNumbers, version: transactionContext.version, }), status: 'success', }; }, } ); /* eslint-disable camelcase, @typescript-eslint/naming-convention */ export const compilerOperationsBCH = { ...compilerOperationsCommon, hdKey: { data_signature: compilerOperationHdKeyEcdsaDataSignatureBCH, public_key: compilerOperationsCommon.hdKey.public_key, schnorr_data_signature: compilerOperationHdKeySchnorrDataSignatureBCH, schnorr_signature: compilerOperationHdKeySchnorrSignatureBCH, signature: compilerOperationHdKeyEcdsaSignatureBCH, }, key: { data_signature: compilerOperationKeyEcdsaDataSignatureBCH, public_key: compilerOperationsCommon.key.public_key, schnorr_data_signature: compilerOperationKeySchnorrDataSignatureBCH, schnorr_signature: compilerOperationKeySchnorrSignatureBCH, signature: compilerOperationKeyEcdsaSignatureBCH, }, signingSerialization: { ...compilerOperationsCommon.signingSerialization, full_all_outputs: compilerOperationSigningSerializationFullBCH, full_all_outputs_single_input: compilerOperationSigningSerializationFullBCH, full_corresponding_output: compilerOperationSigningSerializationFullBCH, full_corresponding_output_single_input: compilerOperationSigningSerializationFullBCH, full_no_outputs: compilerOperationSigningSerializationFullBCH, full_no_outputs_single_input: compilerOperationSigningSerializationFullBCH, }, }; /* eslint-enable camelcase, @typescript-eslint/naming-convention */ export type TransactionContextBCH = TransactionContextCommon; export type CompilationEnvironmentBCH = CompilationEnvironment< TransactionContextBCH, CompilerOperationsKeyBCH >; /** * Create a compiler using the default BCH environment. * * Internally instantiates the necessary crypto and VM implementations – use * `createCompiler` for more control. * * @param scriptsAndOverrides - a compilation environment from which properties * will be used to override properties of the default BCH environment – must * include the `scripts` property */ export const createCompilerBCH = async < TransactionContext extends TransactionContextCommon, Environment extends AnyCompilationEnvironment<TransactionContext>, ProgramState extends AuthenticationProgramStateBCH >( scriptsAndOverrides: Environment ) => { const [sha1, sha256, sha512, ripemd160, secp256k1] = await Promise.all([ instantiateSha1(), instantiateSha256(), instantiateSha512(), instantiateRipemd160(), instantiateSecp256k1(), ]); const vm = createAuthenticationVirtualMachine( createInstructionSetBCH({ flags: getFlagsForInstructionSetBCH(instructionSetBCHCurrentStrict), ripemd160, secp256k1, sha1, sha256, }) ); return createCompiler< TransactionContext, Environment, OpcodesBCH, ProgramState >({ ...{ createAuthenticationProgram: createAuthenticationProgramEvaluationCommon, opcodes: generateBytecodeMap(OpcodesBCH), operations: compilerOperationsBCH, ripemd160, secp256k1, sha256, sha512, vm, }, ...scriptsAndOverrides, }); }; /** * Create a BCH `Compiler` from an `AuthenticationTemplate` and an optional set * of overrides. * @param template - the `AuthenticationTemplate` from which to create the BCH * compiler * @param overrides - a compilation environment from which properties will be * used to override properties of the default BCH environment */ export const authenticationTemplateToCompilerBCH = async < TransactionContext extends TransactionContextCommon, Environment extends AnyCompilationEnvironment<TransactionContext>, ProgramState extends AuthenticationProgramStateBCH >( template: AuthenticationTemplate, overrides?: CompilationEnvironment<TransactionContext> ) => createCompilerBCH<TransactionContext, Environment, ProgramState>({ ...overrides, ...authenticationTemplateToCompilationEnvironment(template), } as Environment);
the_stack
import { Equatable } from "@siteimprove/alfa-equatable"; import { Lazy } from "@siteimprove/alfa-lazy"; import { None, Option } from "@siteimprove/alfa-option"; import { Predicate } from "@siteimprove/alfa-predicate"; import { Refinement } from "@siteimprove/alfa-refinement"; import { Sequence } from "@siteimprove/alfa-sequence"; import { Trampoline } from "@siteimprove/alfa-trampoline"; import * as earl from "@siteimprove/alfa-earl"; import * as json from "@siteimprove/alfa-json"; import * as sarif from "@siteimprove/alfa-sarif"; import { Attribute, Comment, Document, Element, Fragment, Text, Type, Slot, } from "."; const { equals } = Predicate; /** * @public */ export abstract class Node implements Iterable<Node>, Equatable, json.Serializable<Node.JSON>, earl.Serializable<Node.EARL>, sarif.Serializable<sarif.Location> { protected readonly _children: Array<Node>; protected _parent: Option<Node> = None; /** * Whether or not the node is frozen. * * @remarks * As nodes are initialized without a parent and possibly attached to a parent * after construction, this makes hierarchies of nodes mutable. That is, a * node without a parent node may be assigned one by being passed as a child * to a parent node. When this happens, a node becomes frozen. Nodes can also * become frozen before being assigned a parent by using the `Node#freeze()` * method. */ protected _frozen: boolean = false; protected constructor(children: Array<Node>) { this._children = children.filter((child) => child._attachParent(this)); } public get frozen(): boolean { return this._frozen; } /** * Freeze the node. This prevents further expansion of the node hierarchy, * meaning that the node can no longer be passed as a child to a parent node. */ public freeze(): this { this._frozen = this._frozen || true; return this; } /** * {@link https://dom.spec.whatwg.org/#concept-tree-parent} */ public parent(options: Node.Traversal = {}): Option<Node> { return this._parent; } /** * {@link https://dom.spec.whatwg.org/#concept-tree-parent} */ public isParentOf(node: Node, options: Node.Traversal = {}): boolean { return node.parent(options).includes(this); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-root} */ public root(options: Node.Traversal = {}): Node { for (const parent of this.parent(options)) { return parent.root(options); } return this; } /** * {@link https://dom.spec.whatwg.org/#concept-tree-root} */ public isRootOf(node: Node, options: Node.Traversal = {}): boolean { return node.root(options) === this; } /** * {@link https://dom.spec.whatwg.org/#concept-tree-child} */ public children(options: Node.Traversal = {}): Sequence<Node> { return Sequence.from(this._children); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-child} */ public isChildOf(node: Node, options: Node.Traversal = {}): boolean { return node.children(options).includes(this); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-descendant} */ public descendants(options: Node.Traversal = {}): Sequence<Node> { return this.children(options).flatMap((child) => Sequence.of( child, Lazy.of(() => child.descendants(options)) ) ); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-descendant} */ public isDescendantOf(node: Node, options: Node.Traversal = {}): boolean { return node.descendants(options).includes(this); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-inclusive-descendant} */ public inclusiveDescendants(options: Node.Traversal = {}): Sequence<Node> { return Sequence.of( this, Lazy.of(() => this.descendants(options)) ); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-inclusive-descendant} */ public isInclusiveDescendantsOf( node: Node, options: Node.Traversal = {} ): boolean { return node.inclusiveDescendants(options).includes(this); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-ancestor} */ public ancestors(options: Node.Traversal = {}): Sequence<Node> { for (const parent of this.parent(options)) { return Sequence.of( parent, Lazy.of(() => parent.ancestors(options)) ); } return Sequence.empty(); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-ancestor} */ public isAncestorOf(node: Node, options: Node.Traversal = {}): boolean { return node.ancestors(options).includes(this); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor} */ public inclusiveAncestors(options: Node.Traversal = {}): Sequence<Node> { return Sequence.of( this, Lazy.of(() => this.ancestors(options)) ); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor} */ public isInclusiveAncestorOf( node: Node, options: Node.Traversal = {} ): boolean { return node.inclusiveAncestors(options).includes(this); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-sibling} */ public siblings(options: Node.Traversal = {}): Sequence<Node> { return this.inclusiveSiblings(options).reject(equals(this)); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-sibling} */ public isSiblingOf(node: Node, options: Node.Traversal = {}): boolean { return node.siblings(options).includes(this); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-inclusive-sibling} */ public inclusiveSiblings(options: Node.Traversal = {}): Sequence<Node> { for (const parent of this.parent(options)) { return parent.children(options); } return Sequence.empty(); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-inclusive-sibling} */ public isInclusiveSiblingOf( node: Node, options: Node.Traversal = {} ): boolean { return node.inclusiveSiblings(options).includes(this); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-preceding} */ public preceding(options: Node.Traversal = {}): Sequence<Node> { return this.inclusiveSiblings(options).takeUntil(equals(this)).reverse(); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-following} */ public following(options: Node.Traversal = {}): Sequence<Node> { return this.inclusiveSiblings(options).skipUntil(equals(this)).rest(); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-first-child} */ public first(options: Node.Traversal = {}): Option<Node> { return this.children(options).first(); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-last-child} */ public last(options: Node.Traversal = {}): Option<Node> { return this.children(options).last(); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-previous-sibling} */ public previous(options: Node.Traversal = {}): Option<Node> { return this.preceding(options).first(); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-next-sibling} */ public next(options: Node.Traversal = {}): Option<Node> { return this.following(options).first(); } /** * {@link https://dom.spec.whatwg.org/#concept-tree-index} */ public index(options: Node.Traversal = {}): number { return this.preceding(options).size; } /** * {@link https://dom.spec.whatwg.org/#dom-element-closest} */ public closest<T extends Node>( refinement: Refinement<Node, T>, options?: Node.Traversal ): Option<T>; /** * {@link https://dom.spec.whatwg.org/#dom-element-closest} */ public closest( predicate: Predicate<Node>, options?: Node.Traversal ): Option<Node>; /** * {@link https://dom.spec.whatwg.org/#dom-element-closest} */ public closest( predicate: Predicate<Node>, options: Node.Traversal = {} ): Option<Node> { return this.inclusiveAncestors(options).find(predicate); } /** * {@link https://dom.spec.whatwg.org/#concept-descendant-text-content} */ public textContent(options: Node.Traversal = {}): string { return this.descendants(options).filter(Text.isText).join(""); } /** * Construct a sequence of descendants of this node sorted by tab index. Only * nodes with a non-negative tab index are included in the sequence. * * {@link https://html.spec.whatwg.org/#tabindex-value} */ public tabOrder(): Sequence<Element> { const candidates = (node: Node): Sequence<Element> => { if (Element.isElement(node)) { const element = node; const tabIndex = element.tabIndex(); if (element.shadow.isSome()) { // If the element has a negative tab index and is a shadow host then // none of its descendants will be part of the tab order. if (tabIndex.some((i) => i < 0)) { return Sequence.empty(); } else { return Sequence.of(element); } } if (element.content.isSome()) { return Sequence.of(element); } if (Slot.isSlot(element)) { return Sequence.from(element.assignedNodes()).filter( Element.isElement ); } if (tabIndex.some((i) => i >= 0)) { return Sequence.of( element, Lazy.of(() => element.children().flatMap(candidates)) ); } } return node.children().flatMap(candidates); }; return candidates(this) .sortWith((a, b) => a.tabIndex().compareWith(b.tabIndex(), (a, b) => { if (a === 0) { return b === 0 ? 0 : 1; } if (b === 0) { return -1; } return a < b ? -1 : a > b ? 1 : 0; }) ) .flatMap((element) => { const tabIndex = element.tabIndex(); for (const shadow of element.shadow) { if (tabIndex.some((i) => i >= 0)) { return Sequence.of( element, Lazy.of(() => shadow.tabOrder()) ); } else { return shadow.tabOrder(); } } for (const content of element.content) { return content.tabOrder(); } return Sequence.of(element); }); } /** * Get an XPath that uniquely identifies the node across descendants of its * root. */ public path(options?: Node.Traversal): string { let path = this.parent(options) .map((parent) => parent.path(options)) .getOr("/"); path += path === "/" ? "" : "/"; path += "node()"; path += `[${this.index(options) + 1}]`; return path; } public *[Symbol.iterator](): Iterator<Node> { yield* this.descendants(); } public equals(value: Node): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return value === this; } public abstract toJSON(): Node.JSON; public toEARL(): Node.EARL { return { "@context": { ptr: "http://www.w3.org/2009/pointers#", }, "@type": [ "ptr:Pointer", "ptr:SinglePointer", "ptr:ExpressionPointer", "ptr:XPathPointer", ], "ptr:expression": this.path(), }; } public toSARIF(): sarif.Location { return { logicalLocations: [ { fullyQualifiedName: this.path(), }, ], }; } /** * @internal */ public _attachParent(parent: Node): boolean { if (this._frozen || this._parent.isSome()) { return false; } this._parent = Option.of(parent); this._frozen = true; return true; } } /** * @public */ export namespace Node { export interface JSON { [key: string]: json.JSON; type: string; } export interface EARL extends earl.EARL { "@context": { ptr: "http://www.w3.org/2009/pointers#"; }; "@type": [ "ptr:Pointer", "ptr:SinglePointer", "ptr:ExpressionPointer", "ptr:XPathPointer" ]; "ptr:expression": string; "ptr:reference"?: { "@id": string; }; } export function isNode(value: unknown): value is Node { return value instanceof Node; } export interface Traversal { /** * When `true`, traverse the node in shadow-including tree order. * * {@link https://dom.spec.whatwg.org/#concept-shadow-including-tree-order} */ readonly composed?: boolean; /** * When `true`, traverse the flattened element tree rooted at the node. * * {@link https://drafts.csswg.org/css-scoping/#flat-tree} */ readonly flattened?: boolean; /** * When `true`, traverse all nested browsing contexts encountered. * * {@link https://html.spec.whatwg.org/#nested-browsing-context} */ readonly nested?: boolean; } export function from(json: Element.JSON): Element; export function from(json: Attribute.JSON): Attribute; export function from(json: Text.JSON): Text; export function from(json: Comment.JSON): Comment; export function from(json: Document.JSON): Document; export function from(json: Type.JSON): Document; export function from(json: Fragment.JSON): Fragment; export function from(json: JSON): Node; export function from(json: JSON): Node { return fromNode(json).run(); } /** * @internal */ export function fromNode(json: JSON): Trampoline<Node> { switch (json.type) { case "element": return Element.fromElement(json as Element.JSON); case "attribute": return Attribute.fromAttribute(json as Attribute.JSON); case "text": return Text.fromText(json as Text.JSON); case "comment": return Comment.fromComment(json as Comment.JSON); case "document": return Document.fromDocument(json as Document.JSON); case "type": return Type.fromType(json as Type.JSON); case "fragment": return Fragment.fromFragment(json as Fragment.JSON); default: throw new Error(`Unexpected node of type: ${json.type}`); } } }
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * @interface * An interface representing StorageContainerProperties. * The properties of the Azure Storage Container for file archive. * */ export interface StorageContainerProperties { /** * @member {string} [connectionString] The connection string of the storage * account. */ connectionString?: string; /** * @member {string} [subscriptionId] The subscription identifier of the * storage account. */ subscriptionId?: string; /** * @member {string} [resourceGroup] The name of the resource group of the * storage account. */ resourceGroup?: string; /** * @member {string} [containerName] The name of storage container in the * storage account. */ containerName?: string; } /** * @interface * An interface representing IoTSpacesProperties. * The properties of an IoTSpaces instance. * */ export interface IoTSpacesProperties { /** * @member {ProvisioningState} [provisioningState] The provisioning state. * Possible values include: 'Provisioning', 'Deleting', 'Succeeded', * 'Failed', 'Canceled' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: ProvisioningState; /** * @member {string} [managementApiUrl] The management Api endpoint. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly managementApiUrl?: string; /** * @member {string} [webPortalUrl] The management UI endpoint. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly webPortalUrl?: string; /** * @member {StorageContainerProperties} [storageContainer] The properties of * the designated storage container. */ storageContainer?: StorageContainerProperties; } /** * @interface * An interface representing IoTSpacesSkuInfo. * Information about the SKU of the IoTSpaces instance. * */ export interface IoTSpacesSkuInfo { /** * @member {IoTSpacesSku} name The name of the SKU. Possible values include: * 'F1', 'S1', 'S2', 'S3' */ name: IoTSpacesSku; } /** * @interface * An interface representing Resource. * The common properties of an IoTSpaces service. * * @extends BaseResource */ export interface Resource extends BaseResource { /** * @member {string} [id] The resource identifier. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly id?: string; /** * @member {string} [name] The resource name. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly name?: string; /** * @member {string} [type] The resource type. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly type?: string; /** * @member {string} location The resource location. */ location: string; /** * @member {{ [propertyName: string]: string }} [tags] The resource tags. */ tags?: { [propertyName: string]: string }; } /** * @interface * An interface representing IoTSpacesDescription. * The description of the IoTSpaces service. * * @extends Resource */ export interface IoTSpacesDescription extends Resource { /** * @member {IoTSpacesProperties} [properties] The common properties of a * IoTSpaces service. */ properties?: IoTSpacesProperties; /** * @member {IoTSpacesSkuInfo} sku A valid instance SKU. */ sku: IoTSpacesSkuInfo; } /** * @interface * An interface representing IoTSpacesPatchDescription. * The description of the IoTSpaces service. * */ export interface IoTSpacesPatchDescription { /** * @member {{ [propertyName: string]: string }} [tags] Instance tags */ tags?: { [propertyName: string]: string }; /** * @member {IoTSpacesProperties} [properties] The common properties of an * IoTSpaces service. */ properties?: IoTSpacesProperties; } /** * @interface * An interface representing ErrorDetails. * Error details. * */ export interface ErrorDetails { /** * @member {string} [code] The error code. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly code?: string; /** * @member {string} [message] The error message. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly message?: string; /** * @member {string} [target] The target of the particular error. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly target?: string; } /** * @interface * An interface representing OperationDisplay. * The object that represents the operation. * */ export interface OperationDisplay { /** * @member {string} [provider] Service provider: Microsoft IoTSpaces * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provider?: string; /** * @member {string} [resource] Resource Type: IoTSpaces * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly resource?: string; /** * @member {string} [operation] Name of the operation * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly operation?: string; /** * @member {string} [description] Friendly description for the operation, * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly description?: string; } /** * @interface * An interface representing Operation. * IoTSpaces service REST API operation * */ export interface Operation { /** * @member {string} [name] Operation name: {provider}/{resource}/{read | * write | action | delete} * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly name?: string; /** * @member {OperationDisplay} [display] */ display?: OperationDisplay; } /** * @interface * An interface representing OperationInputs. * Input values. * */ export interface OperationInputs { /** * @member {string} name The name of the IoTSpaces service instance to check. */ name: string; } /** * @interface * An interface representing IoTSpacesNameAvailabilityInfo. * The properties indicating whether a given IoTSpaces service name is * available. * */ export interface IoTSpacesNameAvailabilityInfo { /** * @member {boolean} [nameAvailable] The value which indicates whether the * provided name is available. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly nameAvailable?: boolean; /** * @member {IoTSpacesNameUnavailabilityReason} [reason] The reason for * unavailability. Possible values include: 'Invalid', 'AlreadyExists' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly reason?: IoTSpacesNameUnavailabilityReason; /** * @member {string} [message] The detailed reason message. */ message?: string; } /** * @interface * An interface representing IoTSpacesClientOptions. * @extends AzureServiceClientOptions */ export interface IoTSpacesClientOptions extends AzureServiceClientOptions { /** * @member {string} [baseUri] */ baseUri?: string; } /** * @interface * An interface representing the IoTSpacesDescriptionListResult. * A list of IoTSpaces description objects with a next link. * * @extends Array<IoTSpacesDescription> */ export interface IoTSpacesDescriptionListResult extends Array<IoTSpacesDescription> { /** * @member {string} [nextLink] The link used to get the next page of * IoTSpaces description objects. */ nextLink?: string; } /** * @interface * An interface representing the OperationListResult. * A list of IoTSpaces service operations. It contains a list of operations and * a URL link to get the next set of results. * * @extends Array<Operation> */ export interface OperationListResult extends Array<Operation> { /** * @member {string} [nextLink] The link used to get the next page of * IoTSpaces description objects. */ nextLink?: string; } /** * Defines values for ProvisioningState. * Possible values include: 'Provisioning', 'Deleting', 'Succeeded', 'Failed', 'Canceled' * @readonly * @enum {string} */ export type ProvisioningState = 'Provisioning' | 'Deleting' | 'Succeeded' | 'Failed' | 'Canceled'; /** * Defines values for IoTSpacesSku. * Possible values include: 'F1', 'S1', 'S2', 'S3' * @readonly * @enum {string} */ export type IoTSpacesSku = 'F1' | 'S1' | 'S2' | 'S3'; /** * Defines values for IoTSpacesNameUnavailabilityReason. * Possible values include: 'Invalid', 'AlreadyExists' * @readonly * @enum {string} */ export type IoTSpacesNameUnavailabilityReason = 'Invalid' | 'AlreadyExists'; /** * Contains response data for the get operation. */ export type IoTSpacesGetResponse = IoTSpacesDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IoTSpacesDescription; }; }; /** * Contains response data for the createOrUpdate operation. */ export type IoTSpacesCreateOrUpdateResponse = IoTSpacesDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IoTSpacesDescription; }; }; /** * Contains response data for the update operation. */ export type IoTSpacesUpdateResponse = IoTSpacesDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IoTSpacesDescription; }; }; /** * Contains response data for the deleteMethod operation. */ export type IoTSpacesDeleteMethodResponse = IoTSpacesDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IoTSpacesDescription; }; }; /** * Contains response data for the list operation. */ export type IoTSpacesListResponse = IoTSpacesDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IoTSpacesDescriptionListResult; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type IoTSpacesListByResourceGroupResponse = IoTSpacesDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IoTSpacesDescriptionListResult; }; }; /** * Contains response data for the checkNameAvailability operation. */ export type IoTSpacesCheckNameAvailabilityResponse = IoTSpacesNameAvailabilityInfo & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IoTSpacesNameAvailabilityInfo; }; }; /** * Contains response data for the beginCreateOrUpdate operation. */ export type IoTSpacesBeginCreateOrUpdateResponse = IoTSpacesDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IoTSpacesDescription; }; }; /** * Contains response data for the beginUpdate operation. */ export type IoTSpacesBeginUpdateResponse = IoTSpacesDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IoTSpacesDescription; }; }; /** * Contains response data for the beginDeleteMethod operation. */ export type IoTSpacesBeginDeleteMethodResponse = IoTSpacesDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IoTSpacesDescription; }; }; /** * Contains response data for the listNext operation. */ export type IoTSpacesListNextResponse = IoTSpacesDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IoTSpacesDescriptionListResult; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type IoTSpacesListByResourceGroupNextResponse = IoTSpacesDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IoTSpacesDescriptionListResult; }; }; /** * Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; };
the_stack
import { expect } from 'chai'; import ListBuilder from '../../../../../src/lib/device/lists/listBuilder'; describe('./lib/device/lists/listBuilder.ts', () => { describe('initialization', () => { it('should correctly set default values', () => { // WHEN const builder = new ListBuilder({ title: 'title', browseIdentifier: 'foo', }); // THEN expect(builder.title).to.equal('title'); expect(builder._meta.totalItems).to.equal(0); expect(builder._meta.totalMatchingItems).to.equal(0); }); it('should fail to initialize with too big limit (64 max)', () => { // WHEN expect( () => new ListBuilder({ title: 'Foo', limit: 50000, }) ).to.throw(/ERROR_LIST_LIMIT_MAXIMUM_EXCEEDED/); }); it('should initialize simple list', () => { const result = new ListBuilder(); expect(result.title).to.equal(''); }); }); it('should build correct metadata for empty list', () => { // GIVEN const expectedMetaData = { current: { limit: 10, offset: 0, browseIdentifier: 'ident', }, next: { limit: 10, offset: 0, // we didn't add any items therefore we still have the same offset browseIdentifier: 'ident', }, totalItems: 0, totalMatchingItems: 30, }; // WHEN const listBuilder = new ListBuilder({ title: 'title', totalMatchingItems: 30, offset: 0, limit: 10, browseIdentifier: 'ident', }); // THEN expect(listBuilder._meta).to.deep.equal(expectedMetaData); }); it('should build correct metadata for list with real items', () => { // GIVEN const listBuilder = new ListBuilder({ title: 'title', totalMatchingItems: 500, offset: 0, limit: 5, browseIdentifier: 'ident', }); const listParams = { title: 'foo', thumbnailUri: 'http://example.com/someimage.png', actionIdentifier: 'someaction', }; const expectedMetaData = { current: { limit: 5, offset: 0, browseIdentifier: 'ident', }, next: { limit: 5, offset: 5, browseIdentifier: 'ident', }, totalItems: 5, totalMatchingItems: 500, }; // WHEN listBuilder.addListItem(listParams); listBuilder.addListItem(listParams); listBuilder.addListItem(listParams); listBuilder.addListItem(listParams); listBuilder.addListItem(listParams); // THEN expect(listBuilder._meta).to.deep.equal(expectedMetaData); }); it('should build correct metadata for list with real items - second page', () => { // GIVEN const listBuilder = new ListBuilder({ title: 'title', totalMatchingItems: 500, offset: 5, limit: 5, browseIdentifier: 'ident', }); const listParams = { title: 'foo', thumbnailUri: 'http://example.com/someimage.png', actionIdentifier: 'someaction', }; const expectedMetaData = { current: { limit: 5, offset: 5, browseIdentifier: 'ident', }, next: { limit: 5, offset: 10, browseIdentifier: 'ident', }, previous: { limit: 5, offset: 0, browseIdentifier: 'ident', }, totalItems: 5, totalMatchingItems: 500, }; // WHEN listBuilder.addListItem(listParams); listBuilder.addListItem(listParams); listBuilder.addListItem(listParams); listBuilder.addListItem(listParams); listBuilder.addListItem(listParams); // THEN expect(listBuilder._meta).to.deep.equal(expectedMetaData); }); it('should set list title', () => { const title = 'CUSTOM TITLE'; const result = new ListBuilder(); result.setListTitle(title); expect(result.title).to.equal(title); }); describe('adding elements', () => { let listBuilder; beforeEach(() => { listBuilder = new ListBuilder({ title: 'title', browseIdentifier: 'foo', }); }); it('should add list item', () => { // GIVEN const params = { title: 'foo', thumbnailUri: 'http://example.com/someimage.png', actionIdentifier: 'someaction', }; // WHEN listBuilder.addListItem(params); // THEN expect(listBuilder.items.length).to.equal(1); }); it('should add list items', () => { // GIVEN const params = { title: 'foo', thumbnailUri: 'http://example.com/someimage.png', actionIdentifier: 'someaction', }; // WHEN listBuilder.addListItems([params]); // THEN expect(listBuilder.items.length).to.equal(1); }); function _buildListItems(arrayLength) { const params = { thumbnailUri: 'http://example.com/someimage.png', actionIdentifier: 'someaction', }; const listData = new Array(arrayLength).fill(1).map((unused, index) => { const title = 'foo ' + index; return Object.assign({ title }, params); }); return listData; } it('should respect maximal items when using addListItems, list initially empty', () => { // GIVEN const arrayLength = 100; const listData = _buildListItems(arrayLength); // WHEN listBuilder.addListItems(listData).setTotalMatchingItems(arrayLength); // THEN expect(listBuilder.items.length).to.equal(listBuilder.limit); expect(listBuilder.totalMatchingItems).to.equal(arrayLength); expect(listBuilder.items[0].title).to.equal('foo 0'); expect(listBuilder._meta.next).to.deep.equal({ offset: 64, limit: listBuilder.limit, browseIdentifier: 'foo', }); }); it('should respect maximal items when using addListItems, list initially NOT empty', () => { // GIVEN const arrayLength = 100; const listData = _buildListItems(arrayLength); const params = { title: 'foo', thumbnailUri: 'http://example.com/someimage.png', actionIdentifier: 'someaction', }; // WHEN listBuilder .addListItem(params) .addListItems(listData) .setTotalMatchingItems(arrayLength + 1); // THEN expect(listBuilder.items.length).to.equal(64); expect(listBuilder.totalMatchingItems).to.equal(arrayLength + 1); expect(listBuilder.items[1].title).to.equal('foo 0'); }); it('should respect maximal items when using addListItems, overflow', () => { // GIVEN const arrayLength = 100; const listData = _buildListItems(arrayLength); // WHEN listBuilder .addListItems(listData) .addListItems(listData) .setTotalMatchingItems(arrayLength * 2); // THEN expect(listBuilder.items.length).to.equal(64); expect(listBuilder.totalMatchingItems).to.equal(arrayLength * 2); expect(listBuilder.items[0].title).to.equal('foo 0'); }); it('should fail to add list item without params', () => { // WHEN expect(() => { listBuilder.addListItem(); }).to.throw(/ERROR_LIST_ITEM_PARAMS_EMPTY/); expect(listBuilder.items.length).to.equal(0); }); it('should add list header', () => { // GIVEN const title = 'headertitle'; // WHEN listBuilder.addListHeader(title); // THEN expect(listBuilder.items.length).to.equal(1); }); it('should add empty list header without params', () => { listBuilder.addListHeader(); expect(listBuilder.items.length).to.equal(1); expect(listBuilder.items[0]).to.deep.equal({ isHeader: true, title: '' }); }); it('should add list tile', () => { // GIVEN const params = [ { thumbnailUri: 'http://www.image.com/image.jpg', }, ]; // WHEN listBuilder.addListTiles(params); // THEN expect(listBuilder.items.length).to.equal(1); }); it('should fail to add list tile without thumbnail param', () => { // WHEN expect(() => { listBuilder.addListTiles([{ actionIdentifier: 'foo' }]); }).to.throw(/ERROR_LIST_THUMBNAIL_EMPTY/); }); it('should add list info item', () => { // GIVEN const params = { title: 'foo', thumbnailUri: 'http://example.com/someimage.jpg', actionIdentifier: 'someaction', }; // WHEN listBuilder.addListInfoItem(params); // THEN expect(listBuilder.items.length).to.equal(1); expect(listBuilder.items[0].isInfoItem).to.equal(true); }); it('should fail to add list info item without title', () => { listBuilder.addListInfoItem({}); expect(listBuilder.items.length).to.equal(1); expect(listBuilder.items[0].isInfoItem).to.equal(true); expect(listBuilder.items[0].title).to.equal(''); }); it('should add list button', () => { // GIVEN const params = [ { title: 'some title', actionIdentifier: 'action!', }, ]; // WHEN listBuilder.addListButtons(params); // THEN expect(listBuilder.items[0].buttons[0].isButton).to.equal(true); expect(listBuilder.items[0].buttons[0].title).to.equal(params[0].title); expect(listBuilder.items[0].buttons[0].actionIdentifier).to.equal(params[0].actionIdentifier); }); it('should add two list buttons', () => { // GIVEN const buttons = [ { title: 'some title', actionIdentifier: 'action!', }, { title: 'some other', actionIdentifier: 'action2!', }, ]; // WHEN listBuilder.addListButtons(buttons); // THEN expect(listBuilder.items[0].buttons.length).to.equal(2); expect(listBuilder.items[0].buttons[0].isButton).to.equal(true); expect(listBuilder.items[0].buttons[1].isButton).to.equal(true); }); it('should fail to add list button without title and icon param', () => { // WHEN expect(() => listBuilder.addListButtons([{ actionIdentifier: 'foo' }])).to.throw( /ERROR_LIST_BUTTON_TITLE_OR_ICON_EMPTY/ ); }); }); });
the_stack
import { Component, Input, OnInit } from '@angular/core'; import { ProgressModel } from './progressce.component.model'; @Component({ selector: 'amexio-progress-ce', templateUrl: './progressce.component.html', }) export class AmexioProgressCEComponent implements OnInit { /* Properties name : type datatype : string version : 5.6.0 onwards default : description : Set type to the circular creative progress bar('radial/ring/pie'). */ @Input('type') type: string; /* Properties name : font-size datatype : string version : 5.6.0 onwards default : description : Set size to label of progress bar. */ @Input('font-size') size = '30px'; /* Properties name : background-color datatype : string version : 5.6.0 onwards default : description : Set background color to the circular creative progress bar. */ @Input('background-color') background = 'rgb(242,244,245)'; /* Properties name : background-color datatype : string version : 5.6.0 onwards default : description : Set label color to the circular creative progress bar. */ @Input('label-color') labelcolor = 'black'; /* Properties name : progress-color datatype : string version : 5.6.0 onwards default : '#2ecc71' description : Set progress color to the border of creative progress bar. */ @Input('progress-color') progresscolor = '#1565c0'; /* Properties name : inactive-progress-color datatype : string version : 5.6.0 onwards default : '#d0d0d0' description : Set inactive color to the remaining border of creative progress bar. */ @Input('inactive-progress-color') inactiveprogresscolor = '#cce2f5'; /* Properties name : unit datatype : string version : 5.6.0 onwards default : '%' description : Set unit to the label of progress bar. */ @Input('unit') unit = '%'; /* Properties name : label datatype : string version : 5.6.0 onwards default : description : Set label progress bar. */ @Input('label') label: string; /* Properties name : height datatype : string version : 5.6.0 onwards default : 100% description : Set height to progress bar. */ @Input('height') height: string; /* Properties name : width datatype : string version : 5.6.0 onwards default : 100% description : Set width to progress bar. */ @Input('width') width: string; /* Properties name : progress-value datatype : number version : 5.6.0 onwards default : description : Give progress value to progress bar. */ @Input('progress-value') progressvalue: number; @Input('tooltip') tooltip: string; @Input('show-label') showlabel = false; @Input('show-unit') showunit = false; firstProgressBarColor: any; secondProgressBarColor: any; thirdProgressBarColor: any; pStyle: any; outerWidth: any; outerHeight: any; progressBarDegreeMap: Map<any, any>; constructor() { } ngOnInit() { this.dyanmicHeightCreation(); this.progressBarDegreeMap = new Map(); this.progressBarDegreeMap.set('0', new ProgressModel('90deg', '90deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('1', new ProgressModel('90deg', '93.6deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('2', new ProgressModel('90deg', '97.2deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('3', new ProgressModel('90deg', '100.8deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('4', new ProgressModel('90deg', '104.4deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('5', new ProgressModel('90deg', '108deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('6', new ProgressModel('90deg', '111.6deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('7', new ProgressModel('90deg', '115.2deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('8', new ProgressModel('90deg', '118.8deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('9', new ProgressModel('90deg', '122.4deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('10', new ProgressModel('90deg', '126deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('11', new ProgressModel('90deg', '129.6deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('12', new ProgressModel('90deg', '133.2deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('13', new ProgressModel('90deg', '136.8deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('14', new ProgressModel('90deg', '140.4deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('15', new ProgressModel('90deg', '144deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('16', new ProgressModel('90deg', '147.6deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('17', new ProgressModel('90deg', '151.2deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('18', new ProgressModel('90deg', '154.8deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('19', new ProgressModel('90deg', '158.4deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('20', new ProgressModel('90deg', '162deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('21', new ProgressModel('90deg', '165.6deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('22', new ProgressModel('90deg', '169.2deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('23', new ProgressModel('90deg', '172.8deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('24', new ProgressModel('90deg', '176.4deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('25', new ProgressModel('90deg', '180deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('26', new ProgressModel('90deg', '183.6deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('27', new ProgressModel('90deg', '187.2deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('28', new ProgressModel('90deg', '190.8deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('29', new ProgressModel('90deg', '194.4deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('30', new ProgressModel('90deg', '198deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('31', new ProgressModel('90deg', '201.6deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('32', new ProgressModel('90deg', '205.2deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('33', new ProgressModel('90deg', '208.8deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('34', new ProgressModel('90deg', '212.4deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('35', new ProgressModel('90deg', '216deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('36', new ProgressModel('90deg', '219.6deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('37', new ProgressModel('90deg', '223.2deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('38', new ProgressModel('90deg', '226.8deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('39', new ProgressModel('90deg', '230.4deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('40', new ProgressModel('90deg', '234deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('41', new ProgressModel('90deg', '237.6deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('42', new ProgressModel('90deg', '241.2deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('43', new ProgressModel('90deg', '244.8deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('44', new ProgressModel('90deg', '248.4deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('45', new ProgressModel('90deg', '252deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('46', new ProgressModel('90deg', '255.6deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('47', new ProgressModel('90deg', '259.2deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('48', new ProgressModel('90deg', '262.8deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('49', new ProgressModel('90deg', '266.4deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('50', new ProgressModel('-90deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('51', new ProgressModel('-86.4deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('52', new ProgressModel('-82.8deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('53', new ProgressModel('-79.2deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('54', new ProgressModel('-75.6deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('55', new ProgressModel('-72deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('56', new ProgressModel('-68.4deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('57', new ProgressModel('-64.8deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('58', new ProgressModel('-61.2deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('59', new ProgressModel('-57.6deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('60', new ProgressModel('-54deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('61', new ProgressModel('-50.4deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('62', new ProgressModel('-46.8deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('63', new ProgressModel('-43.2deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('64', new ProgressModel('-39.6deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('65', new ProgressModel('-36deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('66', new ProgressModel('-32.4deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('67', new ProgressModel('-28.8deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('68', new ProgressModel('-25.2deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('69', new ProgressModel('-21.6deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('70', new ProgressModel('-18deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('71', new ProgressModel('-14.4deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('72', new ProgressModel('-10.8deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('73', new ProgressModel('-7.2deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('74', new ProgressModel('-3.6deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('75', new ProgressModel('0deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('76', new ProgressModel('3.6deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('77', new ProgressModel('7.2deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('78', new ProgressModel('10.8deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('79', new ProgressModel('14.4deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('80', new ProgressModel('18deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('81', new ProgressModel('21.6deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('82', new ProgressModel('25.2deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('83', new ProgressModel('28.8deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('84', new ProgressModel('32.4deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('85', new ProgressModel('36deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('86', new ProgressModel('39.6deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('87', new ProgressModel('43.2deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('88', new ProgressModel('46.8deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('89', new ProgressModel('50.4deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('90', new ProgressModel('54deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('91', new ProgressModel('57.6deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('92', new ProgressModel('61.2deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('93', new ProgressModel('64.8deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('94', new ProgressModel('68.4deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('95', new ProgressModel('72deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('96', new ProgressModel('76.6deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('97', new ProgressModel('79.2deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('98', new ProgressModel('82.8deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('99', new ProgressModel('86.4deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.set('100', new ProgressModel('90deg', '270deg', this.progresscolor, this.inactiveprogresscolor)); this.progressBarDegreeMap.forEach((element: any, key: string) => { if (this.progressvalue === parseInt(key, 10)) { this.pStyle = element.getStyle(); } }); } dyanmicHeightCreation() { if (this.width && this.width.length > 0 && this.height && this.height.length > 0) { this.outerWidth = this.getCal(this.width); this.outerHeight = this.getCal(this.height); } } getCal(value: any): any { return (parseInt(value, 10) + 32).toString() + 'px'; } }
the_stack
import angular, {ICompileService, IRootScopeService, ITimeoutService} from 'angular' import 'angular-mocks' import {expect} from 'chai' import jQuery from 'jquery' describe('Plugins', function () { // Load the module with MainController beforeEach( angular.mock.module('gantt', 'gantt.labels', 'gantt.sortable', 'gantt.movable', 'gantt.drawtask', 'gantt.tooltips', 'gantt.bounds', 'gantt.progress', 'gantt.table', 'gantt.tree', 'gantt.groups' ) ) let Gantt let $rootScope: IRootScopeService let $compile: ICompileService let $timeout: ITimeoutService let mockData = [ // Order is optional. If not specified it will be assigned automatically { name: 'Milestones', height: '3em', sortable: false, drawTask: false, classes: 'gantt-row-milestone', color: '#45607D', tasks: [ // Dates can be specified as string, timestamp or javascript date object. The data attribute can be used to attach a custom object { name: 'Kickoff', color: '#93C47D', from: '2013-10-07T09:00:00', to: '2013-10-07T10:00:00', data: 'Can contain any custom data or object' }, { name: 'Concept approval', color: '#93C47D', from: new Date(2013, 9, 18, 18, 0, 0), to: new Date(2013, 9, 18, 18, 0, 0), est: new Date(2013, 9, 16, 7, 0, 0), lct: new Date(2013, 9, 19, 0, 0, 0) }, { name: 'Development finished', color: '#93C47D', from: new Date(2013, 10, 15, 18, 0, 0), to: new Date(2013, 10, 15, 18, 0, 0) }, { name: 'Shop is running', color: '#93C47D', from: new Date(2013, 10, 22, 12, 0, 0), to: new Date(2013, 10, 22, 12, 0, 0) }, { name: 'Go-live', color: '#93C47D', from: new Date(2013, 10, 29, 16, 0, 0), to: new Date(2013, 10, 29, 16, 0, 0) } ], data: 'Can contain any custom data or object' }, { name: 'Status meetings', tasks: [ {name: 'Demo #1', color: '#9FC5F8', from: new Date(2013, 9, 25, 15, 0, 0), to: new Date(2013, 9, 25, 18, 30, 0)}, {name: 'Demo #2', color: '#9FC5F8', from: new Date(2013, 10, 1, 15, 0, 0), to: new Date(2013, 10, 1, 18, 0, 0)}, {name: 'Demo #3', color: '#9FC5F8', from: new Date(2013, 10, 8, 15, 0, 0), to: new Date(2013, 10, 8, 18, 0, 0)}, {name: 'Demo #4', color: '#9FC5F8', from: new Date(2013, 10, 15, 15, 0, 0), to: new Date(2013, 10, 15, 18, 0, 0)}, {name: 'Demo #5', color: '#9FC5F8', from: new Date(2013, 10, 24, 9, 0, 0), to: new Date(2013, 10, 24, 10, 0, 0)} ] }, { name: 'Kickoff', movable: {allowResizing: false}, tasks: [ { name: 'Day 1', color: '#9FC5F8', from: new Date(2013, 9, 7, 9, 0, 0), to: new Date(2013, 9, 7, 17, 0, 0), progress: {percent: 100, color: '#3C8CF8'}, movable: false }, { name: 'Day 2', color: '#9FC5F8', from: new Date(2013, 9, 8, 9, 0, 0), to: new Date(2013, 9, 8, 17, 0, 0), progress: {percent: 100, color: '#3C8CF8'} }, { name: 'Day 3', color: '#9FC5F8', from: new Date(2013, 9, 9, 8, 30, 0), to: new Date(2013, 9, 9, 12, 0, 0), progress: {percent: 100, color: '#3C8CF8'} } ] }, { name: 'Create concept', tasks: [ { name: 'Create concept', content: '<i class="fa fa-cog"></i> {{task.model.name}}', color: '#F1C232', from: new Date(2013, 9, 10, 8, 0, 0), to: new Date(2013, 9, 16, 18, 0, 0), est: new Date(2013, 9, 8, 8, 0, 0), lct: new Date(2013, 9, 18, 20, 0, 0), progress: 100 } ] }, { name: 'Finalize concept', tasks: [ { name: 'Finalize concept', color: '#F1C232', from: new Date(2013, 9, 17, 8, 0, 0), to: new Date(2013, 9, 18, 18, 0, 0), progress: 100 } ] }, { id: 'development', name: 'Development', children: ['Sprint 1', 'Sprint 2', 'Sprint 3', 'Sprint 4'], content: '<i class="fa fa-file-code-o"></i> {{row.model.name}}' }, { name: 'Sprint 1', tooltips: false, tasks: [ { name: 'Product list view', color: '#F1C232', from: new Date(2013, 9, 21, 8, 0, 0), to: new Date(2013, 9, 25, 15, 0, 0), progress: 25 } ] }, { name: 'Sprint 2', tasks: [ { name: 'Order basket', color: '#F1C232', from: new Date(2013, 9, 28, 8, 0, 0), to: new Date(2013, 10, 1, 15, 0, 0) } ] }, { name: 'Sprint 3', tasks: [ {name: 'Checkout', color: '#F1C232', from: new Date(2013, 10, 4, 8, 0, 0), to: new Date(2013, 10, 8, 15, 0, 0)} ] }, { name: 'Sprint 4', tasks: [ { name: 'Login & Signup & Admin Views', color: '#F1C232', from: new Date(2013, 10, 11, 8, 0, 0), to: new Date(2013, 10, 15, 15, 0, 0) } ] }, {name: 'Hosting', content: '<i class="fa fa-server"></i> {{row.model.name}}'}, { name: 'Setup', tasks: [ {name: 'HW', color: '#F1C232', from: new Date(2013, 10, 18, 8, 0, 0), to: new Date(2013, 10, 18, 12, 0, 0)} ] }, { name: 'Config', tasks: [ { name: 'SW / DNS/ Backups', color: '#F1C232', from: new Date(2013, 10, 18, 12, 0, 0), to: new Date(2013, 10, 21, 18, 0, 0) } ] }, {name: 'Server', parent: 'Hosting', children: ['Setup', 'Config']}, { name: 'Deployment', parent: 'Hosting', tasks: [ { name: 'Depl. & Final testing', color: '#F1C232', from: new Date(2013, 10, 21, 8, 0, 0), to: new Date(2013, 10, 22, 12, 0, 0), 'classes': 'gantt-task-deployment' } ] }, { name: 'Workshop', tasks: [ { name: 'On-side education', color: '#F1C232', from: new Date(2013, 10, 24, 9, 0, 0), to: new Date(2013, 10, 25, 15, 0, 0) } ] }, { name: 'Content', tasks: [ { name: 'Supervise content creation', color: '#F1C232', from: new Date(2013, 10, 26, 9, 0, 0), to: new Date(2013, 10, 29, 16, 0, 0) } ] }, { name: 'Documentation', tasks: [ { name: 'Technical/User documentation', color: '#F1C232', from: new Date(2013, 10, 26, 8, 0, 0), to: new Date(2013, 10, 28, 18, 0, 0) } ] } ] beforeEach(inject(['$rootScope', '$compile', '$timeout', 'Gantt', function ($tRootScope: IRootScopeService, $tCompile: ICompileService, $tTimeout: ITimeoutService, tGantt) { Gantt = tGantt $rootScope = $tRootScope $compile = $tCompile $timeout = $tTimeout }])) describe('every plugins', function () { it('should load without error', function () { let $scope = $rootScope.$new() $compile('<div gantt api="api">' + '<gantt-labels></gantt-labels>' + '<gantt-tree></gantt-tree>' + '<gantt-table></gantt-table>' + '<gantt-groups></gantt-groups>' + '<gantt-tooltips></gantt-tooltips>' + '<gantt-bounds></gantt-bounds>' + '<gantt-progress></gantt-progress>' + '<gantt-sortable></gantt-sortable>' + '<gantt-movable></gantt-movable>' + '<gantt-draw-task></gantt-draw-task>' + '</div>')($scope) $scope.$digest() $timeout.flush() } ) it('should destroy scope without error', function () { let $scope = $rootScope.$new() $scope.data = angular.copy(mockData) $compile('<div gantt api="api">' + '<gantt-labels></gantt-labels>' + '<gantt-tree></gantt-tree>' + '<gantt-table></gantt-table>' + '<gantt-groups></gantt-groups>' + '<gantt-tooltips></gantt-tooltips>' + '<gantt-bounds></gantt-bounds>' + '<gantt-progress></gantt-progress>' + '<gantt-sortable></gantt-sortable>' + '<gantt-movable></gantt-movable>' + '<gantt-draw-task></gantt-draw-task>' + '</div>')($scope) $scope.$digest() $timeout.flush() $scope.$destroy() } ) }) let checkLabels = function (data, ganttElement, contentNotSupported?) { let rowLabelsElements = jQuery(ganttElement).find('.gantt-row-label').not('.gantt-row-label-header').find('.gantt-label-text') expect(rowLabelsElements.length).to.be.eq(data.length) angular.forEach(rowLabelsElements, function (rowLabelElement, i) { rowLabelElement = jQuery(rowLabelElement) let rowModel = data[i] let rowText = rowLabelElement.text().trim() if (contentNotSupported || rowModel.content === undefined) { expect(rowText).to.be.eq(rowModel.name) } else { let rowHtmlModel = rowModel.content rowHtmlModel = rowHtmlModel.replace('{{row.model.name}}', rowModel.name) let expectedRowText = rowHtmlModel.replace(/<(?:.|\n)*?>/gm, '').trim() // Strip HTML expect(rowText).to.be.eq(expectedRowText) } if (rowModel.classes) { let rowClasses = rowModel.classes if (!angular.isArray(rowClasses)) { rowClasses = [rowClasses] } angular.forEach(rowClasses, function (rowClass) { expect(rowLabelElement.parents().hasClass(rowClass)).to.be.ok }) } }) } describe('labels', function () { it('should display labels', function () { let $scope = $rootScope.$new() $scope.data = angular.copy(mockData) let ganttElement = $compile('<div gantt data="data"><gantt-labels></gantt-labels></div>')($scope) $scope.$digest() $timeout.flush() checkLabels($scope.data, ganttElement, true) } ) }) describe('table', function () { it('should display labels', function () { let $scope = $rootScope.$new() $scope.data = angular.copy(mockData) let ganttElement = $compile('<div gantt data="data"><gantt-table></gantt-table></div>')($scope) $scope.$digest() $timeout.flush() checkLabels($scope.data, ganttElement) } ) }) describe('tree', function () { it('should display labels', function () { let $scope = $rootScope.$new() $scope.data = angular.copy(mockData) let ganttElement = $compile('<div gantt data="data"><gantt-tree></gantt-tree></div>')($scope) $scope.$digest() $timeout.flush() // Set the data in tree view ordering let orderedData = $scope.data.slice() let indices = {} angular.forEach($scope.data, function (rowModel, i) { if (rowModel.name) { indices[rowModel.name] = i } }) /*jshint sub:true */ let configRow = orderedData[indices['Config']] let setupRow = orderedData[indices['Setup']] let serverRow = orderedData[indices['Server']] orderedData[indices['Setup']] = serverRow orderedData[indices['Config']] = setupRow orderedData[indices['Server']] = configRow /*jshint sub:false */ checkLabels(orderedData, ganttElement) } ) it('should contain nodes that can expand and collapse', function () { let $scope = $rootScope.$new() $scope.data = angular.copy(mockData) let ganttApi let ready = false $scope.api = function (api) { ganttApi = api ganttApi.core.on.ready($scope, function () { ready = true }) } let ganttElement = $compile('<div gantt api="api" data="data">' + '<gantt-tree></gantt-tree>' + '</div>')($scope) $scope.$digest() $timeout.flush() expect(ganttApi).to.be.not.undefined expect(ready).to.be.ok expect(ganttApi.tree.isCollapsed(undefined)).to.be.undefined // All rows should be expanded on init angular.forEach(ganttApi.gantt.rowsManager.rows, function (row) { expect(ganttApi.tree.isCollapsed(row)).to.be.not.ok }) // Collapse all rows ganttApi.tree.collapseAll() $scope.$digest() // Development row should be collapsed expect(ganttApi.tree.isCollapsed('development')).to.be.ok // All rows should be collapsed angular.forEach(ganttApi.gantt.rowsManager.rows, function (row) { expect(ganttApi.tree.isCollapsed(row)).to.be.ok }) // Expand all rows ganttApi.tree.expandAll() $scope.$digest() // All rows should be expanded angular.forEach(ganttApi.gantt.rowsManager.rows, function (row) { expect(ganttApi.tree.isCollapsed(row)).to.be.not.ok }) // GanttTreeNodeController let treeNodeElement = jQuery(ganttElement).find('[ng-controller="GanttTreeNodeController"]').first() let ganttTreeNodeController = angular.element(treeNodeElement[0]).scope() // First row name should be "Milestones" expect(ganttTreeNodeController.getValue()).to.be.eq('Milestones') // Collapsing should be disabled - no child rows expect(ganttTreeNodeController.isCollapseDisabled()).to.be.ok // Should get row content correctly. If undefined and if defined expect(ganttTreeNodeController.getRowContent()).to.be.eq('{{row.model.name}}') // Test row let testRow = ganttApi.gantt.rowsManager.rows[0] // Test undefined collapsed testRow._collapsed = undefined expect(ganttApi.tree.isCollapsed(testRow)).to.be.not.ok // Set custom content testRow.model.content = '> {{row.model.name}}' expect(ganttTreeNodeController.getRowContent()).to.be.eq('> {{row.model.name}}') // GanttTreeController let treeElement = jQuery(ganttElement).find('[ng-controller="GanttTreeController"]') let ganttTreeController = angular.element(treeElement).scope() // Get default header expect(ganttTreeController.getHeader()).to.be.eq('Name') // Get default header content expect(ganttTreeController.getHeaderContent()).to.be.eq('{{getHeader()}}') } ) } ) })
the_stack
import { ProcessIEInput } from "./../../../adapters/mongo-db/repo-models"; import { printSeparator } from "../../../adapters/messages/console-log"; import { SubProcessInfo, ElementIFlow, SubProcLinkInfo, IDataInfo, } from "./../../utils/structs/parsing-info"; import { ContractInfo } from "./../../../adapters/ethereum-blockchain/structs/contract-info"; import { NewContractInstRequest, TypeContract, FunctionCallRequest, LinkProcessRequest, } from "./../../utils/structs/async-requests"; import { DeploymentResult } from "../../../adapters/ethereum-blockchain/structs/deployment-output"; import { print, TypeMessage } from "../../../adapters/messages/console-log"; import { printError } from "../../../adapters/messages/error-logs"; import { CompilationResult } from "../../../adapters/ethereum-blockchain/structs/compilation-output"; import { AccountInfo } from "../../../adapters/ethereum-blockchain/structs/account-info"; import * as ethereumAdapter from "../../../adapters/ethereum-blockchain/ethereum-adapter"; import * as mongoDBAdapter from "./../../../adapters/mongo-db/mongo-db-adapter"; import * as eventMonitor from "./../worklist-handler/event-monitor"; import * as registrationService from "./../process-setup-handler/registration-mediator"; import { RepoType } from "../../../adapters/mongo-db/repo-types"; import { ModelMetadata } from "../../../adapters/mongo-db/repo-models"; import { FunctionInfo } from "../../../adapters/ethereum-blockchain/structs/function-info"; import { webSocket } from "../../../app"; class SetUpInfo { rootId: string = undefined; interpreterInfo: NewContractInstRequest; factoryIFlowRel = new Map< number, Map<TypeContract, NewContractInstRequest> >(); constructor( public processInfo: Array<SubProcessInfo>, public iDataInfo: Array<CompilationResult>, public runtimeRegistry: ContractInfo, public bpmnModel: string ) {} } let defaultAcccount: AccountInfo; let setUpInfo = new Map<number, SetUpInfo>(); let contractDeploymentCount = new Map<number, number>(); let functionTransactionCount = new Map<number, number>(); let lastInd = 0; export let deploySmartContractSync = async ( compilationInfo: CompilationResult, params?: Array<any> ): Promise<DeploymentResult> => { try { if (!this.defaultAccount) this.defaultAccount = await ethereumAdapter.defaultDeployment(); let contractDeployment = await ethereumAdapter.deploySmartContractSync( compilationInfo, this.defaultAccount, params ); printDplInfo(compilationInfo, contractDeployment); return contractDeployment as DeploymentResult; } catch (error) { printError( "DeploymentMediator", "deploySmartContractSync", deploySmartContractSync ); return error; } }; export let deploySmartContractAsync = async ( compilationInfo: CompilationResult, pId: number, procIndex: number, type: TypeContract, params?: any ) => { try { if (!this.defaultAccount) this.defaultAccount = await ethereumAdapter.defaultDeployment(); let transactionHash = await ethereumAdapter.deploySmartContractAsync( compilationInfo, this.defaultAccount, params ); let newRequest = new NewContractInstRequest( compilationInfo, pId, procIndex, type, transactionHash, this.handleNewInstanceCreated ); eventMonitor.listenForPendingTransaction(transactionHash, newRequest); return transactionHash; } catch (error) { printError("DeploymentMediator", "deploySmartContractAsync", error); return error; } }; export let deployAllProcessContracts = async ( processInfo: SubProcessInfo, interpreterInfo: CompilationResult, iFlowInfo: CompilationResult, iDataInfo: Array<CompilationResult>, iFactoryInfo: Array<CompilationResult>, runtimeRegistry: ContractInfo, bpmnModel: string ): Promise<any> => { try { let interpreterTHash = await deploySmartContractAsync( interpreterInfo, lastInd, 0, TypeContract.BPMNInterpreter ); let sortedProcesses = sortProcessHierarchy( processInfo, iDataInfo, iFactoryInfo ); iFactoryInfo = sortedProcesses[2]; setUpInfo.set( lastInd, new SetUpInfo( sortedProcesses[0], sortedProcesses[1], runtimeRegistry, bpmnModel ) ); findTotalTransactionCount(lastInd, sortedProcesses[0]); let iFlowTHashes = new Array<string>(); let iFactoryTHashes = new Array<string>(); for (let i = 0; i < iDataInfo.length; i++) { iFlowTHashes.push( await deploySmartContractAsync( iFlowInfo, lastInd, i, TypeContract.IFlow, [runtimeRegistry.address] ) ); iFactoryTHashes.push( await deploySmartContractAsync( iFactoryInfo[i], lastInd, i, TypeContract.IFactory ) ); } lastInd++; return { interpreterTHash: interpreterTHash, iFlowTHashes: iFlowTHashes, iFactoryTHashes: iFactoryTHashes, }; } catch (error) { print(error, TypeMessage.error); return error; } }; ///////////////////////////////////////////////////// /////// CALLBACKS FOR ASYNCHRONOUS OPERATIONS /////// ///////////////////////////////////////////////////// export let handleNewInstanceCreated = async ( reqInfo: NewContractInstRequest ) => { try { printHandlerInfo(1, reqInfo); // (1) Check and relate IFactory and BPMNInterpreter into IFlow once the instances are mined checkAndUpdateIFlowRel(reqInfo); // (2) Register all the BPMN elements into IFlow, and decrease pending transaction count let iDataId = undefined; if (reqInfo.type === TypeContract.IFlow) { registerIFlowElementList( setUpInfo.get(reqInfo.pId).processInfo[reqInfo.contractIndex], reqInfo ); let spInfo = setUpInfo.get(reqInfo.pId); iDataId = await updateContractRepository( spInfo.iDataInfo[reqInfo.contractIndex], "" ); printHandlerInfo(2, [spInfo, reqInfo, iDataId]); } contractDeploymentCount.set( reqInfo.pId, contractDeploymentCount.get(reqInfo.pId) - 1 ); reqInfo.repoId = await updateContractRepository( reqInfo.compilationInfo, reqInfo.contractAddress, iDataId ); printHandlerInfo(3, reqInfo); checkAndLinkSubProcess(reqInfo.pId); checkAndUpdateProcessRepository(reqInfo.pId); } catch (error) { printError("DeploymentMediator", "handleNewInstanceCreated", error); } }; export let handleFunctionCallRequest = (fRequest: FunctionCallRequest) => { functionTransactionCount.set( fRequest.pInd, functionTransactionCount.get(fRequest.pInd) - 1 ); printFunctionCallHandled( fRequest.functionName, fRequest.gasCost, fRequest.params ); if (functionTransactionCount.get(fRequest.pInd) === 0) webSocket.send( JSON.stringify({ bundleId: setUpInfo.get(fRequest.pInd).rootId }) ); }; export let handleSubprocessLink = async (linkRequest: LinkProcessRequest) => { try { functionTransactionCount.set( linkRequest.iFlowP.pId, functionTransactionCount.get(linkRequest.iFlowP.pId) - 1 ); printFunctionCallHandled( "setElement", linkRequest.gasCost, linkRequest.elementInfo ); let transactionHash = await registrationService.linkSubProcess( linkRequest.iFlowP.contractAddress, linkRequest.iFlowP.compilationInfo.abi, linkRequest.toLink ); eventMonitor.listenForPendingTransaction( transactionHash, new FunctionCallRequest( transactionHash, this.handleFunctionCallRequest, linkRequest.iFlowP.pId, "linkSubProcess", linkRequest.toLink ) ); } catch (error) { printError("DeploymentMediator", "handleSubprocessLink", error); } }; //////////////////////////////////////////// //////////// PRIVATE FUNCTIONS ///////////// //////////////////////////////////////////// let sortProcessHierarchy = ( pInfo: SubProcessInfo, iDataInfo: Array<CompilationResult>, iFactoryInfo: Array<CompilationResult> ): Array<any> => { let nodes = [pInfo]; let sortedFactory = []; let sortedData = []; for (let i = 0; i < nodes.length; i++) nodes = nodes.concat(nodes[i].children); nodes = nodes.reverse(); nodes.forEach((node) => { sortedFactory.push( iFactoryInfo.filter((fContract) => { return fContract.contractName === node.procName + "Factory"; }) ); sortedData.push( iDataInfo.filter((fContract) => { return fContract.contractName === node.procName + "Data"; }) ); }); return [nodes, sortedData.flat(), sortedFactory.flat()]; }; let findTotalTransactionCount = ( pIndex: number, processes: Array<SubProcessInfo> ) => { let contractCount = 1; // Deployment of Interpreter let functionCount = 1; // Update of Root process in Runtime Registry for (let i = 0; i < processes.length; i++) { contractCount += 2; // Deployment of IFactory and IFlow contracts functionCount += processes[i].iflow.elementInfo.size + 2; // BPMN Elements to Register + Rel(Iflow-IFactory) + Rel(IFlow-INterpreter) functionCount += processes[i].children.length; // Children registration } contractDeploymentCount.set(pIndex, contractCount); functionTransactionCount.set(pIndex, functionCount); }; let registerIFlowElementList = ( procInfo: SubProcessInfo, iFlowInfo: NewContractInstRequest ) => { procInfo.iflow.nodeIndexMap.forEach(async (eInd, eId) => { try { if (!isSubprocess(eId, procInfo)) { let eInfo = procInfo.iflow.elementInfo.get(eInd); let transactionHash = await registrationService.setIFlowNodeElement( iFlowInfo.contractAddress, iFlowInfo.compilationInfo.abi, eInfo ); eventMonitor.listenForPendingTransaction( transactionHash, new FunctionCallRequest( transactionHash, this.handleFunctionCallRequest, iFlowInfo.pId, "setElement", eInfo ) ); } } catch (error) { printError("DeploymentMediator", "registerIflowElementList", error); } }); }; let isSubprocess = (eId: string, iFlowInfo: SubProcessInfo) => { return ( iFlowInfo.children.filter((node) => { return node.procBpmnId === eId; }).length > 0 ); }; let checkAndUpdateIFlowRel = async (reqInfo: NewContractInstRequest) => { try { let spInd = reqInfo.contractIndex; let pInfo = setUpInfo.get(reqInfo.pId); if (reqInfo.type === TypeContract.BPMNInterpreter) { pInfo.interpreterInfo = reqInfo; } else { if (!pInfo.factoryIFlowRel.has(spInd)) { pInfo.factoryIFlowRel.set( spInd, new Map<TypeContract, NewContractInstRequest>() ); } pInfo.factoryIFlowRel.get(spInd).set(reqInfo.type, reqInfo); } if ( pInfo.interpreterInfo && pInfo.factoryIFlowRel.has(spInd) && pInfo.factoryIFlowRel.get(spInd).get(TypeContract.IFlow) && pInfo.factoryIFlowRel.get(spInd).get(TypeContract.IFactory) ) { let iFlow = pInfo.factoryIFlowRel.get(spInd).get(TypeContract.IFlow); let iFactory = pInfo.factoryIFlowRel .get(spInd) .get(TypeContract.IFactory); if (!this.defaultAccount) this.defaultAccount = await ethereumAdapter.defaultDeployment(); registerContractAddress( iFlow.contractAddress, iFlow.compilationInfo.abi, reqInfo.pId, "setFactoryInst", iFactory.contractAddress ); registerContractAddress( iFlow.contractAddress, iFlow.compilationInfo.abi, reqInfo.pId, "setInterpreterInst", pInfo.interpreterInfo.contractAddress ); } } catch (error) { printError("DeploymentMediator", "checkAndUpdateIFlowRel", error); } }; let checkAndUpdateProcessRepository = async (pInd: number) => { try { if (contractDeploymentCount.get(pInd) === 0) { let procHash = undefined; let spInfo = setUpInfo.get(pInd); let procChildren = new Map<string, Array<string>>(); for (let i = 0; i < spInfo.processInfo.length; i++) procChildren.set(spInfo.processInfo[i].procName, new Array<string>()); for (let i = 0; i < spInfo.iDataInfo.length; i++) { let processInfo = spInfo.processInfo[i]; procHash = await mongoDBAdapter.updateRepository( RepoType.ProcessInterpretedEngine, new ProcessIEInput( processInfo.procBpmnId, processInfo.procName, spInfo.bpmnModel, infoToArray(processInfo.iflow.elementInfo, processInfo.iData), procChildren.get(processInfo.procName), spInfo.factoryIFlowRel.get(i).get(TypeContract.IFactory).repoId, spInfo.factoryIFlowRel.get(i).get(TypeContract.IFlow).repoId ) ); if (processInfo.parent) procChildren.get(processInfo.parent.procName).push(procHash); print( `Process ${processInfo.procName} updated in repositpry`, TypeMessage.success ); print(` ID: ${procHash}`, TypeMessage.data); printSeparator(); } let rootProc = spInfo.processInfo.length - 1; spInfo.rootId = procHash; updateRuntimeRegistry( pInd, spInfo.runtimeRegistry, procHash, spInfo.factoryIFlowRel.get(rootProc).get(TypeContract.IFlow) .contractAddress ); } } catch (error) { printError("DeploymentMediator", "checkAndUpdateProcessRepository", error); } }; let checkAndLinkSubProcess = async (pInd: number) => { try { if (contractDeploymentCount.get(pInd) === 0) { let processes = setUpInfo.get(pInd).processInfo; let stInfo = setUpInfo.get(pInd); for (let i = 0; i < processes.length - 1; i++) { let childP = processes[i]; if (childP.parent) { let parentP = childP.parent; let prtInd = -1; for (let j = i + 1; j < processes.length; j++) if (processes[j].procName === parentP.procName) { prtInd = j; break; } if (prtInd !== -1) { let iFlowP = stInfo.factoryIFlowRel .get(prtInd) .get(TypeContract.IFlow); let iFlowC = stInfo.factoryIFlowRel.get(i).get(TypeContract.IFlow); let childIndex = parentP.iflow.nodeIndexMap.get(childP.procBpmnId); let toLink = new SubProcLinkInfo( childIndex, iFlowC.contractAddress, parentP.iflow.attachedEvents.get(childIndex) ? parentP.iflow.attachedEvents.get(childIndex) : [], childP.instCount ); let transactionHash = await registrationService.setIFlowNodeElement( iFlowP.contractAddress, iFlowP.compilationInfo.abi, parentP.iflow.elementInfo.get(childIndex) ); eventMonitor.listenForPendingTransaction( transactionHash, new LinkProcessRequest( transactionHash, this.handleSubprocessLink, toLink, parentP.iflow.elementInfo.get(childIndex), iFlowP ) ); } } } } } catch (error) { printError("DeploymentMediator", "checkAndLinkSubProcess", error); } }; let updateRuntimeRegistry = async ( pInd: number, runtimeRegistry: ContractInfo, rootProcId: string, iFlowAddress: string ) => { try { if (!this.defaultAccount) this.defaultAccount = await ethereumAdapter.defaultDeployment(); let transactionHash = await ethereumAdapter.execContractFunctionAsync( runtimeRegistry.address, runtimeRegistry.abi, new FunctionInfo("registerIFlow", ["bytes32", "address"]), this.defaultAccount, [rootProcId, iFlowAddress] ); eventMonitor.listenForPendingTransaction( transactionHash, new FunctionCallRequest( transactionHash, this.handleFunctionCallRequest, pInd, "registerIFlow", [rootProcId, iFlowAddress] ) ); } catch (error) { printError("DeploymentMediator", "updateRuntimeRegistry", error); } }; let infoToArray = ( iFlowMap: Map<number, ElementIFlow>, iDataInfo: IDataInfo ) => { let result = []; iFlowMap.forEach((element, index) => { let input = iDataInfo.inParams.has(index) ? iDataInfo.inParams.get(index) : []; let output = iDataInfo.outParams.has(index) ? iDataInfo.outParams.get(index) : []; result[index] = { element: JSON.stringify(element), input: JSON.stringify(input), output: JSON.stringify(output), }; }); return result; }; let updateContractRepository = async ( cInfo: CompilationResult, address: string, linkedId?: string ) => { try { let toSave = new ContractInfo( cInfo.contractName, cInfo.abi, cInfo.bytecode, cInfo.solidity, address ); if (linkedId) toSave._relId = linkedId; return await mongoDBAdapter.updateRepository( RepoType.SmartContract, new ModelMetadata(toSave) ); } catch (error) { printError("DeploymentMediator", "updateContractRepository", error); } }; let registerContractAddress = async ( contractAddress: any, contractAbi: any, pInd: number, funcName: string, addressToRegister: string ) => { try { let transactionHash = await ethereumAdapter.execContractFunctionAsync( contractAddress, contractAbi, new FunctionInfo(funcName, ["address"]), this.defaultAccount, [addressToRegister] ); eventMonitor.listenForPendingTransaction( transactionHash, new FunctionCallRequest( transactionHash, this.handleFunctionCallRequest, pInd, funcName, addressToRegister ) ); } catch (error) { printError("DeploymentMediator", "registerContractAddress", error); } }; let printFunctionCallHandled = ( functionName: string, gasCost: any, params: any ) => { let cName = functionName === "registerIFlow" ? "RuntimeRegistry" : "IFlow"; print(`SUCCESS: Executed function ${cName}.${functionName}`, TypeMessage.success); print(` ${JSON.stringify(params)}`, TypeMessage.data); print(` Cost: ${gasCost} gas`, TypeMessage.data); printSeparator(); }; let printDplInfo = (compilationInfo: any, contractDeployment: any) => { print( `SUCCESS: ${compilationInfo.contractName} deployed successfully`, TypeMessage.success ); print( ` Address: ${(contractDeployment as DeploymentResult).contractAddress}`, TypeMessage.info ); print( ` Cost: ${(contractDeployment as DeploymentResult).gasCost} gas units`, TypeMessage.info ); printSeparator(); }; let printHandlerInfo = (type: number, info: any) => { switch (type) { case 1: { print( `SUCCESS: Transaction ${info.transactionHash} for deploying ${info.type} accepted`, TypeMessage.success ); print(` Contract Address ${info.contractAddress}`, TypeMessage.data); print(` Cost ${info.gasCost} gas units`, TypeMessage.data); printSeparator(); break; } case 2: { print( `SUCCESS: IData metadata from ${ info[0].processInfo[info[1].contractIndex].procName } updated in repositpry`, TypeMessage.success ); print(` ID: ${info[2]}`, TypeMessage.data); printSeparator(); break; } case 3: { print( `SUCCESS: ${info.type} running at ${info.contractAddress} updated in repositpry`, TypeMessage.success ); print(` ID: ${info.repoId}`, TypeMessage.data); printSeparator(); break; } } };
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class AppIntegrations extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: AppIntegrations.Types.ClientConfiguration) config: Config & AppIntegrations.Types.ClientConfiguration; /** * The Amazon AppIntegrations APIs are in preview release and are subject to change. Creates an EventIntegration, given a specified name, description, and a reference to an Amazon Eventbridge bus in your account and a partner event source that will push events to that bus. No objects are created in the your account, only metadata that is persisted on the EventIntegration control plane. */ createEventIntegration(params: AppIntegrations.Types.CreateEventIntegrationRequest, callback?: (err: AWSError, data: AppIntegrations.Types.CreateEventIntegrationResponse) => void): Request<AppIntegrations.Types.CreateEventIntegrationResponse, AWSError>; /** * The Amazon AppIntegrations APIs are in preview release and are subject to change. Creates an EventIntegration, given a specified name, description, and a reference to an Amazon Eventbridge bus in your account and a partner event source that will push events to that bus. No objects are created in the your account, only metadata that is persisted on the EventIntegration control plane. */ createEventIntegration(callback?: (err: AWSError, data: AppIntegrations.Types.CreateEventIntegrationResponse) => void): Request<AppIntegrations.Types.CreateEventIntegrationResponse, AWSError>; /** * The Amazon AppIntegrations APIs are in preview release and are subject to change. Deletes the specified existing event integration. If the event integration is associated with clients, the request is rejected. */ deleteEventIntegration(params: AppIntegrations.Types.DeleteEventIntegrationRequest, callback?: (err: AWSError, data: AppIntegrations.Types.DeleteEventIntegrationResponse) => void): Request<AppIntegrations.Types.DeleteEventIntegrationResponse, AWSError>; /** * The Amazon AppIntegrations APIs are in preview release and are subject to change. Deletes the specified existing event integration. If the event integration is associated with clients, the request is rejected. */ deleteEventIntegration(callback?: (err: AWSError, data: AppIntegrations.Types.DeleteEventIntegrationResponse) => void): Request<AppIntegrations.Types.DeleteEventIntegrationResponse, AWSError>; /** * The Amazon AppIntegrations APIs are in preview release and are subject to change. Return information about the event integration. */ getEventIntegration(params: AppIntegrations.Types.GetEventIntegrationRequest, callback?: (err: AWSError, data: AppIntegrations.Types.GetEventIntegrationResponse) => void): Request<AppIntegrations.Types.GetEventIntegrationResponse, AWSError>; /** * The Amazon AppIntegrations APIs are in preview release and are subject to change. Return information about the event integration. */ getEventIntegration(callback?: (err: AWSError, data: AppIntegrations.Types.GetEventIntegrationResponse) => void): Request<AppIntegrations.Types.GetEventIntegrationResponse, AWSError>; /** * The Amazon AppIntegrations APIs are in preview release and are subject to change. Returns a paginated list of event integration associations in the account. */ listEventIntegrationAssociations(params: AppIntegrations.Types.ListEventIntegrationAssociationsRequest, callback?: (err: AWSError, data: AppIntegrations.Types.ListEventIntegrationAssociationsResponse) => void): Request<AppIntegrations.Types.ListEventIntegrationAssociationsResponse, AWSError>; /** * The Amazon AppIntegrations APIs are in preview release and are subject to change. Returns a paginated list of event integration associations in the account. */ listEventIntegrationAssociations(callback?: (err: AWSError, data: AppIntegrations.Types.ListEventIntegrationAssociationsResponse) => void): Request<AppIntegrations.Types.ListEventIntegrationAssociationsResponse, AWSError>; /** * The Amazon AppIntegrations APIs are in preview release and are subject to change. Returns a paginated list of event integrations in the account. */ listEventIntegrations(params: AppIntegrations.Types.ListEventIntegrationsRequest, callback?: (err: AWSError, data: AppIntegrations.Types.ListEventIntegrationsResponse) => void): Request<AppIntegrations.Types.ListEventIntegrationsResponse, AWSError>; /** * The Amazon AppIntegrations APIs are in preview release and are subject to change. Returns a paginated list of event integrations in the account. */ listEventIntegrations(callback?: (err: AWSError, data: AppIntegrations.Types.ListEventIntegrationsResponse) => void): Request<AppIntegrations.Types.ListEventIntegrationsResponse, AWSError>; /** * The Amazon AppIntegrations APIs are in preview release and are subject to change. Lists the tags for the specified resource. */ listTagsForResource(params: AppIntegrations.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: AppIntegrations.Types.ListTagsForResourceResponse) => void): Request<AppIntegrations.Types.ListTagsForResourceResponse, AWSError>; /** * The Amazon AppIntegrations APIs are in preview release and are subject to change. Lists the tags for the specified resource. */ listTagsForResource(callback?: (err: AWSError, data: AppIntegrations.Types.ListTagsForResourceResponse) => void): Request<AppIntegrations.Types.ListTagsForResourceResponse, AWSError>; /** * The Amazon AppIntegrations APIs are in preview release and are subject to change. Adds the specified tags to the specified resource. */ tagResource(params: AppIntegrations.Types.TagResourceRequest, callback?: (err: AWSError, data: AppIntegrations.Types.TagResourceResponse) => void): Request<AppIntegrations.Types.TagResourceResponse, AWSError>; /** * The Amazon AppIntegrations APIs are in preview release and are subject to change. Adds the specified tags to the specified resource. */ tagResource(callback?: (err: AWSError, data: AppIntegrations.Types.TagResourceResponse) => void): Request<AppIntegrations.Types.TagResourceResponse, AWSError>; /** * The Amazon AppIntegrations APIs are in preview release and are subject to change. Removes the specified tags from the specified resource. */ untagResource(params: AppIntegrations.Types.UntagResourceRequest, callback?: (err: AWSError, data: AppIntegrations.Types.UntagResourceResponse) => void): Request<AppIntegrations.Types.UntagResourceResponse, AWSError>; /** * The Amazon AppIntegrations APIs are in preview release and are subject to change. Removes the specified tags from the specified resource. */ untagResource(callback?: (err: AWSError, data: AppIntegrations.Types.UntagResourceResponse) => void): Request<AppIntegrations.Types.UntagResourceResponse, AWSError>; /** * The Amazon AppIntegrations APIs are in preview release and are subject to change. Updates the description of an event integration. */ updateEventIntegration(params: AppIntegrations.Types.UpdateEventIntegrationRequest, callback?: (err: AWSError, data: AppIntegrations.Types.UpdateEventIntegrationResponse) => void): Request<AppIntegrations.Types.UpdateEventIntegrationResponse, AWSError>; /** * The Amazon AppIntegrations APIs are in preview release and are subject to change. Updates the description of an event integration. */ updateEventIntegration(callback?: (err: AWSError, data: AppIntegrations.Types.UpdateEventIntegrationResponse) => void): Request<AppIntegrations.Types.UpdateEventIntegrationResponse, AWSError>; } declare namespace AppIntegrations { export type Arn = string; export type ClientAssociationMetadata = {[key: string]: NonBlankString}; export type ClientId = string; export interface CreateEventIntegrationRequest { /** * The name of the event integration. */ Name: Name; /** * The description of the event integration. */ Description?: Description; /** * The event filter. */ EventFilter: EventFilter; /** * The Eventbridge bus. */ EventBridgeBus: EventBridgeBus; /** * A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. */ ClientToken?: IdempotencyToken; /** * One or more tags. */ Tags?: TagMap; } export interface CreateEventIntegrationResponse { /** * The Amazon Resource Name (ARN) of the event integration. */ EventIntegrationArn?: Arn; } export interface DeleteEventIntegrationRequest { /** * The name of the event integration. */ Name: Name; } export interface DeleteEventIntegrationResponse { } export type Description = string; export type EventBridgeBus = string; export type EventBridgeRuleName = string; export interface EventFilter { /** * The source of the events. */ Source: Source; } export interface EventIntegration { /** * The Amazon Resource Name (ARN) of the event integration. */ EventIntegrationArn?: Arn; /** * The name of the event integration. */ Name?: Name; /** * The event integration description. */ Description?: Description; /** * The event integration filter. */ EventFilter?: EventFilter; /** * The Amazon Eventbridge bus for the event integration. */ EventBridgeBus?: EventBridgeBus; /** * The tags. */ Tags?: TagMap; } export interface EventIntegrationAssociation { /** * The Amazon Resource Name (ARN) for the event integration association. */ EventIntegrationAssociationArn?: Arn; /** * The identifier for the event integration association. */ EventIntegrationAssociationId?: UUID; /** * The name of the event integration. */ EventIntegrationName?: Name; /** * The identifier for the client that is associated with the event integration. */ ClientId?: ClientId; /** * The name of the Eventbridge rule. */ EventBridgeRuleName?: EventBridgeRuleName; /** * The metadata associated with the client. */ ClientAssociationMetadata?: ClientAssociationMetadata; } export type EventIntegrationAssociationsList = EventIntegrationAssociation[]; export type EventIntegrationsList = EventIntegration[]; export interface GetEventIntegrationRequest { /** * The name of the event integration. */ Name: Name; } export interface GetEventIntegrationResponse { /** * The name of the event integration. */ Name?: Name; /** * The description of the event integration. */ Description?: Description; /** * The Amazon Resource Name (ARN) for the event integration. */ EventIntegrationArn?: Arn; /** * The Eventbridge bus. */ EventBridgeBus?: EventBridgeBus; /** * The event filter. */ EventFilter?: EventFilter; /** * One or more tags. */ Tags?: TagMap; } export type IdempotencyToken = string; export interface ListEventIntegrationAssociationsRequest { /** * The name of the event integration. */ EventIntegrationName: Name; /** * The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. */ NextToken?: NextToken; /** * The maximum number of results to return per page. */ MaxResults?: MaxResults; } export interface ListEventIntegrationAssociationsResponse { /** * The event integration associations. */ EventIntegrationAssociations?: EventIntegrationAssociationsList; /** * If there are additional results, this is the token for the next set of results. */ NextToken?: NextToken; } export interface ListEventIntegrationsRequest { /** * The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. */ NextToken?: NextToken; /** * The maximum number of results to return per page. */ MaxResults?: MaxResults; } export interface ListEventIntegrationsResponse { /** * The event integrations. */ EventIntegrations?: EventIntegrationsList; /** * If there are additional results, this is the token for the next set of results. */ NextToken?: NextToken; } export interface ListTagsForResourceRequest { /** * The Amazon Resource Name (ARN) of the resource. */ resourceArn: Arn; } export interface ListTagsForResourceResponse { /** * Information about the tags. */ tags?: TagMap; } export type MaxResults = number; export type Name = string; export type NextToken = string; export type NonBlankString = string; export type Source = string; export type TagKey = string; export type TagKeyList = TagKey[]; export type TagMap = {[key: string]: TagValue}; export interface TagResourceRequest { /** * The Amazon Resource Name (ARN) of the resource. */ resourceArn: Arn; /** * One or more tags. */ tags: TagMap; } export interface TagResourceResponse { } export type TagValue = string; export type UUID = string; export interface UntagResourceRequest { /** * The Amazon Resource Name (ARN) of the resource. */ resourceArn: Arn; /** * The tag keys. */ tagKeys: TagKeyList; } export interface UntagResourceResponse { } export interface UpdateEventIntegrationRequest { /** * The name of the event integration. */ Name: Name; /** * The description of the event inegration. */ Description?: Description; } export interface UpdateEventIntegrationResponse { } /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2020-07-29"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the AppIntegrations client. */ export import Types = AppIntegrations; } export = AppIntegrations;
the_stack
import {Validator} from "prop-types"; import * as PropTypes from "prop-types"; import * as React from "react"; import {IPropMap, TUpdatePayload} from "../createReconciler"; import final from "../decorators/final"; import isNonProduction from "../utils/isNonProduction"; import "../utils/ReactSharedInternals"; import {IHostDescriptor, IPropTypeMap} from "./IHostDescriptor"; import CustomPropertyDescriptor from "./properties/CustomPropertyDescriptor"; import CustomPropertyGroupDescriptor from "./properties/CustomPropertyGroupDescriptor"; import {PropertyUpdater} from "./properties/PropertyUpdater"; export interface IPropertyUpdaterMap<TProps, TInstance, TDescriptor extends CustomPropertyDescriptor<TProps, TInstance, any>> { [key: string]: TDescriptor | undefined; } export interface IPropertyGroupMap<TProps, TInstance, TGroupDescriptor extends CustomPropertyGroupDescriptor<TProps, TInstance, any>> { [key: string]: TGroupDescriptor; } const emptyObject: any = {}; export type TPropertyDescriptorConstructor<TProps, TInstance, TPropertyDescriptor extends CustomPropertyDescriptor<TProps, TInstance, any>> = new(groupName: string | null, updateFunction: PropertyUpdater<TProps, TInstance, any> | null, updateInitial: boolean, validatorAcceptor: ((validator: Validator<any>) => void) | null) => TPropertyDescriptor; export type TPropertyGroupDescriptorConstructor<TProps, TInstance, TPropertyGroupDescriptor extends CustomPropertyGroupDescriptor<TProps, TInstance, any>> = new(properties: string[], updateFunction: PropertyUpdater<TProps, TInstance, any>, updateInitial: boolean, validatorAcceptor: ((validator: IPropTypeMap) => void) | null) => TPropertyGroupDescriptor; const checkPropTypes: (typeSpecs: any, values: IPropMap, location: string, componentName: string, getStack?: () => (string | null)) => void = (PropTypes as any).checkPropTypes; export abstract class CustomDescriptor< // /** * @typedef {any} CustomDescriptor.TProps * @type CustomDescriptor.TProps * The expected property types to be used for createInstance and property updates. */ TProps = any, /** * @typedef {any} CustomDescriptor.TInstance * @type CustomDescriptor.TInstance * The instance type to be created and updated. */ TInstance = any, /** * @typedef {any} CustomDescriptor.TParent * @type CustomDescriptor.TParent * The parent types that the host instances can be mounted into. */ TParent = any, /** * @typedef {any} CustomDescriptor.TParent * @type CustomDescriptor.TParent * The types of objects the host instance will accept as children. */ TChild = any, TPropertyDescriptor extends CustomPropertyDescriptor<TProps, TInstance, any> = any, TPropertyGroupDescriptor extends CustomPropertyGroupDescriptor<TProps, TInstance, any> = any, TRoot = any> implements IHostDescriptor<TProps, TInstance, TParent, TChild, TRoot> { protected propertyDescriptors: IPropertyUpdaterMap<TProps, TInstance, TPropertyDescriptor>; protected propertyGroups: IPropertyGroupMap<TProps, TInstance, TPropertyGroupDescriptor>; private readonly propTypes: IPropTypeMap; constructor(private propertyDescriptorConstructor: TPropertyDescriptorConstructor<TProps, TInstance, TPropertyDescriptor> = CustomPropertyDescriptor as any, private propertyGroupDescriptorConstructor: TPropertyGroupDescriptorConstructor<TProps, TInstance, TPropertyGroupDescriptor> = CustomPropertyGroupDescriptor as any) { this.propertyDescriptors = {}; this.propertyGroups = {}; this.propTypes = {}; } public checkPropTypes(props: TProps, type: string): any { if (isNonProduction) { checkPropTypes(this.propTypes, props, "prop", type, React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactDebugCurrentFrame!.getStackAddendum); } } /** * * @param {TInstance} instance * @param {TUpdatePayload} updatePayload * @param {TProps} oldProps * @param {TProps} newProps * @return {boolean} Whether a repaint will be necessary */ public commitUpdate(instance: TInstance, updatePayload: TUpdatePayload, oldProps: TProps, newProps: TProps): boolean { const groupedUpdates: { [groupName: string]: { [propertyName: string]: any; }, } = {}; const groupNamesToUpdate: string[] = []; for (let keyIndex = 0; keyIndex < updatePayload.length; keyIndex += 2) { const key: string = updatePayload[keyIndex]; const value: any = updatePayload[keyIndex + 1]; this.updateProperty(key, groupedUpdates, groupNamesToUpdate, value, instance, oldProps, newProps, false); } for (const groupName of groupNamesToUpdate) { const newData = groupedUpdates[groupName]; const propertyGroup = this.propertyGroups[groupName]; propertyGroup.updateFunction(instance, newData, oldProps, newProps); } return false; } /** * This function should create a host instance using the properties. * @param {TProps} props * The properties of the element * @param {any} rootContainerInstance * The object that `MyRenderer.render` was called upon. * @return {TInstance} The new host instance */ public abstract createInstance(props: TProps, rootContainerInstance: any): TInstance; public willBeRemovedFromParent(instance: TInstance, parent: TParent): void { // NO-OP } // Use "parent" behaviour for containers to keep things simple. @final() public willBeRemovedFromContainer(instance: TInstance, container: TParent): void { if (isNonProduction) { throw new Error("Containers are treated as parents for " + (this as any).__proto__.constructor.name); } } @final() public insertInContainerBefore(instance: TInstance, container: TParent, before: any): void { if (isNonProduction) { throw new Error("Containers are treated as parents for " + (this as any).__proto__.constructor.name); } } @final() public appendToContainer(instance: TInstance, container: TParent): void { if (isNonProduction) { throw new Error("Containers are treated as parents for " + (this as any).__proto__.constructor.name); } } public applyInitialPropUpdates(instance: TInstance, props: TProps): void { const groupedUpdates: { [groupName: string]: { [propertyName: string]: any; }, } = {}; const allDescriptorNamesWithDefaultValuesMissingFromProps = Object.keys(this.propertyDescriptors) .filter((key: string) => { const descriptor = (this.propertyDescriptors[key] as any); return (props as any)[key] === undefined && descriptor.updateInitial && descriptor.defaultValue !== undefined; }); const groupNamesToUpdate: string[] = []; const keys = Object.keys(props); for (const key of keys) { if (key === "children") { continue; } const value = (props as any)[key]; this.updateProperty(key, groupedUpdates, groupNamesToUpdate, value, instance, emptyObject, props, true); } const updatedGroupsMap: { [idx: string]: boolean, } = {}; for (const groupName of groupNamesToUpdate) { updatedGroupsMap[groupName] = true; const propertyGroup = this.propertyGroups[groupName]; if (propertyGroup.updateInitial) { let newData; // fill in default values partially // TODO test this if (propertyGroup.defaultValue !== undefined) { newData = Object.assign({}, propertyGroup.defaultValue, groupedUpdates[groupName]); } else { newData = groupedUpdates[groupName]; } propertyGroup.updateFunction(instance, newData, emptyObject, props); } } allDescriptorNamesWithDefaultValuesMissingFromProps.forEach((name) => { const value = (this.propertyDescriptors[name] as any).defaultValue; this.updateProperty(name, groupedUpdates, null, value, instance, emptyObject, props, true); }); const allGroupNamesWithDefaultValuesMissingFromProps = Object.keys(this.propertyGroups) .filter((key: string) => { const groupDescriptor = (this.propertyGroups[key] as any); return !updatedGroupsMap[key] && groupDescriptor.updateInitial && groupDescriptor.defaultValue !== undefined; }); for (const groupName of allGroupNamesWithDefaultValuesMissingFromProps) { const newData = (this.propertyGroups[groupName] as any).defaultValue; this.propertyGroups[groupName].updateFunction(instance, newData, emptyObject, props); } } public appendInitialChild(instance: TInstance, child: TChild): void { /* */ } public appendChild(instance: TInstance, child: TChild): void { /* */ } public insertBefore(parentInstance: TInstance, childInstance: TChild, before: TChild): void { /* */ } public willBeAddedToParentBefore(instance: TInstance, parentInstance: TParent, before: any): void { this.willBeAddedToParent(instance, parentInstance); } // What does it mean for this object to be added into a parent, (as a last sibling)? // For example, geometries and materials can set parent.material = instance // and object types can ensure they are added as children // TODO ensure somehow that this does not get overwritten... // TODO google: "typescript (or javascript) final method or function" public willBeAddedToParent(instance: TInstance, parent: TParent): void { // NO-OP } public removeChild(instance: TInstance, child: TChild): void { // throw new Error("tried to remove a child from " + (instance as any)[r3rFiberSymbol].type); } /** * Allows you to define an update function for a single property. * @param {string} propName * The name of the property * @param {PropertyUpdater<TProps, TInstance, TProp>}updateFunction * Handle updating of the property here. * @param {boolean} updateInitial * Does this property need to be updated right after createInstance? */ public hasProp< // /** * The property type to be updated. */ TProp>(propName: string, updateFunction: PropertyUpdater<TProps, TInstance, TProp>, updateInitial: boolean = true): TPropertyDescriptor { if (this.propertyDescriptors[propName] !== undefined) { throw new Error(`Property type for ${(this as any).__proto__.constructor.name}#${propName} is already defined.`); } const propertyDescriptor = new this.propertyDescriptorConstructor( null, updateFunction, updateInitial, (validator: Validator<TProp>) => { this.propTypes[propName] = validator; }, ); this.propertyDescriptors[propName] = propertyDescriptor; return propertyDescriptor; } /** * Helps to update multiple properties at once. * @param {string[]} propNames * The names of the properties * @param {PropertyUpdater<TProps, TInstance, TPropMap>} updateFunction * Similar to `hasProp`s updateFunction, but it will expect a key-value pair of `propertyName` to `newValue` * @param {boolean} updateInitial * Handle updating of the property here. */ public hasPropGroup<TPropMap>(propNames: string[], updateFunction: PropertyUpdater<TProps, TInstance, TPropMap>, updateInitial: boolean = true): TPropertyGroupDescriptor { const groupName = propNames.join(","); this.propertyGroups[groupName] = new this.propertyGroupDescriptorConstructor( propNames, updateFunction, updateInitial, (validatorMap: IPropTypeMap) => { const missingKeys = propNames.concat().reduce((map, name) => { map[name] = true; return map; }, {} as { [index: string]: boolean }); const errors: string[] = []; Object.keys(validatorMap).forEach((propName: string) => { if (missingKeys[propName]) { missingKeys[propName] = false; } else { errors.push( `Found property type for unknown property "${propName}"`); } this.propTypes[propName] = validatorMap[propName]; }); propNames.forEach((propName) => { if (missingKeys[propName]) { errors.push(`Missing type for property "${propName}"`); } }); if (errors.length > 0) { throw new Error(`Property group for [${propNames .map((name) => `"${name}"`) .join(", ")}] has mismatching types:\n` + errors.join("\n")); } }, ); if (isNonProduction) { this.propertyGroups[groupName] .withErrorName((this as any).__proto__.constructor.name); } propNames.forEach((propName) => { if (typeof this.propertyDescriptors[propName] !== "undefined") { throw new Error(`Property type for ${propName} is already defined.`); } // wantsRepaint is false so that's OK? this.propertyDescriptors[propName] = new this.propertyDescriptorConstructor( groupName, null, false, null, ); }); return this.propertyGroups[groupName]; } protected removeProp(propName: string) { const propertyDescriptor: TPropertyDescriptor | undefined = this.propertyDescriptors[propName]; if (propertyDescriptor === undefined) { throw new Error(`Property type for ${(this as any).__proto__.constructor.name}#${propName} is not defined.`); } if (propertyDescriptor.groupName !== null) { // TODO GH-27 throw new Error("Cannot remove properties in groups yet."); } delete this.propertyDescriptors[propName]; } /** * Declares that this property can be updated with simple assignments. * @param {string} propName * The name of the property * @param {boolean} updateInitial * Does this property need to be updated right after createInstance? */ protected hasSimpleProp(propName: string, updateInitial: boolean = true): TPropertyDescriptor { return this.hasProp(propName, (instance: any, newValue: any): void => { (instance as any)[propName] = newValue; }, updateInitial); } protected updateProperty(propName: string, groupedUpdates: { [p: string]: { [p: string]: any } }, groupNamesToUpdate: null | (string[]), value: any, instance: TInstance, oldProps: TProps, newProps: TProps, isInitialUpdate: boolean): void { const propertyDescriptor: TPropertyDescriptor | undefined = this.propertyDescriptors[propName]; if (propertyDescriptor === undefined) { throw new Error(`Cannot find property descriptor for ${(this as any).__proto__.constructor.name}#${propName}`); } const groupName = propertyDescriptor.groupName; if (groupNamesToUpdate !== null && groupName !== null) { const propertyGroup: TPropertyGroupDescriptor = this.propertyGroups[groupName]; if (isInitialUpdate && !propertyGroup.updateInitial) { return; } if (groupedUpdates[groupName] === undefined) { groupNamesToUpdate.push(groupName); groupedUpdates[groupName] = {}; } if (value === null && propertyGroup.defaultValue !== undefined) { // TODO test partial default values value = propertyGroup.defaultValue[propName]; } groupedUpdates[groupName][propName] = value; } else { if (isInitialUpdate && !propertyDescriptor.updateInitial) { return; } const updateFunction = propertyDescriptor.updateFunction; if (updateFunction === null) { // TODO throw new Error("yarrg test this btw"); // throw new Error("Property updateFunction for " + // `${(instance as any)[r3rFiberSymbol].type}.${propName} is not defined.`); } if (value === null && propertyDescriptor.defaultValue !== undefined) { // TODO test restoring default values for individual property descriptors value = propertyDescriptor.defaultValue; } updateFunction(instance, value, oldProps, newProps); } } }
the_stack
import * as T from '.' import { AllType } from './AllType' import { analyze } from './analyze' import { getPlainAnalysisReport } from './getPlainAnalysisReport' const nonStrict = { strict: false, debug: false } const strict = { strict: true, debug: false } describe('any', () => { test('pass', () => { assertReportEquals(nonStrict, T.any, false, `The subject satisfies type any`) }) test('strict pass', () => { assertReportEquals(strict, T.any, false, `The subject strictly satisfies type any`) }) }) describe('unknown', () => { test('pass', () => { assertReportEquals(nonStrict, T.unknown, false, `The subject satisfies type unknown`) }) test('strict pass', () => { assertReportEquals(strict, T.unknown, false, `The subject strictly satisfies type unknown`) }) }) describe('undefined', () => { test('pass', () => { assertReportEquals(nonStrict, T.undefined, undefined, `The subject satisfies type undefined`) }) test('strict pass', () => { assertReportEquals(strict, T.undefined, undefined, `The subject strictly satisfies type undefined`) }) test('fail with explicit undefined', () => { assertReportEquals(nonStrict, T.undefined, false, `subject expects to be undefined but is actually false`) }) }) describe('null', () => { test('pass', () => { assertReportEquals(nonStrict, T.null, null, `The subject satisfies type null`) }) test('strict pass', () => { assertReportEquals(strict, T.null, null, `The subject strictly satisfies type null`) }) test('fail with explicit null', () => { assertReportEquals(nonStrict, T.null, false, `subject expects to be null but is actually false`) }) }) describe('boolean', () => { test('pass', () => { assertReportEquals(nonStrict, T.boolean, false, `The subject satisfies type boolean`) }) test('strict pass', () => { assertReportEquals(strict, T.boolean, true, `The subject strictly satisfies type boolean`) }) test('not boolean', () => { assertReportEquals(nonStrict, T.boolean, undefined, `subject expects to be boolean but is actually undefined`) }) test('specific boolean violation', () => { assertReportEquals(nonStrict, T.boolean.true, false, `subject expects to be true but is actually false`) }) test('optional boolean violation', () => { assertReportEquals(nonStrict, T.boolean.optional, null, `subject expects to be (boolean | undefined) but is actually null`) }) test('optional specific boolean violation', () => { assertReportEquals(nonStrict, T.boolean.optional.false, true, `subject expects to be (false | undefined) but is actually true`) }) }) describe('number', () => { test('not number', () => { assertReportEquals(nonStrict, T.number, undefined, `subject expects to be number but is actually undefined`) }) test('specific number violation', () => { assertReportEquals(nonStrict, T.number.create(1), false, `subject expects to be 1 but is actually false`) }) test('optional number violation', () => { assertReportEquals(nonStrict, T.number.optional, false, `subject expects to be (number | undefined) but is actually false`) }) test('optional specific number violation', () => { assertReportEquals(nonStrict, T.number.optional.create(2), false, `subject expects to be (2 | undefined) but is actually false`) }) test('number list violation', () => { assertReportEquals(nonStrict, T.number.list(1, 2, 3), false, `subject expects to be (1 | 2 | 3) but is actually false`) }) test('optional number list violation', () => { assertReportEquals(nonStrict, T.number.optional.list(1, 2, 3), false, `subject expects to be (1 | 2 | 3 | undefined) but is actually false`) }) }) describe('string', () => { test('not string', () => { assertReportEquals(nonStrict, T.string, undefined, `subject expects to be string but is actually undefined`) }) test('specific string violation', () => { assertReportEquals(nonStrict, T.string.create('a'), false, `subject expects to be 'a' but is actually false`) }) test('optional string violation', () => { assertReportEquals(nonStrict, T.string.optional, false, `subject expects to be (string | undefined) but is actually false`) }) test('optional specific string violation', () => { assertReportEquals(nonStrict, T.string.optional.create('b'), false, `subject expects to be ('b' | undefined) but is actually false`) }) test('string list violation', () => { assertReportEquals(nonStrict, T.string.list('a', 'b', 'c'), false, `subject expects to be ('a' | 'b' | 'c') but is actually false`) }) test('optional string list violation', () => { assertReportEquals(nonStrict, T.string.optional.list('a', 'b', 'c'), false, `subject expects to be ('a' | 'b' | 'c' | undefined) but is actually false`) }) }) describe('symbol', () => { test('not symbol', () => { assertReportEquals(nonStrict, T.symbol, undefined, `subject expects to be symbol but is actually undefined`) }) }) describe('bigint', () => { // test('not bigint', () => { // assertReportEquals(nonStrict, T.bigint, undefined, // `subject expects to be bigint but is actually undefined`) // }) }) describe('array', () => { test('base violation', () => { assertReportEquals(nonStrict, T.array, undefined, `subject expects to be Array<any> but is actually undefined`) }) test('specific array violation', () => { assertReportEquals(nonStrict, T.array.create(T.number), false, `subject expects to be Array<number> but is actually false`) }) test('optional array violation', () => { assertReportEquals(nonStrict, T.array.optional, false, `subject expects to be (Array<any> | undefined) but is actually false`) }) test('optional specific array violation', () => { assertReportEquals(nonStrict, T.array.optional.create(T.number), false, `subject expects to be (Array<number> | undefined) but is actually false`) }) }) describe('tuple', () => { test('specific tuple violation', () => { assertReportEquals( nonStrict, T.tuple.create(T.number.create(1), T.string.create('a')), false, `subject expects to be [1,'a'] but is actually false`) }) test('optional specific tuple violation', () => { assertReportEquals( nonStrict, T.tuple.optional.create(T.number), false, `subject expects to be ([number] | undefined) but is actually false`) }) test('missing entry', () => { assertReportEquals( nonStrict, T.tuple.create(T.null), [], [ `subject expects to be [null] but is actually []`, `subject[0] expects to be null but is actually undefined` ].join('\n') ) }) test('actual is object', () => { assertReportEquals( nonStrict, T.tuple.create(T.null, T.number), { a: 1 }, [ `subject expects to be [null,number] but is actually { a: 1 }` ].join('\n') ) }) test('strict with extra entry', () => { assertReportEquals( strict, T.tuple.create(T.null), [null, 1], [ `subject expects to be strictly [null] but is actually [null, 1]`, `index 1 should not contain any value` ].join('\n') ) }) test('strict with extra entries', () => { assertReportEquals( strict, T.tuple.create(T.null, T.number), [null, 1, 'a', false], [ `subject expects to be strictly [null,number] but is actually [null, 1, 'a', false]`, `indices 2,3 should not contain any value` ].join('\n') ) }) }) describe('object', () => { test('not object', () => { assertReportEquals(nonStrict, T.object, undefined, `subject expects to be object but is actually undefined`) }) test('specific object violation', () => { assertReportEquals( nonStrict, T.object.create({ a: T.null }), false, `subject expects to be { a: null } but is actually false`) }) test('optional specific object violation', () => { assertReportEquals( nonStrict, T.object.optional.create({ a: T.object.create({ b: T.string }) }), false, `subject expects to be ({ a: { b: string } } | undefined) but is actually false`) }) test('in object violation', () => { assertReportEquals( nonStrict, T.object.create({ a: T.string }), { a: 1 }, [ `subject expects to be { a: string } but is actually { a: 1 }`, `subject.a expects to be string but is actually 1` ].join('\n') ) }) test('nested object violation', () => { assertReportEquals( nonStrict, T.object.create({ a: T.object.create({ b: T.string }) }), { a: { b: 1 } }, [ `subject expects to be { a: { b: string } } but is actually { a: { b: 1 } }`, `subject.a expects to be { b: string } but is actually { b: 1 }`, `subject.a.b expects to be string but is actually 1` ].join('\n') ) }) test('- prop violation', () => { assertReportEquals( nonStrict, T.object.create({ 'a-b': T.string }), { 'a-b': 1 }, [ `subject expects to be { 'a-b': string } but is actually { 'a-b': 1 }`, `subject['a-b'] expects to be string but is actually 1` ].join('\n') ) }) test('strict with extra property', () => { assertReportEquals( strict, T.object.create({ a: T.number }), { a: 1, b: 2 }, [ `subject expects to be strictly { a: number } but is actually { a: 1, b: 2 }`, `property b should not contain any value` ].join('\n') ) }) test('strict with extra properties', () => { assertReportEquals( strict, T.object.create({ a: T.number }), { a: 1, b: 2, c: 'c' }, [ `subject expects to be strictly { a: number } but is actually { a: 1, b: 2, c: 'c' }`, `properties b,c should not contain any value` ].join('\n') ) }) test('object with array', () => { assertReportEquals( nonStrict, T.object.create({ a: T.array, b: T.string }), { a: [], b: 1 }, [ `subject expects to be { a: Array<any>, b: string } but is actually { a: [], b: 1 }`, `subject.b expects to be string but is actually 1` ].join('\n') ) }) }) describe('record', () => { test('specific record violation', () => { assertReportEquals( nonStrict, T.record.create(T.null), false, `subject expects to be Record<string, null> but is actually false`) }) test('optional specific record violation', () => { assertReportEquals( nonStrict, T.record.optional.create(T.record.create(T.string)), false, `subject expects to be (Record<string, Record<string, string>> | undefined) but is actually false`) }) test(`nested violation`, () => { assertReportEquals( nonStrict, T.record.optional.create(T.record.create(T.string)), { a: { b: 1 } }, `subject expects to be (Record<string, Record<string, string>> | undefined) but is actually { a: { b: 1 } }`) }) }) function assertReportEquals(options: analyze.Options, type: AllType, subject: unknown, report: string) { expect(getPlainAnalysisReport(analyze(options, type, subject))).toEqual(report) }
the_stack
import minimist = require("minimist"); import http = require("http"); import fs = require("fs"); import path = require("path"); import url = require("url"); import URL = url.URL; import child_process = require("child_process"); import os = require("os"); import crypto = require("crypto"); import { Readable, Writable } from "stream"; import { isBuffer, isString, isObject } from "util"; import { install, getErrorSource } from "source-map-support"; install(); const port = 8888; // harness.ts and webTestResults.html depend on this exact port number. const baseUrl = new URL(`http://localhost:${port}/`); const rootDir = path.dirname(__dirname); const useCaseSensitiveFileNames = isFileSystemCaseSensitive(); const defaultBrowser = os.platform() === "win32" ? "edge" : "chrome"; let browser: "edge" | "chrome" | "none" = defaultBrowser; let grep: string | undefined; let verbose = false; interface FileBasedTest { file: string; configurations?: FileBasedTestConfiguration[]; } interface FileBasedTestConfiguration { [setting: string]: string; } function isFileSystemCaseSensitive(): boolean { // win32\win64 are case insensitive platforms const platform = os.platform(); if (platform === "win32" || <string>platform === "win64") { return false; } // If this file exists under a different case, we must be case-insensitve. return !fs.existsSync(swapCase(__filename)); } function swapCase(s: string): string { return s.replace(/\w/g, (ch) => { const up = ch.toUpperCase(); return ch === up ? ch.toLowerCase() : up; }); } function hasLeadingSeparator(pathname: string) { const ch = pathname.charAt(0); return ch === "/" || ch === "\\"; } function ensureLeadingSeparator(pathname: string) { return hasLeadingSeparator(pathname) ? pathname : "/" + pathname; } function trimLeadingSeparator(pathname: string) { return hasLeadingSeparator(pathname) ? pathname.slice(1) : pathname; } function normalizeSlashes(path: string) { return path.replace(/\\+/g, "/"); } function hasTrailingSeparator(pathname: string) { const ch = pathname.charAt(pathname.length - 1); return ch === "/" || ch === "\\"; } function toServerPath(url: url.URL | string) { if (typeof url === "string") url = new URL(url, baseUrl); const pathname = decodeURIComponent(url.pathname); return path.join(rootDir, pathname); } function toClientPath(pathname: string) { pathname = normalizeSlashes(pathname); pathname = trimLeadingSeparator(pathname); const serverPath = path.resolve(rootDir, pathname); if (serverPath.slice(0, rootDir.length) !== rootDir) { return undefined; } let clientPath = serverPath.slice(rootDir.length); clientPath = ensureLeadingSeparator(clientPath); clientPath = normalizeSlashes(clientPath); return clientPath; } function flatMap<T, U>(array: T[], selector: (value: T) => U | U[]) { let result: U[] = []; for (const item of array) { const mapped = selector(item); if (Array.isArray(mapped)) { result = result.concat(mapped); } else { result.push(mapped); } } return result; } declare module "http" { interface IncomingHttpHeaders { "if-match"?: string; "if-none-match"?: string; "if-modified-since"?: string; "if-unmodified-since"?: string; "accept-charset"?: string; "accept-encoding"?: string; "range"?: string; } } function getQuality<T extends { quality?: number }>(value: T) { return value.quality === undefined ? 1 : value.quality; } function bestMatch<T, TPattern extends { quality?: number }>(value: T, patterns: TPattern[], isMatch: (value: T, pattern: TPattern) => boolean) { let match: TPattern | undefined; for (const pattern of patterns) { if (!isMatch(value, pattern)) continue; if (match === undefined || getQuality(pattern) > getQuality(match)) { match = pattern; } } return match; } const mediaTypeParser = /^([^\/]+)\/([^\/;]+)(?:;(.*))?$/; interface MediaType { type: string; subtype: string; parameters: Record<string, string>; charset?: string; quality?: number; } function parseMediaType(mediaType: string): MediaType { const match = mediaTypeParser.exec(mediaType); if (!match) throw new Error("Invalid media type"); const type = match[1].trim(); const subtype = match[2].trim(); if (type === "*" && subtype !== "*") throw new Error("Invalid media type"); const parameters: Record<string, string> = {}; let charset: string | undefined; let quality: number | undefined; if (match[3]) { for (const parameter of match[3].split(";")) { const pair = parameter.split("="); const name = pair[0].trim(); const value = pair[1].trim(); parameters[name] = value; if (name === "charset") charset = value; if (name === "q") quality = +value; } } return { type, subtype, parameters, charset, quality }; } function parseMediaTypes(value: string) { const mediaTypes: MediaType[] = []; for (const mediaRange of value.split(",")) { mediaTypes.push(parseMediaType(mediaRange)); } return mediaTypes; } function matchesMediaType(mediaType: MediaType, mediaTypePattern: MediaType) { if (mediaTypePattern.type === "*") return true; if (mediaTypePattern.type === mediaType.type) { if (mediaTypePattern.subtype === "*") return true; if (mediaTypePattern.subtype === mediaType.subtype) return true; } return false; } interface StringWithQuality { value: string; quality?: number; } const stringWithQualityParser = /^([^;]+)(;\s*q\s*=\s*([^\s]+)\s*)?$/; function parseStringWithQuality(value: string) { const match = stringWithQualityParser.exec(value); if (!match) throw new Error("Invalid header value"); return { value: match[1].trim(), quality: match[2] ? +match[2] : undefined }; } function parseStringsWithQuality(value: string) { const charsets: StringWithQuality[] = []; for (const charset of value.split(",")) { charsets.push(parseStringWithQuality(charset)); } return charsets; } function matchesCharSet(charset: string, charsetPattern: StringWithQuality) { return charsetPattern.value === "*" || charsetPattern.value === charset; } function computeETag(stats: fs.Stats) { return JSON.stringify(crypto .createHash("sha1") .update(JSON.stringify({ dev: stats.dev, ino: stats.ino, mtime: stats.mtimeMs, size: stats.size })) .digest("base64")); } function tryParseETags(value: string | undefined): "*" | string[] | undefined { if (!value) return undefined; if (value === "*") return value; const etags: string[] = []; for (const etag of value.split(",")) { etags.push(etag.trim()); } return etags; } function matchesETag(etag: string | undefined, condition: "*" | string[] | undefined) { if (!condition) return true; if (!etag) return false; return condition === "*" || condition.indexOf(etag) >= 0; } function tryParseDate(value: string | undefined) { return value ? new Date(value) : undefined; } interface ByteRange { start: number; end: number; } const byteRangeParser = /^\s*(\d+)\s*-\s*(\d+)\s*$/; function tryParseByteRange(value: string, contentLength: number): ByteRange | undefined { const match = byteRangeParser.exec(value); const firstBytePos = match && match[1] ? +match[1] : undefined; const lastBytePos = match && match[2] ? +match[2] : undefined; if (firstBytePos !== undefined && lastBytePos !== undefined) { if (lastBytePos < firstBytePos) return undefined; return { start: firstBytePos, end: lastBytePos + 1 }; } if (firstBytePos !== undefined) return { start: firstBytePos, end: contentLength }; if (lastBytePos !== undefined) return { start: contentLength - lastBytePos, end: contentLength }; return undefined; } function tryParseByteRanges(value: string, contentLength: number): ByteRange[] | undefined { if (!value.startsWith("bytes=")) return; const ranges: ByteRange[] = []; for (const range of value.slice(6).split(",")) { const byteRange = tryParseByteRange(range, contentLength); if (byteRange === undefined) return undefined; if (byteRange.start >= contentLength) continue; ranges.push(byteRange); } return ranges; } function once<T extends (...args: any[]) => void>(callback: T): T; function once(callback: (...args: any[]) => void) { let called = false; return (...args: any[]) => { if (called) return; called = true; callback(...args); }; } function mkdirp(dirname: string, callback: (err: NodeJS.ErrnoException | null) => void) { fs.mkdir(dirname, err => { if (err && err.code === "EEXIST") err = null; if (err && err.code === "ENOENT") { const parentdir = path.dirname(dirname); if (!parentdir || parentdir === dirname) return callback(err); return mkdirp(parentdir, err => { if (err) return callback(err); return fs.mkdir(dirname, callback); }); } return callback(err); }); } function getAccessibleFileSystemEntries(pathname: string) { try { const entries = fs.readdirSync(pathname).sort(); const files: string[] = []; const directories: string[] = []; for (const entry of entries) { // This is necessary because on some file system node fails to exclude // "." and "..". See https://github.com/nodejs/node/issues/4002 if (entry === "." || entry === "..") { continue; } const name = path.join(pathname, entry); let stat: fs.Stats; try { stat = fs.statSync(name); } catch (e) { continue; } if (stat.isFile()) { files.push(entry); } else if (stat.isDirectory()) { directories.push(entry); } } return { files, directories }; } catch (e) { return { files: [], directories: [] }; } } function guessMediaType(pathname: string) { switch (path.extname(pathname).toLowerCase()) { case ".html": return "text/html; charset=utf-8"; case ".css": return "text/css; charset=utf-8"; case ".js": return "application/javascript; charset=utf-8"; case ".mjs": return "application/javascript; charset=utf-8"; case ".jsx": return "text/jsx; charset=utf-8"; case ".ts": return "text/plain; charset=utf-8"; case ".tsx": return "text/plain; charset=utf-8"; case ".json": return "text/plain; charset=utf-8"; case ".map": return "application/json; charset=utf-8"; default: return "application/octet-stream"; } } function readContent(req: http.ServerRequest, callback: (err: NodeJS.ErrnoException | null, content: string | null) => void) { const chunks: Buffer[] = []; const done = once((err: NodeJS.ErrnoException | null) => { if (err) return callback(err, /*content*/ null); let content: string | null = null; try { content = Buffer.concat(chunks).toString("utf8"); } catch (e) { err = e; } return callback(err, content); }); req.on("data", chunk => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf8"))); req.on("error", err => done(err)); req.on("end", () => done(/*err*/ null)); } function saveToFile(file: string, readable: Readable, callback: (err: NodeJS.ErrnoException | null) => void) { callback = once(callback); const writable = fs.createWriteStream(file, { autoClose: true }); writable.on("error", err => callback(err)); readable.on("end", () => callback(/*err*/ null)); readable.pipe(writable, { end: true }); } function sendContent(res: http.ServerResponse, statusCode: number, content: string | Buffer, contentType: string): void; function sendContent(res: http.ServerResponse, statusCode: number, content: Readable, contentType: string, contentLength: number): void; function sendContent(res: http.ServerResponse, statusCode: number, content: string | Buffer | Readable, contentType: string, contentLength?: number) { res.statusCode = statusCode; res.setHeader("Content-Type", contentType); if (isString(content)) { res.setHeader("Content-Length", Buffer.byteLength(content, "utf8")); res.end(content, "utf8"); } else if (isBuffer(content)) { res.setHeader("Content-Length", content.byteLength); res.end(content); } else { if (contentLength !== undefined) res.setHeader("Content-Length", contentLength); content.on("error", e => sendInternalServerError(res, e)); content.pipe(res, { end: true }); } } function sendJson(res: http.ServerResponse, statusCode: number, value: any) { try { sendContent(res, statusCode, JSON.stringify(value), "application/json; charset=utf-8"); } catch (e) { sendInternalServerError(res, e); } } function sendCreated(res: http.ServerResponse, location?: string, etag?: string) { res.statusCode = 201; if (location) res.setHeader("Location", location); if (etag) res.setHeader("ETag", etag); res.end(); } function sendNoContent(res: http.ServerResponse) { res.statusCode = 204; res.end(); } function sendFound(res: http.ServerResponse, location: string) { res.statusCode = 302; res.setHeader("Location", location); res.end(); } function sendNotModified(res: http.ServerResponse) { res.statusCode = 304; res.end(); } function sendBadRequest(res: http.ServerResponse) { res.statusCode = 400; res.end(); } function sendNotFound(res: http.ServerResponse) { res.statusCode = 404; res.end(); } function sendMethodNotAllowed(res: http.ServerResponse, allowedMethods: string[]) { res.statusCode = 405; res.setHeader("Allow", allowedMethods); res.end(); } function sendNotAcceptable(res: http.ServerResponse) { res.statusCode = 406; res.end(); } function sendPreconditionFailed(res: http.ServerResponse) { res.statusCode = 412; res.end(); } function sendUnsupportedMediaType(res: http.ServerResponse) { res.statusCode = 415; res.end(); } function sendRangeNotSatisfiable(res: http.ServerResponse) { res.statusCode = 416; res.end(); } function sendInternalServerError(res: http.ServerResponse, error: Error) { console.error(error); return sendContent(res, /*statusCode*/ 500, error.stack, "text/plain; charset=utf8"); } function sendNotImplemented(res: http.ServerResponse) { res.statusCode = 501; res.end(); } function shouldIgnoreCache(url: URL) { switch (url.pathname) { case "/built/local/bundle.js": case "/built/local/bundle.js.map": return true; default: return false; } } function isAcceptable(req: http.ServerRequest, contentType: string) { const mediaType = parseMediaType(contentType); return isAcceptableMediaType(req, mediaType) && isAcceptableCharSet(req, mediaType) && isAcceptableEncoding(req); } function isAcceptableMediaType(req: http.ServerRequest, mediaType: MediaType) { if (!req.headers.accept) return true; const acceptedMediaType = bestMatch(mediaType, parseMediaTypes(req.headers.accept), matchesMediaType); return acceptedMediaType ? getQuality(acceptedMediaType) > 0 : false; } function isAcceptableCharSet(req: http.ServerRequest, mediaType: MediaType) { if (!req.headers["accept-charset"]) return true; const acceptedCharSet = bestMatch(mediaType.charset || "utf-8", parseStringsWithQuality(req.headers["accept-charset"]), matchesCharSet); return acceptedCharSet ? getQuality(acceptedCharSet) > 0 : false; } function isAcceptableEncoding(req: http.ServerRequest) { if (!req.headers["accept-encoding"]) return true; const acceptedEncoding = bestMatch(/*value*/ undefined, parseStringsWithQuality(req.headers["accept-encoding"]), (_, pattern) => pattern.value === "*" || pattern.value === "identity"); return acceptedEncoding ? getQuality(acceptedEncoding) > 0 : true; } function shouldSendNotModified(req: http.ServerRequest, stats: fs.Stats, etag: string) { const ifNoneMatch = tryParseETags(req.headers["if-none-match"]); if (ifNoneMatch) return matchesETag(etag, ifNoneMatch); const ifModifiedSince = tryParseDate(req.headers["if-modified-since"]); if (ifModifiedSince) return stats.mtime.getTime() <= ifModifiedSince.getTime(); return false; } function shouldSendPreconditionFailed(req: http.ServerRequest, stats: fs.Stats, etag: string) { const ifMatch = tryParseETags(req.headers["if-match"]); if (ifMatch && !matchesETag(etag, ifMatch)) return true; const ifUnmodifiedSince = tryParseDate(req.headers["if-unmodified-since"]); if (ifUnmodifiedSince && stats.mtime.getTime() > ifUnmodifiedSince.getTime()) return true; return false; } function handleGetRequest(req: http.ServerRequest, res: http.ServerResponse) { const url = new URL(req.url, baseUrl); if (url.pathname === "/") { url.pathname = "/tests/webTestResults.html"; return sendFound(res, url.toString()); } const file = toServerPath(url); fs.stat(file, (err, stats) => { try { if (err) { if (err.code === "ENOENT") return sendNotFound(res); return sendInternalServerError(res, err); } if (stats && stats.isFile()) { const contentType = guessMediaType(file); if (!isAcceptable(req, contentType)) return sendNotAcceptable(res); const etag = computeETag(stats); if (shouldSendNotModified(req, stats, etag)) return sendNotModified(res); if (shouldSendPreconditionFailed(req, stats, etag)) return sendPreconditionFailed(res); if (shouldIgnoreCache(url)) res.setHeader("Cache-Control", "no-store"); res.setHeader("Last-Modified", stats.mtime.toUTCString()); res.setHeader("ETag", etag); res.setHeader("Content-Type", contentType); res.setHeader("Accept-Ranges", "bytes"); const ranges = req.headers.range && tryParseByteRanges(req.headers.range, stats.size); if (ranges && ranges.length === 0) return sendRangeNotSatisfiable(res); let start: number | undefined; let end: number | undefined; if (ranges && ranges.length === 1) { start = ranges[0].start; end = ranges[0].end; if (start >= stats.size || end > stats.size) return sendRangeNotSatisfiable(res); res.statusCode = 206; res.setHeader("Content-Length", end - start); res.setHeader("Content-Range", `bytes ${start}-${end - 1}/${stats.size}`); } else { res.statusCode = 200; res.setHeader("Content-Length", stats.size); } if (req.method === "HEAD") return res.end(); const readable = fs.createReadStream(file, { start, end, autoClose: true }); readable.on("error", err => sendInternalServerError(res, err)); readable.pipe(res, { end: true }); } else { if (req.headers["if-match"] === "*") return sendPreconditionFailed(res); return sendNotFound(res); } } catch (e) { return sendInternalServerError(res, e); } }); } function handlePutRequest(req: http.ServerRequest, res: http.ServerResponse) { if (req.headers["content-encoding"]) return sendUnsupportedMediaType(res); if (req.headers["content-range"]) return sendNotImplemented(res); const file = toServerPath(req.url); fs.stat(file, (err, stats) => { try { if (err && err.code !== "ENOENT") return sendInternalServerError(res, err); if (stats && !stats.isFile()) return sendMethodNotAllowed(res, []); return mkdirp(path.dirname(file), err => { if (err) return sendInternalServerError(res, err); try { const writable = fs.createWriteStream(file, { autoClose: true }); writable.on("error", err => sendInternalServerError(res, err)); writable.on("finish", () => { if (stats) return sendNoContent(res); fs.stat(file, (err, stats) => { if (err) return sendInternalServerError(res, err); return sendCreated(res, toClientPath(file), computeETag(stats)); }); }); req.pipe(writable, { end: true }); return; } catch (e) { return sendInternalServerError(res, e); } }); } catch (e) { return sendInternalServerError(res, e); } }); } function handleDeleteRequest(req: http.ServerRequest, res: http.ServerResponse) { const file = toServerPath(req.url); fs.stat(file, (err, stats) => { try { if (err && err.code !== "ENOENT") return sendInternalServerError(res, err); if (!stats) return sendNotFound(res); if (stats.isFile()) return fs.unlink(file, handleResult); if (stats.isDirectory()) return fs.rmdir(file, handleResult); return sendNotFound(res); function handleResult(err: NodeJS.ErrnoException) { if (err && err.code !== "ENOENT") return sendInternalServerError(res, err); if (err) return sendNotFound(res); return sendNoContent(res); } } catch (e) { return sendInternalServerError(res, e); } }); } function handleOptionsRequest(req: http.ServerRequest, res: http.ServerResponse) { res.setHeader("X-Case-Sensitivity", useCaseSensitiveFileNames ? "CS" : "CI"); return sendNoContent(res); } function handleApiResolve(req: http.ServerRequest, res: http.ServerResponse) { readContent(req, (err, content) => { try { if (err) return sendInternalServerError(res, err); if (!content) return sendBadRequest(res); const serverPath = toServerPath(content); const clientPath = toClientPath(serverPath); if (clientPath === undefined) return sendBadRequest(res); return sendContent(res, /*statusCode*/ 200, clientPath, /*contentType*/ "text/plain;charset=utf-8"); } catch (e) { return sendInternalServerError(res, e); } }); } function handleApiEnumerateTestFiles(req: http.ServerRequest, res: http.ServerResponse) { readContent(req, (err, content) => { try { if (err) return sendInternalServerError(res, err); if (!content) return sendBadRequest(res); const tests: (string | FileBasedTest)[] = enumerateTestFiles(content); return sendJson(res, /*statusCode*/ 200, tests); } catch (e) { return sendInternalServerError(res, e); } }); } function enumerateTestFiles(runner: string) { switch (runner) { case "conformance": case "compiler": return listFiles(`tests/cases/${runner}`, /*serverDirname*/ undefined, /\.tsx?$/, { recursive: true }).map(parseCompilerTestConfigurations); case "fourslash": return listFiles(`tests/cases/fourslash`, /*serverDirname*/ undefined, /\.ts/i, { recursive: false }); case "fourslash-shims": return listFiles(`tests/cases/fourslash/shims`, /*serverDirname*/ undefined, /\.ts/i, { recursive: false }); case "fourslash-shims-pp": return listFiles(`tests/cases/fourslash/shims-pp`, /*serverDirname*/ undefined, /\.ts/i, { recursive: false }); case "fourslash-server": return listFiles(`tests/cases/fourslash/server`, /*serverDirname*/ undefined, /\.ts/i, { recursive: false }); default: throw new Error(`Runner '${runner}' not supported in browser tests.`); } } // Regex for parsing options in the format "@Alpha: Value of any sort" const optionRegex = /^[\/]{2}\s*@(\w+)\s*:\s*([^\r\n]*)/gm; // multiple matches on multiple lines function extractCompilerSettings(content: string): Record<string, string> { const opts: Record<string, string> = {}; let match: RegExpExecArray; while ((match = optionRegex.exec(content)) !== null) { opts[match[1]] = match[2].trim(); } return opts; } function splitVaryBySettingValue(text: string): string[] | undefined { if (!text) return undefined; const entries = text.split(/,/).map(s => s.trim().toLowerCase()).filter(s => s.length > 0); return entries && entries.length > 1 ? entries : undefined; } function computeFileBasedTestConfigurationVariations(configurations: FileBasedTestConfiguration[], variationState: FileBasedTestConfiguration, varyByEntries: [string, string[]][], offset: number) { if (offset >= varyByEntries.length) { // make a copy of the current variation state configurations.push({ ...variationState }); return; } const [varyBy, entries] = varyByEntries[offset]; for (const entry of entries) { // set or overwrite the variation variationState[varyBy] = entry; computeFileBasedTestConfigurationVariations(configurations, variationState, varyByEntries, offset + 1); } } function getFileBasedTestConfigurations(settings: Record<string, string>, varyBy: string[]): FileBasedTestConfiguration[] | undefined { let varyByEntries: [string, string[]][] | undefined; for (const varyByKey of varyBy) { if (Object.prototype.hasOwnProperty.call(settings, varyByKey)) { const entries = splitVaryBySettingValue(settings[varyByKey]); if (entries) { if (!varyByEntries) varyByEntries = []; varyByEntries.push([varyByKey, entries]); } } } if (!varyByEntries) return undefined; const configurations: FileBasedTestConfiguration[] = []; computeFileBasedTestConfigurationVariations(configurations, {}, varyByEntries, 0); return configurations; } function parseCompilerTestConfigurations(file: string): FileBasedTest { const content = fs.readFileSync(path.join(rootDir, file), "utf8"); const settings = extractCompilerSettings(content); const configurations = getFileBasedTestConfigurations(settings, ["module", "target"]); return { file, configurations }; } function handleApiListFiles(req: http.ServerRequest, res: http.ServerResponse) { readContent(req, (err, content) => { try { if (err) return sendInternalServerError(res, err); if (!content) return sendBadRequest(res); const serverPath = toServerPath(content); const files = listFiles(content, serverPath, /*spec*/ undefined, { recursive: true }); return sendJson(res, /*statusCode*/ 200, files); } catch (e) { return sendInternalServerError(res, e); } }); } function listFiles(clientDirname: string, serverDirname: string = path.resolve(rootDir, clientDirname), spec?: RegExp, options: { recursive?: boolean } = {}): string[] { const files: string[] = []; visit(serverDirname, clientDirname, files); return files; function visit(dirname: string, relative: string, results: string[]) { const { files, directories } = getAccessibleFileSystemEntries(dirname); for (const file of files) { if (!spec || file.match(spec)) { results.push(path.join(relative, file)); } } for (const directory of directories) { if (options.recursive) { visit(path.join(dirname, directory), path.join(relative, directory), results); } } } } function handleApiDirectoryExists(req: http.ServerRequest, res: http.ServerResponse) { readContent(req, (err, content) => { try { if (err) return sendInternalServerError(res, err); if (!content) return sendBadRequest(res); const serverPath = toServerPath(content); fs.stat(serverPath, (err, stats) => { try { if (err && err.code !== "ENOENT") return sendInternalServerError(res, err); return sendJson(res, /*statusCode*/ 200, !!stats && stats.isDirectory()); } catch (e) { return sendInternalServerError(res, e); } }); } catch (e) { return sendInternalServerError(res, e); } }); } function handleApiGetAccessibleFileSystemEntries(req: http.ServerRequest, res: http.ServerResponse) { readContent(req, (err, content) => { try { if (err) return sendInternalServerError(res, err); if (!content) return sendBadRequest(res); const serverPath = toServerPath(content); return sendJson(res, /*statusCode*/ 200, getAccessibleFileSystemEntries(serverPath)); } catch (e) { return sendInternalServerError(res, e); } }); } function handlePostRequest(req: http.ServerRequest, res: http.ServerResponse) { // API responses should not be cached res.setHeader("Cache-Control", "no-cache"); switch (new URL(req.url, baseUrl).pathname) { case "/api/resolve": return handleApiResolve(req, res); case "/api/listFiles": return handleApiListFiles(req, res); case "/api/enumerateTestFiles": return handleApiEnumerateTestFiles(req, res); case "/api/directoryExists": return handleApiDirectoryExists(req, res); case "/api/getAccessibleFileSystemEntries": return handleApiGetAccessibleFileSystemEntries(req, res); default: return sendMethodNotAllowed(res, ["HEAD", "GET", "PUT", "DELETE", "OPTIONS"]); } } function handleRequest(req: http.ServerRequest, res: http.ServerResponse) { try { switch (req.method) { case "HEAD": case "GET": return handleGetRequest(req, res); case "PUT": return handlePutRequest(req, res); case "POST": return handlePostRequest(req, res); case "DELETE": return handleDeleteRequest(req, res); case "OPTIONS": return handleOptionsRequest(req, res); default: return sendMethodNotAllowed(res, ["HEAD", "GET", "PUT", "POST", "DELETE"]); } } catch (e) { return sendInternalServerError(res, e); } } function startServer() { console.log(`Static file server running at\n => http://localhost:${port}/\nCTRL + C to shutdown`); return http.createServer(handleRequest).listen(port); } const REG_COLUMN_PADDING = 4; function queryRegistryValue(keyPath: string, callback: (error: Error | null, value: string) => void) { const args = ["query", keyPath]; child_process.execFile("reg", ["query", keyPath, "/ve"], { encoding: "utf8" }, (error, stdout) => { if (error) return callback(error, null); const valueLine = stdout.replace(/^\r\n.+?\r\n|\r\n\r\n$/g, ""); if (!valueLine) { return callback(new Error("Unable to retrieve value."), null); } const valueNameColumnOffset = REG_COLUMN_PADDING; if (valueLine.lastIndexOf("(Default)", valueNameColumnOffset) !== valueNameColumnOffset) { return callback(new Error("Unable to retrieve value."), null); } const dataTypeColumnOffset = valueNameColumnOffset + "(Default)".length + REG_COLUMN_PADDING; if (valueLine.lastIndexOf("REG_SZ", dataTypeColumnOffset) !== dataTypeColumnOffset) { return callback(new Error("Unable to retrieve value."), null); } const valueColumnOffset = dataTypeColumnOffset + "REG_SZ".length + REG_COLUMN_PADDING; const value = valueLine.slice(valueColumnOffset); return callback(null, value); }); } interface Browser { description: string; command: string; } function createBrowserFromPath(path: string): Browser { return { description: path, command: path }; } function getChromePath(callback: (error: Error | null, browser: Browser | string | null) => void) { switch (os.platform()) { case "win32": return queryRegistryValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe", (error, value) => { if (error) return callback(null, "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"); return callback(null, createBrowserFromPath(value)); }); case "darwin": return callback(null, "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"); case "linux": return callback(null, "/opt/google/chrome/chrome"); default: return callback(new Error(`Chrome location is unknown for platform '${os.platform()}'`), null); } } function getEdgePath(callback: (error: Error | null, browser: Browser | null) => void) { switch (os.platform()) { case "win32": return callback(null, { description: "Microsoft Edge", command: "cmd /c start microsoft-edge:%1" }); default: return callback(new Error(`Edge location is unknown for platform '${os.platform()}'`), null); } } function getBrowserPath(callback: (error: Error | null, browser: Browser | null) => void) { switch (browser) { case "chrome": return getChromePath(afterGetBrowserPath); case "edge": return getEdgePath(afterGetBrowserPath); default: return callback(new Error(`Browser location is unknown for '${browser}'`), null); } function afterGetBrowserPath(error: Error | null, browser: Browser | string | null) { if (error) return callback(error, null); if (typeof browser === "object") return callback(null, browser); return fs.stat(browser, (error, stats) => { if (!error && stats.isFile()) { return callback(null, createBrowserFromPath(browser)); } if (browser === "chrome") return callback(null, createBrowserFromPath("chrome")); return callback(new Error(`Browser location is unknown for '${browser}'`), null); }); } } function startClient(server: http.Server) { let browserPath: string; if (browser === "none") { return; } getBrowserPath((error, browser) => { if (error) return console.error(error); console.log(`Using browser: ${browser.description}`); const queryString = grep ? `?grep=${grep}` : ""; const args = [`http://localhost:${port}/tests/webTestResults.html${queryString}`]; if (browser.command.indexOf("%") === -1) { child_process.spawn(browser.command, args); } else { const command = browser.command.replace(/%(\d+)/g, (_, offset) => args[+offset - 1]); child_process.exec(command); } }); } function printHelp() { console.log("Runs an http server on port 8888, looking for tests folder in the current directory\n"); console.log("Syntax: node webTestServer.js [browser] [tests] [--verbose]\n"); console.log("Options:"); console.log(" <browser> The browser to launch. One of 'edge', 'chrome', or 'none' (default 'edge' on Windows, otherwise `chrome`)."); console.log(" <tests> A regular expression to pass to Mocha."); console.log(" --verbose Enables verbose logging."); } function parseCommandLine(args: string[]) { const parsed = minimist(args, { boolean: ["help", "verbose"] }); if (parsed.help) { printHelp(); return false; } if (parsed.verbose) { verbose = true; } const [parsedBrowser = defaultBrowser, parsedGrep, ...unrecognized] = parsed._; if (parsedBrowser !== "edge" && parsedBrowser !== "chrome" && parsedBrowser !== "none") { console.log(`Unrecognized browser '${parsedBrowser}', expected 'edge', 'chrome', or 'none'.`); return false; } if (unrecognized.length > 0) { console.log(`Unrecognized argument: ${unrecognized[0]}`); return false; } browser = parsedBrowser; grep = parsedGrep; return true; } function log(msg: string) { if (verbose) { console.log(msg); } } function main() { if (parseCommandLine(process.argv.slice(2))) { startClient(startServer()); } } main(); // tslint:enable:no-null-keyword
the_stack
import { Workbook } from './../src/workbook'; import './../node_modules/es6-promise/dist/es6-promise'; import { Utils } from './../spec/utils.spec'; describe('ExcelCreation', () => { // afterEach(function () { // sleep(3000); // }); // function sleep(millSecs: any) { // let date: any = new Date(); // let curDate: any = null; // do { curDate = new Date(); } // while (curDate - date < millSecs); // } //Methods testcase it('grouping', (done) => { let book: Workbook = new Workbook({ worksheets: [ { rows: [ /*row -> 1*/ { index: 7, grouping: { outlineLevel: 1, isHidden: true } }, /*row -> 1*/ { index: 8, grouping: { outlineLevel: 1, isHidden: true } }, /*row -> 1*/ { index: 9, grouping: { outlineLevel: 1, isHidden: true } }, /*row -> 1*/ { index: 10, grouping: { outlineLevel: 1, isHidden: true } }, /*row -> 1*/ { index: 11, grouping: { isCollapsed: true } } ] }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'grouping.xlsx'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); }); it('grouping-withoutHidden', (done) => { let book: Workbook = new Workbook({ worksheets: [ { rows: [ /*row -> 1*/ { index: 7, grouping: { outlineLevel: 1 } }, /*row -> 1*/ { index: 8, grouping: { outlineLevel: 1 } }, /*row -> 1*/ { index: 9, grouping: { outlineLevel: 1 } }, /*row -> 1*/ { index: 10, grouping: { outlineLevel: 1 } }, /*row -> 1*/ { index: 11, grouping: { isCollapsed: true } } ] }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'grouping-withouthidden.xlsx'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); }); it('SummaryBelow', (done) => { let book: Workbook = new Workbook({ worksheets: [ { pageSetup: { isSummaryRowBelow: false }, rows: [ /*row -> 1*/ { index: 7, grouping: { outlineLevel: 1, isHidden: true } }, /*row -> 1*/ { index: 8, grouping: { outlineLevel: 1, isHidden: true } }, /*row -> 1*/ { index: 9, grouping: { outlineLevel: 1, isHidden: true } }, /*row -> 1*/ { index: 10, grouping: { outlineLevel: 1, isHidden: true } }, /*row -> 1*/ { index: 11, grouping: { isCollapsed: true } } ] }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'SummaryBelow.xlsx'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); }); it('summaryRow-1', (done) => { let book: Workbook = new Workbook({ worksheets: [ { pageSetup: { isSummaryRowBelow: false }, rows: [ /*row -> 1*/ { index: 3, grouping: { isCollapsed: true } }, /*row -> 1*/ { index: 4, grouping: { outlineLevel: 1, isHidden: true } }, /*row -> 1*/ { index: 5, grouping: { outlineLevel: 1, isHidden: true, isCollapsed: true } }, /*row -> 1*/ { index: 6, grouping: { outlineLevel: 2, isHidden: true } }, /*row -> 1*/ { index: 7, grouping: { outlineLevel: 2, isHidden: true } }, /*row -> 1*/ { index: 8, grouping: { outlineLevel: 2, isHidden: true, isCollapsed: true } }, /*row -> 1*/ { index: 9, grouping: { outlineLevel: 3, isHidden: true } }, /*row -> 1*/ { index: 10, grouping: { outlineLevel: 3, isHidden: true } }, /*row -> 1*/ { index: 11, grouping: { outlineLevel: 3, isHidden: true } }, /*row -> 1*/ { index: 12, grouping: { outlineLevel: 3, isHidden: true } }, /*row -> 1*/ { index: 13, grouping: { outlineLevel: 3, isHidden: true } }, /*row -> 1*/ { index: 14, grouping: { outlineLevel: 3, isHidden: true } }, /*row -> 1*/ { index: 15, grouping: { outlineLevel: 3, isHidden: true } }, /*row -> 1*/ { index: 16, grouping: { outlineLevel: 3, isHidden: true } }, /*row -> 1*/ { index: 17, grouping: { outlineLevel: 2, isHidden: true, isCollapsed: true } }, /*row -> 1*/ { index: 18, grouping: { outlineLevel: 1, isHidden: true, isCollapsed: true } }, /*row -> 1*/ { index: 19, grouping: { isCollapsed: true } } ] }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'summaryRow-1.xlsx'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); }); it('grouping-1', (done) => { let book: Workbook = new Workbook({ worksheets: [ { rows: [ /*row -> 1*/ { index: 3, grouping: { isCollapsed: true } }, /*row -> 1*/ { index: 4, grouping: { outlineLevel: 1, isHidden: true } }, /*row -> 1*/ { index: 5, grouping: { outlineLevel: 1, isHidden: true, isCollapsed: true } }, /*row -> 1*/ { index: 6, grouping: { outlineLevel: 2, isHidden: true } }, /*row -> 1*/ { index: 7, grouping: { outlineLevel: 2, isHidden: true } }, /*row -> 1*/ { index: 8, grouping: { outlineLevel: 2, isHidden: true, isCollapsed: true } }, /*row -> 1*/ { index: 9, grouping: { outlineLevel: 3, isHidden: true } }, /*row -> 1*/ { index: 10, grouping: { outlineLevel: 3, isHidden: true } }, /*row -> 1*/ { index: 11, grouping: { outlineLevel: 3, isHidden: true } }, /*row -> 1*/ { index: 12, grouping: { outlineLevel: 3, isHidden: true } }, /*row -> 1*/ { index: 13, grouping: { outlineLevel: 3, isHidden: true } }, /*row -> 1*/ { index: 14, grouping: { outlineLevel: 3, isHidden: true } }, /*row -> 1*/ { index: 15, grouping: { outlineLevel: 3, isHidden: true } }, /*row -> 1*/ { index: 16, grouping: { outlineLevel: 3, isHidden: true } }, /*row -> 1*/ { index: 17, grouping: { outlineLevel: 2, isHidden: true, isCollapsed: true } }, /*row -> 1*/ { index: 18, grouping: { outlineLevel: 1, isHidden: true, isCollapsed: true } }, /*row -> 1*/ { index: 19, grouping: { isCollapsed: true } } ] }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'grouping-1.xlsx'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); }); it('SummaryBelow-Coverage', (done) => { let book: Workbook = new Workbook({ worksheets: [ { pageSetup: { isSummaryRowBelow: undefined }, rows: [ /*row -> 1*/ { index: 7, grouping: { outlineLevel: 1, isHidden: true } }, /*row -> 1*/ { index: 8, grouping: { outlineLevel: 1, isHidden: true } }, /*row -> 1*/ { index: 9, grouping: { outlineLevel: 1, isHidden: true } }, /*row -> 1*/ { index: 10, grouping: { outlineLevel: 1, isHidden: true } }, /*row -> 1*/ { index: 11, grouping: { isCollapsed: true } } ] }] }, 'xlsx'); book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'SummaryBelow-Coverage.xlsx'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); }); });
the_stack
import { Point } from './point'; import { isArray, isNumber, isString } from '@xiao-ai/utils'; type MatrixInput = number[][] | Matrix; /** * 矩阵类 * @class Matrix */ export class Matrix { /** * 矩阵的行数 * @type {number} */ row: number; /** * 矩阵的列数 * @type {number} */ column: number; /** * 矩阵数据 * @type {Float64Array} */ private _data: number[]; /** * Creates an instance of Matrix. * @param {number} row * @param {(number | 'E')} [column] * @param {(number | 'E')} [value=0] */ constructor(order: number, value?: number | 'E'); constructor(row: number, column: number, value?: number | 'E'); constructor(row: number, column?: number | 'E', value?: number | 'E') { /** 输入一个值 - 零矩阵 */ if (arguments.length === 1) { this.row = row; this.column = row; this._data = Array(row * row).fill(0); } /** * 输入两个值 * - 第二个值为填充值 * - 若第二个值为 'E' 则为单位矩阵 */ else if (arguments.length === 2) { this.row = row; this.column = row; if (column === 'E') { // 默认全为 0 this._data = Array(row * row).fill(0); // 对角线为 1 for (let i = 0; i < row; i++) { this.set(i, i, 1); } } else { this._data = Array(row * row).fill(column); } } /** * 输入三个值 * - 第三个值为填充值 * - 若第三个值为 'E',则从左上角开始的最大子矩阵对角线为 1 */ else { this.row = row; this.column = column as number; if (value === 'E') { // 行列数中,较小的那个是最大子矩阵的大小 const size = this.row < this.column ? this.row : this.column; // 默认全为 0 this._data = Array(this.row * this.column).fill(0); // 对角线为 1 for (let i = 0; i < size; i++) { this.set(i, i, 1); } } else { this._data = Array(this.row * this.column).fill(value); } } } static from(matrix: MatrixInput) { let result: Matrix; // 从数组创建矩阵 if (isArray(matrix)) { const { row, column } = calMatrixSize(matrix); const data = matrix.reduce((ans, item) => ans.concat(item), []); result = new Matrix(row, column, 0); result._data = data.slice(); } // 复制矩阵 else { result = new Matrix(matrix.row, matrix.column, 0); result._data = matrix._data.slice(); } return result; } /** * 矩阵组合 * * @example * [[0, 4, A], * [B, 'E', 0], * [0, C, D]] * * 将形如上面的矩阵合并成一个矩阵,其中 A、B、C、D 为四个不同的矩阵 * 在同一行(列)的矩阵必须有相同的行(列)数 * 纯数字或者是'E'矩阵,不影响行列数,只做填充 */ static merge(ma: Array<Array<'E' | number | MatrixInput>>) { // 每一行有效矩阵的行数 const rowNumbers: number[] = []; for (let i = 0; i < ma.length; i++) { let rowNumber = -1; for (let j = 0; j < ma[i].length; j++) { const cell = ma[i][j]; if (isNumber(cell) || isString(cell)) { continue; } const tempRow = cell instanceof Matrix ? cell.row : calMatrixSize(cell).row; if (rowNumber > 0 && (rowNumber !== tempRow)) { throw new Error(`无法组合矩阵,第(${i},${j})元素矩阵行数错误`); } rowNumber = tempRow; } if (rowNumber < 0) { throw new Error(`无法组合矩阵,第${i}行没有有效矩阵`); } rowNumbers.push(rowNumber); } // 每一列有效矩阵的列数 const colNumbers: number[] = []; for (let j = 0; j < ma[0].length; j++) { let colNumber = -1; for (let i = 0; i < ma.length; i++) { const cell = ma[i][j]; if (isNumber(cell) || isString(cell)) { continue; } const tempCol = cell instanceof Matrix ? cell.column : calMatrixSize(cell).column; if (colNumber > 0 && (colNumber !== tempCol)) { throw new Error(`无法组合矩阵,第(${i},${j})元素矩阵列数错误`); } colNumber = tempCol; } if (colNumber < 0) { throw new Error(`无法组合矩阵,第${j}列没有有效矩阵`); } colNumbers.push(colNumber); } // 串联所有矩阵 let ColumnMatrix!: Matrix; for (let i = 0; i < ma.length; i++) { let RowMatrix!: Matrix; for (let j = 0; j < ma[i].length; j++) { const cell = ma[i][j]; const temp = (isString(cell) || isNumber(cell)) ? new Matrix(rowNumbers[i], colNumbers[j], cell) : Matrix.from(cell); if (RowMatrix) { RowMatrix = RowMatrix.concatRight(temp); } else { RowMatrix = temp; } } if (ColumnMatrix) { ColumnMatrix = ColumnMatrix.concatDown(RowMatrix); } else { ColumnMatrix = RowMatrix; } } return ColumnMatrix; } /** * 取出矩阵元素 * @param {number} i * @param {number} j * @returns {number} */ get(i: number, j: number) { return this._data[i * this.column + j]; } /** * 设置矩阵值 * @param {number} i * @param {number} j * @param {number} value */ set(i: number, j: number, value: number) { this._data[i * this.column + j] = value; } /** * 取出矩阵某一行 * @param {number} row * @returns {number[]} */ getRow(row: number): number[] { const index = row < 0 ? this.row + row : row; if (index > this.row || index < 0) { throw new Error('(matrix) index of row out of bounds.'); } const ans: number[] = [], start = index * this.column; for (let i = 0; i < this.column; i++) { ans[i] = this._data[start + i]; } return ans; } /** * 取出矩阵某一列 * @param {number} column * @returns {number[]} */ getColumn(column: number): number[] { const index = column < 0 ? this.column + column : column; if (index > this.column || index < 0) { throw new Error('(matrix) index of column out of bounds.'); } const ans: number[] = []; for (let i = 0; i < this.row; i++) { ans[i] = this._data[index + i * this.column]; } return ans; } /** * 取出矩阵的中间一部分 * @param a 左上角位置 * @param b 右下角位置 */ slice(a: [number, number] | number[] | Point, b: [number, number] | number[] | Point) { // 取出坐标 const [ax, ay] = a, [bx, by] = b; // 输入格式检查 if (!( ax >= 0 && ax < this.row && bx >= 0 && bx < this.row && ay >= 0 && ay < this.column && by >= 0 && by < this.column )) { throw new Error(`输入位置错误 a: ${a.join()}, b: ${b.join()}`); } const xMin = Math.min(ax, bx); const xMax = Math.max(ax, bx); const yMin = Math.min(ay, by); const yMax = Math.max(ay, by); const result = new Matrix(xMax - xMin + 1, yMax - yMin + 1, 0); for (let i = xMin; i <= xMax; i++) { for (let j = yMin; j <= yMin; j++) { result.set(i - xMin, j - yMin, this.get(i, j)); } } return (result); } /** * 字符串连接 * @param {string} str * @returns {string} */ join(str = ','): string { return this._data.join(str); } /** * 输出数据 * @return {number[][]} */ toData() { const arr: number[][] = []; for (let i = 0; i < this.row; i++) { arr.push(this.getRow(i)); } return arr; } /** * 交换 from、to 所在的行 * @param {number} from * @param {number} to * @returns {this} */ exchangeRow(from: number, to: number): this { if (from !== to) { const start = from * this.column; const end = to * this.column; for (let i = 0; i < this.column; i++) { const temp = this._data[start + i]; this._data[start + i] = this._data[end + i]; this._data[end + i] = temp; } } return this; } /** * 交换 from、to 所在的列 * @param {number} from * @param {number} to * @returns {this} */ exchangeColumn(from: number, to: number): this { if (from !== to) { for (let i = 0; i < this.row; i++) { const nowRow = i * this.column; const temp = this._data[nowRow + from]; this._data[nowRow + from] = this._data[nowRow + to]; this._data[nowRow + to] = temp; } } return this; } /** * 矩阵转置 * @returns {Matrix} */ transpose() { const result = new Matrix(this.column, this.row, 0); for (let i = 0; i < this.row; i++) { for (let j = 0; j < this.column; j++) { result.set(j, i, this.get(i, j)); } } return (result); } /** * 矩阵乘法 * - this * ma * @param {(number[][] | Matrix)} ma * @returns {Matrix} */ mul(ma: number[][] | Matrix): Matrix { const a = (ma instanceof Matrix) ? ma : (Matrix.from(ma)); if (this.column !== a.row) { throw new Error('(matrix) this can not be multiplied with ma.'); } // 乘法结果的行与列 const row = this.row; const column = a.column; // 乘法计算 const ans = new Matrix(row, column, 0); for (let i = 0; i < row; i++) { for (let j = 0; j < column; j++) { let value = ans.get(i, j); for (let sub = 0; sub < this.column; sub++) { value += this.get(i, sub) * a.get(sub, j); } ans.set(i, j, value); } } return (ans); } /** * 矩阵乘法 * - ma * this * @param {(number[][] | Matrix)} ma * @returns {Matrix} */ multo(ma: number[][] | Matrix): Matrix { const a = (ma instanceof Matrix) ? ma : (Matrix.from(ma)); if (this.column !== a.row) { throw new Error('(matrix) ma can not be multiplied with this.'); } return a.mul(this); } /** * 矩阵加法 * - ma + this * @param {(number[][] | Matrix)} ma * @returns {Matrix} */ add(ma: number[][] | Matrix): Matrix { const result = Matrix.from(ma); if (this.row !== result.row || this.column !== result.column) { throw new Error('(matrix) ma can not be add with this.'); } for (let i = 0; i < this.row; i++) { for (let j = 0; j < this.column; j++) { result.set(i, j, result.get(i, j) + this.get(i, j)); } } return result; } /** * 矩阵数值缩放 * - num * this * @param num 放大系数 */ factor(num: number): Matrix { const result = Matrix.from(this); for (let i = 0; i < this.row; i++) { for (let j = 0; j < this.column; j++) { result.set(i, j, result.get(i, j) * num); } } return result; } /** * 列主元 LU 三角分解,返回 L、U、P 矩阵 * @returns {{ L: Matrix, U: Matrix, P: Matrix }} */ luDecompose() { if (this.row !== this.column) { throw new Error('(matrix) only the matrix can be decomposed.'); } /** 行列式行数 */ const n = this.row; /** 上三角行列式 */ const U = Matrix.from(this); /** 下三角行列式 */ const L = new Matrix(n); /** 变换行列式,初始为单位矩阵 */ const P = new Matrix(n, 'E'); for (let k = 0; k < n; k++) { if (k > 0) { for (let i = k; i < n; i++) { L.set(i, k - 1, U.get(i, k - 1) / U.get(k - 1, k - 1)); for (let j = k; j < n; j++) { const temp = U.get(i, j) - L.get(i, k - 1) * U.get(k - 1, j); U.set(i, j, temp); } U.set(i, k - 1, 0); } } if (k < n - 1) { // 取绝对值最大的系数为主元 let tempMax = 0, tempSub = 0; for (let i = k; i < n; i++) { const now = Math.abs(U.get(i, k)); if (now > tempMax) { tempMax = now; tempSub = i; } } // 交换主元 if (tempSub !== 0) { L.exchangeRow(k, tempSub); U.exchangeRow(k, tempSub); P.exchangeRow(k, tempSub); } } } // 下三角对角线为1 for (let i = 0; i < n; i++) { L.set(i, i, 1); } return ({ L, U, P }); } /** * 基于LU分解的矩阵求逆 * @returns {Matrix} */ inverse(): Matrix { const n = this.row; const { L, U, P } = this.luDecompose(); for (let i = 0; i < U.row; i++) { if (U.get(i, i) === 0) { throw new Error('(matrix) this matrix has no inverse.'); } } // L、U 的逆矩阵初始化 const li = new Matrix(n); const ui = new Matrix(n); // U 的逆矩阵 for (let i = 0; i < n; i++) { ui.set(i, i, 1 / U.get(i, i)); for (let j = i - 1; j >= 0; j--) { let s = 0; for (let k = j + 1; k <= i; k++) { s -= U.get(j, k) * ui.get(k, i); } ui.set(j, i, s / U.get(j, j)); } } // L 的逆矩阵 for (let i = 0; i < n; i++) { li.set(i, i, 1); for (let j = i + 1; j < n; j++) { let s = li.get(j, i); for (let k = i; k <= j - 1; k++) { s -= L.get(j, k) * li.get(k, i); } li.set(j, i, s); } } // ul的逆矩阵相乘得到原矩阵的逆矩阵 return ui.mul(li).mul(P); } /** * 向右串联矩阵,原矩阵不变,返回新矩阵 * @param args {MatrixInput[]} */ concatRight(...args: MatrixInput[]) { const matrixes = args.map(Matrix.from); const errIndex = matrixes.findIndex((ma) => ma.row !== this.row); if (errIndex >= 0) { throw new Error(`(matrix) The row number of the ${errIndex} matrix is not equal to this.`); } const totalCol = matrixes.reduce((col, ma) => col + ma.column, this.column); const result = new Matrix(this.row, totalCol, 0); // 添加 this 矩阵元素到 result this.forEach((n, [i, j]) => result.set(i, j, n)); let lastCol = this.column; // 添加扩展矩阵元素到 result for (const ma of matrixes) { ma.forEach((n, [i, j]) => { result.set(i, j + lastCol, n); }); lastCol += ma.column; } return result; } /** * 向下串联矩阵,原矩阵不变,返回新矩阵 * @param args {MatrixInput[]} */ concatDown(...args: MatrixInput[]) { const matrixes = args.map((Matrix.from)); const errIndex = matrixes.findIndex((ma) => ma.column !== this.column); if (errIndex >= 0) { throw new Error(`(matrix) The column number of the ${errIndex} matrix is not equal to this.`); } const totalRow = matrixes.reduce((row, ma) => row + ma.row, this.row); const result = new Matrix(totalRow, this.column, 0); // 添加 this 矩阵元素到 result this.forEach((n, [i, j]) => result.set(i, j, n)); let lastRow = this.row; // 添加扩展矩阵元素到 result for (const ma of matrixes) { ma.forEach((n, [i, j]) => { result.set(i + lastRow, j, n); }); lastRow += ma.row; } return result; } /** * forEach 迭代 * - 从第一行开始,从左至右 * @param {(value: number, position: [number, number]) => number} callback * @returns {this} */ forEach(callback: (value: number, position: [number, number]) => any) { for (let i = 0; i < this._data.length; i++) { const x = Math.floor(i / this.column); const y = i % this.column; callback(this._data[i], [x, y]); } } /** * map 迭代 * - 从第一行开始,从左至右 * @param {(value: number, position: [number, number]) => number} callback * @returns {this} */ map(callback: (value: number, position: [number, number]) => number) { const newMa = Matrix.from(this); for (let i = 0; i < newMa._data.length; i++) { const x = Math.floor(i / newMa.column); const y = i % newMa.column; const result = callback(newMa._data[i], [x, y]); newMa._data[i] = result; } return newMa; } /** * 过滤矩阵的位置 * @param callback 一个数字或者是回调 * - 数字相等或者是回调返回 true,此时矩阵元素的位置会被记录 */ filterPosition(callback: number | ((value: number, position: [number, number]) => boolean)) { const position: Array<[number, number]> = []; const pre = isNumber(callback) ? (val: number) => val === callback : callback; for (let i = 0; i < this._data.length; i++) { const x = Math.floor(i / this.column); const y = i % this.column; const result = pre(this._data[i], [x, y]); if (result) { position.push([x, y]); } } return position; } } /** * 输入的二维数组能否转化为矩阵 * * @param {number[][]} ma * @returns {{ row: number; column: number })} */ function calMatrixSize(ma: number[][]): { row: number; column: number } { // 记录行列数 const row = ma.length, column = ma[0].length; // 行连续 if (!Object.keys(ma).every((n, i) => Number(n) === i)) { throw new Error('(matrix) this is not a matrix.'); } // 列连续且列长均相等 if (!ma.every((col) => isArray(col) && col.length === column && Object.keys(col).every((n, i) => Number(n) === i) && Object.values(col).every((n) => isNumber(n) && !Number.isNaN(n)), )) { throw new Error('(matrix) this is not a matrix.'); } return ({ row, column }); } /** 旋转方向定义 */ export enum Rotate { /** 同向 */ Same, /** 反向 */ Reverse, /** 顺时针 */ Clockwise, /** 逆时针 */ AntiClockwise, } export const RotateMatrix: Readonly<Record<Rotate, Matrix>> = { [Rotate.Same]: Matrix.from([[1, 0], [0, 1]]), [Rotate.Reverse]: Matrix.from([[-1, 0], [0, -1]]), [Rotate.Clockwise]: Matrix.from([[0, 1], [-1, 0]]), [Rotate.AntiClockwise]: Matrix.from([[0, -1], [1, 0]]), };
the_stack
import { DraftBotShopMessage, DraftBotShopMessageBuilder, ShopItem, ShopItemCategory } from "../../core/messages/DraftBotShopMessage"; import {TranslationModule, Translations} from "../../core/Translations"; import {DraftBotEmbed} from "../../core/messages/DraftBotEmbed"; import {Constants} from "../../core/Constants"; import {Entities} from "../../core/models/Entity"; import {Message, TextChannel, User} from "discord.js"; import {generateRandomItem, giveItemToPlayer} from "../../core/utils/ItemUtils"; import {DraftBotReactionMessageBuilder} from "../../core/messages/DraftBotReactionMessage"; import {DraftBotErrorEmbed} from "../../core/messages/DraftBotErrorEmbed"; import {DraftBotReaction} from "../../core/messages/DraftBotReaction"; import {MissionsController} from "../../core/missions/MissionsController"; import {getDayNumber} from "../../core/utils/TimeUtils"; import {BlockingUtils} from "../../core/utils/BlockingUtils"; declare function sendBlockedError(user: User, channel: TextChannel, language: string): Promise<boolean>; module.exports.commandInfo = { name: "missionshop", aliases: ["ms", "mshop", "questshop", "missionsshop", "questsshop", "qs", "qshop"], disallowEffects: [Constants.EFFECT.BABY, Constants.EFFECT.DEAD, Constants.EFFECT.LOCKED] }; /** * Displays the mission shop * @param {Message} message - Message from the discord server * @param {("fr"|"en")} language - Language to use in the response */ const MissionShopCommand = async (message: Message, language: string) => { const [entity] = await Entities.getOrRegister(message.author.id); if (await sendBlockedError(message.author, <TextChannel>message.channel, language)) { return; } const shopTranslations = Translations.getModule("commands.missionShop", language); const resCategory = new ShopItemCategory( [ getMoneyShopItem(shopTranslations), getValuableItemShopItem(shopTranslations), getAThousandPointsShopItem(shopTranslations) ], shopTranslations.get("resTitle") ); const utilCategory = new ShopItemCategory( [ getSkipMapMissionShopItem(shopTranslations), getValueLovePointsPetShopItem(shopTranslations) ], shopTranslations.get("utilTitle") ); const presCategory = new ShopItemCategory( [ getBadgeShopItem(shopTranslations) ], shopTranslations.get("presTitle") ); const shopMessage = await new DraftBotShopMessageBuilder( message.author, shopTranslations.get("title"), language ) .addCategory(resCategory) .addCategory(utilCategory) .addCategory(presCategory) .endCallback(shopEndCallback) .setGetUserMoney(getUserGems) .setRemoveUserMoney(removeUserGems) .setTranslationPosition("commands.missionShop") .build(); await shopMessage.send(message.channel, collector => BlockingUtils.blockPlayerWithCollector(entity.discordUserId, "missionShop", collector)); }; /** * get the amount of gems a user has * @param userId */ const getUserGems = async (userId: string): Promise<number> => { const user = (await Entities.getOrRegister(userId))[0].Player; return user.PlayerMissionsInfo.gems; }; /** * allow a user to pay * @param userId * @param amount */ async function removeUserGems(userId: string, amount: number): Promise<void> { const player = (await Entities.getByDiscordUserId(userId)).Player; player.PlayerMissionsInfo.addGems(-amount); await player.PlayerMissionsInfo.save(); } function shopEndCallback(shopMessage: DraftBotShopMessage) { BlockingUtils.unblockPlayer(shopMessage.user.id); } function getItemShopItem(name: string, translationModule: TranslationModule, buyCallback: (message: DraftBotShopMessage, amount: number) => Promise<boolean>): ShopItem { return new ShopItem( translationModule.get("items." + name + ".emote"), translationModule.get("items." + name + ".name"), parseInt(translationModule.get("items." + name + ".price")), translationModule.format("items." + name + ".info", {amount: calculateGemsToMoneyRatio()} ), buyCallback ); } function getSkipMapMissionShopItem(translationModule: TranslationModule): ShopItem { return getItemShopItem( "skipMapMission", translationModule, async (message) => { const [entity] = await Entities.getOrRegister(message.user.id); const allMissions = entity.Player.MissionSlots.filter(slot => !slot.isCampaign()); if (!allMissions.length) { message.sentMessage.channel.send({ embeds: [new DraftBotErrorEmbed( message.user, message.language, translationModule.get("error.noMissionToSkip") )] }); return false; } const chooseMission = new DraftBotReactionMessageBuilder() .allowUser(message.user) .endCallback(async (missionMessage) => { const reaction = missionMessage.getFirstReaction(); if (!reaction || reaction.emoji.name === Constants.REACTIONS.REFUSE_REACTION) { BlockingUtils.unblockPlayer(message.user.id); await message.sentMessage.channel.send({ embeds: [new DraftBotErrorEmbed( message.user, message.language, translationModule.get("error.canceledPurchase") )] }); return false; } for (let i = 0; i < allMissions.length; ++i) { if (reaction.emoji.name === Constants.REACTIONS.NUMBERS[i + 1]) { entity.Player.PlayerMissionsInfo.addGems(-parseInt(translationModule.get("items.skipMapMission.price"), 10)); await entity.Player.PlayerMissionsInfo.save(); await message.sentMessage.channel.send({ embeds: [ new DraftBotEmbed() .formatAuthor(translationModule.get("items.skipMapMission.successTitle"), message.user) .setDescription(translationModule.format("items.skipMapMission.successDescription", { num: i + 1, missionInfo: await allMissions[i].Mission.formatDescription(allMissions[i].missionObjective, allMissions[i].missionVariant, message.language) })) ] }); await allMissions[i].destroy(); break; } } BlockingUtils.unblockPlayer(message.user.id); await MissionsController.update(message.user.id, <TextChannel>message.sentMessage.channel, message.language, "spendGems"); }); let desc = ""; for (let i = 0; i < allMissions.length; ++i) { chooseMission.addReaction(new DraftBotReaction(Constants.REACTIONS.NUMBERS[i + 1])); desc += Constants.REACTIONS.NUMBERS[i + 1] + " " + await allMissions[i].Mission.formatDescription(allMissions[i].missionObjective, allMissions[i].missionVariant, message.language) + "\n"; } chooseMission.addReaction(new DraftBotReaction(Constants.REACTIONS.REFUSE_REACTION)); const chooseMissionBuilt = chooseMission.build(); chooseMissionBuilt.formatAuthor(translationModule.get("items.skipMapMission.giveTitle"), message.user); chooseMissionBuilt.setDescription(translationModule.get("items.skipMapMission.giveDesc") + "\n\n" + desc); await chooseMissionBuilt.send(message.sentMessage.channel); BlockingUtils.blockPlayerWithCollector(entity.discordUserId, "missionShop", chooseMissionBuilt.collector); return false; }); } /** * Calculate the amount of money the player will have if he buys some with gems */ function calculateGemsToMoneyRatio() { const frac = function(x: number) { return x >= 0 ? x % 1 : 1 + x % 1; }; return Constants.MISSION_SHOP.BASE_RATIO + Math.round(Constants.MISSION_SHOP.RANGE_MISSION_MONEY * 2 * frac(100 * Math.sin(100000 * (getDayNumber() % Constants.MISSION_SHOP.SEED_RANGE) + 1)) - Constants.MISSION_SHOP.RANGE_MISSION_MONEY); } function getMoneyShopItem(translationModule: TranslationModule): ShopItem { return getItemShopItem( "money", translationModule, async (message) => { const [entity] = await Entities.getOrRegister(message.user.id); await entity.Player.addMoney(entity, calculateGemsToMoneyRatio(), <TextChannel>message.sentMessage.channel, translationModule.language); await entity.Player.save(); await message.sentMessage.channel.send( { embeds: [new DraftBotEmbed() .formatAuthor(translationModule.get("items.money.giveTitle"), message.user) .setDescription(translationModule.format("items.money.giveDescription", {amount: calculateGemsToMoneyRatio()}) )] }); await MissionsController.update(message.user.id, <TextChannel>message.sentMessage.channel, message.language, "spendGems"); return true; }); } function getValuableItemShopItem(translationModule: TranslationModule): ShopItem { return getItemShopItem( "valuableItem", translationModule, async (message) => { const [entity] = await Entities.getOrRegister(message.user.id); const item = await generateRandomItem(Constants.RARITY.MYTHICAL, null, Constants.RARITY.SPECIAL); await giveItemToPlayer(entity, item, message.language, message.user, <TextChannel>message.sentMessage.channel); await MissionsController.update(message.user.id, <TextChannel>message.sentMessage.channel, message.language, "spendGems"); return true; }); } function getAThousandPointsShopItem(translationModule: TranslationModule): ShopItem { return getItemShopItem( "1000Points", translationModule, async (message) => { const [entity] = await Entities.getOrRegister(message.user.id); if (entity.Player.PlayerMissionsInfo.hasBoughtPointsThisWeek) { message.sentMessage.channel.send({ embeds: [new DraftBotErrorEmbed( message.user, message.language, translationModule.get("error.remainingCooldown") )] }); return false; } await entity.Player.addScore(entity, 1000, <TextChannel>message.sentMessage.channel, translationModule.language); await entity.Player.save(); await message.sentMessage.channel.send( { embeds: [new DraftBotEmbed() .formatAuthor(translationModule.get("items.1000Points.giveTitle"), message.user) .setDescription(translationModule.get("items.1000Points.giveDescription") )] }); entity.Player.PlayerMissionsInfo.hasBoughtPointsThisWeek = true; await entity.Player.PlayerMissionsInfo.save(); await MissionsController.update(message.user.id, <TextChannel>message.sentMessage.channel, message.language, "spendGems"); return true; }); } function getValueLovePointsPetShopItem(translationModule: TranslationModule): ShopItem { return getItemShopItem( "lovePointsValue", translationModule, async (message) => { const [entity] = await Entities.getOrRegister(message.user.id); if (entity.Player.petId === null) { message.sentMessage.channel.send({ embeds: [new DraftBotErrorEmbed( message.user, message.language, translationModule.get("error.noPet") )] }); return false; } const sentenceGotten = translationModule.getRandom("items.lovePointsValue.advice." + entity.Player.Pet.getLoveLevelNumber()); await message.sentMessage.channel.send({ embeds: [new DraftBotEmbed() .formatAuthor(translationModule.get("items.lovePointsValue.giveTitle"), message.user) .setDescription(translationModule.format("items.lovePointsValue.giveDesc", { petName: entity.Player.Pet.displayName(message.language), actualLP: entity.Player.Pet.lovePoints, regime: entity.Player.Pet.getDietDisplay(message.language), nextFeed: entity.Player.Pet.getFeedCooldownDisplay(message.language), commentOnResult: sentenceGotten })) ] }); await MissionsController.update(message.user.id, <TextChannel>message.sentMessage.channel, message.language, "spendGems"); return true; }); } function getBadgeShopItem(translationModule: TranslationModule): ShopItem { return getItemShopItem( "badge", translationModule, async (message) => { const [entity] = await Entities.getOrRegister(message.user.id); if (entity.Player.hasBadge("💍")) { message.sentMessage.channel.send({ embeds: [new DraftBotErrorEmbed( message.user, message.language, translationModule.get("error.alreadyHasItem") )] }); return false; } entity.Player.addBadge("💍"); await entity.Player.save(); await message.sentMessage.channel.send({ embeds: [new DraftBotEmbed() .formatAuthor(translationModule.get("items.badge.give"), message.user) .setDescription("💍 " + translationModule.get("items.badge.name")) ] }); await MissionsController.update(message.user.id, <TextChannel>message.sentMessage.channel, message.language, "spendGems"); return true; } ); } module.exports.execute = MissionShopCommand;
the_stack
export interface ISetSource<K=any> { /** Returns the number of key/value pairs in the map object. */ size: number; /** Returns a boolean asserting whether the key exists in the map object or not. */ has(key: K): boolean; /** Returns a new iterator for iterating the items in the set (the order is implementation-dependent). */ keys(): IterableIterator<K>; } /** Read-only map interface (i.e. a source of key-value pairs). */ export interface IMapSource<K=any, V=any> extends ISetSource<K> { /** Returns the number of key/value pairs in the map object. */ size: number; /** Returns the value associated to the key, or undefined if there is none. */ get(key: K): V|undefined; /** Returns a boolean asserting whether the key exists in the map object or not. */ has(key: K): boolean; /** Calls callbackFn once for each key-value pair present in the map object. * The ES6 Map class sends the value to the callback before the key, so * this interface must do likewise. */ forEach(callbackFn: (v:V, k:K, map:IMapSource<K,V>) => void, thisArg: any): void; /** Returns an iterator that provides all key-value pairs from the collection (as arrays of length 2). */ entries(): IterableIterator<[K,V]>; /** Returns a new iterator for iterating the keys of each pair. */ keys(): IterableIterator<K>; /** Returns a new iterator for iterating the values of each pair. */ values(): IterableIterator<V>; // TypeScript compiler decided Symbol.iterator has type 'any' //[Symbol.iterator](): IterableIterator<[K,V]>; } /** Write-only set interface (the set cannot be queried, but items can be added to it.) * @description Note: BTree<K,V> does not officially implement this interface, * but BTree<K> can be used as an instance of ISetSink<K>. */ export interface ISetSink<K=any> { /** Adds the specified item to the set, if it was not in the set already. */ add(key: K): any; /** Returns true if an element in the map object existed and has been * removed, or false if the element did not exist. */ delete(key: K): boolean; /** Removes everything so that the set is empty. */ clear(): void; } /** Write-only map interface (i.e. a drain into which key-value pairs can be "sunk") */ export interface IMapSink<K=any, V=any> { /** Returns true if an element in the map object existed and has been * removed, or false if the element did not exist. */ delete(key: K): boolean; /** Sets the value for the key in the map object (the return value is * boolean in BTree but Map returns the Map itself.) */ set(key: K, value: V): any; /** Removes all key/value pairs from the IMap object. */ clear(): void; } /** Set interface. * @description Note: BTree<K,V> does not officially implement this interface, * but BTree<K> can be used as an instance of ISet<K>. */ export interface ISet<K=any> extends ISetSource<K>, ISetSink<K> { } /** An interface compatible with ES6 Map and BTree. This interface does not * describe the complete interface of either class, but merely the common * interface shared by both. */ export interface IMap<K=any, V=any> extends IMapSource<K, V>, IMapSink<K, V> { } /** An data source that provides read-only access to a set of items called * "keys" in sorted order. This is a subinterface of ISortedMapSource. */ export interface ISortedSetSource<K=any> extends ISetSource<K> { /** Gets the lowest key in the collection. */ minKey(): K | undefined; /** Gets the highest key in the collection. */ maxKey(): K | undefined; /** Returns the next key larger than the specified key (or undefined if there is none) */ nextHigherKey(key: K): K|undefined; /** Returns the next key smaller than the specified key (or undefined if there is none) */ nextLowerKey(key: K): K|undefined; /** Calls `callback` on the specified range of keys, in ascending order by key. * @param low The first key scanned will be greater than or equal to `low`. * @param high Scanning stops when a key larger than this is reached. * @param includeHigh If the `high` key is present in the map, `onFound` is called * for that final pair if and only if this parameter is true. * @param onFound A function that is called for each key pair. Because this * is a subinterface of ISortedMapSource, if there is a value * associated with the key, it is passed as the second parameter. * @param initialCounter Initial third argument of `onFound`. This value * increases by one each time `onFound` is called. Default: 0 * @returns Number of pairs found and the number of times `onFound` was called. */ forRange(low: K, high: K, includeHigh: boolean, onFound?: (k:K,v:any,counter:number) => void, initialCounter?: number): number; /** Returns a new iterator for iterating the keys of each pair in ascending order. * @param firstKey: Minimum key to include in the output. */ keys(firstKey?: K): IterableIterator<K>; } /** An data source that provides read-only access to items in sorted order. */ export interface ISortedMapSource<K=any, V=any> extends IMapSource<K, V>, ISortedSetSource<K> { /** Returns the next pair whose key is larger than the specified key (or undefined if there is none) */ nextHigherPair(key: K): [K,V]|undefined; /** Returns the next pair whose key is smaller than the specified key (or undefined if there is none) */ nextLowerPair(key: K): [K,V]|undefined; /** Builds an array of pairs from the specified range of keys, sorted by key. * Each returned pair is also an array: pair[0] is the key, pair[1] is the value. * @param low The first key in the array will be greater than or equal to `low`. * @param high This method returns when a key larger than this is reached. * @param includeHigh If the `high` key is present in the map, its pair will be * included in the output if and only if this parameter is true. Note: * if the `low` key is present, it is always included in the output. * @param maxLength Maximum length of the returned array (default: unlimited) * @description Computational complexity: O(result.length + log size) */ getRange(low: K, high: K, includeHigh?: boolean, maxLength?: number): [K,V][]; /** Calls `callback` on the specified range of keys, in ascending order by key. * @param low The first key scanned will be greater than or equal to `low`. * @param high Scanning stops when a key larger than this is reached. * @param includeHigh If the `high` key is present in the map, `onFound` is called * for that final pair if and only if this parameter is true. * @param onFound A function that is called for each key-value pair. * @param initialCounter Initial third argument of onFound. This value * increases by one each time `onFound` is called. Default: 0 * @returns Number of pairs found and the number of times `callback` was called. */ forRange(low: K, high: K, includeHigh: boolean, onFound?: (k:K,v:V,counter:number) => void, initialCounter?: number): number; /** Returns an iterator that provides items in order by key. * @param firstKey: Minimum key to include in the output. */ entries(firstKey?: K): IterableIterator<[K,V]>; /** Returns a new iterator for iterating the keys of each pair in ascending order. * @param firstKey: Minimum key to include in the output. */ keys(firstKey?: K): IterableIterator<K>; /** Returns a new iterator for iterating the values of each pair in order by key. * @param firstKey: Minimum key whose associated value is included in the output. */ values(firstKey?: K): IterableIterator<V>; // This method should logically be in IMapSource but is not supported by ES6 Map /** Performs a reduce operation like the `reduce` method of `Array`. * It is used to combine all pairs into a single value, or perform conversions. */ reduce<R>(callback: (previous:R,currentPair:[K,V],counter:number,tree:IMapF<K,V>) => R, initialValue: R): R; /** Performs a reduce operation like the `reduce` method of `Array`. * It is used to combine all pairs into a single value, or perform conversions. */ reduce<R>(callback: (previous:R|undefined,currentPair:[K,V],counter:number,tree:IMapF<K,V>) => R): R|undefined; } /** An interface for a set of keys (the combination of ISortedSetSource<K> and ISetSink<K>) */ export interface ISortedSet<K=any> extends ISortedSetSource<K>, ISetSink<K> { } /** An interface for a sorted map (dictionary), * not including functional/persistent methods. */ export interface ISortedMap<K=any, V=any> extends IMap<K,V>, ISortedMapSource<K, V> { // All of the following methods should be in IMap but are left out of IMap // so that IMap is compatible with ES6 Map. /** Adds or overwrites a key-value pair in the sorted map. * @param key the key is used to determine the sort order of data in the tree. * @param value data to associate with the key * @param overwrite Whether to overwrite an existing key-value pair * (default: true). If this is false and there is an existing * key-value pair then the call to this method has no effect. * @returns true if a new key-value pair was added, false if the key * already existed. */ set(key: K, value: V, overwrite?: boolean): boolean; /** Adds all pairs from a list of key-value pairs. * @param pairs Pairs to add to this tree. If there are duplicate keys, * later pairs currently overwrite earlier ones (e.g. [[0,1],[0,7]] * associates 0 with 7.) * @param overwrite Whether to overwrite pairs that already exist (if false, * pairs[i] is ignored when the key pairs[i][0] already exists.) * @returns The number of pairs added to the collection. */ setPairs(pairs: [K,V][], overwrite?: boolean): number; /** Deletes a series of keys from the collection. */ deleteKeys(keys: K[]): number; /** Removes a range of key-value pairs from the B+ tree. * @param low The first key deleted will be greater than or equal to `low`. * @param high Deleting stops when a key larger than this is reached. * @param includeHigh Specifies whether the `high` key, if present, is deleted. * @returns The number of key-value pairs that were deleted. */ deleteRange(low: K, high: K, includeHigh: boolean): number; // TypeScript requires these methods of ISortedMapSource to be repeated entries(firstKey?: K): IterableIterator<[K,V]>; keys(firstKey?: K): IterableIterator<K>; values(firstKey?: K): IterableIterator<V>; } /** An interface for a functional set, in which the set object could be read-only * but new versions of the set can be created by calling "with" or "without" * methods to add or remove keys. This is a subinterface of IMapF<K,V>, * so the items in the set may be referred to as "keys". */ export interface ISetF<K=any> extends ISetSource<K> { /** Returns a copy of the set with the specified key included. * @description You might wonder why this method accepts only one key * instead of `...keys: K[]`. The reason is that the derived interface * IMapF expects the second parameter to be a value. Therefore * withKeys() is provided to set multiple keys at once. */ with(key: K): ISetF<K>; /** Returns a copy of the set with the specified key removed. */ without(key: K): ISetF<K>; /** Returns a copy of the tree with all the keys in the specified array present. * @param keys The keys to add. * @param returnThisIfUnchanged If true, the method returns `this` when * all of the keys are already present in the collection. The * default value may be true or false depending on the concrete * implementation of the interface (in BTree, the default is false.) */ withKeys(keys: K[], returnThisIfUnchanged?: boolean): ISetF<K>; /** Returns a copy of the tree with all the keys in the specified array removed. */ withoutKeys(keys: K[], returnThisIfUnchanged?: boolean): ISetF<K>; /** Returns a copy of the tree with items removed whenever the callback * function returns false. * @param callback A function to call for each item in the set. * The second parameter to `callback` exists because ISetF * is a subinterface of IMapF. If the object is a map, v * is the value associated with the key, otherwise v could be * undefined or another copy of the third parameter (counter). */ filter(callback: (k:K,v:any,counter:number) => boolean, returnThisIfUnchanged?: boolean): ISetF<K>; } /** An interface for a functional map, in which the map object could be read-only * but new versions of the map can be created by calling "with" or "without" * methods to add or remove keys or key-value pairs. */ export interface IMapF<K=any, V=any> extends IMapSource<K, V>, ISetF<K> { /** Returns a copy of the tree with the specified key set (the value is undefined). */ with(key: K): IMapF<K,V|undefined>; /** Returns a copy of the tree with the specified key-value pair set. */ with<V2>(key: K, value: V2, overwrite?: boolean): IMapF<K,V|V2>; /** Returns a copy of the tree with the specified key-value pairs set. */ withPairs<V2>(pairs: [K,V|V2][], overwrite: boolean): IMapF<K,V|V2>; /** Returns a copy of the tree with all the keys in the specified array present. * @param keys The keys to add. If a key is already present in the tree, * neither the existing key nor the existing value is modified. * @param returnThisIfUnchanged If true, the method returns `this` when * all of the keys are already present in the collection. The * default value may be true or false depending on the concrete * implementation of the interface (in BTree, the default is false.) */ withKeys(keys: K[], returnThisIfUnchanged?: boolean): IMapF<K,V|undefined>; /** Returns a copy of the tree with all values altered by a callback function. */ mapValues<R>(callback: (v:V,k:K,counter:number) => R): IMapF<K,R>; /** Performs a reduce operation like the `reduce` method of `Array`. * It is used to combine all pairs into a single value, or perform conversions. */ reduce<R>(callback: (previous:R,currentPair:[K,V],counter:number,tree:IMapF<K,V>) => R, initialValue: R): R; /** Performs a reduce operation like the `reduce` method of `Array`. * It is used to combine all pairs into a single value, or perform conversions. */ reduce<R>(callback: (previous:R|undefined,currentPair:[K,V],counter:number,tree:IMapF<K,V>) => R): R|undefined; // Update return types in ISetF without(key: K): IMapF<K,V>; withoutKeys(keys: K[], returnThisIfUnchanged?: boolean): IMapF<K,V>; /** Returns a copy of the tree with pairs removed whenever the callback * function returns false. */ filter(callback: (k:K,v:V,counter:number) => boolean, returnThisIfUnchanged?: boolean): IMapF<K,V>; } /** An interface for a functional sorted set: a functional set in which the * keys (items) are sorted. This is a subinterface of ISortedMapF. */ export interface ISortedSetF<K=any> extends ISetF<K>, ISortedSetSource<K> { // TypeScript requires this method of ISortedSetSource to be repeated keys(firstKey?: K): IterableIterator<K>; } export interface ISortedMapF<K=any,V=any> extends ISortedSetF<K>, IMapF<K,V>, ISortedMapSource<K,V> { /** Returns a copy of the tree with the specified range of keys removed. */ withoutRange(low: K, high: K, includeHigh: boolean, returnThisIfUnchanged?: boolean): ISortedMapF<K,V>; // TypeScript requires these methods of ISortedSetF and ISortedMapSource to be repeated entries(firstKey?: K): IterableIterator<[K,V]>; keys(firstKey?: K): IterableIterator<K>; values(firstKey?: K): IterableIterator<V>; forRange(low: K, high: K, includeHigh: boolean, onFound?: (k:K,v:V,counter:number) => void, initialCounter?: number): number; // Update the return value of methods from base interfaces with(key: K): ISortedMapF<K,V|undefined>; with<V2>(key: K, value: V2, overwrite?: boolean): ISortedMapF<K,V|V2>; withKeys(keys: K[], returnThisIfUnchanged?: boolean): ISortedMapF<K,V|undefined>; withPairs<V2>(pairs: [K,V|V2][], overwrite: boolean): ISortedMapF<K,V|V2>; mapValues<R>(callback: (v:V,k:K,counter:number) => R): ISortedMapF<K,R>; without(key: K): ISortedMapF<K,V>; withoutKeys(keys: K[], returnThisIfUnchanged?: boolean): ISortedMapF<K,V>; filter(callback: (k:K,v:any,counter:number) => boolean, returnThisIfUnchanged?: boolean): ISortedMapF<K,V>; } export interface ISortedMapConstructor<K,V> { new (entries?: [K,V][], compare?: (a: K, b: K) => number): ISortedMap<K,V>; } export interface ISortedMapFConstructor<K,V> { new (entries?: [K,V][], compare?: (a: K, b: K) => number): ISortedMapF<K,V>; }
the_stack
import { delay } from "./common"; import { Point } from "./structs/point"; import { FacetResult, PathPoint, OrientationEnum } from "./facetmanagement"; /** * Path segment is a segment of a border path that is adjacent to a specific neighbour facet */ export class PathSegment { constructor(public points: PathPoint[], public neighbour: number) { } } /** * Facet boundary segment describes the matched segment that is shared between 2 facets * When 2 segments are matched, one will be the original segment and the other one is removed * This ensures that all facets share the same segments, but sometimes in reverse order to ensure * the correct continuity of its entire oborder path */ export class FacetBoundarySegment { constructor(public originalSegment: PathSegment, public neighbour: number, public reverseOrder: boolean) { } } export class FacetBorderSegmenter { /** * Builds border segments that are shared between facets * While border paths are all nice and fancy, they are not linked to neighbour facets * So any change in the paths makes a not so nice gap between the facets, which makes smoothing them out impossible */ public static async buildFacetBorderSegments(facetResult: FacetResult, nrOfTimesToHalvePoints: number = 2, onUpdate: ((progress: number) => void) | null = null) { // first chop up the border path in segments each time the neighbour at that point changes // (and sometimes even when it doesn't on that side but does on the neighbour's side) const segmentsPerFacet: Array<Array<PathSegment | null>> = FacetBorderSegmenter.prepareSegmentsPerFacet(facetResult); // now reduce the segment complexity with Haar wavelet reduction to smooth them out and make them // more curvy with data points instead of zig zag of a grid FacetBorderSegmenter.reduceSegmentComplexity(facetResult, segmentsPerFacet, nrOfTimesToHalvePoints); // now see which segments of facets with the prepared segments of the neighbour facets // and point them to the same one await FacetBorderSegmenter.matchSegmentsWithNeighbours(facetResult, segmentsPerFacet, onUpdate); } /** * Chops up the border paths per facet into segments adjacent tothe same neighbour */ private static prepareSegmentsPerFacet(facetResult: FacetResult) { const segmentsPerFacet: Array<Array<PathSegment | null>> = new Array(facetResult.facets.length); for (const f of facetResult.facets) { if (f != null) { const segments: PathSegment[] = []; if (f.borderPath.length > 1) { let currentPoints: PathPoint[] = []; currentPoints.push(f.borderPath[0]); for (let i: number = 1; i < f.borderPath.length; i++) { const prevBorderPoint = f.borderPath[i - 1]; const curBorderPoint = f.borderPath[i]; const oldNeighbour = prevBorderPoint.getNeighbour(facetResult); const curNeighbour = curBorderPoint.getNeighbour(facetResult); let isTransitionPoint = false; if (oldNeighbour !== curNeighbour) { isTransitionPoint = true; } else { // it's possible that due to inner facets inside the current facet that the // border is interrupted on that facet's side, but not on the neighbour's side if (oldNeighbour !== -1) { // check for tight rotations to break path if diagonals contain a different neighbour, // see https://i.imgur.com/o6Srqwj.png for visual path of the issue if (prevBorderPoint.x === curBorderPoint.x && prevBorderPoint.y === curBorderPoint.y) { // rotation turn // check the diagonal neighbour to see if it remains the same // +---+---+ // | dN| | // +---xxxx> (x = wall, dN = diagNeighbour) // | x f | // +---v---+ if ((prevBorderPoint.orientation === OrientationEnum.Top && curBorderPoint.orientation === OrientationEnum.Left) || (prevBorderPoint.orientation === OrientationEnum.Left && curBorderPoint.orientation === OrientationEnum.Top)) { const diagNeighbour = facetResult.facetMap.get(curBorderPoint.x - 1, curBorderPoint.y - 1); if (diagNeighbour !== oldNeighbour) { isTransitionPoint = true; } } else if ((prevBorderPoint.orientation === OrientationEnum.Top && curBorderPoint.orientation === OrientationEnum.Right) || (prevBorderPoint.orientation === OrientationEnum.Right && curBorderPoint.orientation === OrientationEnum.Top)) { const diagNeighbour = facetResult.facetMap.get(curBorderPoint.x + 1, curBorderPoint.y - 1); if (diagNeighbour !== oldNeighbour) { isTransitionPoint = true; } } else if ((prevBorderPoint.orientation === OrientationEnum.Bottom && curBorderPoint.orientation === OrientationEnum.Left) || (prevBorderPoint.orientation === OrientationEnum.Left && curBorderPoint.orientation === OrientationEnum.Bottom)) { const diagNeighbour = facetResult.facetMap.get(curBorderPoint.x - 1, curBorderPoint.y + 1); if (diagNeighbour !== oldNeighbour) { isTransitionPoint = true; } } else if ((prevBorderPoint.orientation === OrientationEnum.Bottom && curBorderPoint.orientation === OrientationEnum.Right) || (prevBorderPoint.orientation === OrientationEnum.Right && curBorderPoint.orientation === OrientationEnum.Bottom)) { const diagNeighbour = facetResult.facetMap.get(curBorderPoint.x + 1, curBorderPoint.y + 1); if (diagNeighbour !== oldNeighbour) { isTransitionPoint = true; } } } } } currentPoints.push(curBorderPoint); if (isTransitionPoint) { // aha! a transition point, create the current points as new segment // and start a new list if (currentPoints.length > 1) { const segment = new PathSegment(currentPoints, oldNeighbour); segments.push(segment); currentPoints = [curBorderPoint]; } } } // finally check if there is a remainder partial segment and either prepend // the points to the first segment if they have the same neighbour or construct a // new segment if (currentPoints.length > 1) { const oldNeighbour = f.borderPath[f.borderPath.length - 1].getNeighbour(facetResult); if (segments.length > 0 && segments[0].neighbour === oldNeighbour) { // the first segment and the remainder of the last one are the same part // add the current points to the first segment by prefixing it const mergedPoints = currentPoints.concat(segments[0].points); segments[0].points = mergedPoints; } else { // add the remainder as final segment const segment = new PathSegment(currentPoints, oldNeighbour); segments.push(segment); currentPoints = []; } } } segmentsPerFacet[f.id] = segments; } } return segmentsPerFacet; } /** * Reduces each segment border path points */ private static reduceSegmentComplexity(facetResult: FacetResult, segmentsPerFacet: Array<Array<PathSegment | null>>, nrOfTimesToHalvePoints: number) { for (const f of facetResult.facets) { if (f != null) { for (const segment of segmentsPerFacet[f.id]) { for (let i: number = 0; i < nrOfTimesToHalvePoints; i++) { segment!.points = FacetBorderSegmenter.reduceSegmentHaarWavelet(segment!.points, true, facetResult.width, facetResult.height); } } } } } /** * Remove the points by taking the average per pair and using that as a new point * in the reduced segment. The delta values that create the Haar wavelet are not tracked * because they are unneeded. */ private static reduceSegmentHaarWavelet(newpath: PathPoint[], skipOutsideBorders: boolean, width: number, height: number) { if (newpath.length <= 5) { return newpath; } const reducedPath: PathPoint[] = []; reducedPath.push(newpath[0]); for (let i: number = 1; i < newpath.length - 2; i += 2) { if (!skipOutsideBorders || (skipOutsideBorders && !FacetBorderSegmenter.isOutsideBorderPoint(newpath[i], width, height))) { const cx = (newpath[i].x + newpath[i + 1].x) / 2; const cy = (newpath[i].y + newpath[i + 1].y) / 2; reducedPath.push(new PathPoint(new Point(cx, cy), OrientationEnum.Left)); } else { reducedPath.push(newpath[i]); reducedPath.push(newpath[i + 1]); } } // close the loop reducedPath.push(newpath[newpath.length - 1]); return reducedPath; } private static isOutsideBorderPoint(point: Point, width: number, height: number) { return point.x === 0 || point.y === 0 || point.x === width - 1 || point.y === height - 1; } private static calculateArea(path: Point[]) { let total = 0; for (let i = 0; i < path.length; i++) { const addX = path[i].x; const addY = path[i === path.length - 1 ? 0 : i + 1].y; const subX = path[i === path.length - 1 ? 0 : i + 1].x; const subY = path[i].y; total += (addX * addY * 0.5); total -= (subX * subY * 0.5); } return Math.abs(total); } /** * Matches all segments with each other between facets and their neighbour * A segment matches when the start and end match or the start matches with the end and vice versa * (then the segment will need to be traversed in reverse order) */ private static async matchSegmentsWithNeighbours(facetResult: FacetResult, segmentsPerFacet: Array<Array<PathSegment | null>>, onUpdate: ((progress: number) => void) | null = null) { // max distance of the start/end points of the segment that it can be before the segments don't match up const MAX_DISTANCE = 4; // reserve room for (const f of facetResult.facets) { if (f != null) { f.borderSegments = new Array(segmentsPerFacet[f.id].length); } } let count = 0; // and now the fun begins to match segments from 1 facet to its neighbours and vice versa for (const f of facetResult.facets) { if (f != null) { const debug = false; for (let s: number = 0; s < segmentsPerFacet[f.id].length; s++) { const segment = segmentsPerFacet[f.id][s]; if (segment != null && f.borderSegments[s] == null) { f.borderSegments[s] = new FacetBoundarySegment(segment, segment.neighbour, false); if (debug) { console.log("Setting facet " + f.id + " segment " + s + " to " + f.borderSegments[s]); } if (segment.neighbour !== -1) { const neighbourFacet = facetResult.facets[segment.neighbour]; // see if there is a match to be found let matchFound = false; if (neighbourFacet != null) { const neighbourSegments = segmentsPerFacet[segment.neighbour]; for (let ns: number = 0; ns < neighbourSegments.length; ns++) { const neighbourSegment = neighbourSegments[ns]; // only try to match against the segments that aren't processed yet // and which are adjacent to the boundary of the current facet if (neighbourSegment != null && neighbourSegment.neighbour === f.id) { const segStartPoint = segment.points[0]; const segEndPoint = segment.points[segment.points.length - 1]; const nSegStartPoint = neighbourSegment.points[0]; const nSegEndPoint = neighbourSegment.points[neighbourSegment.points.length - 1]; let matchesStraight = (segStartPoint.distanceTo(nSegStartPoint) <= MAX_DISTANCE && segEndPoint.distanceTo(nSegEndPoint) <= MAX_DISTANCE); let matchesReverse = (segStartPoint.distanceTo(nSegEndPoint) <= MAX_DISTANCE && segEndPoint.distanceTo(nSegStartPoint) <= MAX_DISTANCE); if (matchesStraight && matchesReverse) { // dang it , both match, it must be a tiny segment, but when placed wrongly it'll overlap in the path creating an hourglass // e.g. https://i.imgur.com/XZQhxRV.png // determine which is the closest if (segStartPoint.distanceTo(nSegStartPoint) + segEndPoint.distanceTo(nSegEndPoint) < segStartPoint.distanceTo(nSegEndPoint) + segEndPoint.distanceTo(nSegStartPoint)) { matchesStraight = true; matchesReverse = false; } else { matchesStraight = false; matchesReverse = true; } } if (matchesStraight) { // start & end points match if (debug) { console.log("Match found for facet " + f.id + " to neighbour " + neighbourFacet.id); } neighbourFacet!.borderSegments[ns] = new FacetBoundarySegment(segment, f.id, false); if (debug) { console.log("Setting facet " + neighbourFacet!.id + " segment " + ns + " to " + neighbourFacet!.borderSegments[ns]); } segmentsPerFacet[neighbourFacet.id][ns] = null; matchFound = true; break; } else if (matchesReverse) { // start & end points match but in reverse order if (debug) { console.log("Reverse match found for facet " + f.id + " to neighbour " + neighbourFacet.id); } neighbourFacet!.borderSegments[ns] = new FacetBoundarySegment(segment, f.id, true); if (debug) { console.log("Setting facet " + neighbourFacet!.id + " segment " + ns + " to " + neighbourFacet!.borderSegments[ns]); } segmentsPerFacet[neighbourFacet.id][ns] = null; matchFound = true; break; } } } } if (!matchFound && debug) { // it's possible that the border is not shared with its neighbour // this can happen when the segment fully falls inside the other facet // though the above checks in the preparation of the segments should probably // cover all cases console.error("No match found for segment of " + f.id + ": " + ("siding " + segment.neighbour + " " + segment.points[0] + " -> " + segment.points[segment.points.length - 1])); } } } // clear the current segment so it can't be processed again when processing the neighbour facet segmentsPerFacet[f.id][s] = null; } if (count % 100 === 0) { await delay(0); if (onUpdate != null) { onUpdate(f.id / facetResult.facets.length); } } } count++; } if (onUpdate != null) { onUpdate(1); } } }
the_stack
import {Inspection, InspectionTimeRange, InspectionTimeRangeType} from '@/services/data/tuples/inspection-types'; import {ICON_SELECTED} from '@/widgets/basic/constants'; import {DropdownOption} from '@/widgets/basic/types'; import {Lang} from '@/widgets/langs'; import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'; import { getValidAmPmRanges, getValidDayKindRanges, getValidDayOfMonthRanges, getValidDayOfWeekRanges, getValidHalfMonthRanges, getValidHalfWeekRanges, getValidHalfYearRanges, getValidHourKindRanges, getValidHourRanges, getValidMonthRanges, getValidQuarterRanges, getValidTenDaysRanges, getValidWeekOfMonthRanges, getValidWeekOfYearRanges, getValidYearRanges } from '../../../utils/range'; import { TimePeriodFilterDisplayLabel, TimePeriodFilterDisplayLabelSegment, TimePeriodFilterDropdownOption } from '../widgets'; import {FilterValidTimeRanges, RangeCandidate, RangeCreator, RangeEquation, RangesToLabel} from './types'; const buildOnValueChange = (options: { inspection: Inspection; filterValid: FilterValidTimeRanges; equals: RangeEquation; create: RangeCreator onValueChanged: () => void; }) => { const {inspection, filterValid, equals, create, onValueChanged} = options; return (option: DropdownOption) => { const value = option.value as number; if (value === -1) { delete inspection.timeRanges; onValueChanged(); } else { const ranges = filterValid(inspection); // eslint-disable-next-line if (ranges.some(range => equals(range, value))) { // eslint-disable-next-line inspection.timeRanges = ranges.filter(range => !equals(range, value)); } else { if (inspection!.timeRanges == null) { inspection!.timeRanges = []; } inspection!.timeRanges.push(create(value)); } onValueChanged(); return {active: true}; } }; }; const buildDropdownOptions = (options: { inspection: Inspection; filterValid: FilterValidTimeRanges; equals: RangeEquation; candidates: Array<RangeCandidate>; }) => { const {inspection, filterValid, candidates, equals} = options; const ranges = filterValid(inspection); return [ {value: -1, label: Lang.INDICATOR_WORKBENCH.INSPECTION.ALL_TIME_PERIOD}, ...candidates.map(candidate => { return { value: candidate.value, label: () => { // eslint-disable-next-line const selected = ranges.some(range => equals(range, candidate.value)); return { node: <TimePeriodFilterDropdownOption> <span>{candidate.node ?? candidate.label}</span> {selected ? <FontAwesomeIcon icon={ICON_SELECTED}/> : null} </TimePeriodFilterDropdownOption>, label: candidate.label }; } }; }) ]; }; const buildSelection = (options: { inspection: Inspection; toLabel: RangesToLabel }) => { const {inspection, toLabel} = options; return () => { const displayRanges = toLabel(inspection); if (displayRanges.length === 0) { return Lang.INDICATOR_WORKBENCH.INSPECTION.ALL_TIME_PERIOD; } else { return <TimePeriodFilterDisplayLabel>{displayRanges}</TimePeriodFilterDisplayLabel>; } }; }; const buildFilter = (options: { inspection: Inspection; filterValid: FilterValidTimeRanges; equals: RangeEquation; create: RangeCreator; candidates: Array<RangeCandidate>; toLabel: RangesToLabel; onValueChanged: () => void; }) => { const {inspection, filterValid, equals, create, candidates, toLabel, onValueChanged} = options; const onValueChange = buildOnValueChange({inspection, filterValid, equals, create, onValueChanged}); const dropdownOptions = buildDropdownOptions({inspection, filterValid, equals, candidates}); const selection = buildSelection({inspection, toLabel}); return {options: dropdownOptions, selection, onValueChange}; }; const build = (options: { inspection: Inspection; getValidRanges: (inspection: Inspection) => Array<InspectionTimeRange>; rangeType: InspectionTimeRangeType; candidates: Array<RangeCandidate>; onValueChanged: () => void; }) => { const {inspection, getValidRanges, rangeType, candidates, onValueChanged} = options; return buildFilter({ inspection, filterValid: inspection => getValidRanges(inspection), // eslint-disable-next-line equals: (range, value) => range.value == value, create: (value) => ({type: rangeType, value}), candidates, toLabel: (inspection: Inspection) => { return getValidRanges(inspection) .sort(({value: v1}, {value: v2}) => `${v1}`.localeCompare(`${v2}`, void 0, {numeric: true})) .map(range => { // eslint-disable-next-line const candidate = candidates.find(candidate => candidate.value == range.value); return <TimePeriodFilterDisplayLabelSegment key={range.value}> {candidate?.node ?? candidate?.label ?? range.value} </TimePeriodFilterDisplayLabelSegment>; }); }, onValueChanged }); }; export const buildYearsFilter = (inspection: Inspection, onValueChanged: () => void) => { const currentYear = new Date().getFullYear(); return build({ inspection, getValidRanges: getValidYearRanges, rangeType: InspectionTimeRangeType.YEAR, candidates: new Array(10).fill(1).map((_, index) => { return {value: currentYear - index, label: `${currentYear - index}`}; }), onValueChanged }); }; export const buildHalfYearsFilter = (inspection: Inspection, onValueChanged: () => void) => { return build({ inspection, getValidRanges: getValidHalfYearRanges, rangeType: InspectionTimeRangeType.HALF_YEAR, candidates: [ {value: 1, label: Lang.CALENDAR.HALF_YEAR_1ST}, {value: 2, label: Lang.CALENDAR.HALF_YEAR_2ND} ], onValueChanged }); }; export const buildQuartersFilter = (inspection: Inspection, onValueChanged: () => void) => { return build({ inspection, getValidRanges: getValidQuarterRanges, rangeType: InspectionTimeRangeType.QUARTER, candidates: [ {value: 1, label: Lang.CALENDAR.QUARTER_1ST}, {value: 2, label: Lang.CALENDAR.QUARTER_2ND}, {value: 3, label: Lang.CALENDAR.QUARTER_3RD}, {value: 4, label: Lang.CALENDAR.QUARTER_4TH} ], onValueChanged }); }; export const buildMonthsFilter = (inspection: Inspection, onValueChanged: () => void) => { return build({ inspection, getValidRanges: getValidMonthRanges, rangeType: InspectionTimeRangeType.MONTH, candidates: [ {value: 1, label: Lang.CALENDAR.JAN}, {value: 2, label: Lang.CALENDAR.FEB}, {value: 3, label: Lang.CALENDAR.MAR}, {value: 4, label: Lang.CALENDAR.APR}, {value: 5, label: Lang.CALENDAR.MAY}, {value: 6, label: Lang.CALENDAR.JUN}, {value: 7, label: Lang.CALENDAR.JUL}, {value: 8, label: Lang.CALENDAR.AUG}, {value: 9, label: Lang.CALENDAR.SEP}, {value: 10, label: Lang.CALENDAR.OCT}, {value: 11, label: Lang.CALENDAR.NOV}, {value: 12, label: Lang.CALENDAR.DEC} ], onValueChanged }); }; export const buildHalfMonthsFilter = (inspection: Inspection, onValueChanged: () => void) => { return build({ inspection, getValidRanges: getValidHalfMonthRanges, rangeType: InspectionTimeRangeType.HALF_MONTH, candidates: [ {value: 1, label: Lang.CALENDAR.HALF_MONTH_1ST}, {value: 2, label: Lang.CALENDAR.HALF_MONTH_2ND} ], onValueChanged }); }; export const buildTenDaysFilter = (inspection: Inspection, onValueChanged: () => void) => { return build({ inspection, getValidRanges: getValidTenDaysRanges, rangeType: InspectionTimeRangeType.TEN_DAYS, candidates: [ {value: 1, label: Lang.CALENDAR.TEN_DAYS_1ST}, {value: 2, label: Lang.CALENDAR.TEN_DAYS_2ND}, {value: 3, label: Lang.CALENDAR.TEN_DAYS_3RD} ], onValueChanged }); }; export const buildWeeksOfYearFilter = (inspection: Inspection, onValueChanged: () => void) => { return build({ inspection, getValidRanges: getValidWeekOfYearRanges, rangeType: InspectionTimeRangeType.WEEK_OF_YEAR, candidates: new Array(54).fill(1).map((_, index) => { return {value: index, label: `${index}`, node: <>{Lang.CALENDAR.WEEK} #{index}</>}; }), onValueChanged }); }; export const buildWeeksOfMonthFilter = (inspection: Inspection, onValueChanged: () => void) => { return build({ inspection, getValidRanges: getValidWeekOfMonthRanges, rangeType: InspectionTimeRangeType.WEEK_OF_MONTH, candidates: [ {value: 0, label: Lang.CALENDAR.WEEK_0}, {value: 1, label: Lang.CALENDAR.WEEK_1}, {value: 2, label: Lang.CALENDAR.WEEK_2}, {value: 3, label: Lang.CALENDAR.WEEK_3}, {value: 4, label: Lang.CALENDAR.WEEK_4}, {value: 5, label: Lang.CALENDAR.WEEK_5} ], onValueChanged }); }; export const buildHalfWeeksFilter = (inspection: Inspection, onValueChanged: () => void) => { return build({ inspection, getValidRanges: getValidHalfWeekRanges, rangeType: InspectionTimeRangeType.HALF_WEEK, candidates: [ {value: 1, label: Lang.CALENDAR.HALF_WEEK_1ST}, {value: 2, label: Lang.CALENDAR.HALF_WEEK_2ND} ], onValueChanged }); }; export const buildDaysOfMonthFilter = (inspection: Inspection, onValueChanged: () => void) => { return build({ inspection, getValidRanges: getValidDayOfMonthRanges, rangeType: InspectionTimeRangeType.DAY_OF_MONTH, candidates: new Array(31).fill(1).map((_, index) => { return {value: index + 1, label: `#${index + 1}`}; }), onValueChanged }); }; export const buildDaysOfWeekFilter = (inspection: Inspection, onValueChanged: () => void) => { return build({ inspection, getValidRanges: getValidDayOfWeekRanges, rangeType: InspectionTimeRangeType.DAY_OF_WEEK, candidates: [ {value: 1, label: Lang.CALENDAR.SUNDAY}, {value: 2, label: Lang.CALENDAR.MONDAY}, {value: 3, label: Lang.CALENDAR.TUESDAY}, {value: 4, label: Lang.CALENDAR.WEDNESDAY}, {value: 5, label: Lang.CALENDAR.THURSDAY}, {value: 6, label: Lang.CALENDAR.FRIDAY}, {value: 7, label: Lang.CALENDAR.SATURDAY} ], onValueChanged }); }; export const buildDayKindsFilter = (inspection: Inspection, onValueChanged: () => void) => { return build({ inspection, getValidRanges: getValidDayKindRanges, rangeType: InspectionTimeRangeType.DAY_KIND, candidates: [ {value: 1, label: Lang.CALENDAR.WORKDAY}, {value: 2, label: Lang.CALENDAR.WEEKEND}, {value: 3, label: Lang.CALENDAR.HOLIDAY} ], onValueChanged }); }; export const buildHoursFilter = (inspection: Inspection, onValueChanged: () => void) => { return build({ inspection, getValidRanges: getValidHourRanges, rangeType: InspectionTimeRangeType.HOUR, candidates: new Array(24).fill(1).map((_, index) => { return {value: index, label: `[${index}:00, ${index + 1}:00)`}; }), onValueChanged }); }; export const buildHourKindsFilter = (inspection: Inspection, onValueChanged: () => void) => { return build({ inspection, getValidRanges: getValidHourKindRanges, rangeType: InspectionTimeRangeType.HOUR_KIND, candidates: [ {value: 1, label: Lang.CALENDAR.WORK_TIME}, {value: 2, label: Lang.CALENDAR.OFF_HOURS}, {value: 3, label: Lang.CALENDAR.SLEEPING_TIME} ], onValueChanged }); }; export const buildAmPmFilter = (inspection: Inspection, onValueChanged: () => void) => { return build({ inspection, getValidRanges: getValidAmPmRanges, rangeType: InspectionTimeRangeType.AM_PM, candidates: [ {value: 1, label: Lang.CALENDAR.AM}, {value: 2, label: Lang.CALENDAR.PM} ], onValueChanged }); };
the_stack
import {Component, Input, NgModule, OnInit} from "@angular/core"; import {CommonModule} from "@angular/common"; import sdk from '@stackblitz/sdk'; import {CommonUtils} from "../../jigsaw/common/core/utils/common-utils"; import {JigsawMarkdownModule} from "../markdown/markdown"; import {MockData} from "../app.interceptor"; const urlParams = CommonUtils.parseUrlParam(location.search.substr(1)); @Component({ selector: 'jigsaw-demo-description, j-demo-description', styles: [` hr { margin: 3px 0 10px 0; } div { padding-top: 6px; } .summary { font-size: 16px; } .links { margin-left: 12px; font-size: 12px; } `], template: ` <div style="max-width: calc(100vw - 340px)"> <span class="summary" [innerHtml]="summary"></span> <span class="links"> <span *ngIf="!!content">|</span> <a *ngIf="!!content" (click)="toggleDesc()">{{showDetail ? '隐藏' : '展开'}}详情</a> | <a (click)="openDemoCode()">查看本DEMO源码</a> </span> <br *ngIf="showDetail"> <jigsaw-markdown *ngIf="showDetail" [markdown]="content"></jigsaw-markdown> <br> <span class="links" *ngIf="showDetail && !!content"> <a (click)="showDetail = !showDetail">{{showDetail ? '隐藏' : '展开'}}详情</a> | <a (click)="openDemoCode()">查看本DEMO源码</a> </span> </div> <hr> ` }) export class JigsawDemoDescription implements OnInit { @Input() showDetail: boolean = undefined; @Input() content: string = ''; @Input() codes: any; private _summary: string; @Input() get summary(): string { return this._summary; } set summary(value: string) { value = value ? value : '这个demo暂无使用说明,有任何疑问的话,' + '请将你的疑问<a href="https://github.com/rdkmaster/jigsaw" target="_blank">填写</a>在issue里,' + '我们会尽快协助你解决问题'; this._summary = value.replace(/`(.*?)`/g, '<code>$1</code>'); } openDemoCode() { const projectData = this.createProjectData(); if (!projectData) { alert('如需使用这个功能,请执行patch-demos.js对这些demo打补丁,打补丁过程会修改demo的源码,请备份demo的修改,避免丢失。'); return; } window.name = 'jigsaw-demo-main'; const url = location.href.replace(/#/, '#/demo-code'); const win: any = window.open(url, 'jigsaw-demo-code'); win.getJigsawDemoCode = () => (projectData); } createProjectData(): any { const project: any = {files: {}}; let hasFile = false; for (let file in this.codes) { if (!this.codes.hasOwnProperty(file)) { continue; } hasFile = true; let code = this.codes[file]; if (file.match(/.+\.ts$/i)) { code = fixImport(code); code = fixTemplateUrl(code); code = fixStyleUrls(code); code = fixCodeForDemoOnly(code); } project.files[`src/app/${file}`] = code; } if (!hasFile) { return; } const moduleCode = project.files[`src/app/demo.module.ts`]; project.files[`src/app/demo.module.ts`] = fixDemoModuleTs(moduleCode); const cmpCode = project.files[`src/app/demo.component.ts`]; project.files[`src/app/demo.component.ts`] = fixDemoComponentTs(cmpCode, moduleCode); const htmlCode = project.files[`src/app/demo.component.html`]; project.files[`src/app/demo.component.html`] = fixDemoComponentHtml(htmlCode); project.dependencies = getDependencies(); project.title = `Jigsaw demo url: ${location.href}`; project.description = this.summary.replace(/<\/?\w+.*?>/g, '') + `\n\n${project.title}`; project.template = 'angular-cli'; project.tags = ['jigsaw', 'angular', 'zte', 'awade']; const moduleClassName = findModuleClassName(project.files['src/app/demo.module.ts']); const [angularJson, styles, scripts] = getAngularJson(project.dependencies); project.files['src/app/app.module.ts'] = getAppModuleTs(moduleClassName); project.files['src/app/app.component.ts'] = getAppComponentTS(); project.files['src/app/app.component.html'] = getAppComponentHtml(); project.files['src/app/app.interceptor.ts'] = getAjaxInterceptor(project.files); project.files['src/app/app.component.css'] = require('!!raw-loader!../../../src/app/live-demo-wrapper.css').default; project.files['src/main.ts'] = getMainTs(scripts); project.files['src/polyfills.ts'] = getPolyfills(); project.files['angular.json'] = angularJson; project.files['src/index.html'] = getIndexHtml(project.title, styles); return project; } toggleDesc() { this.showDetail = !this.showDetail; } ngOnInit() { if (this.showDetail === undefined) { this.showDetail = urlParams['open-desc'] == 'true'; } } } @NgModule({ declarations: [JigsawDemoDescription], imports: [JigsawMarkdownModule, CommonModule], exports: [JigsawDemoDescription] }) export class JigsawDemoDescriptionModule { } function getPolyfills() { return `import 'zone.js/dist/zone';`; } function getMainTs(scripts: string) { return ` import './polyfills'; import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; // ============================================================================= // 注意!这部分代码是为了适配当前这个运行时而做的针对性修改,实际情况下不能这么搞, // 请不要以这部分代码作为种子工程 // ============================================================================= const scripts = ${scripts}; loadScript(); function loadScript() { if (scripts.length == 0) { platformBrowserDynamic().bootstrapModule(AppModule).then(ref => { // Ensure Angular destroys itself on hot reloads. if (window['ngRef']) { window['ngRef'].destroy(); } window['ngRef'] = ref; // Otherwise, log the boot error }).catch(err => console.error(err)); return; } const src = scripts.shift(); const elements = document.head.getElementsByTagName('script'); for (let i = 0; i < elements.length; i++) { const element = elements[i]; if (element.getAttribute('src') == src) { loadScript(); return; } } console.log('Loading', src); const element = document.createElement('script'); element.type = 'text/javascript'; element.src = src; element.onload = () => { element.onload = null; loadScript(); }; document.head.appendChild(element); } `.trim(); } function getIndexHtml(title: string, styles: string) { return ` <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>${title}</title> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="icon" type="image/x-icon" href="favicon.ico"> ${styles} </head> <body style="margin: 12px"> <jigsaw-app> <div style="padding: 12px"> <h3>Demo正在运行,请稍候...</h3> <ul style="line-height: 24px;margin:12px 0 0 12px;list-style:circle;"> <li>访问 <a href="https://jigsaw-zte.gitee.io/" target="_blank"></a> 可以了解中兴大数据UED的更多信息;</li> <li>如果长时间停留在这个界面,那很可能Demo的运行出了问题,你可以继续浏览左边的代码;</li> <li>如果这个页面的控制台上有异常打印,那请你将这些打印通过 <a href="https://github.com/rdkmaster/jigsaw/issues/new">提交issue</a> 的方式告知我们,这可以帮助我们修复这个问题;</li> </ul> </div> </jigsaw-app> </body> </html>`.trim(); } function getAppComponentTS() { return ` import { Component,ViewEncapsulation } from "@angular/core"; @Component({ selector: 'jigsaw-app', styleUrls: ['./app.component.css'], templateUrl: './app.component.html', encapsulation: ViewEncapsulation.None }) export class AppComponent { }`.trim(); } function getAppComponentHtml() { return ` <jigsaw-root> <div class="app-wrap"> <jigsaw-demo></jigsaw-demo> </div> </jigsaw-root>`.trim(); } function getAppModuleTs(moduleClassName: string) { return ` import { NgModule } from "@angular/core"; import { HTTP_INTERCEPTORS, HttpClientModule } from "@angular/common/http"; import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { JigsawRootModule } from "@rdkmaster/jigsaw"; import { AjaxInterceptor } from "./app.interceptor"; import { AppComponent } from "./app.component"; import { ${moduleClassName} } from "./demo.module"; @NgModule({ declarations: [AppComponent], bootstrap: [AppComponent], providers: [ { provide: HTTP_INTERCEPTORS, useClass: AjaxInterceptor, multi: true, }, ], imports: [ BrowserModule, BrowserAnimationsModule, HttpClientModule, JigsawRootModule, ${moduleClassName} ] }) export class AppModule { }`.trim(); } function getAjaxInterceptor(files: any) { let code = require('!!raw-loader!../../../src/app/app.interceptor.ts').default; code = fixImport(code); // 不能位于在replace之后 let urls = findMockDataUrls(code, files); // merge all mock data json file into this class let re = /\bthis\.dataSet\s*\[\s*['"](.*?)['"]\s*]\s*=\s*require\s*\(['"](\.\.\/mock-data\/)?.+['"]\s*\);?\s*/g; code = code.replace(re, (found, prop) => { const file = `mock-data/${prop}`; const using = urls.indexOf(file) != -1; return using ? `this.dataSet['${prop}'] = ${JSON.stringify(MockData.get(file))};` : ''; }); if (urls.indexOf(`mock-data/big-table-data`) == -1) { code = code.replace(/this\.dataSet\['big-table-data'] = .*;?\s*/, ''); } return code; } function findMockDataUrls(interceptorCode: string, files: any): string[] { let match = interceptorCode.match(/\bthis\.dataSet\s*\[\s*['"].*?['"]\s*]\s*=/g); if (!match) { console.error('ERROR: parse app.interceptor.ts failed, no mock-data url found!'); return []; } let allUrls = []; match.forEach(item => allUrls.push('mock-data/' + item.match(/['"]\s*(.*?)\s*['"]/)[1])); if (allUrls.length == 0) { console.error('ERROR: parse app.interceptor.ts failed, no mock-data url found! allUrls.length == 0'); return []; } return allUrls.filter(url => { for (let file in files) { if (!files.hasOwnProperty(file)) { continue; } if (!file.match(/^src\/app\/.*\.ts$/i)) { continue; } // 如果demo的代码的注释部分有这个url,则会有bug,仅靠静态分析如何解决? const re = new RegExp('[\'"`/]' + url + '[\'"`]'); if (files[file].match(re)) { return true; } } return false; }); } function getAngularJson(deps: any): [string, string, string] { const json: any = CommonUtils.deepCopy(require('./angular.json')); if (json.hasOwnProperty('jigsawTips')) { return null; } const options = json.projects['jigsaw-seed'].architect.build.options; const toUnpkgUrl = (entry: string): string => { const re = entry.indexOf('@') == -1 ? /\bnode_modules\/(.*?)\/(.*)/ : /\bnode_modules\/(.*?\/.*?)\/(.*)/; const match = entry.match(re); let version = deps[match[1]]; version = !!version ? `@${version}` : ''; return `https://unpkg.com/${match[1]}${version}/${match[2]}`; }; // 由于stackblitz加载这里的styles会有问题,因此把这里的styles依赖挪到index.html里去 const styles: string = options.styles.concat(["./node_modules/@rdkmaster/jigsaw/prebuilt-themes/paletx-pro-light.css"]) .filter(style => style.match(/^(\.\/)?node_modules\/.+/)) .map(style => ` <link rel="stylesheet" type="text/css" href="${toUnpkgUrl(style)}">`) .join('\n'); options.styles = []; const scripts: string = JSON.stringify(options.scripts.map(script => toUnpkgUrl(script)), null, ' '); options.scripts = []; return [JSON.stringify(json, null, ' '), styles, scripts]; } function getDependencies() { const json: any = require('./package.json'); if (json.hasOwnProperty('jigsawTips')) { return null; } return {...json.dependencies, ...json.devDependencies}; } function fixImport(code: string): string { let jigsawImports = []; let rawImports = []; while (true) { let match = code.match(/\bimport\s+{([\s\S]+?)}\s+from\s+['"](.+?)['"]/); if (!match) { break; } if (match[2].match(/jigsaw\/.+?/)) { let importString = match[1]; let imports = importString.split(/,/g).map(item => item.trim()); imports.forEach(item => { if (!!item) jigsawImports.push(item) }); } else if (match[1].includes('AjaxInterceptor')) { rawImports.push('import {AjaxInterceptor} from "./app.interceptor"'); } else { rawImports.push(match[0]); } code = code.substring(match.index + match[0].length); } jigsawImports = jigsawImports.sort((a, b) => a.localeCompare(b)); let jigsawImportString = ''; if (jigsawImports.length > 0) { jigsawImportString = 'import {\n'; for (let i = 0, len = jigsawImports.length; i < len; i += 3) { jigsawImportString += ' ' + jigsawImports.slice(i, i + 3).join(', ') + ',\n'; } jigsawImportString += '} from "@rdkmaster/jigsaw";'; } return jigsawImportString + '\n' + rawImports.join(';\n') + code; } function fixTemplateUrl(code: string): string { return code.replace(/\btemplateUrl\s*:\s*['"]\s*(.*?)\s*['"]/g, (found, templateUrl) => { if (templateUrl.substring(0, 2) !== './') { templateUrl = './' + templateUrl; } return 'templateUrl: "' + templateUrl + '"'; }); } function fixStyleUrls(code: string): string { return code.replace(/\bstyleUrls\s*:\s*(\[[\s\S]*?])/g, (found, urlString) => { let urls = eval(urlString); urls = urls.map(url => { if (url.substring(0, 2) !== './') { url = './' + url; } return url; }); return 'styleUrls: ["' + urls.join('", "') + '"]'; }); } function fixCodeForDemoOnly(code: string): string { return code.replace(/\/\* #for-live-demo-only#([\s\S]*?)\*\//g, (found, codeForDemo) => codeForDemo.trim()); } function fixDemoModuleTs(moduleCode: string): string { // 删除 JigsawDemoDescriptionModule 相关的东西 moduleCode = moduleCode.replace(/import\s*{\s*JigsawDemoDescriptionModule\s*}\s*from.*\r?\n/, ''); moduleCode = moduleCode.replace(/\bJigsawDemoDescriptionModule\b\s*,?/g, ''); return moduleCode; } function findExportsComponent(moduleCode: string): string { // 如果demo代码中,把exports这行给注释掉了,则会有bug,仅靠静态分析如何解决这个问题? const match = moduleCode.match(/@NgModule\s*\(\s*{[\s\S]*\bexports\s*:\s*\[\s*(\w+)\s*]/); return match && match[1] ? match[1] : ''; } function fixDemoComponentTs(cmpCode: string, moduleCode: string): string { let mainComp = findExportsComponent(moduleCode); if (!mainComp) { return 'throw `看来Jigsaw自动生成的Demo代码出了问题了,请把这些文本拷贝一下,并在这里创建一个issue: ' + 'https://github.com/rdkmaster/jigsaw/issues/new 这样可以协助我们解决这个问题。' + '错误详情为:Need a "exports" property in the module code, and the value of which should contains only one component,' + 'DEMO的URL为:' + location.href + '`\n\n\n// ============================\n// 以下这些是此demo的原始代码\n' + cmpCode.replace(/^/gm, '// --> '); } cmpCode = cmpCode // 给组件加上jigsaw-demo的selector,这个在index.html里会用到 .replace(/@Component\s*\(\s*{([\s\S]*?)}\s*\)[\s\S]*?export\s+class\s+(\w+?)\b/g, (found, props, className) => { if (className != mainComp) { // 在demo.component.ts文件中可能被定义了多个组件 return found; } // 后面会自动给添加一个selector,这里如果有,就要删掉 return found.replace(/\bselector\s*:\s*['"].*?['"],?\s*/, '') .replace(/@Component\s*\(\s*{/, '@Component({\n selector: "jigsaw-demo",'); }) // 去掉demo-desc相关的变量 .replace(/\s*\/\/\s*={60,}\s+\/\/[\s\S]*\/\/\s*={60,}\s+/, '\n'); // 类似 cascade/lazy-load 这样的用例,有通过require获取静态json数据,需要把这些文件加进来 cmpCode = cmpCode.replace(/\bMockData\s*\.\s*get\s*\(\s*['"`]\s*(mock-data\/.*?)\s*['"`]\s*\);?/g, // 这里必须采用webpack的内部api来读取main.bundle里的数据 (found, file) => JSON.stringify(MockData.get(file), null, ' ')); return cmpCode; } function fixDemoComponentHtml(html: string): string { return html .replace(/<!-- ignore the following lines[\s\S]*<!-- start to learn the demo from here -->\r?\n/, '') .replace(/<j(igsaw)?-demo-description\s+.+>[\s\S]*?<\/j(igsaw)?-demo-description>/, ''); } function findModuleClassName(moduleCode: string): string { const match = moduleCode.match(/@NgModule\s*\(\s*{[\s\S]*?}\s*\)[\s\S]*?export\s+class\s+(\w+?)\b/); return match[1]; }
the_stack
import { CSSResultGroup, unsafeCSS } from 'lit'; import { EmblaCarouselType } from 'embla-carousel'; import { createRef, Ref } from 'lit/directives/ref'; import { customElement } from 'lit/decorators.js'; import { FrigateCardCarousel } from './carousel.js'; import type { MediaShowInfo } from '../types.js'; import { dispatchExistingMediaShowInfoAsEvent, isValidMediaShowInfo, } from '../common.js'; import './next-prev-control.js'; import mediaCarouselStyle from '../scss/media-carousel.scss'; import { FrigateCardNextPreviousControl } from './next-prev-control.js'; const getEmptyImageSrc = (width: number, height: number) => `data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}"%3E%3C/svg%3E`; export const IMG_EMPTY = getEmptyImageSrc(16, 9); @customElement('frigate-card-media-carousel') export class FrigateCardMediaCarousel extends FrigateCardCarousel { // A "map" from slide number to MediaShowInfo object. protected _mediaShowInfo: Record<number, MediaShowInfo> = {}; // Whether or not a given slide has been successfully lazily loaded. protected _slideHasBeenLazyLoaded: Record<number, boolean> = {}; protected _nextControlRef: Ref<FrigateCardNextPreviousControl> = createRef(); protected _previousControlRef: Ref<FrigateCardNextPreviousControl> = createRef(); /** * Returns the number of slides to lazily load. 0 means all slides are lazy * loaded, 1 means that 1 slide on each side of the currently selected slide * should lazy load, etc. `null` means lazy loading is disabled and everything * should load simultaneously. * @returns */ protected _getLazyLoadCount(): number | null { // Defaults to fully-lazy loading. return 0; } /** * Determine if lazy loading is being used. * @returns `true` is lazy loading is in use. */ protected _isLazyLoading(): boolean { return this._getLazyLoadCount() !== null; } protected _destroyCarousel(): void { super._destroyCarousel(); // Notes on instance variables: // * this._mediaShowInfo: This is set when the media in the DOM loads. If a // new View included the same media, the DOM would not change and so the // prior contents would still be valid and would not re-appear (as the // media would not reload) -- as such, leave this alone on carousel // destroy. New media in that slide will replace the prior contents on // load. // * this._slideHasBeenLazyLoaded: This is a performance optimization and // can be safely reset. this._slideHasBeenLazyLoaded = {}; } /** * Initialize the carousel. */ protected _initCarousel(): void { super._initCarousel(); // Necessary because typescript local type narrowing is not paying attention // to the side-effect of the call to super._initCarousel(). const carousel = this._carousel as EmblaCarouselType | undefined; // Update the view object as the carousel is moved. carousel?.on('select', this._selectSlideSetViewHandler.bind(this)); // Update the next/previous controls as the carousel is moved. carousel?.on('select', this._selectSlideNextPreviousHandler.bind(this)); // Dispatch MediaShow events as the carousel is moved. carousel?.on('init', this._selectSlideMediaShowHandler.bind(this)); carousel?.on('select', this._selectSlideMediaShowHandler.bind(this)); // Adapt the height of the container to the media as the carousel is moved. carousel?.on('init', this._adaptiveHeightResizeHandler.bind(this)); carousel?.on('resize', this._adaptiveHeightResizeHandler.bind(this)); carousel?.on('init', this._adaptiveHeightSetHandler.bind(this)); carousel?.on('select', this._adaptiveHeightSetHandler.bind(this)); carousel?.on('resize', this._adaptiveHeightSetHandler.bind(this)); if (this._getLazyLoadCount() != null) { // Load media as the carousel is moved (if lazy loading is in use). carousel?.on('init', this._lazyLoadMediaHandler.bind(this)); carousel?.on('select', this._lazyLoadMediaHandler.bind(this)); carousel?.on('resize', this._lazyLoadMediaHandler.bind(this)); } } /** * Remove height restrictions on the media when the carousel is resized to let * it naturally render. * @returns */ protected _adaptiveHeightResizeHandler(): void { if (!this._carousel) { return; } this._carousel.containerNode().style.removeProperty('max-height'); } /** * Adapt the height of the container to the height of the media (for cases * where the carousel has different media heights, e.g. live cameras with * different aspect ratios). */ protected _adaptiveHeightSetHandler(): void { // Don't gather slide heights until the next browser re-paint to ensure the // measured heights are correct on the media that has (potentially) just // loaded. window.requestAnimationFrame(() => { if (!this._carousel) { return; } const slides = this._carousel.slideNodes(); const heights = this._carousel.slidesInView(true).map((index) => { return slides[index].getBoundingClientRect().height; }); const targetHeight = Math.max(...heights); if (targetHeight > 0) { this._carousel.containerNode().style.maxHeight = `${targetHeight}px`; } else { this._carousel.containerNode().style.removeProperty('max-height'); } }); } /** * Handle the user selecting a new slide in the carousel. */ protected _selectSlideSetViewHandler(): void { // To be overridden in children. } /** * Handle updating of the next/previous controls when the carousel is moved. */ protected _selectSlideNextPreviousHandler(): void { // To be overridden in children. } /** * Handle a next/previous control interaction. * @param direction The direction requested, previous or next. */ protected _nextPreviousHandler(direction: 'previous' | 'next'): void { if (direction == 'previous') { this._carousel?.scrollPrev(); } else if (direction == 'next') { this._carousel?.scrollNext(); } } /** * Lazily load media in the carousel. */ protected _lazyLoadMediaHandler(): void { if (!this._carousel) { return; } const lazyLoadCount = this._getLazyLoadCount(); if (lazyLoadCount === null) { return; } const slides = this._carousel.slideNodes(); const slidesInView = this._carousel.slidesInView(true); const slidesToLoad = new Set<number>(); const minSlide = Math.min(...slidesInView); const maxSlide = Math.max(...slidesInView); // Lazily load 'lazyLoadCount' slides on either side of the slides in view. for (let i = 1; i <= lazyLoadCount && minSlide - i >= 0; i++) { slidesToLoad.add(minSlide - i); } slidesInView.forEach((index) => slidesToLoad.add(index)); for (let i = 1; i <= lazyLoadCount && maxSlide + i < slides.length; i++) { slidesToLoad.add(maxSlide + i); } slidesToLoad.forEach((index) => { // Only lazy load slides that are not already loaded. if (this._slideHasBeenLazyLoaded[index]) { return; } this._slideHasBeenLazyLoaded[index] = true; this._lazyLoadSlide(index, slides[index]); }); } /** * Lazy load a slide. * @param _index The index of the slide to lazy load. * @param _slide The slide to lazy load. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars protected _lazyLoadSlide(_index: number, _slide: HTMLElement): void { // To be overridden in children. } /** * Fire a media show event when a slide is selected. */ protected _selectSlideMediaShowHandler(): void { if (!this._carousel) { return; } this._carousel.slidesInView(true).forEach((slideIndex) => { if (slideIndex in this._mediaShowInfo) { dispatchExistingMediaShowInfoAsEvent(this, this._mediaShowInfo[slideIndex]); } }); } /** * Handle a media-show event that is generated by a child component, saving the * contents for future use when the relevant slide is actually shown. * @param slideIndex The relevant slide index. * @param event The media-show event from the child component. */ protected _mediaShowEventHandler( slideIndex: number, event: CustomEvent<MediaShowInfo>, ): void { // Don't allow the inbound event to propagate upwards, that will be // automatically done at the appropriate time as the slide is shown. event.stopPropagation(); this._mediaLoadedHandler(slideIndex, event.detail); } /** * Handle a MediaShowInfo object that is generated on media load, by saving it * for future, or immediate use, when the relevant slide is displayed. * @param slideIndex The relevant slide index. * @param mediaShowInfo The MediaShowInfo object generated by the media. */ protected _mediaLoadedHandler( slideIndex: number, mediaShowInfo?: MediaShowInfo | null, ): void { // isValidMediaShowInfo is used to prevent saving media info that will be // rejected upstream (empty 1x1 images will be rejected here). if (mediaShowInfo && isValidMediaShowInfo(mediaShowInfo)) { this._mediaShowInfo[slideIndex] = mediaShowInfo; if (this._carousel && this._carousel?.slidesInView(true).includes(slideIndex)) { dispatchExistingMediaShowInfoAsEvent(this, mediaShowInfo); } // After media has been loaded, the height of the container may need to be // re-adjusted. this._adaptiveHeightSetHandler(); /** * Images need a width/height from initial load, and browsers will assume * that the aspect ratio of the initial dummy-image load will persist. In * lazy-loading, this can cause a 1x1 pixel dummy image to cause the * browser to assume all images will be square, so the whole carousel will * have the wrong aspect-ratio until every single image has been lazily * loaded. Adaptive height helps in that the carousel gets resized on each * img display to the correct size, but it still causes a minor noticeable * flicker until the height change is complete. * * To avoid this, we use a 16:9 dummy image at first (most * likely?) and once the first piece of real media has been loaded, all * dummy images are replaced with dummy images that match the aspect ratio * of the real image. It still might be wrong, but it's the best option * available. */ const firstMediaLoad = !Object.keys(this._mediaShowInfo).length; if (firstMediaLoad && this._getLazyLoadCount() != null) { const replacementImageSrc = getEmptyImageSrc( mediaShowInfo.width, mediaShowInfo.height, ); this.renderRoot.querySelectorAll('.embla__container img').forEach((img) => { const imageElement = img as HTMLImageElement; if (imageElement.src === IMG_EMPTY) { imageElement.src = replacementImageSrc; } }); } } } /** * Get element styles. */ static get styles(): CSSResultGroup { return [super.styles, unsafeCSS(mediaCarouselStyle)]; } }
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * IoTSpaces * __NOTE__: An instance of this class is automatically created for an * instance of the IoTSpacesClient. */ export interface IoTSpaces { /** * Get the metadata of a IoTSpaces instance. * * @param {string} resourceGroupName The name of the resource group that * contains the IoTSpaces instance. * * @param {string} resourceName The name of the IoTSpaces instance. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IoTSpacesDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IoTSpacesDescription>>; /** * Get the metadata of a IoTSpaces instance. * * @param {string} resourceGroupName The name of the resource group that * contains the IoTSpaces instance. * * @param {string} resourceName The name of the IoTSpaces instance. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IoTSpacesDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IoTSpacesDescription} [result] - The deserialized result object if an error did not occur. * See {@link IoTSpacesDescription} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IoTSpacesDescription>; get(resourceGroupName: string, resourceName: string, callback: ServiceCallback<models.IoTSpacesDescription>): void; get(resourceGroupName: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IoTSpacesDescription>): void; /** * Create or update the metadata of an IoTSpaces instance. The usual pattern to * modify a property is to retrieve the IoTSpaces instance metadata and * security metadata, and then combine them with the modified values in a new * body to update the IoTSpaces instance. * * @param {string} resourceGroupName The name of the resource group that * contains the IoTSpaces instance. * * @param {string} resourceName The name of the IoTSpaces instance. * * @param {object} iotSpaceDescription The IoTSpaces instance metadata and * security metadata. * * @param {object} [iotSpaceDescription.properties] The common properties of a * IoTSpaces service. * * @param {object} [iotSpaceDescription.properties.storageContainer] The * properties of the designated storage container. * * @param {string} * [iotSpaceDescription.properties.storageContainer.connectionString] The * connection string of the storage account. * * @param {string} * [iotSpaceDescription.properties.storageContainer.subscriptionId] The * subscription identifier of the storage account. * * @param {string} * [iotSpaceDescription.properties.storageContainer.resourceGroup] The name of * the resource group of the storage account. * * @param {string} * [iotSpaceDescription.properties.storageContainer.containerName] The name of * storage container in the storage account. * * @param {object} iotSpaceDescription.sku A valid instance SKU. * * @param {string} iotSpaceDescription.sku.name The name of the SKU. Possible * values include: 'F1', 'S1', 'S2', 'S3' * * @param {string} iotSpaceDescription.location The resource location. * * @param {object} [iotSpaceDescription.tags] The resource tags. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IoTSpacesDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, resourceName: string, iotSpaceDescription: models.IoTSpacesDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IoTSpacesDescription>>; /** * Create or update the metadata of an IoTSpaces instance. The usual pattern to * modify a property is to retrieve the IoTSpaces instance metadata and * security metadata, and then combine them with the modified values in a new * body to update the IoTSpaces instance. * * @param {string} resourceGroupName The name of the resource group that * contains the IoTSpaces instance. * * @param {string} resourceName The name of the IoTSpaces instance. * * @param {object} iotSpaceDescription The IoTSpaces instance metadata and * security metadata. * * @param {object} [iotSpaceDescription.properties] The common properties of a * IoTSpaces service. * * @param {object} [iotSpaceDescription.properties.storageContainer] The * properties of the designated storage container. * * @param {string} * [iotSpaceDescription.properties.storageContainer.connectionString] The * connection string of the storage account. * * @param {string} * [iotSpaceDescription.properties.storageContainer.subscriptionId] The * subscription identifier of the storage account. * * @param {string} * [iotSpaceDescription.properties.storageContainer.resourceGroup] The name of * the resource group of the storage account. * * @param {string} * [iotSpaceDescription.properties.storageContainer.containerName] The name of * storage container in the storage account. * * @param {object} iotSpaceDescription.sku A valid instance SKU. * * @param {string} iotSpaceDescription.sku.name The name of the SKU. Possible * values include: 'F1', 'S1', 'S2', 'S3' * * @param {string} iotSpaceDescription.location The resource location. * * @param {object} [iotSpaceDescription.tags] The resource tags. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IoTSpacesDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IoTSpacesDescription} [result] - The deserialized result object if an error did not occur. * See {@link IoTSpacesDescription} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, resourceName: string, iotSpaceDescription: models.IoTSpacesDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IoTSpacesDescription>; createOrUpdate(resourceGroupName: string, resourceName: string, iotSpaceDescription: models.IoTSpacesDescription, callback: ServiceCallback<models.IoTSpacesDescription>): void; createOrUpdate(resourceGroupName: string, resourceName: string, iotSpaceDescription: models.IoTSpacesDescription, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IoTSpacesDescription>): void; /** * Update the metadata of a IoTSpaces instance. * * @param {string} resourceGroupName The name of the resource group that * contains the IoTSpaces instance. * * @param {string} resourceName The name of the IoTSpaces instance. * * @param {object} iotSpacePatchDescription The IoTSpaces instance metadata and * security metadata. * * @param {object} [iotSpacePatchDescription.tags] Instance tags * * @param {object} [iotSpacePatchDescription.properties] The common properties * of an IoTSpaces service. * * @param {object} [iotSpacePatchDescription.properties.storageContainer] The * properties of the designated storage container. * * @param {string} * [iotSpacePatchDescription.properties.storageContainer.connectionString] The * connection string of the storage account. * * @param {string} * [iotSpacePatchDescription.properties.storageContainer.subscriptionId] The * subscription identifier of the storage account. * * @param {string} * [iotSpacePatchDescription.properties.storageContainer.resourceGroup] The * name of the resource group of the storage account. * * @param {string} * [iotSpacePatchDescription.properties.storageContainer.containerName] The * name of storage container in the storage account. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IoTSpacesDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, resourceName: string, iotSpacePatchDescription: models.IoTSpacesPatchDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IoTSpacesDescription>>; /** * Update the metadata of a IoTSpaces instance. * * @param {string} resourceGroupName The name of the resource group that * contains the IoTSpaces instance. * * @param {string} resourceName The name of the IoTSpaces instance. * * @param {object} iotSpacePatchDescription The IoTSpaces instance metadata and * security metadata. * * @param {object} [iotSpacePatchDescription.tags] Instance tags * * @param {object} [iotSpacePatchDescription.properties] The common properties * of an IoTSpaces service. * * @param {object} [iotSpacePatchDescription.properties.storageContainer] The * properties of the designated storage container. * * @param {string} * [iotSpacePatchDescription.properties.storageContainer.connectionString] The * connection string of the storage account. * * @param {string} * [iotSpacePatchDescription.properties.storageContainer.subscriptionId] The * subscription identifier of the storage account. * * @param {string} * [iotSpacePatchDescription.properties.storageContainer.resourceGroup] The * name of the resource group of the storage account. * * @param {string} * [iotSpacePatchDescription.properties.storageContainer.containerName] The * name of storage container in the storage account. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IoTSpacesDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IoTSpacesDescription} [result] - The deserialized result object if an error did not occur. * See {@link IoTSpacesDescription} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, resourceName: string, iotSpacePatchDescription: models.IoTSpacesPatchDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IoTSpacesDescription>; update(resourceGroupName: string, resourceName: string, iotSpacePatchDescription: models.IoTSpacesPatchDescription, callback: ServiceCallback<models.IoTSpacesDescription>): void; update(resourceGroupName: string, resourceName: string, iotSpacePatchDescription: models.IoTSpacesPatchDescription, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IoTSpacesDescription>): void; /** * Delete an IoTSpaces instance. * * @param {string} resourceGroupName The name of the resource group that * contains the IoTSpaces instance. * * @param {string} resourceName The name of the IoTSpaces instance. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IoTSpacesDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IoTSpacesDescription>>; /** * Delete an IoTSpaces instance. * * @param {string} resourceGroupName The name of the resource group that * contains the IoTSpaces instance. * * @param {string} resourceName The name of the IoTSpaces instance. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IoTSpacesDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IoTSpacesDescription} [result] - The deserialized result object if an error did not occur. * See {@link IoTSpacesDescription} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IoTSpacesDescription>; deleteMethod(resourceGroupName: string, resourceName: string, callback: ServiceCallback<models.IoTSpacesDescription>): void; deleteMethod(resourceGroupName: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IoTSpacesDescription>): void; /** * Get all the IoTSpaces instances in a subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IoTSpacesDescriptionListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IoTSpacesDescriptionListResult>>; /** * Get all the IoTSpaces instances in a subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IoTSpacesDescriptionListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IoTSpacesDescriptionListResult} [result] - The deserialized result object if an error did not occur. * See {@link IoTSpacesDescriptionListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IoTSpacesDescriptionListResult>; list(callback: ServiceCallback<models.IoTSpacesDescriptionListResult>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IoTSpacesDescriptionListResult>): void; /** * Get all the IoTSpaces instances in a resource group. * * @param {string} resourceGroupName The name of the resource group that * contains the IoTSpaces instance. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IoTSpacesDescriptionListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IoTSpacesDescriptionListResult>>; /** * Get all the IoTSpaces instances in a resource group. * * @param {string} resourceGroupName The name of the resource group that * contains the IoTSpaces instance. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IoTSpacesDescriptionListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IoTSpacesDescriptionListResult} [result] - The deserialized result object if an error did not occur. * See {@link IoTSpacesDescriptionListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IoTSpacesDescriptionListResult>; listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.IoTSpacesDescriptionListResult>): void; listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IoTSpacesDescriptionListResult>): void; /** * Check if an IoTSpaces instance name is available. * * @param {object} operationInputs Set the name parameter in the * OperationInputs structure to the name of the IoTSpaces instance to check. * * @param {string} operationInputs.name The name of the IoTSpaces service * instance to check. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IoTSpacesNameAvailabilityInfo>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ checkNameAvailabilityWithHttpOperationResponse(operationInputs: models.OperationInputs, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IoTSpacesNameAvailabilityInfo>>; /** * Check if an IoTSpaces instance name is available. * * @param {object} operationInputs Set the name parameter in the * OperationInputs structure to the name of the IoTSpaces instance to check. * * @param {string} operationInputs.name The name of the IoTSpaces service * instance to check. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IoTSpacesNameAvailabilityInfo} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IoTSpacesNameAvailabilityInfo} [result] - The deserialized result object if an error did not occur. * See {@link IoTSpacesNameAvailabilityInfo} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ checkNameAvailability(operationInputs: models.OperationInputs, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IoTSpacesNameAvailabilityInfo>; checkNameAvailability(operationInputs: models.OperationInputs, callback: ServiceCallback<models.IoTSpacesNameAvailabilityInfo>): void; checkNameAvailability(operationInputs: models.OperationInputs, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IoTSpacesNameAvailabilityInfo>): void; /** * Create or update the metadata of an IoTSpaces instance. The usual pattern to * modify a property is to retrieve the IoTSpaces instance metadata and * security metadata, and then combine them with the modified values in a new * body to update the IoTSpaces instance. * * @param {string} resourceGroupName The name of the resource group that * contains the IoTSpaces instance. * * @param {string} resourceName The name of the IoTSpaces instance. * * @param {object} iotSpaceDescription The IoTSpaces instance metadata and * security metadata. * * @param {object} [iotSpaceDescription.properties] The common properties of a * IoTSpaces service. * * @param {object} [iotSpaceDescription.properties.storageContainer] The * properties of the designated storage container. * * @param {string} * [iotSpaceDescription.properties.storageContainer.connectionString] The * connection string of the storage account. * * @param {string} * [iotSpaceDescription.properties.storageContainer.subscriptionId] The * subscription identifier of the storage account. * * @param {string} * [iotSpaceDescription.properties.storageContainer.resourceGroup] The name of * the resource group of the storage account. * * @param {string} * [iotSpaceDescription.properties.storageContainer.containerName] The name of * storage container in the storage account. * * @param {object} iotSpaceDescription.sku A valid instance SKU. * * @param {string} iotSpaceDescription.sku.name The name of the SKU. Possible * values include: 'F1', 'S1', 'S2', 'S3' * * @param {string} iotSpaceDescription.location The resource location. * * @param {object} [iotSpaceDescription.tags] The resource tags. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IoTSpacesDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateOrUpdateWithHttpOperationResponse(resourceGroupName: string, resourceName: string, iotSpaceDescription: models.IoTSpacesDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IoTSpacesDescription>>; /** * Create or update the metadata of an IoTSpaces instance. The usual pattern to * modify a property is to retrieve the IoTSpaces instance metadata and * security metadata, and then combine them with the modified values in a new * body to update the IoTSpaces instance. * * @param {string} resourceGroupName The name of the resource group that * contains the IoTSpaces instance. * * @param {string} resourceName The name of the IoTSpaces instance. * * @param {object} iotSpaceDescription The IoTSpaces instance metadata and * security metadata. * * @param {object} [iotSpaceDescription.properties] The common properties of a * IoTSpaces service. * * @param {object} [iotSpaceDescription.properties.storageContainer] The * properties of the designated storage container. * * @param {string} * [iotSpaceDescription.properties.storageContainer.connectionString] The * connection string of the storage account. * * @param {string} * [iotSpaceDescription.properties.storageContainer.subscriptionId] The * subscription identifier of the storage account. * * @param {string} * [iotSpaceDescription.properties.storageContainer.resourceGroup] The name of * the resource group of the storage account. * * @param {string} * [iotSpaceDescription.properties.storageContainer.containerName] The name of * storage container in the storage account. * * @param {object} iotSpaceDescription.sku A valid instance SKU. * * @param {string} iotSpaceDescription.sku.name The name of the SKU. Possible * values include: 'F1', 'S1', 'S2', 'S3' * * @param {string} iotSpaceDescription.location The resource location. * * @param {object} [iotSpaceDescription.tags] The resource tags. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IoTSpacesDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IoTSpacesDescription} [result] - The deserialized result object if an error did not occur. * See {@link IoTSpacesDescription} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreateOrUpdate(resourceGroupName: string, resourceName: string, iotSpaceDescription: models.IoTSpacesDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IoTSpacesDescription>; beginCreateOrUpdate(resourceGroupName: string, resourceName: string, iotSpaceDescription: models.IoTSpacesDescription, callback: ServiceCallback<models.IoTSpacesDescription>): void; beginCreateOrUpdate(resourceGroupName: string, resourceName: string, iotSpaceDescription: models.IoTSpacesDescription, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IoTSpacesDescription>): void; /** * Update the metadata of a IoTSpaces instance. * * @param {string} resourceGroupName The name of the resource group that * contains the IoTSpaces instance. * * @param {string} resourceName The name of the IoTSpaces instance. * * @param {object} iotSpacePatchDescription The IoTSpaces instance metadata and * security metadata. * * @param {object} [iotSpacePatchDescription.tags] Instance tags * * @param {object} [iotSpacePatchDescription.properties] The common properties * of an IoTSpaces service. * * @param {object} [iotSpacePatchDescription.properties.storageContainer] The * properties of the designated storage container. * * @param {string} * [iotSpacePatchDescription.properties.storageContainer.connectionString] The * connection string of the storage account. * * @param {string} * [iotSpacePatchDescription.properties.storageContainer.subscriptionId] The * subscription identifier of the storage account. * * @param {string} * [iotSpacePatchDescription.properties.storageContainer.resourceGroup] The * name of the resource group of the storage account. * * @param {string} * [iotSpacePatchDescription.properties.storageContainer.containerName] The * name of storage container in the storage account. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IoTSpacesDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginUpdateWithHttpOperationResponse(resourceGroupName: string, resourceName: string, iotSpacePatchDescription: models.IoTSpacesPatchDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IoTSpacesDescription>>; /** * Update the metadata of a IoTSpaces instance. * * @param {string} resourceGroupName The name of the resource group that * contains the IoTSpaces instance. * * @param {string} resourceName The name of the IoTSpaces instance. * * @param {object} iotSpacePatchDescription The IoTSpaces instance metadata and * security metadata. * * @param {object} [iotSpacePatchDescription.tags] Instance tags * * @param {object} [iotSpacePatchDescription.properties] The common properties * of an IoTSpaces service. * * @param {object} [iotSpacePatchDescription.properties.storageContainer] The * properties of the designated storage container. * * @param {string} * [iotSpacePatchDescription.properties.storageContainer.connectionString] The * connection string of the storage account. * * @param {string} * [iotSpacePatchDescription.properties.storageContainer.subscriptionId] The * subscription identifier of the storage account. * * @param {string} * [iotSpacePatchDescription.properties.storageContainer.resourceGroup] The * name of the resource group of the storage account. * * @param {string} * [iotSpacePatchDescription.properties.storageContainer.containerName] The * name of storage container in the storage account. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IoTSpacesDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IoTSpacesDescription} [result] - The deserialized result object if an error did not occur. * See {@link IoTSpacesDescription} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginUpdate(resourceGroupName: string, resourceName: string, iotSpacePatchDescription: models.IoTSpacesPatchDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IoTSpacesDescription>; beginUpdate(resourceGroupName: string, resourceName: string, iotSpacePatchDescription: models.IoTSpacesPatchDescription, callback: ServiceCallback<models.IoTSpacesDescription>): void; beginUpdate(resourceGroupName: string, resourceName: string, iotSpacePatchDescription: models.IoTSpacesPatchDescription, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IoTSpacesDescription>): void; /** * Delete an IoTSpaces instance. * * @param {string} resourceGroupName The name of the resource group that * contains the IoTSpaces instance. * * @param {string} resourceName The name of the IoTSpaces instance. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IoTSpacesDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IoTSpacesDescription>>; /** * Delete an IoTSpaces instance. * * @param {string} resourceGroupName The name of the resource group that * contains the IoTSpaces instance. * * @param {string} resourceName The name of the IoTSpaces instance. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IoTSpacesDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IoTSpacesDescription} [result] - The deserialized result object if an error did not occur. * See {@link IoTSpacesDescription} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IoTSpacesDescription>; beginDeleteMethod(resourceGroupName: string, resourceName: string, callback: ServiceCallback<models.IoTSpacesDescription>): void; beginDeleteMethod(resourceGroupName: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IoTSpacesDescription>): void; /** * Get all the IoTSpaces instances in a subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IoTSpacesDescriptionListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IoTSpacesDescriptionListResult>>; /** * Get all the IoTSpaces instances in a subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IoTSpacesDescriptionListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IoTSpacesDescriptionListResult} [result] - The deserialized result object if an error did not occur. * See {@link IoTSpacesDescriptionListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IoTSpacesDescriptionListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.IoTSpacesDescriptionListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IoTSpacesDescriptionListResult>): void; /** * Get all the IoTSpaces instances in a resource group. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IoTSpacesDescriptionListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IoTSpacesDescriptionListResult>>; /** * Get all the IoTSpaces instances in a resource group. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IoTSpacesDescriptionListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IoTSpacesDescriptionListResult} [result] - The deserialized result object if an error did not occur. * See {@link IoTSpacesDescriptionListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IoTSpacesDescriptionListResult>; listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.IoTSpacesDescriptionListResult>): void; listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IoTSpacesDescriptionListResult>): void; } /** * @class * Operations * __NOTE__: An instance of this class is automatically created for an * instance of the IoTSpacesClient. */ export interface Operations { /** * Lists all of the available IoTSpaces service REST API operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * Lists all of the available IoTSpaces service REST API operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; list(callback: ServiceCallback<models.OperationListResult>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; /** * Lists all of the available IoTSpaces service REST API operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * Lists all of the available IoTSpaces service REST API operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.OperationListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; }
the_stack
import * as dagre from 'dagre'; import { Vertex, BaseVertex, Edge, BaseEdge, VertexGroup } from '../type'; import { Point } from '../Utils/graph'; import { find, findIndex } from '../Utils/utils'; import { BaseGroupLayout } from './base'; export interface LayoutVertex extends BaseVertex { name?: string; width: number; height: number; x?: number; y?: number; isMount?: boolean; opacity?: number; widthPath?: number[]; heightPath?: number[]; xPath?: number[]; yPath?: number[]; opacityPath?: number[]; } export interface LayoutGroupVertex extends BaseVertex { name: string; expand: boolean; width?: number; height?: number; x?: number; y?: number; isMount?: boolean; opacity?: number; widthPath?: number[]; heightPath?: number[]; xPath?: number[]; yPath?: number[]; opacityPath?: number[]; } export interface LayoutEdge extends BaseEdge { points?: Point[]; isMount?: boolean; opacity?: number; opacityPath?: number[]; } /** * 普通图布局 */ export class GraphLayout< N extends LayoutVertex, NL extends LayoutEdge > extends BaseGroupLayout<N, NL, any> { config: dagre.GraphLabel; constructor( /** 节点 */ nodes: Array<Vertex<N>>, /** 节点连线 */ links: Array<Edge<NL>>, /** 图配置 */ config: dagre.GraphLabel ) { super(); this.nodes = this.getNodes(nodes); this.links = links; this.config = config; this.init(); } init() { this.g = new dagre.graphlib.Graph(); // 配置 this.g.setGraph(this.config); // Default to assigning a new object as a label for each new edge. this.g.setDefaultEdgeLabel(function() { return {}; }); } layout(): { nodes: Vertex<N>[]; links: Edge<NL>[]; } { this.nodes.forEach(node => { const { id, width, height } = node; this.g.setNode(id, { id, width, height }); }); this.links.forEach(link => { const { u, v } = link; this.g.setEdge(u, v); }); dagre.layout(this.g); return { nodes: this.nodes.map(node => { const { x, y } = this.g.node(node.id); return { ...(node as object), x, y } as N; }), links: this.links.map(link => { const { points } = this.g.edge({ v: link.u, w: link.v }); return { ...(link as object), u: link.u, v: link.v, points } as NL; }) }; } } interface GroupConfig { /** dagre 配置 */ dagreConfig: dagre.GraphLabel; /** 组宽度 */ defaultGroupWidth: number; /** 组高度 */ defaultGroupHeight: number; /** group padding */ groupPadding: number[]; } /** * 带组布局 */ export class GroupGraphLayout< N extends LayoutVertex, NL extends LayoutEdge, G extends LayoutGroupVertex, GL extends LayoutEdge > extends BaseGroupLayout<N, NL, G> { groupLinks: Edge<GL>[]; groupNodeMap: Map<string, VertexGroup<N, G>>; groupLinkMap: Map<string, NL[]>; config: GroupConfig; /** 渲染结果 */ renderGroups: VertexGroup<N, G>[] = []; renderNodes: Vertex<N>[] = []; renderNodeLinks: Edge<NL>[] = []; renderGroupLinks: Edge<NL & { uGroupId: string; vGroupId: string; groupPoints: [Point[], Point[], Point[]] }>[] = []; preRenderGroups: VertexGroup<N, G>[] = []; preRenderNodes: Vertex<N>[] = []; preRenderNodeLinks: Edge<NL>[] = []; preRenderGroupLinks: Edge<NL & { uGroupId: string; vGroupId: string; groupPoints: [Point[], Point[], Point[]] }>[] = []; constructor( /** 节点 */ nodes: Array<Vertex<N>>, /** 节点连线 */ links: Array<Edge<NL>>, /** 组 */ groups: Array<VertexGroup<N, G>>, /** 组连线 */ groupLinks: Array<Edge<GL>>, /** 图配置 */ config: GroupConfig ) { super(); this.init(nodes, links, groups, groupLinks, config); } init( /** 节点 */ nodes: Array<Vertex<N>>, /** 节点连线 */ links: Array<Edge<NL>>, /** 组 */ groups: Array<VertexGroup<N, G>>, /** 组连线 */ groupLinks: Array<Edge<GL>>, /** 图配置 */ config: GroupConfig ) { // node 与 group 要保证顺序稳定,这样布局才能稳定 this.nodes = this.getNodes(nodes); this.links = links; this.groups = this.getGroups(groups); this.groupLinks = groupLinks; this.config = config; // 生成组与点的对应关系 this.groupNodeMap = new Map(); this.groupLinkMap = new Map(); this.getGroupNodeMap(); } getGroupNodeMap() { this.groups.forEach(group => { group.vertexes.forEach(vertex => { this.groupNodeMap.set(vertex.id, group); }); }); } getDownGroup(groupId: string): Array<VertexGroup<N, G>> { return this.groupLinks .filter(link => { return link.u === groupId; }) .map(link => { const { v } = link; return find(this.groups, group => { return group.id === v; }); }); } /** 处理一个 group 与其下游组及组内节点连通 */ processGroupConnect(g: dagre.graphlib.Graph, groupId: string, nodeId: string = '', forceNoExpand: boolean = false) { const downGroups = this.getDownGroup(groupId); const connectId = nodeId || groupId; downGroups.forEach(downGroup => { if (downGroup.vertexes.length === 1) { g.setEdge(connectId, downGroup.vertexes[0].id); } else if (downGroup.expand && !forceNoExpand) { // 展开就相关节点相连 const downGroupNodeIds = downGroup.vertexes.map(vertex => vertex.id); this.links .filter(link => { return link.u === connectId && downGroupNodeIds.includes(link.v); }) .forEach(link => { g.setEdge(link.u, link.v); }); } else { // 未展开就两个 group 相连 g.setEdge(connectId, downGroup.id); } }); } getLayoutInGroup(group: VertexGroup<N, G>) { const g = new dagre.graphlib.Graph(); // 配置 g.setGraph(this.config.dagreConfig); // Default to assigning a new object as a label for each new edge. g.setDefaultEdgeLabel(function() { return {}; }); const groupNodeIds = group.vertexes.map(vertex => vertex.id); const links: Edge<NL>[] = []; groupNodeIds.forEach(nodeId => { const node = find(this.nodes, n => { return n.id === nodeId; }); g.setNode(nodeId, { id: nodeId, width: node.width, height: node.height }); // 组内节点连接 this.links .filter(link => { if (link.u === nodeId && this.groupNodeMap.has(link.v)) { const nodeGroup = this.groupNodeMap.get(link.v); return nodeGroup.id === group.id; } return false; }) .forEach(link => { links.push(link); g.setEdge(nodeId, link.v); }); }); dagre.layout(g); return { vertexes: group.vertexes.map(vertex => { if (g.hasNode(vertex.id)) { const { x, y, width, height } = g.node(vertex.id); return { ...(vertex as object), x, y, width, height } as N; } return vertex; }), edges: links.map(link => { const { points } = g.edge({ v: link.u, w: link.v }); return { ...(link as object), u: link.u, v: link.v, points } as NL; }) }; } /** * 先获取 Group 的大小,以及 Group 中 node 在 Group 中的位置 */ getGroupSize() { const { groupPadding } = this.config; this.groups = this.groups.map(group => { // 当组内只有一个节点时,直接显示节点,没有展开关闭状态 // 对于展开的组的内部节点进行布局 if (group.vertexes.length !== 1 && group.expand) { let maxChildX = -Infinity; let maxChildY = -Infinity; let minChildX = Infinity; let minChildY = Infinity; const { vertexes, edges } = this.getLayoutInGroup(group); vertexes.forEach(vertex => { const { x, y, width, height } = vertex; if (maxChildX < x + width / 2 + groupPadding[1]) { maxChildX = x + width / 2 + groupPadding[1]; } if (maxChildY < y + height / 2 + groupPadding[2]) { maxChildY = y + height / 2 + groupPadding[2]; } if (minChildX > x - width / 2 - groupPadding[3]) { minChildX = x - width / 2 - groupPadding[3]; } if (minChildY > y - height / 2 - groupPadding[0]) { minChildY = y - height / 2 - groupPadding[0]; } }); const links: NL[] = edges.map(edge => { const points = edge.points.map(point => { return { x: point.x - minChildX, y: point.y - minChildY }; }); return { ...(edge as object), points } as NL; }); this.groupLinkMap.set(group.id, links); const groupWidth = maxChildX - minChildX; const groupHeight = maxChildY - minChildY; return { ...(group as object), width: groupWidth, height: groupHeight, vertexes: vertexes.map(vertex => { const { x, y, width, height } = vertex; return { ...(vertex as object), x: x - width / 2 - minChildX, y: y - height / 2 - minChildY } as N; }) } as VertexGroup<N, G>; } return group; }); } /** * 对 group 进行布局 */ groupLayout() { const nodeLinks: NL[] = []; const g = new dagre.graphlib.Graph({}); // 配置 g.setGraph(this.config.dagreConfig); // Default to assigning a new object as a label for each new edge. g.setDefaultEdgeLabel(function() { return {}; }); this.groups.forEach(group => { const groupId = group.id; if (group.vertexes.length === 1) { // 当组内只有一个节点时,直接显示节点,没有展开关闭状态 const { id, width, height } = group.vertexes[0]; g.setNode(String(id), { id, width, height }); this.processGroupConnect(g, groupId, String(id), true); } else if (!group.expand) { // 没有展开,取组的默认宽高 g.setNode(groupId, { id: groupId, width: this.config.defaultGroupWidth, height: this.config.defaultGroupHeight }); this.processGroupConnect(g, groupId, '', true); } else { g.setNode(groupId, { id: groupId, width: group.width, height: group.height }); this.processGroupConnect(g, groupId, '', true); } }); dagre.layout(g); this.groups = this.groups.map(group => { const groupId = group.id; if (g.hasNode(group.id)) { const { x, y, width, height } = g.node(groupId); const vertexes = group.vertexes.map(vertex => { return { ...(vertex as object), x: x - width / 2 + vertex.x + vertex.width / 2, y: y - height / 2 + vertex.y + vertex.height / 2 } as Vertex<N>; }); const edges = this.groupLinkMap.get(groupId) || []; edges.forEach(edge => { const points = edge.points.map(point => { return { x: point.x + (x - width / 2), y: point.y + (y - height / 2) }; }); nodeLinks.push({ ...(edge as object), points } as NL); }); return { ...(group as object), x, y, vertexes } as VertexGroup<N, G>; } return { ...(group as object), vertexes: group.vertexes.map(vertex => { if (g.hasNode(vertex.id)) { const { x, y } = g.node(vertex.id); return { ...(vertex as object), x, y }; } return vertex; }) } as VertexGroup<N, G>; }); const nodes = this.groups.reduce((pre, cur) => { if (cur.expand || cur.vertexes.length === 1) { return [...pre, ...cur.vertexes]; } return pre; }, []); this.getGroupNodeMap(); // 先绘制组与组之间的连线,然后在根据组与组之间的连线来绘制节点与节点之间的连线 // 一个组与一个组之间,最多只有一条连线,如果一个组内有多条线到另一个组,需要在组内合并 // 确定组与组之间的连线路径,同时确定组的点位 this.groupLinks = this.groupLinks.map(groupLink => { const { u, v } = groupLink; // 第二段起始点 let startPoint: Point; // 第二段终止点 let endPoint: Point; const uGroup = find(this.groups, (group) => group.id === u); const vGroup = find(this.groups, (group) => group.id === v); // uGroup,有几条出边 const uGroupLink = this.groupLinks.filter(gl => { return gl.u === u; }).sort((glA, glB) => { const glAGroup = find(this.groups, (group) => group.id === glA.v); const glBGroup = find(this.groups, (group) => group.id === glB.v); const { points: glAGroupPoint } = g.edge({ v: uGroup.vertexes.length === 1 ? uGroup.vertexes[0].id : uGroup.id, w: glAGroup.vertexes.length === 1 ? glAGroup.vertexes[0].id : glAGroup.id, }); const { points: glBGroupPoint } = g.edge({ v: uGroup.vertexes.length === 1 ? uGroup.vertexes[0].id : uGroup.id, w: glBGroup.vertexes.length === 1 ? glBGroup.vertexes[0].id : glBGroup.id, }); if (glAGroupPoint[0].y < glBGroupPoint[0].y) { return -1; } return 1; }); const uIndex = findIndex(uGroupLink, link => link.v === v); if (uGroup.vertexes.length === 1) { // 如果当前组只有一个节点,那么 const vertex = uGroup.vertexes[0]; startPoint = { x: vertex.x + vertex.width / 2, y: vertex.y - vertex.height / 2 + ((uIndex + 1) / (uGroupLink.length + 1)) * vertex.height, }; } else { startPoint = { x: uGroup.x + uGroup.width / 2, y: uGroup.y - uGroup.height / 2 + ((uIndex + 1) / (uGroupLink.length + 1)) * uGroup.height, }; } // vGroup,有几条入边 const vGroupLink = this.groupLinks.filter(gl => { return gl.v === v; }).sort((glA, glB) => { const glAGroup = find(this.groups, (group) => group.id === glA.u); const glBGroup = find(this.groups, (group) => group.id === glB.u); const { points: glAGroupPoint } = g.edge({ v: glAGroup.vertexes.length === 1 ? glAGroup.vertexes[0].id : glAGroup.id, w: vGroup.vertexes.length === 1 ? vGroup.vertexes[0].id : vGroup.id, }); const { points: glBGroupPoint } = g.edge({ v: glBGroup.vertexes.length === 1 ? glBGroup.vertexes[0].id : glBGroup.id, w: vGroup.vertexes.length === 1 ? vGroup.vertexes[0].id : vGroup.id, }); if (glAGroupPoint[0].y < glBGroupPoint[0].y) { return -1; } return 1; }); const vIndex = findIndex(vGroupLink, link => link.u === u); if (vGroup.vertexes.length === 1) { // 如果当前组只有一个节点,那么 const vertex = vGroup.vertexes[0]; endPoint = { x: vertex.x - vertex.width / 2, y: vertex.y - vertex.height / 2 + ((vIndex + 1) / (vGroupLink.length + 1)) * vertex.height, }; } else { endPoint = { x: vGroup.x - vGroup.width / 2, y: vGroup.y - vGroup.height / 2 + ((vIndex + 1) / (vGroupLink.length + 1)) * vGroup.height, } } const { points } = g.edge({ v: uGroup.vertexes.length === 1 ? uGroup.vertexes[0].id : uGroup.id, w: vGroup.vertexes.length === 1 ? vGroup.vertexes[0].id : vGroup.id, }); let middlePoints = points.slice(1, points.length - 1); // 防止节点出现突转 if (middlePoints.length === 1) { middlePoints = [{ x: middlePoints[0].x, y: endPoint.y }]; } return { ...(groupLink as object), points: [ startPoint, { x: startPoint.x + 10, y: startPoint.y }, ...middlePoints, { x: endPoint.x - 20, y: endPoint.y }, endPoint ] } as Edge<GL>; }); const groupLinks: (NL & { uGroupId: string; vGroupId: string; groupPoints: [Point[], Point[], Point[]] })[] = []; this.links .filter(link => { const uGroup = this.groupNodeMap.get(link.u); const vGroup = this.groupNodeMap.get(link.v); return uGroup.id !== vGroup.id; }).forEach(link => { const { u, v } = link; const uGroup = this.groupNodeMap.get(u); const vGroup = this.groupNodeMap.get(v); const uNode = find(nodes, node => node.id === u); const vNode = find(nodes, node => node.id === v); const groupLink = find(this.groupLinks, (link) => { return link.u === uGroup.id && link.v === vGroup.id; }); const startPoint = groupLink.points[0]; const endPoint = groupLink.points[groupLink.points.length - 1]; let point_1: Point[] = []; if (uGroup.expand) { point_1 = [ { x: uNode.x + uNode.width / 2, y: uNode.y }, { x: uNode.x + uNode.width / 2 + 10, y: uNode.y }, { x: startPoint.x - 20, y: startPoint.y }, startPoint ]; } let point_3: Point[] = []; if (vGroup.expand) { point_3 = [ endPoint, { x: endPoint.x + 10, y: endPoint.y }, { x: vNode.x - vNode.width / 2 - 20, y: vNode.y }, { x: vNode.x - vNode.width / 2, y: vNode.y }, ]; } groupLinks.push({ ...(link as object), uGroupId: uGroup.vertexes.length === 1 ? uGroup.vertexes[0].id : uGroup.id, vGroupId: vGroup.vertexes.length === 1 ? vGroup.vertexes[0].id : vGroup.id, groupPoints: [point_1, groupLink.points, point_3], } as (NL & { uGroupId: string; vGroupId: string; groupPoints: [Point[], Point[], Point[]] })); }); return { nodes, nodeLinks, groupLinks }; } getTween(start: number, end: number) { const duration = 100; const times = Math.floor(duration / 16); const paths = []; const interval = (end - start) / times; for (let i = 0; i <= times; i++) { paths.push(start + interval * i); } return paths; } getAnimationPath(pre: LayoutVertex | LayoutGroupVertex, current: LayoutVertex | LayoutGroupVertex) { const preWidth = pre.width; const preHeight = pre.height; const preX = pre.x; const preY = pre.y; const currentWidth = current.width; const currentHeight = current.height; const currentX = current.x; const currentY = current.y; return { widthPath: this.getTween(preWidth, currentWidth), heightPath: this.getTween(preHeight, currentHeight), xPath: this.getTween(preX, currentX), yPath: this.getTween(preY, currentY) }; } animation() { this.renderNodes = this.renderNodes.map(renderNode => { const preRenderNode = find(this.preRenderNodes, node => node.id === renderNode.id); // 之前存在 if (preRenderNode) { const { widthPath, heightPath, xPath, yPath } = this.getAnimationPath(preRenderNode, renderNode); return { ...(renderNode as object), widthPath, heightPath, xPath, yPath, isMount: false, width: preRenderNode.width, height: preRenderNode.height, x: preRenderNode.x, y: preRenderNode.y, opacity: 1 } as N; } return { ...(renderNode as object), isMount: true, opacity: 0, opacityPath: this.getTween(0, 1) } as N; }); this.renderGroups = this.renderGroups.map(renderGroup => { const preRenderGroup = find(this.preRenderGroups, group => group.id === renderGroup.id); // 之前存在 if (preRenderGroup) { const { widthPath, heightPath, xPath, yPath } = this.getAnimationPath(preRenderGroup, renderGroup); return { ...(renderGroup as object), widthPath, heightPath, xPath, yPath, isMount: false, width: preRenderGroup.width, height: preRenderGroup.height, x: preRenderGroup.x, y: preRenderGroup.y, opacity: 1 } as VertexGroup<N, G>; } return { ...(renderGroup as object), isMount: true, opacity: 0, opacityPath: this.getTween(0, 1) } as VertexGroup<N, G>; }); this.renderNodeLinks = this.renderNodeLinks.map(renderNodeLink => { const preNodeRenderLink = find(this.renderNodeLinks, link => link.u === renderNodeLink.u && link.v === renderNodeLink.v); if (preNodeRenderLink) { return { ...(renderNodeLink as object), isMount: false, opacity: 1 } as Edge<NL>; } return { ...(renderNodeLink as object), isMount: true, opacity: 0, opacityPath: this.getTween(0, 1) } as Edge<NL>; }); this.renderGroupLinks = this.renderGroupLinks.map(renderGroupLink => { const preGroupRenderLink = find(this.renderGroupLinks, link => link.u === renderGroupLink.u && link.v === renderGroupLink.v); if (preGroupRenderLink) { return { ...(renderGroupLink as object), isMount: false, opacity: 1 } as Edge<NL & { uGroupId: string; vGroupId: string; groupPoints: [Point[], Point[], Point[]] }>; } return { ...(renderGroupLink as object), isMount: true, opacity: 0, opacityPath: this.getTween(0, 1) } as Edge<NL & { uGroupId: string; vGroupId: string; groupPoints: [Point[], Point[], Point[]] }>; }); } update( /** 节点 */ nodes: Array<Vertex<N>>, /** 节点连线 */ links: Array<Edge<NL>>, /** 组 */ groups: Array<VertexGroup<N, G>>, /** 组连线 */ groupLinks: Array<Edge<GL>>, /** 图配置 */ config: GroupConfig ) { this.init(nodes, links, groups, groupLinks, config); } /** * 布局生成 * 当组内只有一个节点时,直接显示节点 * 当前组展开时,内部节点与外部组或节点相连接 * 当组闭合时,组与相关节点/组连接 * 返回组数据,用于渲染 * 算法:组内节点独自布局,获得节点在组中的位置以及组的位置,然后组布局 */ layout(): { renderGroups: VertexGroup<N, G>[]; renderNodes: Vertex<N>[]; renderNodeLinks: Edge<NL>[]; renderGroupLinks: Edge<NL & { uGroupId: string; vGroupId: string; groupPoints: [Point[], Point[], Point[]] }>[]; } { this.preRenderNodes = this.renderNodes.map(node => { const { isMount, widthPath, heightPath, xPath, yPath } = node; if (isMount) { return node; } return { ...(node as object), width: widthPath[widthPath.length - 1], height: heightPath[heightPath.length - 1], x: xPath[xPath.length - 1], y: yPath[yPath.length - 1] } as N; }); this.preRenderGroups = this.renderGroups.map(group => { const { isMount, widthPath, heightPath, xPath, yPath } = group; if (isMount) { return group; } return { ...(group as object), width: widthPath[widthPath.length - 1], height: heightPath[heightPath.length - 1], x: xPath[xPath.length - 1], y: yPath[yPath.length - 1] } as VertexGroup<N, G>; }); this.preRenderNodeLinks = this.renderNodeLinks; this.preRenderGroupLinks = this.renderGroupLinks; this.getGroupSize(); const { nodeLinks, nodes, groupLinks } = this.groupLayout(); this.renderGroups = this.groups.filter((group) => { return group.vertexes.length !== 1; }); this.renderNodes = this.groups.reduce((pre, cur) => { if (cur.expand || cur.vertexes.length === 1) { return [ ...pre, ...cur.vertexes, ]; } return pre; }, []); this.renderNodeLinks = nodeLinks.map(link => { const { u, v } = link; const uNode = find(nodes, node => node.id === u); const vNode = find(nodes, node => node.id === v); const uLinks = nodeLinks .filter(link => link.u === u) .sort((linkA, linkB) => { const linkAStartPointY = linkA.points[0].y; const linkBStartPointY = linkB.points[0].y; if (linkAStartPointY < linkBStartPointY) { return -1; } return 1; }); const uNodeIndex = findIndex(uLinks, link => link.v === v); const startPoint = { x: uNode.x + uNode.width / 2, y: uNode.y - uNode.height / 2 + ((uNodeIndex + 1) / (uLinks.length + 1)) * uNode.height }; const vLinks = nodeLinks .filter(link => link.v === v) .sort((linkA, linkB) => { const linkAEndPointY = linkA.points[linkA.points.length - 1].y; const linkBEndPointY = linkB.points[linkB.points.length - 1].y; if (linkAEndPointY < linkBEndPointY) { return -1; } return 1; }); const vNodeIndex = findIndex(vLinks, link => link.u === u); const endPoint = { x: vNode.x - vNode.width / 2, y: vNode.y - vNode.height / 2 + ((vNodeIndex + 1) / (vLinks.length + 1)) * vNode.height }; const points = [ startPoint, { x: startPoint.x + 10, y: startPoint.y }, ...link.points.slice(1, link.points.length - 1), { x: endPoint.x - 20, y: endPoint.y }, endPoint ]; return { ...(link as object), points } as NL; }); this.renderGroupLinks = groupLinks; this.animation(); return { renderGroups: this.renderGroups, renderNodes: this.renderNodes, renderNodeLinks: this.renderNodeLinks, renderGroupLinks: this.renderGroupLinks, }; } }
the_stack
import { action } from 'mobx'; import { observer } from 'mobx-react-lite'; import { useEffect, useState } from 'react'; import { Alert, Box, Button, FormField, Grid, Header, Input, Modal, Select, SpaceBetween, StatusIndicator, Table, TokenGroup, } from '@awsui/components-react'; import { useI18n } from '@/components/i18n-context'; import { useInput } from '@/utils/hooks'; import { AcceleratorConfigurationNode } from '../configuration'; import { LabelWithDescription } from './label-with-description'; import { OptionDefinition } from '../../../../node_modules/@awsui/components-react/internal/components/option/interfaces'; const organizationalUnitsNode = AcceleratorConfigurationNode.nested('organizational-units'); interface SimpleOrganizationalUnitValue { key: string; description: string; amount: number; email: string; type: string; scps: String[]; } export interface OrganizationalUnitTableProps { state: any; } export const OrganizationalUnitTable = observer(({ state }: OrganizationalUnitTableProps) => { const { tr, currency } = useI18n(); const [modalVisible, setModalVisible] = useState(false); const [modalType, setModalType] = useState<'add' | 'edit'>('add'); const [modalInitialValue, setModalInitialValue] = useState<Partial<SimpleOrganizationalUnitValue>>({}); const [selectedItem, setSelectedItem] = useState<SimpleOrganizationalUnitValue | undefined>(); const [permAlertVisible, setPermAlertVisible] = useState(false); const [dependencyAlertVisible, setDependencyAlertVisible] = useState(false); const [editNameAlert, setEditNameAlert] = useState(false); const [addNameAlert, setAddNameAlert] = useState(false); const [cannotAddOU, setCannotAddOU] = useState(false); const nameTitle = tr('wizard.labels.ou_name'); const budgetAmountTitle = tr('wizard.labels.ou_default_per_account_budget'); const budgetEmailTitle = tr('wizard.labels.ou_default_per_account_email'); const organizationalUnits = organizationalUnitsNode.get(state) ?? {}; // Map OUs to items that are easy to render const items: SimpleOrganizationalUnitValue[] = Object.entries(organizationalUnits).map( ([key, ouConfig]: [string, any]) => { const budgets = ouConfig?.['default-budgets']; return { key, description: ouConfig?.description, amount: budgets?.amount ?? 1000, email: budgets?.alerts?.[0]?.['emails']?.[0] ?? 'you@example.com', type: ouConfig?.type ?? "", scps: ouConfig?.['scps'], }; }, ); const validateForm = (key: string, amount: number, email: string, type: string, scps: String[] ) => { console.log(amount) if (key == '' || key == null || Number.isNaN(amount) || email == '' || type == '' || scps.length == 0) { return false } else { return true } } const handleAdd = () => { setModalType('add'); setModalInitialValue({}); setModalVisible(true); }; const handleEdit = () => { setModalType('edit'); setModalInitialValue(selectedItem ?? {}); setModalVisible(true); }; const handleSubmitAdd = action((value: SubmitValue) => { const { key, amount, email, type, scps } = value; if (nameExists(key)) { setAddNameAlert(true); } else if (validateForm(key, amount, email, type, scps)) { organizationalUnits[key] = { 'default-budgets': createInitialBudget(amount, email), 'type': type, 'scps': scps, }; } else { setCannotAddOU(true); } }); const handleSubmitEdit = action((value: SubmitValue) => { const { key, amount, email, origKey, type, scps } = value; if (key != origKey && nameExists(key)) { setEditNameAlert(true); } else if (key != origKey) { ouRecurs(key, origKey, state) } const budget = organizationalUnits[key]['default-budgets']; if (budget) { const alerts = budget?.alerts; budget.amount = amount; if (Array.isArray(alerts)) { alerts.forEach(alert => (alert.emails = [email])); } } else { organizationalUnits[key]['default-budgets'] = createInitialBudget(amount, email); } organizationalUnits[key]['scps'] = scps }); const nameExists = (editKey: string | undefined) => { for (let each in items) { if (items[each]['key'] == editKey) { return true; } } return false; } const ouRecurs = action((newValue: string, oldValue: string | undefined, node: any) => { Object.entries(node).forEach(([key, value]) => { if (key == oldValue) { node[newValue] = node[key] delete node[key] } if (typeof(value) != 'object') { if (Array.isArray(value)) { for (const each of value) { if (typeof(each == 'object')) ouRecurs(newValue, oldValue, each) } } else { if ((key == 'ou' && node[key] == oldValue) || (key == 'name' && node[key] == oldValue)) { node[key] = newValue } return } } ouRecurs(newValue, oldValue, value) }) }); const handleSubmit = action((value: SubmitValue) => { if (modalType === 'add') { handleSubmitAdd(value); } else { handleSubmitEdit(value); } setModalVisible(false); }); const checkDependency = (ouName: string, node: any) => { var dependencyExists = false; Object.entries(node).forEach(([key, value]) => { if (typeof(value) != 'object') { if (Array.isArray(value)) { for (const each of value) { if (typeof(each == 'object')) dependencyExists = dependencyExists || checkDependency(ouName, each) } } else { if ((key == 'ou' && node[key] == ouName) || (key == 'name' && node[key] == ouName)) { dependencyExists = true; return true } return dependencyExists } } dependencyExists = dependencyExists || checkDependency(ouName, value) }) return dependencyExists }; const handleRemove = action(() => { const { key } = selectedItem ?? {}; if (organizationalUnits[String(key)]['gui-perm'] == true) { setPermAlertVisible(true); } else if (checkDependency(String(key), state) == true) { setDependencyAlertVisible(true); } else { delete organizationalUnits[String(key)]; } setSelectedItem(undefined); }); return ( <> <AddModifyOrganizationalUnitModal type={modalType} visible={modalVisible} initialValue={modalInitialValue} onDismiss={() => setModalVisible(false)} onSubmit={handleSubmit} /> <Table items={items} trackBy="key" selectionType="single" selectedItems={selectedItem ? [selectedItem] : []} onSelectionChange={e => setSelectedItem(e.detail.selectedItems?.[0])} columnDefinitions={[ { header: nameTitle, cell: ({ key, description }) => <LabelWithDescription label={key} description={description} />, }, { header: budgetEmailTitle, cell: ({ email }) => email, }, { header: budgetAmountTitle, cell: ({ amount }) => <Box textAlign="right">{currency(amount)}</Box>, }, { header: "Type of Organization", cell: ({ type }) => type, }, { header: "Service Control Policies", cell: ({ scps }) => scps.join(", "), } ]} header={ <> <Header variant="h2" counter={`(${items.length})`} description={tr('wizard.headers.organizational_units_desc')} actions={ <SpaceBetween size="xs" direction="horizontal"> <Button disabled={selectedItem == null} onClick={handleRemove}> {tr('buttons.remove')} </Button> <Button disabled={selectedItem == null} onClick={handleEdit}> {tr('buttons.edit')} </Button> <Button iconName="add-plus" variant="primary" onClick={handleAdd}> {tr('buttons.add')} </Button> </SpaceBetween> } > {tr('wizard.headers.organizational_units')} </Header> { cannotAddOU === true && <Alert onDismiss={() => setCannotAddOU(false)} visible={cannotAddOU} dismissible type="error" dismissAriaLabel="Close alert" header="Can't add new Organizational Unit" > Fields cannot be left empty when adding a new Organizational Unit. </Alert> } { permAlertVisible === true && <Alert onDismiss={() => setPermAlertVisible(false)} visible={permAlertVisible} dismissible type="error" dismissAriaLabel="Close alert" header="This has been marked as a non-removable organizational unit in the configuration file." > Review the configuration file and remove the "gui-perm" field under the organizational unit if you would like to change this. </Alert> } { dependencyAlertVisible === true && <Alert onDismiss={() => setDependencyAlertVisible(false)} visible={dependencyAlertVisible} dismissible type="error" dismissAriaLabel="Close alert" header="Cannot remove this organizational unit due to dependency" > There are other sections of your configuration that depend on this organizational unit. Remove those dependencies first and try again. </Alert> } { editNameAlert === true && <Alert onDismiss={() => setEditNameAlert(false)} visible={editNameAlert} dismissible type="error" dismissAriaLabel="Close alert" header="Unsuccessful name change for Organizational Unit" > You cannot rename an OU to an already existing OU name. </Alert> } { addNameAlert === true && <Alert onDismiss={() => setAddNameAlert(false)} visible={addNameAlert} dismissible type="error" dismissAriaLabel="Close alert" header="Unable to add Organizational Unit" > You cannot add an OU with the same name of an already existing OU. </Alert> } </> } footer={ <SpaceBetween size="m"> <StatusIndicator type="info">{tr('wizard.labels.ou_name_email_change_text')}</StatusIndicator> <StatusIndicator type="info">{tr('wizard.labels.ou_email_uniqueness_text')}</StatusIndicator> </SpaceBetween> } /> </> ); }); interface SubmitValue { key: string; amount: number; email: string; origKey: string | undefined; type: string; scps: String[]; } interface AddModifyOrganizationalUnitModalProps { type: 'add' | 'edit'; visible: boolean; initialValue: Partial<SimpleOrganizationalUnitValue>; onDismiss: () => void; onSubmit: (value: SubmitValue) => void; } /** * Custom renderer for OU budget configuration. */ const AddModifyOrganizationalUnitModal = ({ type, visible, initialValue, onDismiss, onSubmit, }: AddModifyOrganizationalUnitModalProps) => { const { tr } = useI18n(); const ouKeyInputProps = useInput(); const budgetAmountInputProps = useInput(); const budgetEmailInputProps = useInput(); // prettier-ignore const headerText = type === 'add' ? tr('wizard.headers.add_organizational_unit') : tr('wizard.headers.edit_organizational_unit'); // prettier-ignore const buttonText = type === 'add' ? tr('buttons.add') : tr('buttons.save_changes'); const keyTitle = tr('wizard.labels.ou_key'); const budgetAmountTitle = tr('wizard.labels.ou_default_per_account_budget'); const budgetEmailTitle = tr('wizard.labels.ou_default_per_account_email'); const orgType = { title: 'Type of Organization', description: '\ Mandatory for core accounts, Workload for workload accounts, or Ignore for Organizational Management account'} const scpsTitle = { title: 'Service control policies (SCPs)', description: '' } var populatedScpList: any[]= [] const populateScpList = () => { for (const each in initialValue.scps) { populatedScpList.push( { label: initialValue.scps[parseInt(each)], dismissLabel: initialValue.scps[parseInt(each)] } ) } } const [selectedOption, setSelectedOption] = useState<OptionDefinition>({ label: "Mandatory", value: "mandatory" }); const [scpList, setScpList] = useState<any[]>([]); const [newScp, setNewScp] = useState(""); const configScpList = (scps: any[]) => { var configScpList = [] for (let each in scps) { configScpList.push(scps[each].label) } return configScpList } const handleSubmit = () => { onSubmit({ key: ouKeyInputProps.value, amount: Number(budgetAmountInputProps.value), email: budgetEmailInputProps.value, origKey: initialValue.key, type: String(selectedOption.value) ?? '', scps: configScpList(scpList) }); }; useEffect(() => { ouKeyInputProps.setValue(initialValue.key ?? ''); budgetAmountInputProps.setValue(`${initialValue.amount}`); budgetEmailInputProps.setValue(initialValue.email ?? ''); populateScpList() setScpList([...populatedScpList]) }, [visible]); return ( <Modal visible={visible} onDismiss={onDismiss} header={<Header variant="h3">{headerText}</Header>} footer={ <Button variant="primary" className="float-button" onClick={handleSubmit}> {buttonText} </Button> } > <form onSubmit={event => { event.stopPropagation(); event.preventDefault(); handleSubmit(); }} > <SpaceBetween size="m"> <FormField label={keyTitle} stretch> <Input {...ouKeyInputProps}/> </FormField> <FormField label={budgetAmountTitle} stretch> <Input {...budgetAmountInputProps} type="number" /> </FormField> <FormField label={budgetEmailTitle} stretch> <Input {...budgetEmailInputProps} /> </FormField> <FormField label={orgType.title} description={orgType.description} stretch> <Select selectedOption={selectedOption} onChange={({ detail }) => setSelectedOption(detail.selectedOption) } options={[ { label: "Mandatory", value: "mandatory" }, { label: "Workload", value: "workload" }, { label: "Ignore", value: "ignore" },]} selectedAriaLabel="Selected" /> </FormField> <FormField label={scpsTitle.title} description={scpsTitle.description} stretch> <SpaceBetween size="xs"> <TokenGroup onDismiss={({ detail: { itemIndex } }) => { setScpList([ ...scpList.slice(0, itemIndex), ...scpList.slice(itemIndex + 1) ]); }} items={scpList} /> <Grid gridDefinition={[{ colspan: 9 }, { colspan: 3 }]} > <div> <Input onChange={({ detail }) => setNewScp(detail.value)} value={newScp} /> </div> <div> <Button variant="normal" formAction="none" onClick={ () => { scpList.push({label: newScp, dismissLabel: "Remove item"}) setScpList([...scpList]) }} >Add SCP</Button> </div> </Grid> </SpaceBetween> </FormField> </SpaceBetween> </form> </Modal> ); }; export function createInitialBudget(amount: number, email: string) { return { name: 'Budget', period: 'Monthly', amount, include: [ 'Upfront-reservation-fees', 'Recurring-reservation-charges', 'Other-subscription-costs', 'Taxes', 'Support-charges', 'Discounts', ], alerts: [ { type: 'Actual', 'threshold-percent': 50, emails: [email], }, { type: 'Actual', 'threshold-percent': 75, emails: [email], }, { type: 'Actual', 'threshold-percent': 90, emails: [email], }, { type: 'Actual', 'threshold-percent': 100, emails: [email], }, ], }; } function organizationalUnits(organizationalUnits: any) { throw new Error('Function not implemented.'); }
the_stack
import type * as tfvis from '@tensorflow/tfjs-vis'; import type { Tensor } from '@tensorflow/tfjs'; import type { BarChartOpts, ConfusionMatrixData, ConfusionMatrixOptions, HeatmapData, HeatmapOptions, HistogramOpts, SurfaceInfo, SurfaceInfoStrict, TableData, TypedArray, XYPlotData, XYPlotOptions } from '@tensorflow/tfjs-vis'; import type { VisorComponent } from '@tensorflow/tfjs-vis/dist/components/visor'; import type { fitCallbacks } from '@tensorflow/tfjs-vis/dist/show/history'; import type { Visor } from '@tensorflow/tfjs-vis/dist/visor'; import type { Logs } from '@tensorflow/tfjs-layers/dist/logs'; import { Layer } from '@tensorflow/tfjs-layers/dist/engine/topology'; import { LayersModel } from '@tensorflow/tfjs-layers/dist/engine/training'; import { sendMessage } from '../comms'; import { serialize } from '../../serializer'; import { heatmap } from './heatmap'; class VisorProxy { constructor( private visorComponent: VisorComponent, visorEl: HTMLElement, private surfaceList: Map<string, SurfaceInfoStrict>, private renderVisor: (domNode: HTMLElement, surfaceList: Map<string, SurfaceInfoStrict>) => VisorComponent ) {} el!: HTMLElement; public __mock() { console.log(this.visorComponent); console.log(this.surfaceList); console.log(this.renderVisor); console.log(this.el); } surface(options: tfvis.SurfaceInfo): { container: HTMLElement; label: HTMLElement; drawArea: HTMLElement } { throw new Error(`Method not implemented. ${options}`); } isFullscreen(): boolean { return true; } isOpen(): boolean { return true; } close(): void { // } open(): void { sendMessage({ type: 'tensorFlowVis', requestId: TensorflowJsVisualizer.requestId, request: 'show' }); } toggle(): void { // } toggleFullScreen(): void { // } bindKeys(): void { // } unbindKeys(): void { // } setActiveTab(tabName: string): void { sendMessage({ type: 'tensorFlowVis', request: 'setactivetab', requestId: TensorflowJsVisualizer.requestId, tabName }); } } /* * Gets summary stats and shape for all weights in a layer. */ async function getLayerDetails(layer: Layer, math: typeof import('@tensorflow/tfjs-vis/dist/util/math')) { const weights = layer.getWeights(); const layerVariables = layer.weights; const statsPromises = weights.map(math.tensorStats); const stats = await Promise.all(statsPromises); const shapes = weights.map((w) => w.shape); return weights.map((weight, i) => ({ name: layerVariables[i].name, stats: stats[i], shape: formatShape(shapes[i]), weight })); } function formatShape(shape) { const oShape = shape.slice(); if (oShape.length === 0) { return 'Scalar'; } if (oShape[0] === null) { oShape[0] = 'batch'; } return `[${oShape.join(',')}]`; } class ShowProxy { constructor(readonly math: typeof import('@tensorflow/tfjs-vis/dist/util/math')) {} public fitCallbacks( container: SurfaceInfo, metrics: string[], opts?: { callbacks?: string[] } ): ReturnType<typeof fitCallbacks> { const requestId = TensorflowJsVisualizer.requestId; const callbackNames = opts?.callbacks || ['onEpochEnd', 'onBatchEnd']; sendMessage({ type: 'tensorFlowVis', request: 'registerfitcallback', container, requestId, metrics, opts }); const handlers: ReturnType<typeof fitCallbacks> = {}; function createHandler(callbackName: string) { return async (iteration: number, log: Logs) => { sendMessage({ type: 'tensorFlowVis', request: 'fitcallback', container, requestId, handler: callbackName, iteration, log }); }; } callbackNames.forEach((callbackName) => { handlers[callbackName] = createHandler(callbackName); }); return handlers; } public async history(container: SurfaceInfo | string, history: {}, metrics: string[], opts?: {}): Promise<void> { sendMessage({ type: 'tensorFlowVis', request: 'history', requestId: TensorflowJsVisualizer.requestId, container, history, metrics, opts }); } public async perClassAccuracy( container: SurfaceInfo | string, classAccuracy: Array<{ accuracy: number; count: number; }>, classLabels?: string[] ): Promise<void> { sendMessage({ type: 'tensorFlowVis', request: 'perclassaccuracy', requestId: TensorflowJsVisualizer.requestId, container, classAccuracy, classLabels }); } public async valuesDistribution(container: SurfaceInfo | string, tensor: Tensor): Promise<void> { const [stats, values] = await Promise.all([this.math.tensorStats(tensor), tensor.data()]); sendMessage({ type: 'tensorFlowVis', request: 'valuesdistribution', container, requestId: TensorflowJsVisualizer.requestId, tensor: { stats, values: Array.from(values) } }); } public async layer(container: SurfaceInfo | string, layer: Layer): Promise<void> { const details = await getLayerDetails(layer, this.math); const weights = {}; await Promise.all( details.map(async (item) => { weights[item.name] = Array.from(await item.weight.data()); }) ); const detailsToSend = details.map((item) => { return { ...item, weight: { size: item.weight.size } }; }); sendMessage({ type: 'tensorFlowVis', request: 'layer', requestId: TensorflowJsVisualizer.requestId, container, layer: { details: detailsToSend, weights } as any }); } public async modelSummary(container: SurfaceInfo | string, model: LayersModel): Promise<void> { const layers = model.layers.map((layer) => { return { outputShape: layer.outputShape, name: layer.name, parameters: layer.countParams() }; }); const slimmedModel = { layers }; sendMessage({ type: 'tensorFlowVis', request: 'modelsummary', requestId: TensorflowJsVisualizer.requestId, container, model: slimmedModel as any }); } // perClassAccuracy: typeof showPerClassAccuracy; // valuesDistribution: typeof valuesDistribution; // layer: typeof layer; // modelSummary: typeof modelSummary; } class RendererProxy { constructor(readonly tf: typeof import('@tensorflow/tfjs-core')) {} public async barchart( container: SurfaceInfo | string, data: Array<{ index: number; value: number; }>, opts?: BarChartOpts ): Promise<void> { sendMessage({ type: 'tensorFlowVis', request: 'barchart', requestId: TensorflowJsVisualizer.requestId, container, data, opts }); } public table( container: SurfaceInfo | string, data: TableData, opts?: { fontSize?: number; } ) { sendMessage({ type: 'tensorFlowVis', request: 'table', requestId: TensorflowJsVisualizer.requestId, container, data, opts }); } public async histogram( container: SurfaceInfo | string, data: | Array<{ value: number; }> | number[] | TypedArray, opts?: HistogramOpts ): Promise<void> { sendMessage({ type: 'tensorFlowVis', request: 'histogram', requestId: TensorflowJsVisualizer.requestId, container, data: serialize(data) as any, // We'll deserialize this at our end. opts }); } public async linechart(container: SurfaceInfo | string, data: XYPlotData, opts?: XYPlotOptions): Promise<void> { sendMessage({ type: 'tensorFlowVis', request: 'linechart', requestId: TensorflowJsVisualizer.requestId, container, data, opts }); } public async scatterplot(container: SurfaceInfo | string, data: XYPlotData, opts?: XYPlotOptions): Promise<void> { sendMessage({ type: 'tensorFlowVis', request: 'scatterplot', requestId: TensorflowJsVisualizer.requestId, container, data, opts }); } public async confusionMatrix( container: SurfaceInfo | string, data: ConfusionMatrixData, opts?: ConfusionMatrixOptions ): Promise<void> { sendMessage({ type: 'tensorFlowVis', request: 'confusionmatrix', requestId: TensorflowJsVisualizer.requestId, container, data, opts }); } public async heatmap(container: SurfaceInfo | string, data: HeatmapData, opts?: HeatmapOptions): Promise<void> { const requestId = TensorflowJsVisualizer.requestId; const details = await heatmap(this.tf, data, opts); sendMessage({ type: 'tensorFlowVis', request: 'heatmap', requestId, container, data: details, opts }); } } const _visor: Visor = new VisorProxy(undefined as any, undefined as any, undefined as any, undefined as any) as any; export class TensorflowJsVisualizer { public static requestId: string = ''; public static instance?: typeof tfvis; public static async serializeTensor(tensor: Tensor) { return tensor.array(); } public static initialize( tf: typeof import('@tensorflow/tfjs-core'), math: typeof import('@tensorflow/tfjs-vis/dist/util/math') ) { if (TensorflowJsVisualizer.instance) { return TensorflowJsVisualizer.instance; } TensorflowJsVisualizer.instance = { version_vis: '1.5.0', show: new ShowProxy(math), render: new RendererProxy(tf), metrics: { accuracy: math.accuracy, perClassAccuracy: math.perClassAccuracy, confusionMatrix: math.confusionMatrix }, visor: () => _visor } as any; return TensorflowJsVisualizer.instance!; } }
the_stack
import { StringParser } from '@/parsers/StringParser'; import { TestParser, Scope } from '../../lib/TestParser'; describe('parsers/StringParser', () => { TestParser.Case({ case: '0.0', description: 'parser.clear()', given: { parser: new StringParser({ schema: { type: 'string', pattern: 'arya|jon', minLength: 5, maxLength: 15 }, model: 'arya' }) }, expected: { parser: { kind: ({ value }: Scope) => expect(value).toBe('string'), field: { attrs: { type: ({ value }: Scope) => expect(value).toBe('text'), minlength: ({ value, options }: Scope) => expect(value).toBe(options.schema.minLength), maxlength: ({ value, options }: Scope) => expect(value).toBe(options.schema.maxLength), pattern: ({ value, options }: Scope) => expect(value).toBe(options.schema.pattern), value: ({ value, options }: Scope) => expect(value).toBe(`${options.model}`) }, value: ({ value, options }: Scope) => expect(value).toBe(options.model) } } } }); const formatTypes: Record<string, string> = { date: 'date', 'date-time': 'datetime-local', email: 'email', 'idn-email': 'email', time: 'time', uri: 'url' }; Object.keys(formatTypes).forEach((format) => { const type = formatTypes[format]; it(`field.attrs.type should be equal to '${type}' with schema.format === '${format}'`, () => { const parser = new StringParser({ schema: { type: 'string', format }, model: '' }); parser.parse(); expect(parser.field.attrs.type).toBe(type); }); }); it('should parse default undefined value as an undefined string', () => { const parser = new StringParser({ schema: { type: 'string' }, model: undefined }); parser.parse(); expect(parser.field.value).toBeUndefined(); }); it('should parse default non string value as a string', () => { const parser = new StringParser({ schema: { type: 'string' }, model: 12 as any }); parser.parse(); expect(parser.field.value).toBe('12'); }); TestParser.Case({ case: '1.0: schema.contentMediaType', description: 'with `text/*`', given: { parser: new StringParser({ schema: { type: 'string', contentMediaType: 'text/plain' }, model: undefined as any }) }, expected: { parser: { kind: ({ value }: Scope) => expect(value).toBe('textarea'), type: ({ value }: Scope) => expect(value).toBeUndefined(), field: { kind({ value, parser }: Scope) { expect(value).toBe(parser.kind); }, attrs: { accept: ({ value }: Scope) => expect(value).toBeUndefined() }, descriptor: { kind({ value, field }: Scope) { expect(value).toBe(field.kind); } } } } } }); TestParser.Case({ case: '1.1: schema.contentMediaType', description: 'with `image/*`', given: { parser: new StringParser({ schema: { type: 'string', contentMediaType: 'image/png' }, model: undefined as any }) }, expected: { parser: { kind: ({ value }: Scope) => expect(value).toBe('image'), field: { kind({ value, parser }: Scope) { expect(value).toBe(parser.kind); }, attrs: { type: ({ value }: Scope) => expect(value).toBe('file'), accept({ value, parser: { options } }: Scope) { expect(value).toBe(options.schema.contentMediaType); } }, descriptor: { kind({ value, parser }: Scope) { expect(value).toBe(parser.field.kind); } } } } } }); TestParser.Case({ case: '1.2: schema.contentMediaType', description: 'with custom descriptor.kind', given: { parser: new StringParser({ schema: { type: 'string', contentMediaType: 'audio/ogg' }, model: undefined as any, descriptor: { kind: 'string' }, get kind() { return this.descriptor.kind; } }) }, expected: { parser: { kind: ({ value }: Scope) => expect(value).toBe('string'), field: { kind({ value, parser }: Scope) { expect(value).toBe(parser.kind); }, attrs: { type: ({ value }: Scope) => expect(value).toBe('text'), accept: ({ value }: Scope) => expect(value).toBeUndefined() }, descriptor: { kind({ value }: Scope) { expect(value).toBe('string'); } } } } } }); TestParser.Case({ case: '1.3: schema.contentMediaType', description: 'any other values', given: { parser: new StringParser({ schema: { type: 'string', contentMediaType: 'any/mime' }, model: undefined as any }) }, expected: { parser: { kind: ({ value }: Scope) => expect(value).toBe('file'), field: { kind({ value, parser }: Scope) { expect(value).toBe(parser.kind); }, attrs: { type: ({ value }: Scope) => expect(value).toBe('file'), accept({ value, parser: { options } }: Scope) { expect(value).toBe(options.schema.contentMediaType); } }, descriptor: { kind({ value, parser: { field } }: Scope) { expect(value).toBe(field.kind); } } } } } }); TestParser.Case({ case: '1.4: schema.contentMediaType', description: 'with `image/*`', given: { parser: new StringParser({ schema: { type: 'string', contentMediaType: 'image/png' }, model: undefined as any }) }, expected: { parser: { field: { kind: ({ value }: Scope) => expect(value).toBe('image'), attrs: { type: ({ value }: Scope) => expect(value).toBe('file'), accept({ value, parser: { options } }: Scope) { expect(value).toBe(options.schema.contentMediaType); } }, descriptor: { kind({ value, parser: { field } }: Scope) { expect(value).toBe(field.kind); } } } } } }); TestParser.Case({ case: '3.0: parser.isEmpty()', description: 'with non empty string', given: { parser: new StringParser({ schema: { type: 'string' }, model: undefined as any }) }, expected: { parser: { isEmpty: ({ parser }: Scope) => expect(parser.isEmpty('non empty')).toBeFalsy() } } }); TestParser.Case({ case: '3.1: parser.isEmpty()', description: 'with an empty string', given: { parser: new StringParser({ schema: { type: 'string' }, model: undefined as any }) }, expected: { parser: { isEmpty: ({ parser }: Scope) => expect(parser.isEmpty('')).toBeTruthy() } } }); TestParser.Case({ case: '3.2: parser.isEmpty()', description: 'with a non string', given: { parser: new StringParser({ schema: { type: 'string' }, model: 12 as any }) }, expected: { parser: { isEmpty: ({ parser }: Scope) => expect(parser.isEmpty([ 12 ])).toBeTruthy() } } }); TestParser.Case({ case: '3.3: parser.isEmpty()', description: 'with default value', given: { parser: new StringParser({ schema: { type: 'string' }, model: 'hello' as any }) }, expected: { parser: { isEmpty: ({ parser }: Scope) => expect(parser.isEmpty()).toBeFalsy() } } }); TestParser.Case({ case: '4.0', description: 'parser.reset()', given: { parser: new StringParser({ schema: { type: 'string', pattern: 'arya|jon', minLength: 5, maxLength: 15 }, model: 'arya', onChange: jest.fn() }) }, expected: { parser: { reset({ parser }: Scope) { expect(parser.rawValue).toBe('arya'); expect(parser.model).toBe('arya'); parser.field.setValue('jon'); expect(parser.rawValue).toBe('jon'); expect(parser.model).toBe('jon'); parser.reset(); // reset without calling onChange expect(parser.rawValue).toBe('arya'); expect(parser.model).toBe('arya'); parser.field.reset(); // reset with calling onChange const onChange = parser.options.onChange; const result = onChange.mock.calls.map(([ value ]: any) => value); expect(result).toEqual([ 'arya', 'jon', 'arya' ]); } } } }); TestParser.Case({ case: '5.0', description: 'parser.clear()', given: { parser: new StringParser({ schema: { type: 'string', pattern: 'arya|jon', minLength: 5, maxLength: 15 }, model: 'arya', onChange: jest.fn() }) }, expected: { parser: { clear({ parser }: Scope) { expect(parser.rawValue).toBe('arya'); expect(parser.model).toBe('arya'); parser.field.setValue('jon'); expect(parser.rawValue).toBe('jon'); expect(parser.model).toBe('jon'); parser.clear(); // clear without calling onChange expect(parser.rawValue).toBeUndefined(); expect(parser.model).toBeUndefined(); parser.field.clear(); // clear with calling onChange const onChange = parser.options.onChange; const result = onChange.mock.calls.map(([ value ]: any) => value); expect(result).toEqual([ 'arya', 'jon', undefined ]); } } } }); });
the_stack
// clang-format off import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {PaymentsManagerImpl, SettingsCreditCardEditDialogElement, SettingsPaymentsSectionElement} from 'chrome://settings/lazy_load.js'; import {MetricsBrowserProxyImpl, PrivacyElementInteractions, SettingsToggleButtonElement} from 'chrome://settings/settings.js'; import {assertEquals, assertFalse, assertNotEquals, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {eventToPromise, whenAttributeIs} from 'chrome://webui-test/test_util.js'; import {createCreditCardEntry, createEmptyCreditCardEntry,TestPaymentsManager} from './passwords_and_autofill_fake_data.js'; import {TestMetricsBrowserProxy} from './test_metrics_browser_proxy.js'; // clang-format on suite('PaymentSectionUiTest', function() { test('testAutofillExtensionIndicator', function() { // Initializing with fake prefs const section = document.createElement('settings-payments-section'); section.prefs = { autofill: {credit_card_enabled: {}, credit_card_fido_auth_enabled: {}} }; document.body.appendChild(section); assertFalse( !!section.shadowRoot!.querySelector('#autofillExtensionIndicator')); section.set('prefs.autofill.credit_card_enabled.extensionId', 'test-id-1'); section.set( 'prefs.autofill.credit_card_fido_auth_enabled.extensionId', 'test-id-2'); flush(); assertTrue( !!section.shadowRoot!.querySelector('#autofillExtensionIndicator')); }); }); suite('PaymentsSection', function() { setup(function() { document.body.innerHTML = ''; loadTimeData.overrideValues({ migrationEnabled: true, }); }); /** * Creates the payments autofill section for the given list. * @param {!Object} prefValues */ function createPaymentsSection( creditCards: chrome.autofillPrivate.CreditCardEntry[], upiIds: string[], prefValues: any): SettingsPaymentsSectionElement { // Override the PaymentsManagerImpl for testing. const paymentsManager = new TestPaymentsManager(); paymentsManager.data.creditCards = creditCards; paymentsManager.data.upiIds = upiIds; PaymentsManagerImpl.setInstance(paymentsManager); const section = document.createElement('settings-payments-section'); section.prefs = {autofill: prefValues}; document.body.appendChild(section); flush(); return section; } /** * Creates the Edit Credit Card dialog. */ function createCreditCardDialog( creditCardItem: chrome.autofillPrivate.CreditCardEntry): SettingsCreditCardEditDialogElement { const section = document.createElement('settings-credit-card-edit-dialog'); section.creditCard = creditCardItem; document.body.appendChild(section); flush(); return section; } // Fakes the existence of a platform authenticator. function addFakePlatformAuthenticator() { if (!window.PublicKeyCredential) { (window.PublicKeyCredential as PublicKeyCredential) = {} as PublicKeyCredential; } window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable = function() { return Promise.resolve(true); }; } /** * Returns an array containing the local and server credit card items. */ function getLocalAndServerCreditCardListItems() { return document.body.querySelector('settings-payments-section')!.shadowRoot! .querySelector('#paymentsList')!.shadowRoot!.querySelectorAll( 'settings-credit-card-list-entry')!; } /** * Returns the shadow root of the card row from the specified list of * payment methods. */ function getCardRowShadowRoot(paymentsList: HTMLElement): ShadowRoot { const row = paymentsList.shadowRoot!.querySelector( 'settings-credit-card-list-entry'); assertTrue(!!row); return row!.shadowRoot!; } /** * Returns the shadow root of the UPI ID row from the specified list of * payment methods. */ function getUPIRowShadowRoot(paymentsList: HTMLElement): ShadowRoot { const row = paymentsList.shadowRoot!.querySelector('settings-upi-id-list-entry'); assertTrue(!!row); return row!.shadowRoot!; } test('verifyNoCreditCards', function() { const section = createPaymentsSection( /*creditCards=*/[], /*upiIds=*/[], {credit_card_enabled: {value: true}}); const creditCardList = section.$.paymentsList; assertTrue(!!creditCardList); assertEquals(0, getLocalAndServerCreditCardListItems().length); assertFalse( creditCardList.shadowRoot! .querySelector<HTMLElement>('#noPaymentMethodsLabel')!.hidden); assertTrue(creditCardList.shadowRoot! .querySelector<HTMLElement>('#creditCardsHeading')!.hidden); assertFalse(section.$.autofillCreditCardToggle.disabled); assertFalse(section.$.addCreditCard.disabled); }); test('verifyCreditCardsDisabled', function() { const section = createPaymentsSection( /*creditCards=*/[], /*upiIds=*/[], {credit_card_enabled: {value: false}}); assertFalse(section.$.autofillCreditCardToggle.disabled); assertTrue(section.$.addCreditCard.hidden); }); test('verifyCreditCardCount', function() { const creditCards = [ createCreditCardEntry(), createCreditCardEntry(), createCreditCardEntry(), createCreditCardEntry(), createCreditCardEntry(), createCreditCardEntry(), ]; const section = createPaymentsSection( creditCards, /*upiIds=*/[], {credit_card_enabled: {value: true}}); const creditCardList = section.$.paymentsList; assertTrue(!!creditCardList); assertEquals( creditCards.length, getLocalAndServerCreditCardListItems().length); assertTrue( creditCardList.shadowRoot! .querySelector<HTMLElement>('#noPaymentMethodsLabel')!.hidden); assertFalse(creditCardList.shadowRoot! .querySelector<HTMLElement>('#creditCardsHeading')!.hidden); assertFalse(section.$.autofillCreditCardToggle.disabled); assertFalse(section.$.addCreditCard.disabled); }); test('verifyCreditCardFields', function() { const creditCard = createCreditCardEntry(); const section = createPaymentsSection([creditCard], /*upiIds=*/[], /*prefValues=*/ {}); const rowShadowRoot = getCardRowShadowRoot(section.$.paymentsList); assertEquals( creditCard.metadata!.summaryLabel, rowShadowRoot.querySelector<HTMLElement>( '#creditCardLabel')!.textContent); assertEquals( creditCard.expirationMonth + '/' + creditCard.expirationYear, rowShadowRoot.querySelector<HTMLElement>( '#creditCardExpiration')!.textContent!.trim()); }); test('verifyCreditCardRowButtonIsDropdownWhenLocal', function() { const creditCard = createCreditCardEntry(); creditCard.metadata!.isLocal = true; const section = createPaymentsSection([creditCard], /*upiIds=*/[], /*prefValues=*/ {}); const rowShadowRoot = getCardRowShadowRoot(section.$.paymentsList); const menuButton = rowShadowRoot.querySelector('#creditCardMenu'); assertTrue(!!menuButton); const outlinkButton = rowShadowRoot.querySelector('cr-icon-button.icon-external'); assertFalse(!!outlinkButton); }); test('verifyCreditCardMoreDetailsTitle', function() { let creditCard = createCreditCardEntry(); creditCard.metadata!.isLocal = true; const section = createPaymentsSection([creditCard], /*upiIds=*/[], /*prefValues=*/ {}); const rowShadowRoot = getCardRowShadowRoot(section.$.paymentsList); const menuButton = rowShadowRoot.querySelector('#creditCardMenu'); assertTrue(!!menuButton); const updateCreditCardCallback = (creditCard: chrome.autofillPrivate.CreditCardEntry) => { (PaymentsManagerImpl.getInstance() as TestPaymentsManager) .lastCallback.setPersonalDataManagerListener!([], [creditCard]); flush(); }; // Case 1: a card with a nickname creditCard = createCreditCardEntry(); creditCard.nickname = 'My card name'; updateCreditCardCallback(creditCard); assertEquals( 'More actions for My card name', menuButton!.getAttribute('title')); // Case 2: a card without nickname creditCard = createCreditCardEntry(); creditCard.cardNumber = '0000000000001234'; creditCard.network = 'Visa'; updateCreditCardCallback(creditCard); assertEquals( 'More actions for Visa ending in 1234', menuButton!.getAttribute('title')); // Case 3: a card without network creditCard = createCreditCardEntry(); creditCard.cardNumber = '0000000000001234'; creditCard.network = undefined; updateCreditCardCallback(creditCard); assertEquals( 'More actions for Card ending in 1234', menuButton!.getAttribute('title')); // Case 4: a card without number creditCard = createCreditCardEntry(); creditCard.cardNumber = undefined; updateCreditCardCallback(creditCard); assertEquals( 'More actions for Jane Doe', menuButton!.getAttribute('title')); }); test('verifyCreditCardRowButtonIsOutlinkWhenRemote', function() { const creditCard = createCreditCardEntry(); creditCard.metadata!.isLocal = false; const section = createPaymentsSection([creditCard], /*upiIds=*/[], /*prefValues=*/ {}); const rowShadowRoot = getCardRowShadowRoot(section.$.paymentsList); const menuButton = rowShadowRoot.querySelector('#creditCardMenu'); assertFalse(!!menuButton); const outlinkButton = rowShadowRoot.querySelector('cr-icon-button.icon-external'); assertTrue(!!outlinkButton); }); test('verifyAddVsEditCreditCardTitle', function() { const newCreditCard = createEmptyCreditCardEntry(); const newCreditCardDialog = createCreditCardDialog(newCreditCard); const oldCreditCard = createCreditCardEntry(); const oldCreditCardDialog = createCreditCardDialog(oldCreditCard); function getTitle(dialog: SettingsCreditCardEditDialogElement) { return dialog.shadowRoot!.querySelector('[slot=title]')!.textContent; } const oldTitle = getTitle(oldCreditCardDialog); const newTitle = getTitle(newCreditCardDialog); assertNotEquals(oldTitle, newTitle); assertNotEquals('', oldTitle); assertNotEquals('', newTitle); // Wait for dialogs to open before finishing test. return Promise.all([ whenAttributeIs(newCreditCardDialog.$.dialog, 'open', ''), whenAttributeIs(oldCreditCardDialog.$.dialog, 'open', ''), ]); }); test('verifyExpiredCreditCardYear', function() { const creditCard = createCreditCardEntry(); // 2015 is over unless time goes wobbly. const twentyFifteen = 2015; creditCard.expirationYear = twentyFifteen.toString(); const creditCardDialog = createCreditCardDialog(creditCard); return whenAttributeIs(creditCardDialog.$.dialog, 'open', '') .then(function() { const now = new Date(); const maxYear = now.getFullYear() + 19; const yearOptions = creditCardDialog.$.year.options; assertEquals('2015', yearOptions[0]!.textContent!.trim()); assertEquals( maxYear.toString(), yearOptions[yearOptions.length - 1]!.textContent!.trim()); assertEquals( creditCard.expirationYear, creditCardDialog.$.year.value); }); }); test('verifyVeryFutureCreditCardYear', function() { const creditCard = createCreditCardEntry(); // Expiring 25 years from now is unusual. const now = new Date(); const farFutureYear = now.getFullYear() + 25; creditCard.expirationYear = farFutureYear.toString(); const creditCardDialog = createCreditCardDialog(creditCard); return whenAttributeIs(creditCardDialog.$.dialog, 'open', '') .then(function() { const yearOptions = creditCardDialog.$.year.options; assertEquals( now.getFullYear().toString(), yearOptions[0]!.textContent!.trim()); assertEquals( farFutureYear.toString(), yearOptions[yearOptions.length - 1]!.textContent!.trim()); assertEquals( creditCard.expirationYear, creditCardDialog.$.year.value); }); }); test('verifyVeryNormalCreditCardYear', function() { const creditCard = createCreditCardEntry(); // Expiring 2 years from now is not unusual. const now = new Date(); const nearFutureYear = now.getFullYear() + 2; creditCard.expirationYear = nearFutureYear.toString(); const maxYear = now.getFullYear() + 19; const creditCardDialog = createCreditCardDialog(creditCard); return whenAttributeIs(creditCardDialog.$.dialog, 'open', '') .then(function() { const yearOptions = creditCardDialog.$.year.options; assertEquals( now.getFullYear().toString(), yearOptions[0]!.textContent!.trim()); assertEquals( maxYear.toString(), yearOptions[yearOptions.length - 1]!.textContent!.trim()); assertEquals( creditCard.expirationYear, creditCardDialog.$.year.value); }); }); test('verify save new credit card', function() { const creditCard = createEmptyCreditCardEntry(); const creditCardDialog = createCreditCardDialog(creditCard); return whenAttributeIs(creditCardDialog.$.dialog, 'open', '') .then(function() { // Not expired, but still can't be saved, because there's no // name. const expiredError = creditCardDialog.$.expiredError; assertEquals('hidden', getComputedStyle(expiredError).visibility); assertTrue(creditCardDialog.$.saveButton.disabled); // Add a name. creditCardDialog.set('creditCard.name', 'Jane Doe'); flush(); assertEquals('hidden', getComputedStyle(expiredError).visibility); assertFalse(creditCardDialog.$.saveButton.disabled); const savedPromise = eventToPromise('save-credit-card', creditCardDialog); creditCardDialog.$.saveButton.click(); return savedPromise; }) .then(function(event) { assertEquals(creditCard.guid, event.detail.guid); }); }); test('verifyCancelCreditCardEdit', function(done) { const creditCard = createEmptyCreditCardEntry(); const creditCardDialog = createCreditCardDialog(creditCard); whenAttributeIs(creditCardDialog.$.dialog, 'open', '').then(function() { eventToPromise('save-credit-card', creditCardDialog).then(function() { // Fail the test because the save event should not be called // when cancel is clicked. assertTrue(false); done(); }); eventToPromise('close', creditCardDialog).then(function() { // Test is |done| in a timeout in order to ensure that // 'save-credit-card' is NOT fired after this test. window.setTimeout(done, 100); }); creditCardDialog.$.cancelButton.click(); }); }); test('verifyLocalCreditCardMenu', function() { const creditCard = createCreditCardEntry(); // When credit card is local, |isCached| will be undefined. creditCard.metadata!.isLocal = true; creditCard.metadata!.isCached = undefined; const section = createPaymentsSection([creditCard], /*upiIds=*/[], /*prefValues=*/ {}); assertEquals(1, getLocalAndServerCreditCardListItems().length); // Local credit cards will show the overflow menu. const rowShadowRoot = getCardRowShadowRoot(section.$.paymentsList); assertFalse(!!rowShadowRoot.querySelector('#remoteCreditCardLink')); const menuButton = rowShadowRoot.querySelector<HTMLElement>('#creditCardMenu'); assertTrue(!!menuButton); menuButton!.click(); flush(); // Menu should have 2 options. assertFalse(section.$.menuEditCreditCard.hidden); assertFalse(section.$.menuRemoveCreditCard.hidden); assertTrue(section.$.menuClearCreditCard.hidden); section.$.creditCardSharedMenu.close(); flush(); }); test('verifyCachedCreditCardMenu', function() { const creditCard = createCreditCardEntry(); creditCard.metadata!.isLocal = false; creditCard.metadata!.isCached = true; const section = createPaymentsSection([creditCard], /*upiIds=*/[], /*prefValues=*/ {}); assertEquals(1, getLocalAndServerCreditCardListItems().length); // Cached remote CCs will show overflow menu. const rowShadowRoot = getCardRowShadowRoot(section.$.paymentsList); assertFalse(!!rowShadowRoot.querySelector('#remoteCreditCardLink')); const menuButton = rowShadowRoot.querySelector<HTMLElement>('#creditCardMenu'); assertTrue(!!menuButton); menuButton!.click(); flush(); // Menu should have 2 options. assertFalse(section.$.menuEditCreditCard.hidden); assertTrue(section.$.menuRemoveCreditCard.hidden); assertFalse(section.$.menuClearCreditCard.hidden); section.$.creditCardSharedMenu.close(); flush(); }); test('verifyNotCachedCreditCardMenu', function() { const creditCard = createCreditCardEntry(); creditCard.metadata!.isLocal = false; creditCard.metadata!.isCached = false; const section = createPaymentsSection([creditCard], /*upiIds=*/[], /*prefValues=*/ {}); assertEquals(1, getLocalAndServerCreditCardListItems().length); // No overflow menu when not cached. const rowShadowRoot = getCardRowShadowRoot(section.$.paymentsList); assertTrue(!!rowShadowRoot.querySelector('#remoteCreditCardLink')); assertFalse(!!rowShadowRoot.querySelector('#creditCardMenu')); }); test('verifyMigrationButtonNotShownIfMigrationNotEnabled', function() { // Mock prerequisites are not met. loadTimeData.overrideValues({migrationEnabled: false}); // Add one migratable credit card. const creditCard = createCreditCardEntry(); creditCard.metadata!.isMigratable = true; const section = createPaymentsSection( [creditCard], /*upiIds=*/[], {credit_card_enabled: {value: true}}); assertTrue(section.$.migrateCreditCards.hidden); }); test('verifyMigrationButtonNotShownIfCreditCardDisabled', function() { // Add one migratable credit card. const creditCard = createCreditCardEntry(); creditCard.metadata!.isMigratable = true; // Mock credit card save toggle is turned off by users. const section = createPaymentsSection( [creditCard], /*upiIds=*/[], {credit_card_enabled: {value: false}}); assertTrue(section.$.migrateCreditCards.hidden); }); test('verifyMigrationButtonNotShownIfNoCardIsMigratable', function() { // Add one migratable credit card. const creditCard = createCreditCardEntry(); // Mock credit card is not valid. creditCard.metadata!.isMigratable = false; const section = createPaymentsSection( [creditCard], /*upiIds=*/[], {credit_card_enabled: {value: true}}); assertTrue(section.$.migrateCreditCards.hidden); }); test('verifyMigrationButtonShown', function() { // Add one migratable credit card. const creditCard = createCreditCardEntry(); creditCard.metadata!.isMigratable = true; const section = createPaymentsSection( [creditCard], /*upiIds=*/[], {credit_card_enabled: {value: true}}); assertFalse(section.$.migrateCreditCards.hidden); }); test('verifyFIDOAuthToggleShownIfUserIsVerifiable', function() { // Set |fidoAuthenticationAvailableForAutofill| to true. loadTimeData.overrideValues({fidoAuthenticationAvailableForAutofill: true}); addFakePlatformAuthenticator(); const section = createPaymentsSection( /*creditCards=*/[], /*upiIds=*/[], {credit_card_enabled: {value: true}}); assertTrue(!!section.shadowRoot!.querySelector( '#autofillCreditCardFIDOAuthToggle')); }); test('verifyFIDOAuthToggleNotShownIfUserIsNotVerifiable', function() { // Set |fidoAuthenticationAvailableForAutofill| to false. loadTimeData.overrideValues( {fidoAuthenticationAvailableForAutofill: false}); const section = createPaymentsSection( /*creditCards=*/[], /*upiIds=*/[], {credit_card_enabled: {value: true}}); assertFalse(!!section.shadowRoot!.querySelector( '#autofillCreditCardFIDOAuthToggle')); }); test('verifyFIDOAuthToggleCheckedIfOptedIn', function() { // Set FIDO auth pref value to true. loadTimeData.overrideValues({fidoAuthenticationAvailableForAutofill: true}); addFakePlatformAuthenticator(); const section = createPaymentsSection(/*creditCards=*/[], /*upiIds=*/[], { credit_card_enabled: {value: true}, credit_card_fido_auth_enabled: {value: true} }); assertTrue(section.shadowRoot! .querySelector<SettingsToggleButtonElement>( '#autofillCreditCardFIDOAuthToggle')!.checked); }); test('verifyFIDOAuthToggleUncheckedIfOptedOut', function() { // Set FIDO auth pref value to false. loadTimeData.overrideValues({fidoAuthenticationAvailableForAutofill: true}); addFakePlatformAuthenticator(); const section = createPaymentsSection(/*creditCards=*/[], /*upiIds=*/[], { credit_card_enabled: {value: true}, credit_card_fido_auth_enabled: {value: false} }); assertFalse(section.shadowRoot! .querySelector<SettingsToggleButtonElement>( '#autofillCreditCardFIDOAuthToggle')!.checked); }); test('verifyUpiIdRow', function() { loadTimeData.overrideValues({showUpiIdSettings: true}); const section = createPaymentsSection( /*creditCards=*/[], ['vpa@indianbank'], /*prefValues=*/ {}); const rowShadowRoot = getUPIRowShadowRoot(section.$.paymentsList); assertTrue(!!rowShadowRoot); assertEquals( rowShadowRoot.querySelector<HTMLElement>('#upiIdLabel')!.textContent, 'vpa@indianbank'); }); test('verifyNoUpiId', function() { loadTimeData.overrideValues({showUpiIdSettings: true}); const section = createPaymentsSection( /*creditCards=*/[], /*upiIds=*/[], /*prefValues=*/ {}); const paymentsList = section.$.paymentsList; const upiRows = paymentsList.shadowRoot!.querySelectorAll('settings-upi-id-list-entry'); assertEquals(0, upiRows.length); }); test('verifyUpiIdCount', function() { loadTimeData.overrideValues({showUpiIdSettings: true}); const upiIds = ['vpa1@indianbank', 'vpa2@indianbank']; const section = createPaymentsSection( /*creditCards=*/[], upiIds, /*prefValues=*/ {}); const paymentsList = section.$.paymentsList; const upiRows = paymentsList.shadowRoot!.querySelectorAll('settings-upi-id-list-entry'); assertEquals(upiIds.length, upiRows.length); }); // Test that |showUpiIdSettings| controls showing UPI IDs in the page. test('verifyShowUpiIdSettings', function() { loadTimeData.overrideValues({showUpiIdSettings: false}); const upiIds = ['vpa1@indianbank']; const section = createPaymentsSection( /*creditCards=*/[], upiIds, /*prefValues=*/ {}); const paymentsList = section.$.paymentsList; const upiRows = paymentsList.shadowRoot!.querySelectorAll('settings-upi-id-list-entry'); assertEquals(0, upiRows.length); }); test('CanMakePaymentToggle_RecordsMetrics', async function() { const testMetricsBrowserProxy = new TestMetricsBrowserProxy(); MetricsBrowserProxyImpl.setInstance(testMetricsBrowserProxy); const section = createPaymentsSection( /*creditCards=*/[], /*upiIds=*/[], /*prefValues=*/ {}); section.$.canMakePaymentToggle.click(); const result = await testMetricsBrowserProxy.whenCalled('recordSettingsPageHistogram'); assertEquals(PrivacyElementInteractions.PAYMENT_METHOD, result); }); });
the_stack
import * as React from 'react' import { ContentSection } from '../components/content/ContentSection' import Layout from '../components/Layout' import ArrowRightIcon from 'mdi-react/ArrowRightIcon' import ArrowLeftIcon from 'mdi-react/ArrowLeftIcon' export const GetStartedPage: React.FunctionComponent<PageProps> = props => { const buttonRef = React.useRef() const newContainerLeftRef = React.useRef() const backBtn = React.useRef() const expandColumn = e => { const column = e.target.parentNode.parentNode const id = column.getAttribute('id') if (id == 'sg-self-hosted') { // Toggle sg-self-hosted column column.classList.remove('d-none') column.classList.add('expanded') column.classList.replace('col-lg-6', 'col-lg-12') // Toggle New container newContainerLeftRef.current.classList.replace('d-none', 'd-inline-block') // Toggle arrow image buttonRef.current.classList.toggle('d-none') // Toggle other column const cloudSection = document.querySelector('#sg-cloud') cloudSection.classList.toggle('d-none') cloudSection.classList.add('high') } /* else { // Toggle sg-cloud column column.classList.remove('d-none') column.classList.add('expanded') column.classList.replace('col-lg-6', 'col-lg-12') // Toggle arrow image buttonRef.current.classList.toggle('d-none') // Toggle other column document.querySelector('#sg-self-hosted').classList.toggle('d-none') }*/ } const goBack = e => { const targetNode = e.target.parentNode.parentNode let column if (targetNode.id == 'sg-self-hosted' || targetNode.id == 'sg-cloud') { column = targetNode } else if (targetNode.parentNode.id == 'sg-self-hosted' || targetNode.parentNode.id == 'sg-cloud') { column = targetNode.parentNode } else if ( targetNode.parentNode.parentNode.id == 'sg-self-hosted' || targetNode.parentNode.parentNode.id == 'sg-cloud' ) { column = targetNode.parentNode.parentNode } const id = column.getAttribute('id') if (id == 'sg-self-hosted') { // Toggle sg-self-hosted column column.classList.remove('expanded') column.classList.replace('col-lg-12', 'col-lg-6') // Toggle New container newContainerLeftRef.current.classList.replace('d-inline-block', 'd-none') // Toggle arrow image buttonRef.current.classList.toggle('d-none') // Toggle other column const cloudSection = document.querySelector('#sg-cloud') cloudSection.classList.toggle('d-none') // To fix issue that the sg-cloud section is not high enough when it gets visible when going back to the delpoyment methods setTimeout(() => { cloudSection.classList.remove('high') }, 0) } /*else { // Toggle sg-cloud column column.classList.remove('expanded') column.classList.replace('col-lg-12', 'col-lg-6') // Toggle arrow image buttonRef.current.classList.toggle('d-none') // Toggle other column document.querySelector('#sg-self-hosted').classList.toggle('d-none') }*/ } const copyText = () => { const copyText = document.getElementById('installText').textContent const textArea = document.createElement('textarea') document.getElementById('installText').style.backgroundColor = '#ccedff' textArea.textContent = copyText document.body.append(textArea) textArea.select() document.execCommand('copy') document.body.removeChild(textArea) } return ( <Layout location={props.location} meta={{ title: 'Choose Your Deployment Model | Get Started with Sourcegraph', description: "From Sourcegraph Self-hosted to Sourcegraph Cloud, choose the deployment model that's best for you and get started for free today. ", image: 'https://about.sourcegraph.com/sourcegraph-og.png', }} heroAndHeaderClassName="get-started-page__hero-and-header" hero={ <div className="row"> <div className="col-lg-9 column"> <h1 className="display-1">What's best for you?</h1> <p className="subTitle"> From Amazon to Uber, the world’s best developers use Sourcegraph every day. </p> </div> </div> } hideFooter={true} hideGetStartedButton={true} > <div className="cta-container get-started-page"> <div className="row"> <div id="sg-self-hosted" className="col-lg-6 column bg-gradient-blue-purple"> <div className="original-container"> <div className="btn back-link" onClick={goBack} ref={node => (backBtn.current = node)}> <ArrowLeftIcon /> <span>Deployment Options</span> </div> <h1 className="display-2 title">Sourcegraph Self-Hosted</h1> <span className="badge"> <img src="../star.svg" /> <span>Most Popular</span> </span> <p> Deploy and control Sourcegraph in your own infrastructure, or use Docker to install locally. Get started for free. </p> <div className="small-title">Best For</div> <p>Teams and enterprises</p> <p> Collaborate with your team on any code host (including private hosts) and access advanced security functionality. </p> <span className="btn btn-primary temporary mt-2" onClick={expandColumn} ref={node => (buttonRef.current = node)} > Get started for free <ArrowRightIcon className="mobileIcon" /> </span> </div> <div className="new-container d-none" ref={node => (newContainerLeftRef.current = node)}> <div className="get-started-page__local"> <div className="get-started-page__installtext" onClick={copyText}> <h2 className="get-started-page__search-headings"> Install Sourcegraph locally <span className="get-started-page__copytext"> <img src="../copy-text-icon.svg" className="copytext icon-inline ml-1 medium" /> </span> </h2> <span id="installText"> docker run <br /> --publish 7080:7080 --publish 127.0.0.1:3370:3370 --rm <br /> --volume ~/.sourcegraph/config:/etc/sourcegraph <br /> --volume ~/.sourcegraph/data:/var/opt/sourcegraph <br /> sourcegraph/server:3.35.0 </span> </div> <a className="btn" href="https://info.sourcegraph.com/talk-to-a-developer"> Talk to an engineer <ArrowRightIcon /> </a> <a className="btn" href="https://docs.sourcegraph.com/"> Deploy to a server or cluster <ArrowRightIcon /> </a> </div> </div> </div> <div id="sg-cloud" className="col-lg-6 column bg-gradient-blue-green"> <div className="original-container"> <div className="btn back-link" onClick={goBack} ref={node => (backBtn.current = node)}> <ArrowLeftIcon /> <span>Deployment Options</span> </div> <h1 className="display-2 title">Sourcegraph Cloud</h1> <p> Sync your code from GitHub.com or GitLab.com. No technical setup is required. Sign up for free. </p> <div className="small-title">Best For</div> <p>Individual developers (small teams coming soon)</p> <p>Search across your repositories and the open-source universe.</p> <p className="small-font"> Already have a Sourcegraph Cloud account?{' '} <a href="https://sourcegraph.com/sign-in" title="Search public code with Sourcegraph Cloud" className="sign-in-link" > Sign in </a> </p> <a className="btn btn-primary temporary mt-2" href="https://sourcegraph.com/search" ref={node => (buttonRef.current = node)} > Try it for free <ArrowRightIcon className="mobileIcon" /> </a> </div> </div> </div> </div> </Layout> ) } export default GetStartedPage
the_stack
import { NonIdealState, Spinner } from '@blueprintjs/core'; import { IconNames } from '@blueprintjs/icons'; import { Octokit } from '@octokit/rest'; import { GetResponseDataTypeFromEndpointMethod } from '@octokit/types'; import * as React from 'react'; import { useEffect, useState } from 'react'; import { useSelector } from 'react-redux'; import { Redirect, Route, Switch, useLocation } from 'react-router-dom'; import { OverallState } from '../../commons/application/ApplicationTypes'; import ContentDisplay from '../../commons/ContentDisplay'; import { MissionRepoData } from '../../commons/githubAssessments/GitHubMissionTypes'; import GitHubAssessmentsNavigationBar from '../../commons/navigationBar/subcomponents/GitHubAssessmentsNavigationBar'; import { showWarningMessage } from '../../commons/utils/NotificationsHelper'; import { assessmentTypeLink } from '../../commons/utils/ParamParseHelper'; import GitHubAssessmentListing from './GitHubAssessmentListing'; import GitHubAssessmentWorkspaceContainer from './GitHubAssessmentWorkspaceContainer'; import GitHubClassroomWelcome from './GitHubClassroomWelcome'; type DispatchProps = { handleGitHubLogIn: () => void; handleGitHubLogOut: () => void; }; /** * A page that lists the missions available to the authenticated user. * This page should only be reachable if using a GitHub-hosted deployment. */ const GitHubClassroom: React.FC<DispatchProps> = props => { const location = useLocation<{ courses: string[] | undefined; assessmentTypeOverviews: GHAssessmentTypeOverview[] | undefined; selectedCourse: string | undefined; }>(); const octokit: Octokit | undefined = useSelector( (store: OverallState) => store.session.githubOctokitObject ).octokit; const [courses, setCourses] = useState<string[] | undefined>(location.state?.courses); const [selectedCourse, setSelectedCourse] = useState<string>( location.state?.selectedCourse || '' ); const [assessmentTypeOverviews, setAssessmentTypeOverviews] = useState< GHAssessmentTypeOverview[] | undefined >(location.state?.assessmentTypeOverviews); const types = assessmentTypeOverviews?.map(overview => overview.typeName); useEffect(() => { if (octokit === undefined) { return; } if (!courses) { fetchCourses(octokit, setCourses, setSelectedCourse, setAssessmentTypeOverviews); } }, [courses, octokit]); const changeCourseHandler = React.useCallback( (e: any) => { if (octokit === undefined) { return; } fetchAssessmentOverviews(octokit, e.target.innerText, setAssessmentTypeOverviews); setSelectedCourse(e.target.innerText); }, [octokit, setSelectedCourse, setAssessmentTypeOverviews] ); const refreshAssessmentOverviews = () => { if (octokit === undefined) { return; } fetchAssessmentOverviews(octokit, selectedCourse, setAssessmentTypeOverviews); }; const redirectToLogin = () => <Redirect to="/githubassessments/login" />; const redirectToAssessments = () => ( <Redirect to={{ // Types should exist whenever we redirect to assessments as this redirect is only called // when a course exists. Unless the course.json is configured wrongly. pathname: `/githubassessments/${assessmentTypeLink(types ? types[0] : 'welcome')}`, state: { courses: courses, assessmentTypeOverviews: assessmentTypeOverviews, selectedCourse: selectedCourse } }} /> ); return ( <div className="Academy" style={{ overflow: 'hidden' }}> <GitHubAssessmentsNavigationBar changeCourseHandler={changeCourseHandler} handleGitHubLogIn={props.handleGitHubLogIn} handleGitHubLogOut={() => { props.handleGitHubLogOut(); setCourses(undefined); setAssessmentTypeOverviews(undefined); setSelectedCourse(''); }} octokit={octokit} courses={courses} selectedCourse={selectedCourse} types={types} assessmentTypeOverviews={assessmentTypeOverviews} /> <Switch> <Route path="/githubassessments/login" render={() => { return octokit && (!courses || (courses.length > 0 && !assessmentTypeOverviews)) ? ( <ContentDisplay display={<NonIdealState description="Loading..." icon={<Spinner />} />} loadContentDispatch={() => {}} /> ) : octokit && courses && courses.length === 0 ? ( <Redirect to="/githubassessments/welcome" /> ) : octokit ? ( redirectToAssessments() ) : ( <ContentDisplay display={ <NonIdealState description="Please sign in to GitHub." icon={IconNames.WARNING_SIGN} /> } loadContentDispatch={() => {}} /> ); }} /> <Route path="/githubassessments/welcome" component={() => (octokit ? <GitHubClassroomWelcome /> : redirectToLogin())} /> <Route path="/githubassessments/editor" component={GitHubAssessmentWorkspaceContainer} /> {octokit ? types?.map((type, idx) => { const filteredAssessments = assessmentTypeOverviews ? assessmentTypeOverviews[idx].assessments : undefined; return ( <Route path={`/githubassessments/${assessmentTypeLink(type)}`} render={() => ( <GitHubAssessmentListing assessmentOverviews={filteredAssessments} refreshAssessmentOverviews={refreshAssessmentOverviews} /> )} key={idx} /> ); }) : null} <Route render={ octokit && courses && courses.length > 0 ? redirectToAssessments : redirectToLogin } /> </Switch> </div> ); }; /** * Retrieves list of organizations for the authenticated user. * * @param octokit The Octokit instance for the authenticated user * @param setCourses The React setter function for an array of courses string names * @param setSelectedCourse The React setter function for string name of selected course */ async function fetchCourses( octokit: Octokit, setCourses: (courses: string[]) => void, setSelectedCourse: (course: string) => void, setAssessmentTypeOverviews: (assessmentTypeOverviews: GHAssessmentTypeOverview[]) => void ) { const courses: string[] = []; const results = (await octokit.orgs.listForAuthenticatedUser({ per_page: 100 })).data; const orgs = results.filter(org => org.login.includes('source-academy-course')); // filter only organisations with 'source-academy-course' in name orgs.forEach(org => { courses.push(org.login.replace('source-academy-course-', '')); }); setCourses(courses); if (courses.length > 0) { setSelectedCourse(courses[0]); fetchAssessmentOverviews(octokit, courses[0], setAssessmentTypeOverviews); } } export type GHAssessmentTypeOverview = { typeName: string; assessments: GHAssessmentOverview[]; }; export type GHAssessmentOverview = { title: string; coverImage: string; webSummary: string; missionRepoData: MissionRepoData; dueDate: Date; link?: string; }; type GitHubAssessment = { id: string; title: string; openAt: string; closeAt: string; published: string; coverImage: string; shortSummary: string; acceptLink: string; repoPrefix: string; }; async function fetchAssessmentOverviews( octokit: Octokit, selectedCourse: string, setAssessmentTypeOverviews: (assessmentTypeOverviews: GHAssessmentTypeOverview[]) => void ) { const userLogin = (await octokit.users.getAuthenticated()).data.login; const orgLogin = 'source-academy-course-'.concat(selectedCourse); type ListForAuthenticatedUserData = GetResponseDataTypeFromEndpointMethod< typeof octokit.repos.listForAuthenticatedUser >; const userRepos: ListForAuthenticatedUserData = ( await octokit.repos.listForAuthenticatedUser({ per_page: 100 }) ).data; const courseRepos = userRepos.filter(repo => repo.owner!.login === orgLogin); const courseInfoRepo = courseRepos.find(repo => repo.name.includes('course-info')); if (courseInfoRepo === undefined) { showWarningMessage('The course-info repository cannot be located.', 2000); return; } const files = ( await octokit.repos.getContent({ owner: courseInfoRepo.owner!.login, repo: courseInfoRepo.name, path: '' }) ).data; if (Array.isArray(files)) { if (files.find(file => file.name === 'course-info.json')) { const result = await octokit.repos.getContent({ owner: courseInfoRepo.owner!.login, repo: courseInfoRepo.name, path: 'course-info.json' }); const courseInfo = JSON.parse(Buffer.from((result.data as any).content, 'base64').toString()); courseInfo.types.forEach((type: { typeName: string; assessments: [GitHubAssessment] }) => { const assessmentOverviews: GHAssessmentOverview[] = []; type.assessments.forEach((assessment: GitHubAssessment) => { if (!assessment.published) { return; } const prefixLogin = assessment.repoPrefix + '-' + userLogin; const missionRepo = userRepos.find(repo => repo.name === prefixLogin); let createdAt = new Date(); let acceptLink = undefined; if (missionRepo === undefined) { acceptLink = assessment.acceptLink; } else { if (missionRepo.created_at !== null) { createdAt = new Date(missionRepo.created_at); } } assessmentOverviews.push({ title: assessment.title, coverImage: assessment.coverImage, webSummary: assessment.shortSummary, missionRepoData: { repoOwner: courseInfoRepo.owner!.login, repoName: prefixLogin, dateOfCreation: createdAt }, dueDate: new Date(assessment.closeAt), link: acceptLink }); assessmentOverviews.sort((a, b) => (a.dueDate <= b.dueDate ? -1 : 1)); }); (type as any).assessments = assessmentOverviews; }); setAssessmentTypeOverviews(courseInfo.types); } else { showWarningMessage('The course-info.json file cannot be located.', 2000); return; } } } export default GitHubClassroom;
the_stack
import { MarkdownView, Plugin, FileSystemAdapter, Editor, Menu, MenuItem, TFile, normalizePath, Notice, addIcon, } from "obsidian"; import { resolve, extname, relative, join, parse, posix } from "path"; import { existsSync, mkdirSync, writeFileSync } from "fs"; import fetch from "node-fetch"; import { clipboard } from "electron"; import { SettingTab, PluginSettings, DEFAULT_SETTINGS } from "./setting"; const REGEX_FILE = /\!\[(.*?)\]\((.*?)\)/g; interface Image { path: string; name: string; source: string; } interface PicGoResponse { success: string; msg: string; } export default class imageAutoUploadPlugin extends Plugin { settings: PluginSettings; readonly cmAndHandlersMap = new WeakMap(); async loadSettings() { this.settings = Object.assign(DEFAULT_SETTINGS, await this.loadData()); } async saveSettings() { await this.saveData(this.settings); } onunload() {} async onload() { addIcon( "upload", `<svg t="1636630783429" class="icon" viewBox="0 0 100 100" version="1.1" p-id="4649" xmlns="http://www.w3.org/2000/svg"> <path d="M 71.638 35.336 L 79.408 35.336 C 83.7 35.336 87.178 38.662 87.178 42.765 L 87.178 84.864 C 87.178 88.969 83.7 92.295 79.408 92.295 L 17.249 92.295 C 12.957 92.295 9.479 88.969 9.479 84.864 L 9.479 42.765 C 9.479 38.662 12.957 35.336 17.249 35.336 L 25.019 35.336 L 25.019 42.765 L 17.249 42.765 L 17.249 84.864 L 79.408 84.864 L 79.408 42.765 L 71.638 42.765 L 71.638 35.336 Z M 49.014 10.179 L 67.326 27.688 L 61.835 32.942 L 52.849 24.352 L 52.849 59.731 L 45.078 59.731 L 45.078 24.455 L 36.194 32.947 L 30.702 27.692 L 49.012 10.181 Z" p-id="4650" fill="#8a8a8a"></path> </svg>` ); await this.loadSettings(); this.addSettingTab(new SettingTab(this.app, this)); this.setupPasteHandler(); this.addCommand({ id: "upload all images", name: "upload all images", checkCallback: (checking: boolean) => { let leaf = this.app.workspace.activeLeaf; if (leaf) { if (!checking) { this.uploadAllFile(); } return true; } return false; }, }); this.addCommand({ id: "doanload all images", name: "download all images", checkCallback: (checking: boolean) => { let leaf = this.app.workspace.activeLeaf; if (leaf) { if (!checking) { this.downloadAllImageFiles(); } return true; } return false; }, }); this.registerFileMenu(); } ///TODO: asset路径处理(assets文件夹不存在处理),下载图片失败处理 async downloadAllImageFiles() { const folderPath = this.getFileAssetPath(); const fileArray = this.getAllFiles(); if (!existsSync(folderPath)) { mkdirSync(folderPath); } let imageArray = []; for (const file of fileArray) { if (!file.path.startsWith("http")) { continue; } const url = file.path; const asset = this.getUrlAsset(url); if (!this.isAnImage(asset.substr(asset.lastIndexOf(".")))) { continue; } let [name, ext] = [ decodeURI(parse(asset).name).replaceAll(/[\\\\/:*?\"<>|]/g, "-"), parse(asset).ext, ]; // 如果文件名已存在,则用随机值替换 if (existsSync(join(folderPath, encodeURI(asset)))) { name = (Math.random() + 1).toString(36).substr(2, 5); } const response = await this.download( url, join(folderPath, `${name}${ext}`) ); if (response.ok) { const activeFolder = this.app.vault.getAbstractFileByPath( this.app.workspace.getActiveFile().path ).parent.path; const basePath = ( this.app.vault.adapter as FileSystemAdapter ).getBasePath(); const abstractActiveFolder = resolve(basePath, activeFolder); imageArray.push({ source: file.source, name: name, path: normalizePath(relative(abstractActiveFolder, response.path)), }); } } let editor = this.getEditor(); let value = editor.getValue(); imageArray.map(image => { value = value.replace(image.source, `![${image.name}](${image.path})`); }); this.setValue(value); new Notice( `all: ${fileArray.length}\nsuccess: ${imageArray.length}\nfailed: ${ fileArray.length - imageArray.length }` ); } // 获取当前文件所属的附件文件夹 getFileAssetPath() { const basePath = ( this.app.vault.adapter as FileSystemAdapter ).getBasePath(); // @ts-ignore const assetFolder: string = this.app.vault.config.attachmentFolderPath; const activeFile = this.app.vault.getAbstractFileByPath( this.app.workspace.getActiveFile().path ); // 当前文件夹下的子文件夹 if (assetFolder.startsWith("./")) { const activeFolder = decodeURI(resolve(basePath, activeFile.parent.path)); return join(activeFolder, assetFolder); } else { // 根文件夹 return join(basePath, assetFolder); } } async download(url: string, path: string) { const response = await fetch(url); if (response.status !== 200) { return { ok: false, msg: response.statusText, }; } const buffer = await response.buffer(); try { writeFileSync(path, buffer); return { ok: true, msg: "ok", path: path, }; } catch (err) { return { ok: false, msg: err, }; } } getUrlAsset(url: string) { return (url = url.substr(1 + url.lastIndexOf("/")).split("?")[0]).split( "#" )[0]; } registerFileMenu() { this.app.workspace.on( "file-menu", (menu: Menu, file: TFile, source: string) => { if (!this.isAssetTypeAnImage(file.path)) { return false; } menu.addItem((item: MenuItem) => { item .setTitle("Upload") .setIcon("upload") .onClick(() => { if (!(file instanceof TFile)) { return false; } const basePath = ( this.app.vault.adapter as FileSystemAdapter ).getBasePath(); const uri = decodeURI(resolve(basePath, file.path)); const editor = this.getEditor(); this.uploadFiles([uri]).then(res => { if (res.success) { let uploadUrl = [...res.result][0]; let value = editor .getValue() .replaceAll( encodeURI( relative( this.app.workspace.getActiveFile().parent.path, file.path ).replaceAll("\\", "/") ), uploadUrl ); this.setValue(value); } }); }); }); } ); } setValue(value: string) { const editor = this.getEditor(); const { left, top } = editor.getScrollInfo(); editor.setValue(value); editor.scrollTo(left, top); } uploadFile() {} isAnImage(ext: string) { return [".png", ".jpg", ".jpeg", ".bmp", ".gif", ".svg", ".tiff"].includes( ext.toLowerCase() ); } isAssetTypeAnImage(path: string): Boolean { return ( [".png", ".jpg", ".jpeg", ".bmp", ".gif", ".svg", ".tiff"].indexOf( extname(path).toLowerCase() ) !== -1 ); } // get all file urls, include local and internet getAllFiles(): Image[] { let editor = this.getEditor(); let key = editor.getValue(); const matches = key.matchAll(REGEX_FILE); let fileArray: Image[] = []; for (const match of matches) { const name = match[1]; const path = match[2]; const source = match[0]; fileArray.push({ path: path, name: name, source: source, }); } return fileArray; } // uploda all file uploadAllFile() { let editor = this.getEditor(); if (!editor) { return false; } let key = editor.getValue(); const thisPath = this.app.vault.getAbstractFileByPath( this.app.workspace.getActiveFile().path ); const basePath = ( this.app.vault.adapter as FileSystemAdapter ).getBasePath(); let imageList: Image[] = []; const fileArray = this.getAllFiles(); for (const match of fileArray) { const imageName = match.name; const encodedUri = match.path; if (!encodedUri.startsWith("http")) { const abstractImageFile = decodeURI( join( basePath, posix.resolve(posix.join("/", thisPath.parent.path), encodedUri) ) ); if ( existsSync(abstractImageFile) && this.isAssetTypeAnImage(abstractImageFile) ) { imageList.push({ path: abstractImageFile, name: imageName, source: match.source, }); } } } this.uploadFiles(imageList.map(item => item.path)).then(res => { if (res.success) { let uploadUrlList = [...res.result]; imageList.map(item => { // gitea不能上传超过1M的数据,上传多张照片,错误的话会返回什么?还有待验证 const uploadImage = uploadUrlList.shift(); key = key.replaceAll(item.source, `![${item.name}](${uploadImage})`); }); this.setValue(key); } }); } setupPasteHandler() { this.app.workspace.on( "editor-paste", (evt: ClipboardEvent, editor: Editor, markdownView: MarkdownView) => { let files = evt.clipboardData.files; if ( this.isCopyImageFile() || files.length !== 0 || files[0].type.startsWith("image") ) { this.uploadFileAndEmbedImgurImage(editor).catch(console.error); evt.preventDefault(); } } ); this.app.workspace.on( "editor-drop", async (evt: DragEvent, editor: Editor, markdownView: MarkdownView) => { let files = evt.dataTransfer.files; if (files.length !== 0 || files[0].type.startsWith("image")) { let sendFiles: Array<String> = []; let files = evt.dataTransfer.files; Array.from(files).forEach((item, index) => { sendFiles.push(item.path); }); evt.preventDefault(); const data = await this.uploadFiles(sendFiles); console.log(data); if (data.success) { data.result.map((value: string) => { let pasteId = (Math.random() + 1).toString(36).substr(2, 5); this.insertTemporaryText(editor, pasteId); this.embedMarkDownImage(editor, pasteId, value); }); } else { new Notice("Upload error"); } } } ); } isCopyImageFile() { let filePath = ""; const os = this.getOS(); if (os === "Windows") { var rawFilePath = clipboard.read("FileNameW"); filePath = rawFilePath.replace( new RegExp(String.fromCharCode(0), "g"), "" ); } else if (os === "MacOS") { filePath = clipboard.read("public.file-url").replace("file://", ""); } else { filePath = ""; } return this.isAssetTypeAnImage(filePath); } getOS() { const { appVersion } = navigator; if (appVersion.indexOf("Win") !== -1) { return "Windows"; } else if (appVersion.indexOf("Mac") !== -1) { return "MacOS"; } else if (appVersion.indexOf("X11") !== -1) { return "Linux"; } else { return "Unknown OS"; } } backupOriginalPasteHandler(cm: any) { if (!this.cmAndHandlersMap.has(cm)) { let originalHandler = cm._handlers.paste[0]; this.cmAndHandlersMap.set(cm, originalHandler); } return this.cmAndHandlersMap.get(cm); } async uploadFileAndEmbedImgurImage(editor: Editor) { let pasteId = (Math.random() + 1).toString(36).substr(2, 5); this.insertTemporaryText(editor, pasteId); try { let resp = await this.uploadFileByClipboard(); let data: PicGoResponse = await resp.json(); if (!data.success) { let err = { response: data, body: data.msg }; this.handleFailedUpload(editor, pasteId, err); return; } this.embedMarkDownImage(editor, pasteId, data.result[0]); } catch (e) { this.handleFailedUpload(editor, pasteId, e); } } insertTemporaryText(editor: Editor, pasteId: string) { let progressText = imageAutoUploadPlugin.progressTextFor(pasteId); editor.replaceSelection(progressText + "\n"); } private static progressTextFor(id: string) { return `![Uploading file...${id}]()`; } async uploadFiles(fileList: Array<String>): Promise<any> { const response = await fetch(this.settings.uploadServer, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ list: fileList }), }); const data = await response.json(); return data; } uploadFileByClipboard(): Promise<any> { return fetch(this.settings.uploadServer, { method: "POST", }); } embedMarkDownImage(editor: Editor, pasteId: string, imageUrl: any) { let progressText = imageAutoUploadPlugin.progressTextFor(pasteId); let markDownImage = `![](${imageUrl})`; imageAutoUploadPlugin.replaceFirstOccurrence( editor, progressText, markDownImage ); } handleFailedUpload(editor: Editor, pasteId: string, reason: any) { console.error("Failed request: ", reason); let progressText = imageAutoUploadPlugin.progressTextFor(pasteId); imageAutoUploadPlugin.replaceFirstOccurrence( editor, progressText, "⚠️upload failed, check dev console" ); } static replaceFirstOccurrence( editor: Editor, target: string, replacement: string ) { let lines = editor.getValue().split("\n"); for (let i = 0; i < lines.length; i++) { let ch = lines[i].indexOf(target); if (ch != -1) { let from = { line: i, ch: ch }; let to = { line: i, ch: ch + target.length }; editor.replaceRange(replacement, from, to); break; } } } getEditor() { const mdView = this.app.workspace.getActiveViewOfType(MarkdownView); if (mdView) { return mdView.editor; } else { return null; } } getFrontmatterValue(key: string, defaultValue: any = undefined) { const file = this.app.workspace.getActiveFile(); if (!file) { return undefined; } const path = file.path; const cache = this.app.metadataCache.getCache(path); let value = defaultValue; if (cache?.frontmatter && cache.frontmatter.hasOwnProperty(key)) { value = cache.frontmatter[key]; } return value; } }
the_stack
namespace egret.web { export class TextBlock extends HashObject { private readonly _width: number = 0; private readonly _height: number = 0; private readonly _border: number = 0; public line: Line = null; public x: number = 0; public y: number = 0; public u: number = 0; public v: number = 0; public tag: string = ''; public readonly measureWidth: number = 0; public readonly measureHeight: number = 0; public readonly canvasWidthOffset: number = 0; public readonly canvasHeightOffset: number = 0; public readonly stroke2: number = 0; constructor(width: number, height: number, measureWidth: number, measureHeight: number, canvasWidthOffset: number, canvasHeightOffset: number, stroke2: number, border: number) { super(); this._width = width; this._height = height; this._border = border; this.measureWidth = measureWidth; this.measureHeight = measureHeight; this.canvasWidthOffset = canvasWidthOffset; this.canvasHeightOffset = canvasHeightOffset; this.stroke2 = stroke2; } public get border(): number { return this._border; } public get width(): number { return this._width + this.border * 2; } public get height(): number { return this._height + this.border * 2; } public get contentWidth(): number { return this._width; } public get contentHeight(): number { return this._height; } public get page(): Page { return this.line ? this.line.page : null; } public updateUV(): boolean { const line = this.line; if (!line) { return false;//不属于任何的line就是错的 } this.u = line.x + this.x + this.border * 1; this.v = line.y + this.y + this.border * 1; return true; } public get subImageOffsetX(): number { const line = this.line; if (!line) { return 0; } return line.x + this.x + this.border; } public get subImageOffsetY(): number { const line = this.line; if (!line) { return 0; } return line.y + this.y + this.border; } } export class Line extends HashObject { public page: Page = null; private readonly textBlocks: TextBlock[] = []; public dynamicMaxHeight: number = 0; public readonly maxWidth: number = 0; public x: number = 0; public y: number = 0; constructor(maxWidth: number) { super(); this.maxWidth = maxWidth; } public isCapacityOf(textBlock: TextBlock): boolean { if (!textBlock) { return false; } // let posx = 0; let posy = 0; const lastTxtBlock = this.lastTextBlock(); if (lastTxtBlock) { posx = lastTxtBlock.x + lastTxtBlock.width; posy = lastTxtBlock.y; } // if (posx + textBlock.width > this.maxWidth) { return false;//宽度不够 } // if (this.dynamicMaxHeight > 0) { if (textBlock.height > this.dynamicMaxHeight || (textBlock.height / this.dynamicMaxHeight < 0.5)) { return false;//如果有已经有动态高度,到这里,要么高度不够,要么小于动态高度的0.6差距, 就不填充 } } return true; } private lastTextBlock(): TextBlock { const textBlocks = this.textBlocks; if (textBlocks.length > 0) { return textBlocks[textBlocks.length - 1]; } return null; } public addTextBlock(textBlock: TextBlock, needCheck: boolean): boolean { // if (!textBlock) { return false; } // if (needCheck) { if (!this.isCapacityOf(textBlock)) { return false; } } // let posx = 0; let posy = 0; const lastTxtBlock = this.lastTextBlock(); if (lastTxtBlock) { posx = lastTxtBlock.x + lastTxtBlock.width; posy = lastTxtBlock.y; } // textBlock.x = posx; textBlock.y = posy; textBlock.line = this; this.textBlocks.push(textBlock); this.dynamicMaxHeight = Math.max(this.dynamicMaxHeight, textBlock.height); return true; } } export class Page extends HashObject { public readonly lines: Line[] = []; public readonly pageWidth: number = 0; public readonly pageHeight: number = 0; public webGLTexture: WebGLTexture = null; constructor(pageWidth: number, pageHeight: number) { super(); this.pageWidth = pageWidth; this.pageHeight = pageHeight; } public addLine(line: Line): boolean { if (!line) { return false; } // let posx = 0; let posy = 0; // const lines = this.lines; if (lines.length > 0) { const lastLine = lines[lines.length - 1]; posx = lastLine.x; posy = lastLine.y + lastLine.dynamicMaxHeight; } if (line.maxWidth > this.pageWidth) { console.error('line.maxWidth = ' + line.maxWidth + ', ' + 'this.pageWidth = ' + this.pageWidth); return false;//宽度不够 } if (posy + line.dynamicMaxHeight > this.pageHeight) { return false;//满了 } //更新数据 line.x = posx; line.y = posy; line.page = this; this.lines.push(line); return true; } } export class Book extends HashObject { private readonly _pages: Page[] = []; private _sortLines: Line[] = []; private readonly _maxSize: number = 1024; private readonly _border: number = 1; constructor(maxSize: number, border: number) { super(); this._maxSize = maxSize; this._border = border; } public addTextBlock(textBlock: TextBlock): boolean { const result = this._addTextBlock(textBlock); if (!result) { return false; } //更新下uv textBlock.updateUV(); //没有才要添加 let exist = false; const cast = result as [Page, Line]; const _sortLines = this._sortLines; for (const line of _sortLines) { if (line === cast[1]) { exist = true; break; } } if (!exist) { _sortLines.push(cast[1]); } //重新排序 this.sort(); return true; } private _addTextBlock(textBlock: TextBlock): [Page, Line] | null { if (!textBlock) { return null; } if (textBlock.width > this._maxSize || textBlock.height > this._maxSize) { //console.log('this._maxSize = ' + this._maxSize + ', textBlock.width = ' + textBlock.width + ', textBlock.height = ' + textBlock.height); return null; } //找到最合适的 const _sortLines = this._sortLines; for (let i = 0, length = _sortLines.length; i < length; ++i) { const line = _sortLines[i]; if (!line.isCapacityOf(textBlock)) { continue; } if (line.addTextBlock(textBlock, false)) { return [line.page, line]; } } //做新的行 const newLine = new Line(this._maxSize); if (!newLine.addTextBlock(textBlock, true)) { console.error('_addTextBlock !newLine.addTextBlock(textBlock, true)'); return null; } //现有的page中插入 const _pages = this._pages; for (let i = 0, length = _pages.length; i < length; ++i) { const page = _pages[i]; if (page.addLine(newLine)) { return [page, newLine]; } } //都没有,就做新的page //添加目标行 const newPage = this.createPage(this._maxSize, this._maxSize); if (!newPage.addLine(newLine)) { console.error('_addText newPage.addLine failed'); return null; } return [newPage, newLine]; } private createPage(pageWidth: number, pageHeight: number): Page { const newPage = new Page(pageWidth, pageHeight); this._pages.push(newPage); return newPage; } private sort(): void { if (this._sortLines.length <= 1) { return; } const sortFunc = (a: Line, b: Line): number => { return (a.dynamicMaxHeight < b.dynamicMaxHeight) ? -1 : 1; } this._sortLines = this._sortLines.sort(sortFunc); } public createTextBlock(tag: string, width: number, height: number, measureWidth: number, measureHeight: number, canvasWidthOffset: number, canvasHeightOffset: number, stroke2: number): TextBlock { const txtBlock = new TextBlock(width, height, measureWidth, measureHeight, canvasWidthOffset, canvasHeightOffset, stroke2, this._border); if (!this.addTextBlock(txtBlock)) { //走到这里几乎是不可能的,除非内存分配没了 //暂时还没有到提交纹理的地步,现在都是虚拟的 return null; } txtBlock.tag = tag; return txtBlock; } } }
the_stack
import Debug from "debug"; import Client from "bittorrent-tracker/client"; import { Buffer } from "buffer"; import sha1 from "sha.js/sha1"; import { STEEmitter } from "./stringly-typed-event-emitter"; import { Segment } from "./loader-interface"; import { MediaPeer, MediaPeerSegmentStatus } from "./media-peer"; import { version } from "./index"; import { SegmentsStorage, SegmentValidatorCallback } from "./hybrid-loader"; const PEER_PROTOCOL_VERSION = 2; const PEER_ID_VERSION_STRING = version.replace(/\d*./g, (v) => `0${parseInt(v, 10) % 100}`.slice(-2)).slice(0, 4); const PEER_ID_VERSION_PREFIX = `-WW${PEER_ID_VERSION_STRING}-`; // Using WebTorrent client ID in order to not be banned by websocket trackers class PeerSegmentRequest { constructor(readonly peerId: string, readonly segment: Segment) {} } function generatePeerId(): ArrayBuffer { const PEER_ID_SYMBOLS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; const PEER_ID_LENGTH = 20; let peerId = PEER_ID_VERSION_PREFIX; for (let i = 0; i < PEER_ID_LENGTH - PEER_ID_VERSION_PREFIX.length; i++) { peerId += PEER_ID_SYMBOLS.charAt(Math.floor(Math.random() * PEER_ID_SYMBOLS.length)); } return new TextEncoder().encode(peerId).buffer; } export class P2PMediaManager extends STEEmitter< | "peer-connected" | "peer-closed" | "peer-data-updated" | "segment-loaded" | "segment-error" | "bytes-downloaded" | "bytes-uploaded" | "tracker-update" > { // eslint-disable-next-line @typescript-eslint/no-explicit-any private trackerClient: any = null; private peers = new Map<string, MediaPeer>(); private peerCandidates = new Map<string, MediaPeer[]>(); private peerSegmentRequests = new Map<string, PeerSegmentRequest>(); private streamSwarmId: string | null = null; private readonly peerId: ArrayBuffer; private debug = Debug("p2pml:p2p-media-manager"); private pendingTrackerClient: { isDestroyed: boolean; } | null = null; private masterSwarmId?: string; public constructor( private segmentsStorage: SegmentsStorage, private settings: { useP2P: boolean; trackerAnnounce: string[]; p2pSegmentDownloadTimeout: number; segmentValidator?: SegmentValidatorCallback; webRtcMaxMessageSize: number; rtcConfig?: RTCConfiguration; peerRequestsPerAnnounce: number; } ) { super(); this.peerId = settings.useP2P ? generatePeerId() : new ArrayBuffer(0); if (this.debug.enabled) { this.debug("peer ID", this.getPeerId(), new TextDecoder().decode(this.peerId)); } } public getPeers = (): Map<string, MediaPeer> => { return this.peers; }; public getPeerId = (): string => { return Buffer.from(this.peerId).toString("hex"); }; public setStreamSwarmId = (streamSwarmId: string, masterSwarmId: string): void => { if (this.streamSwarmId === streamSwarmId) { return; } this.destroy(true); this.streamSwarmId = streamSwarmId; this.masterSwarmId = masterSwarmId; this.debug("stream swarm ID", this.streamSwarmId); this.pendingTrackerClient = { isDestroyed: false, }; const pendingTrackerClient = this.pendingTrackerClient; // TODO: native browser 'crypto.subtle' implementation doesn't work in Chrome in insecure pages // TODO: Edge doesn't support SHA-1. Change to SHA-256 once Edge support is required. // const infoHash = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(PEER_PROTOCOL_VERSION + this.streamSwarmId)); const infoHash = new sha1().update(`${PEER_PROTOCOL_VERSION}${this.streamSwarmId}`).digest(); // destroy may be called while waiting for the hash to be calculated if (!pendingTrackerClient.isDestroyed) { this.pendingTrackerClient = null; this.createClient(infoHash); } else if (this.trackerClient !== null) { this.trackerClient.destroy(); this.trackerClient = null; } }; private createClient = (infoHash: ArrayBuffer): void => { if (!this.settings.useP2P) { return; } const clientOptions = { infoHash: Buffer.from(infoHash, 0, 20), peerId: Buffer.from(this.peerId, 0, 20), announce: this.settings.trackerAnnounce, rtcConfig: this.settings.rtcConfig, port: 6881, // a dummy value allows running in Node.js environment getAnnounceOpts: () => { return { numwant: this.settings.peerRequestsPerAnnounce }; }, }; let oldTrackerClient = this.trackerClient; this.trackerClient = new Client(clientOptions); this.trackerClient.on("error", this.onTrackerError); this.trackerClient.on("warning", this.onTrackerWarning); this.trackerClient.on("update", this.onTrackerUpdate); this.trackerClient.on("peer", this.onTrackerPeer); this.trackerClient.start(); if (oldTrackerClient !== null) { oldTrackerClient.destroy(); oldTrackerClient = null; } }; private onTrackerError = (error: unknown) => { this.debug("tracker error", error); }; private onTrackerWarning = (warning: unknown) => { this.debug("tracker warning", warning); }; private onTrackerUpdate = (data: unknown): void => { this.debug("tracker update", data); this.emit("tracker-update", data); }; // eslint-disable-next-line @typescript-eslint/no-explicit-any private onTrackerPeer = (trackerPeer: any): void => { this.debug("tracker peer", trackerPeer.id, trackerPeer); if (this.peers.has(trackerPeer.id)) { this.debug("tracker peer already connected", trackerPeer.id, trackerPeer); trackerPeer.destroy(); return; } const peer = new MediaPeer(trackerPeer, this.settings); peer.on("connect", this.onPeerConnect); peer.on("close", this.onPeerClose); peer.on("data-updated", this.onPeerDataUpdated); peer.on("segment-request", this.onSegmentRequest); peer.on("segment-loaded", this.onSegmentLoaded); peer.on("segment-absent", this.onSegmentAbsent); peer.on("segment-error", this.onSegmentError); peer.on("segment-timeout", this.onSegmentTimeout); peer.on("bytes-downloaded", this.onPieceBytesDownloaded); peer.on("bytes-uploaded", this.onPieceBytesUploaded); let peerCandidatesById = this.peerCandidates.get(peer.id); if (!peerCandidatesById) { peerCandidatesById = []; this.peerCandidates.set(peer.id, peerCandidatesById); } peerCandidatesById.push(peer); }; public download = (segment: Segment): boolean => { if (this.isDownloading(segment)) { return false; } const candidates: MediaPeer[] = []; for (const peer of this.peers.values()) { if ( peer.getDownloadingSegmentId() === null && peer.getSegmentsMap().get(segment.id) === MediaPeerSegmentStatus.Loaded ) { candidates.push(peer); } } if (candidates.length === 0) { return false; } const peer = candidates[Math.floor(Math.random() * candidates.length)]; peer.requestSegment(segment.id); this.peerSegmentRequests.set(segment.id, new PeerSegmentRequest(peer.id, segment)); return true; }; public abort = (segment: Segment): ArrayBuffer[] | undefined => { let downloadingSegment: ArrayBuffer[] | undefined; const peerSegmentRequest = this.peerSegmentRequests.get(segment.id); if (peerSegmentRequest) { const peer = this.peers.get(peerSegmentRequest.peerId); if (peer) { downloadingSegment = peer.cancelSegmentRequest(); } this.peerSegmentRequests.delete(segment.id); } return downloadingSegment; }; public isDownloading = (segment: Segment): boolean => { return this.peerSegmentRequests.has(segment.id); }; public getActiveDownloadsCount = (): number => { return this.peerSegmentRequests.size; }; public destroy = (swarmChange = false): void => { this.streamSwarmId = null; if (this.trackerClient) { this.trackerClient.stop(); if (swarmChange) { // Don't destroy trackerClient to reuse its WebSocket connection to the tracker server this.trackerClient.removeAllListeners("error"); this.trackerClient.removeAllListeners("warning"); this.trackerClient.removeAllListeners("update"); this.trackerClient.removeAllListeners("peer"); } else { this.trackerClient.destroy(); this.trackerClient = null; } } if (this.pendingTrackerClient) { this.pendingTrackerClient.isDestroyed = true; this.pendingTrackerClient = null; } this.peers.forEach((peer) => peer.destroy()); this.peers.clear(); this.peerSegmentRequests.clear(); for (const peerCandidateById of this.peerCandidates.values()) { for (const peerCandidate of peerCandidateById) { peerCandidate.destroy(); } } this.peerCandidates.clear(); }; public sendSegmentsMapToAll = (segmentsMap: { [key: string]: [string, number[]] }): void => { this.peers.forEach((peer) => peer.sendSegmentsMap(segmentsMap)); }; public sendSegmentsMap = (peerId: string, segmentsMap: { [key: string]: [string, number[]] }): void => { const peer = this.peers.get(peerId); if (peer) { peer.sendSegmentsMap(segmentsMap); } }; public getOverallSegmentsMap = (): Map<string, MediaPeerSegmentStatus> => { const overallSegmentsMap = new Map<string, MediaPeerSegmentStatus>(); for (const peer of this.peers.values()) { for (const [segmentId, segmentStatus] of peer.getSegmentsMap()) { if (segmentStatus === MediaPeerSegmentStatus.Loaded) { overallSegmentsMap.set(segmentId, MediaPeerSegmentStatus.Loaded); } else if (!overallSegmentsMap.get(segmentId)) { overallSegmentsMap.set(segmentId, MediaPeerSegmentStatus.LoadingByHttp); } } } return overallSegmentsMap; }; private onPieceBytesDownloaded = (peer: MediaPeer, bytes: number) => { this.emit("bytes-downloaded", bytes, peer.id); }; private onPieceBytesUploaded = (peer: MediaPeer, bytes: number) => { this.emit("bytes-uploaded", bytes, peer.id); }; private onPeerConnect = (peer: MediaPeer) => { const connectedPeer = this.peers.get(peer.id); if (connectedPeer) { this.debug("tracker peer already connected (in peer connect)", peer.id, peer); peer.destroy(); return; } // First peer with the ID connected this.peers.set(peer.id, peer); // Destroy all other peer candidates const peerCandidatesById = this.peerCandidates.get(peer.id); if (peerCandidatesById) { for (const peerCandidate of peerCandidatesById) { if (peerCandidate !== peer) { peerCandidate.destroy(); } } this.peerCandidates.delete(peer.id); } this.emit("peer-connected", { id: peer.id, remoteAddress: peer.remoteAddress }); }; private onPeerClose = (peer: MediaPeer) => { if (this.peers.get(peer.id) !== peer) { // Try to delete the peer candidate const peerCandidatesById = this.peerCandidates.get(peer.id); if (!peerCandidatesById) { return; } const index = peerCandidatesById.indexOf(peer); if (index !== -1) { peerCandidatesById.splice(index, 1); } if (peerCandidatesById.length === 0) { this.peerCandidates.delete(peer.id); } return; } for (const [key, value] of this.peerSegmentRequests) { if (value.peerId === peer.id) { this.peerSegmentRequests.delete(key); } } this.peers.delete(peer.id); this.emit("peer-data-updated"); this.emit("peer-closed", peer.id); }; private onPeerDataUpdated = () => { this.emit("peer-data-updated"); }; private onSegmentRequest = async (peer: MediaPeer, segmentId: string) => { if (this.masterSwarmId === undefined) { return; } const segment = await this.segmentsStorage.getSegment(segmentId, this.masterSwarmId); if (segment && segment.data) { peer.sendSegmentData(segmentId, segment.data); } else { peer.sendSegmentAbsent(segmentId); } }; private onSegmentLoaded = async (peer: MediaPeer, segmentId: string, data: ArrayBuffer) => { const peerSegmentRequest = this.peerSegmentRequests.get(segmentId); if (!peerSegmentRequest) { return; } const segment = peerSegmentRequest.segment; if (this.settings.segmentValidator) { try { await this.settings.segmentValidator({ ...segment, data: data }, "p2p", peer.id); } catch (error) { this.debug("segment validator failed", error); this.peerSegmentRequests.delete(segmentId); this.emit("segment-error", segment, error, peer.id); this.onPeerClose(peer); return; } } this.peerSegmentRequests.delete(segmentId); this.emit("segment-loaded", segment, data, peer.id); }; private onSegmentAbsent = (peer: MediaPeer, segmentId: string) => { this.peerSegmentRequests.delete(segmentId); this.emit("peer-data-updated"); }; private onSegmentError = (peer: MediaPeer, segmentId: string, description: string) => { const peerSegmentRequest = this.peerSegmentRequests.get(segmentId); if (peerSegmentRequest) { this.peerSegmentRequests.delete(segmentId); this.emit("segment-error", peerSegmentRequest.segment, description, peer.id); } }; private onSegmentTimeout = (peer: MediaPeer, segmentId: string) => { const peerSegmentRequest = this.peerSegmentRequests.get(segmentId); if (peerSegmentRequest) { this.peerSegmentRequests.delete(segmentId); peer.destroy(); if (this.peers.delete(peerSegmentRequest.peerId)) { this.emit("peer-data-updated"); } } }; }
the_stack
import { disposableTimeout, RunOnceScheduler } from 'vs/base/common/async'; import { Disposable, dispose, IDisposable } from 'vs/base/common/lifecycle'; import { localize } from 'vs/nls'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { themeColorFromId, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { ICellVisibilityChangeEvent, NotebookVisibleCellObserver } from 'vs/workbench/contrib/notebook/browser/contrib/cellStatusBar/notebookVisibleCellObserver'; import { ICellViewModel, INotebookEditor, INotebookEditorContribution, INotebookViewModel } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { registerNotebookContribution } from 'vs/workbench/contrib/notebook/browser/notebookEditorExtensions'; import { cellStatusIconError, cellStatusIconSuccess } from 'vs/workbench/contrib/notebook/browser/notebookEditorWidget'; import { errorStateIcon, executingStateIcon, pendingStateIcon, successStateIcon } from 'vs/workbench/contrib/notebook/browser/notebookIcons'; import { CellStatusbarAlignment, INotebookCellStatusBarItem, NotebookCellExecutionState, NotebookCellInternalMetadata } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { INotebookCellExecution, INotebookExecutionStateService } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService'; export function formatCellDuration(duration: number): string { const minutes = Math.floor(duration / 1000 / 60); const seconds = Math.floor(duration / 1000) % 60; const tenths = String(duration - minutes * 60 * 1000 - seconds * 1000).charAt(0); if (minutes > 0) { return `${minutes}m ${seconds}.${tenths}s`; } else { return `${seconds}.${tenths}s`; } } export class NotebookStatusBarController extends Disposable { private readonly _visibleCells = new Map<number, IDisposable>(); private readonly _observer: NotebookVisibleCellObserver; constructor( private readonly _notebookEditor: INotebookEditor, private readonly _itemFactory: (vm: INotebookViewModel, cell: ICellViewModel) => IDisposable, ) { super(); this._observer = this._register(new NotebookVisibleCellObserver(this._notebookEditor)); this._register(this._observer.onDidChangeVisibleCells(this._updateVisibleCells, this)); this._updateEverything(); } private _updateEverything(): void { this._visibleCells.forEach(dispose); this._visibleCells.clear(); this._updateVisibleCells({ added: this._observer.visibleCells, removed: [] }); } private _updateVisibleCells(e: ICellVisibilityChangeEvent): void { const vm = this._notebookEditor._getViewModel(); if (!vm) { return; } for (const newCell of e.added) { this._visibleCells.set(newCell.handle, this._itemFactory(vm, newCell)); } for (const oldCell of e.removed) { this._visibleCells.get(oldCell.handle)?.dispose(); this._visibleCells.delete(oldCell.handle); } } override dispose(): void { super.dispose(); this._visibleCells.forEach(dispose); this._visibleCells.clear(); } } export class ExecutionStateCellStatusBarContrib extends Disposable implements INotebookEditorContribution { static id: string = 'workbench.notebook.statusBar.execState'; constructor(notebookEditor: INotebookEditor, @IInstantiationService instantiationService: IInstantiationService ) { super(); this._register(new NotebookStatusBarController(notebookEditor, (vm, cell) => instantiationService.createInstance(ExecutionStateCellStatusBarItem, vm, cell))); } } registerNotebookContribution(ExecutionStateCellStatusBarContrib.id, ExecutionStateCellStatusBarContrib); /** * Shows the cell's execution state in the cell status bar. When the "executing" state is shown, it will be shown for a minimum brief time. */ class ExecutionStateCellStatusBarItem extends Disposable { private static readonly MIN_SPINNER_TIME = 500; private _currentItemIds: string[] = []; private _currentExecutingStateTimer: IDisposable | undefined; constructor( private readonly _notebookViewModel: INotebookViewModel, private readonly _cell: ICellViewModel, @INotebookExecutionStateService private readonly _executionStateService: INotebookExecutionStateService ) { super(); this._update(); this._register(this._executionStateService.onDidChangeCellExecution(e => { if (e.affectsCell(this._cell.uri)) { this._update(); } })); this._register(this._cell.model.onDidChangeInternalMetadata(() => this._update())); } private async _update() { const items = this._getItemsForCell(); if (Array.isArray(items)) { this._currentItemIds = this._notebookViewModel.deltaCellStatusBarItems(this._currentItemIds, [{ handle: this._cell.handle, items }]); } } /** * Returns undefined if there should be no change, and an empty array if all items should be removed. */ private _getItemsForCell(): INotebookCellStatusBarItem[] | undefined { const runState = this._executionStateService.getCellExecution(this._cell.uri); if (this._currentExecutingStateTimer && !runState?.isPaused) { return; } const item = this._getItemForState(runState, this._cell.internalMetadata); // Show the execution spinner for a minimum time if (runState?.state === NotebookCellExecutionState.Executing) { this._currentExecutingStateTimer = this._register(disposableTimeout(() => { const runState = this._executionStateService.getCellExecution(this._cell.uri); this._currentExecutingStateTimer = undefined; if (runState?.state !== NotebookCellExecutionState.Executing) { this._update(); } }, ExecutionStateCellStatusBarItem.MIN_SPINNER_TIME)); } return item ? [item] : []; } private _getItemForState(runState: INotebookCellExecution | undefined, internalMetadata: NotebookCellInternalMetadata): INotebookCellStatusBarItem | undefined { const state = runState?.state; const { lastRunSuccess } = internalMetadata; if (!state && lastRunSuccess) { return <INotebookCellStatusBarItem>{ text: `$(${successStateIcon.id})`, color: themeColorFromId(cellStatusIconSuccess), tooltip: localize('notebook.cell.status.success', "Success"), alignment: CellStatusbarAlignment.Left, priority: Number.MAX_SAFE_INTEGER }; } else if (!state && lastRunSuccess === false) { return <INotebookCellStatusBarItem>{ text: `$(${errorStateIcon.id})`, color: themeColorFromId(cellStatusIconError), tooltip: localize('notebook.cell.status.failed', "Failed"), alignment: CellStatusbarAlignment.Left, priority: Number.MAX_SAFE_INTEGER }; } else if (state === NotebookCellExecutionState.Pending || state === NotebookCellExecutionState.Unconfirmed) { return <INotebookCellStatusBarItem>{ text: `$(${pendingStateIcon.id})`, tooltip: localize('notebook.cell.status.pending', "Pending"), alignment: CellStatusbarAlignment.Left, priority: Number.MAX_SAFE_INTEGER }; } else if (state === NotebookCellExecutionState.Executing) { const icon = runState?.didPause ? executingStateIcon : ThemeIcon.modify(executingStateIcon, 'spin'); return <INotebookCellStatusBarItem>{ text: `$(${icon.id})`, tooltip: localize('notebook.cell.status.executing', "Executing"), alignment: CellStatusbarAlignment.Left, priority: Number.MAX_SAFE_INTEGER }; } return; } override dispose() { super.dispose(); this._notebookViewModel.deltaCellStatusBarItems(this._currentItemIds, [{ handle: this._cell.handle, items: [] }]); } } export class TimerCellStatusBarContrib extends Disposable implements INotebookEditorContribution { static id: string = 'workbench.notebook.statusBar.execTimer'; constructor( notebookEditor: INotebookEditor, @IInstantiationService instantiationService: IInstantiationService) { super(); this._register(new NotebookStatusBarController(notebookEditor, (vm, cell) => instantiationService.createInstance(TimerCellStatusBarItem, vm, cell))); } } registerNotebookContribution(TimerCellStatusBarContrib.id, TimerCellStatusBarContrib); class TimerCellStatusBarItem extends Disposable { private static UPDATE_INTERVAL = 100; private _currentItemIds: string[] = []; private _scheduler: RunOnceScheduler; constructor( private readonly _notebookViewModel: INotebookViewModel, private readonly _cell: ICellViewModel, @INotebookExecutionStateService private readonly _executionStateService: INotebookExecutionStateService ) { super(); this._scheduler = this._register(new RunOnceScheduler(() => this._update(), TimerCellStatusBarItem.UPDATE_INTERVAL)); this._update(); this._register(this._cell.model.onDidChangeInternalMetadata(() => this._update())); } private async _update() { let item: INotebookCellStatusBarItem | undefined; const runState = this._executionStateService.getCellExecution(this._cell.uri); const state = runState?.state; if (runState?.didPause) { item = undefined; } else if (state === NotebookCellExecutionState.Executing) { const startTime = this._cell.internalMetadata.runStartTime; const adjustment = this._cell.internalMetadata.runStartTimeAdjustment; if (typeof startTime === 'number') { item = this._getTimeItem(startTime, Date.now(), adjustment); this._scheduler.schedule(); } } else if (!state) { const startTime = this._cell.internalMetadata.runStartTime; const endTime = this._cell.internalMetadata.runEndTime; if (typeof startTime === 'number' && typeof endTime === 'number') { item = this._getTimeItem(startTime, endTime); } } const items = item ? [item] : []; this._currentItemIds = this._notebookViewModel.deltaCellStatusBarItems(this._currentItemIds, [{ handle: this._cell.handle, items }]); } private _getTimeItem(startTime: number, endTime: number, adjustment: number = 0): INotebookCellStatusBarItem { const duration = endTime - startTime + adjustment; return <INotebookCellStatusBarItem>{ text: formatCellDuration(duration), alignment: CellStatusbarAlignment.Left, priority: Number.MAX_SAFE_INTEGER - 1 }; } override dispose() { super.dispose(); this._notebookViewModel.deltaCellStatusBarItems(this._currentItemIds, [{ handle: this._cell.handle, items: [] }]); } }
the_stack
import { CodeWorkflowInformation, ContainerWorkflowInformation, WorkflowOption, SiteSourceControlRequestBody, } from '../DeploymentCenter.types'; import { RuntimeStacks, JavaContainers } from '../../../../utils/stacks-utils'; import { getWorkflowFileName, getLogId } from './DeploymentCenterUtility'; import DeploymentCenterData from '../DeploymentCenter.data'; import LogService from '../../../../utils/LogService'; import { LogCategories } from '../../../../utils/LogCategories'; import { DeploymentCenterConstants } from '../DeploymentCenterConstants'; export const updateGitHubActionAppSettingsForPython = async ( deploymentCenterData: DeploymentCenterData, resourceId: string, isFunctionApp: boolean ) => { const fetchExistingAppSettingsResponse = await deploymentCenterData.fetchApplicationSettings(resourceId); if (!fetchExistingAppSettingsResponse.metadata.success) { LogService.error(LogCategories.deploymentCenter, getLogId('GitHubActionUtility', 'updateGitHubActionAppSettingsForPython'), { error: fetchExistingAppSettingsResponse.metadata.error, }); return fetchExistingAppSettingsResponse; } let updateAppSettings = false; const properties = fetchExistingAppSettingsResponse.data && fetchExistingAppSettingsResponse.data.properties; if (properties && !properties[DeploymentCenterConstants.appSettings_SCM_DO_BUILD_DURING_DEPLOYMENT]) { updateAppSettings = true; properties[DeploymentCenterConstants.appSettings_SCM_DO_BUILD_DURING_DEPLOYMENT] = '1'; } if (isFunctionApp && properties && !properties[DeploymentCenterConstants.appSettings_ENABLE_ORYX_BUILD]) { updateAppSettings = true; properties[DeploymentCenterConstants.appSettings_ENABLE_ORYX_BUILD] = '1'; } fetchExistingAppSettingsResponse.data.properties = properties; // NOTE(michinoy): ONLY update the appsettings IF one of the values is missing. This is to prevent an unnecessary restart of the app. if (updateAppSettings) { const updateAppSettingsResponse = await deploymentCenterData.updateApplicationSettings( resourceId, fetchExistingAppSettingsResponse.data ); if (!updateAppSettingsResponse.metadata.success) { LogService.error(LogCategories.deploymentCenter, getLogId('GitHubActionUtility', 'updateGitHubActionAppSettingsForPython'), { error: updateAppSettingsResponse.metadata.error, }); } return updateAppSettingsResponse; } else { return fetchExistingAppSettingsResponse; } }; export const updateGitHubActionSourceControlPropertiesManually = async ( deploymentCenterData: DeploymentCenterData, resourceId: string, payload: SiteSourceControlRequestBody, gitHubToken: string, isKubeApp: boolean ) => { // NOTE(michinoy): To be on the safe side, the update operations should be sequential rather than // parallel. The reason behind this is because incase the metadata update fails, but the scmtype is updated // the /sourcecontrols API GET will start failing. const fetchExistingMetadataResponse = await deploymentCenterData.getConfigMetadata(resourceId); if (!fetchExistingMetadataResponse.metadata.success) { LogService.error(LogCategories.deploymentCenter, getLogId('GitHubActionUtility', 'updateGitHubActionSourceControlPropertiesManually'), { error: fetchExistingMetadataResponse.metadata.error, }); return fetchExistingMetadataResponse; } const properties = !!fetchExistingMetadataResponse.data.properties ? fetchExistingMetadataResponse.data.properties : {}; delete properties[DeploymentCenterConstants.metadataRepoUrl]; delete properties[DeploymentCenterConstants.metadataScmUri]; delete properties[DeploymentCenterConstants.metadataCloneUri]; delete properties[DeploymentCenterConstants.metadataBranch]; delete properties[DeploymentCenterConstants.metadataOAuthToken]; delete properties[DeploymentCenterConstants.metadataIsGitHubAction]; properties[DeploymentCenterConstants.metadataRepoUrl] = payload.repoUrl; properties[DeploymentCenterConstants.metadataBranch] = payload.branch; properties[DeploymentCenterConstants.metadataOAuthToken] = gitHubToken; properties[DeploymentCenterConstants.metadataIsGitHubAction] = 'true'; const updateMetadataResponse = await deploymentCenterData.updateConfigMetadata(resourceId, properties); if (!updateMetadataResponse.metadata.success) { LogService.error(LogCategories.deploymentCenter, getLogId('GitHubActionUtility', 'updateGitHubActionSourceControlPropertiesManually'), { error: updateMetadataResponse.metadata.error, }); return updateMetadataResponse; } const patchSiteConfigResponse = await deploymentCenterData.patchSiteConfig(resourceId, { properties: { scmType: 'GitHubAction', }, }); if (!patchSiteConfigResponse.metadata.success) { LogService.error(LogCategories.deploymentCenter, getLogId('GitHubActionUtility', 'updateGitHubActionSourceControlPropertiesManually'), { error: patchSiteConfigResponse.metadata.error, }); } return patchSiteConfigResponse; }; export const clearGitHubActionSourceControlPropertiesManually = async (deploymentCenterData: DeploymentCenterData, resourceId: string) => { // NOTE(michinoy): To be on the safe side, the update operations should be sequential rather than // parallel. The reason behind this is because incase the metadata update fails, but the scmtype is updated // the /sourcecontrols API GET will start failing. const fetchExistingMetadataResponse = await deploymentCenterData.getConfigMetadata(resourceId); if (!fetchExistingMetadataResponse.metadata.success) { LogService.error(LogCategories.deploymentCenter, getLogId('GitHubActionUtility', 'clearGitHubActionSourceControlPropertiesManually'), { error: fetchExistingMetadataResponse.metadata.error, }); return fetchExistingMetadataResponse; } const properties = !!fetchExistingMetadataResponse.data.properties ? fetchExistingMetadataResponse.data.properties : {}; delete properties[DeploymentCenterConstants.metadataRepoUrl]; delete properties[DeploymentCenterConstants.metadataScmUri]; delete properties[DeploymentCenterConstants.metadataCloneUri]; delete properties[DeploymentCenterConstants.metadataBranch]; delete properties[DeploymentCenterConstants.metadataOAuthToken]; delete properties[DeploymentCenterConstants.metadataIsGitHubAction]; const updateMetadataResponse = await deploymentCenterData.updateConfigMetadata(resourceId, properties); if (!updateMetadataResponse.metadata.success) { LogService.error(LogCategories.deploymentCenter, getLogId('GitHubActionUtility', 'clearGitHubActionSourceControlPropertiesManually'), { error: updateMetadataResponse.metadata.error, }); return updateMetadataResponse; } const patchSiteConfigResponse = await deploymentCenterData.patchSiteConfig(resourceId, { properties: { scmType: 'None', }, }); if (!patchSiteConfigResponse.metadata.success) { LogService.error(LogCategories.deploymentCenter, getLogId('GitHubActionUtility', 'clearGitHubActionSourceControlPropertiesManually'), { error: patchSiteConfigResponse.metadata.error, }); } return patchSiteConfigResponse; }; // Detect the specific error which is indicative of Ant89 Geo/Stamp sync issues. export const isApiSyncError = (error?: any): boolean => { return ( error && error.Message && error.Message.indexOf && error.Message.indexOf('500 (InternalServerError)') > -1 && error.Message.indexOf('GeoRegionServiceClient') > -1 ); }; export const isWorkflowOptionExistingOrAvailable = (workflowOption: string): boolean => { return workflowOption === WorkflowOption.UseExistingWorkflowConfig || workflowOption === WorkflowOption.UseAvailableWorkflowConfigs; }; export const getContainerAppWorkflowInformation = ( serverUrl: string, image: string, branch: string, publishingProfileSecretNameGuid: string, containerUsernameSecretNameGuid: string, containerPasswordSecretNameGuid: string, siteName: string, slotName: string ): ContainerWorkflowInformation => { const fileName = getWorkflowFileName(branch, siteName, slotName); const publishingProfileSecretName = `AzureAppService_PublishProfile_${publishingProfileSecretNameGuid}`; const containerUsernameSecretName = `AzureAppService_ContainerUsername_${containerUsernameSecretNameGuid}`; const containerPasswordSecretName = `AzureAppService_ContainerPassword_${containerPasswordSecretNameGuid}`; const content = getContainerGithubActionWorkflowDefinition( siteName, slotName, branch, publishingProfileSecretName, containerUsernameSecretName, containerPasswordSecretName, serverUrl, image ); return { fileName, content, publishingProfileSecretName, containerUsernameSecretName, containerPasswordSecretName, }; }; export const getCodeWebAppWorkflowInformation = ( runtimeStack: string, runtimeVersion: string, runtimeStackRecommendedVersion: string, branch: string, isLinuxApp: boolean, secretNameGuid: string, siteName: string, slotName: string, javaContainer?: string ): CodeWorkflowInformation => { const repoBranch = branch || 'master'; const fileName = getWorkflowFileName(repoBranch, siteName, slotName); const secretName = `AzureAppService_PublishProfile_${secretNameGuid}`; let content = ''; const runtimeStackVersion = getRuntimeVersion(isLinuxApp, runtimeVersion, runtimeStackRecommendedVersion); switch (runtimeStack) { case RuntimeStacks.node: content = getNodeGithubActionWorkflowDefinition(siteName, slotName, repoBranch, isLinuxApp, secretName, runtimeStackVersion); break; case RuntimeStacks.python: content = isLinuxApp ? getPythonGithubActionWorkflowDefinitionForLinux(siteName, slotName, repoBranch, secretName, runtimeStackVersion) : getPythonGithubActionWorkflowDefinitionForWindows(siteName, slotName, repoBranch, secretName, runtimeStackVersion); break; case RuntimeStacks.java: // NOTE(michinoy): In case of Java, if the container is tomcat, set up the workflow to produce a WAR package. Else to be on the // safe side produce a JAR package. Internally they are both MAVEN builds. if (javaContainer === JavaContainers.Tomcat) { content = getJavaWarGithubActionWorkflowDefinition(siteName, slotName, repoBranch, isLinuxApp, secretName, runtimeStackVersion); } else { content = getJavaJarGithubActionWorkflowDefinition(siteName, slotName, repoBranch, isLinuxApp, secretName, runtimeStackVersion); } break; case RuntimeStacks.dotnet: // NOTE(michinoy): All of the dotnet related stacks are under the 'dotnet' stack now // so workflow file creation will diverge based on the runtime version instead. const version = runtimeVersion.toLocaleLowerCase(); content = version === 'v4.0' || version === 'v2.0' ? getAspNetGithubActionWorkflowDefinition(siteName, slotName, repoBranch, secretName, runtimeStackVersion) : getDotnetCoreGithubActionWorkflowDefinition(siteName, slotName, repoBranch, isLinuxApp, secretName, runtimeStackVersion); break; case RuntimeStacks.php: content = isLinuxApp ? getPhpLinuxGithubActionWorkflowDefinition(siteName, slotName, repoBranch, secretName, runtimeStackVersion) : getPhpWindowsGithubActionWorkflowDefinition(siteName, slotName, repoBranch, secretName, runtimeStackVersion); break; default: throw Error(`Incorrect stack value '${runtimeStack}' provided.`); } return { fileName, secretName, content, }; }; export const getCodeFunctionAppCodeWorkflowInformation = ( runtimeStack: string, runtimeVersion: string, runtimeStackRecommendedVersion: string, branch: string, isLinuxApp: boolean, secretNameGuid: string, siteName: string, slotName: string ): CodeWorkflowInformation => { const repoBranch = branch || 'master'; const fileName = getWorkflowFileName(repoBranch, siteName, slotName); const secretName = `AzureAppService_PublishProfile_${secretNameGuid}`; let content = ''; const runtimeStackVersion = getRuntimeVersion(isLinuxApp, runtimeVersion, runtimeStackRecommendedVersion); switch (runtimeStack) { case RuntimeStacks.node: content = isLinuxApp ? getFunctionAppNodeLinuxWorkflow(siteName, slotName, repoBranch, secretName, runtimeStackVersion) : getFunctionAppNodeWindowsWorkflow(siteName, slotName, repoBranch, secretName, runtimeStackVersion); break; case RuntimeStacks.python: content = getFunctionAppPythonLinuxWorkflow(siteName, slotName, repoBranch, secretName, runtimeStackVersion); break; case RuntimeStacks.dotnet: content = isLinuxApp ? getFunctionAppDotNetCoreLinuxWorkflow(siteName, slotName, repoBranch, secretName, runtimeStackVersion) : getFunctionAppDotNetCoreWindowsWorkflow(siteName, slotName, repoBranch, secretName, runtimeStackVersion); break; case RuntimeStacks.java: content = isLinuxApp ? getFunctionAppJavaLinuxWorkflow(siteName, slotName, repoBranch, secretName, runtimeStackVersion) : getFunctionAppJavaWindowsWorkflow(siteName, slotName, repoBranch, secretName, runtimeStackVersion); break; case RuntimeStacks.powershell: content = getFunctionAppPowershellWindowsWorkflow(siteName, slotName, repoBranch, secretName, runtimeStackVersion); break; default: throw Error(`Incorrect stack value '${runtimeStack}' provided.`); } return { fileName, secretName, content, }; }; export const getRuntimeVersion = (isLinuxApp: boolean, runtimeVersion: string, runtimeStackRecommendedVersion: string) => { if (runtimeStackRecommendedVersion) { return runtimeStackRecommendedVersion; } else { return isLinuxApp ? runtimeVersion.split('|')[1] : runtimeVersion; } }; // TODO(michinoy): Need to implement templated github action workflow generation. // Current reference - https://github.com/Azure/actions-workflow-templates const getNodeGithubActionWorkflowDefinition = ( siteName: string, slotName: string, branch: string, isLinuxApp: boolean, secretName: string, runtimeStackVersion: string ) => { const webAppName = slotName ? `${siteName}(${slotName})` : siteName; const slot = slotName || 'production'; return `# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy # More GitHub Actions for Azure: https://github.com/Azure/actions name: Build and deploy Node.js app to Azure Web App - ${webAppName} on: push: branches: - ${branch} workflow_dispatch: jobs: build: runs-on: ${isLinuxApp ? 'ubuntu-latest' : 'windows-latest'} steps: - uses: actions/checkout@v2 - name: Set up Node.js version uses: actions/setup-node@v1 with: node-version: '${runtimeStackVersion}' - name: npm install, build, and test run: | npm install npm run build --if-present npm run test --if-present - name: Upload artifact for deployment job uses: actions/upload-artifact@v2 with: name: node-app path: . deploy: runs-on: ${isLinuxApp ? 'ubuntu-latest' : 'windows-latest'} needs: build environment: name: '${slot}' url: \${{ steps.deploy-to-webapp.outputs.webapp-url }} steps: - name: Download artifact from build job uses: actions/download-artifact@v2 with: name: node-app - name: 'Deploy to Azure Web App' id: deploy-to-webapp uses: azure/webapps-deploy@v2 with: app-name: '${siteName}' slot-name: '${slot}' publish-profile: \${{ secrets.${secretName} }} package: .`; }; // TODO(michinoy): Need to implement templated github action workflow generation. // Current reference - https://github.com/Azure/actions-workflow-templates const getPythonGithubActionWorkflowDefinitionForWindows = ( siteName: string, slotName: string, branch: string, secretName: string, runtimeStackVersion: string ) => { const webAppName = slotName ? `${siteName}(${slotName})` : siteName; const slot = slotName || 'production'; return `# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy # More GitHub Actions for Azure: https://github.com/Azure/actions name: Build and deploy Python app to Azure Web App - ${webAppName} on: push: branches: - ${branch} workflow_dispatch: jobs: build-and-deploy: runs-on: windows-latest steps: - uses: actions/checkout@v2 - name: Set up Python version uses: actions/setup-python@v1 with: python-version: '${runtimeStackVersion}' - name: Install Python dependencies run: | python -m venv env .\\env\\Scripts\\activate pip install -r requirements.txt - name: Zip the application files run: Compress-Archive .\\* app.zip - name: 'Deploy to Azure Web App' uses: azure/webapps-deploy@v2 with: app-name: '${siteName}' slot-name: '${slot}' publish-profile: \${{ secrets.${secretName} }} package: '.\\app.zip'`; }; // TODO(michinoy): Need to implement templated github action workflow generation. // Current reference - https://github.com/Azure/actions-workflow-templates const getPythonGithubActionWorkflowDefinitionForLinux = ( siteName: string, slotName: string, branch: string, secretName: string, runtimeStackVersion: string ) => { const webAppName = slotName ? `${siteName}(${slotName})` : siteName; const slot = slotName || 'production'; return `# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy # More GitHub Actions for Azure: https://github.com/Azure/actions # More info on Python, GitHub Actions, and Azure App Service: https://aka.ms/python-webapps-actions name: Build and deploy Python app to Azure Web App - ${webAppName} on: push: branches: - ${branch} workflow_dispatch: jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python version uses: actions/setup-python@v1 with: python-version: '${runtimeStackVersion}' - name: Create and start virtual environment run: | python -m venv venv source venv/bin/activate - name: Install dependencies run: pip install -r requirements.txt # Optional: Add step to run tests here (PyTest, Django test suites, etc.) - name: Upload artifact for deployment jobs uses: actions/upload-artifact@v2 with: name: python-app path: | . !venv/ deploy: runs-on: ubuntu-latest needs: build environment: name: '${slot}' url: \${{ steps.deploy-to-webapp.outputs.webapp-url }} steps: - name: Download artifact from build job uses: actions/download-artifact@v2 with: name: python-app path: . - name: 'Deploy to Azure Web App' uses: azure/webapps-deploy@v2 with: app-name: '${siteName}' slot-name: '${slot}' publish-profile: \${{ secrets.${secretName} }}`; }; // TODO(michinoy): Need to implement templated github action workflow generation. // Current reference - https://github.com/Azure/actions-workflow-templates const getDotnetCoreGithubActionWorkflowDefinition = ( siteName: string, slotName: string, branch: string, isLinuxApp: boolean, secretName: string, runtimeStackVersion: string ) => { const webAppName = slotName ? `${siteName}(${slotName})` : siteName; const slot = slotName || 'production'; return `# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy # More GitHub Actions for Azure: https://github.com/Azure/actions name: Build and deploy ASP.Net Core app to Azure Web App - ${webAppName} on: push: branches: - ${branch} workflow_dispatch: jobs: build: runs-on: ${isLinuxApp ? 'ubuntu-latest' : 'windows-latest'} steps: - uses: actions/checkout@v2 - name: Set up .NET Core uses: actions/setup-dotnet@v1 with: dotnet-version: '${runtimeStackVersion}' include-prerelease: true - name: Build with dotnet run: dotnet build --configuration Release - name: dotnet publish run: dotnet publish -c Release -o \${{env.DOTNET_ROOT}}/myapp - name: Upload artifact for deployment job uses: actions/upload-artifact@v2 with: name: .net-app path: \${{env.DOTNET_ROOT}}/myapp deploy: runs-on: ${isLinuxApp ? 'ubuntu-latest' : 'windows-latest'} needs: build environment: name: '${slot}' url: \${{ steps.deploy-to-webapp.outputs.webapp-url }} steps: - name: Download artifact from build job uses: actions/download-artifact@v2 with: name: .net-app - name: Deploy to Azure Web App id: deploy-to-webapp uses: azure/webapps-deploy@v2 with: app-name: '${siteName}' slot-name: '${slot}' publish-profile: \${{ secrets.${secretName} }} package: .`; }; // TODO(michinoy): Need to implement templated github action workflow generation. // Current reference - https://github.com/Azure/actions-workflow-templates const getJavaJarGithubActionWorkflowDefinition = ( siteName: string, slotName: string, branch: string, isLinuxApp: boolean, secretName: string, runtimeStackVersion: string ) => { const webAppName = slotName ? `${siteName}(${slotName})` : siteName; const slot = slotName || 'production'; return `# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy # More GitHub Actions for Azure: https://github.com/Azure/actions name: Build and deploy JAR app to Azure Web App - ${webAppName} on: push: branches: - ${branch} workflow_dispatch: jobs: build: runs-on: ${isLinuxApp ? 'ubuntu-latest' : 'windows-latest'} steps: - uses: actions/checkout@v2 - name: Set up Java version uses: actions/setup-java@v1 with: java-version: '${runtimeStackVersion}' - name: Build with Maven run: mvn clean install - name: Upload artifact for deployment job uses: actions/upload-artifact@v2 with: name: java-app path: '\${{ github.workspace }}/target/*.jar' deploy: runs-on: ${isLinuxApp ? 'ubuntu-latest' : 'windows-latest'} needs: build environment: name: '${slot}' url: \${{ steps.deploy-to-webapp.outputs.webapp-url }} steps: - name: Download artifact from build job uses: actions/download-artifact@v2 with: name: java-app - name: Deploy to Azure Web App id: deploy-to-webapp uses: azure/webapps-deploy@v2 with: app-name: '${siteName}' slot-name: '${slot}' publish-profile: \${{ secrets.${secretName} }} package: '*.jar'`; }; // TODO(michinoy): Need to implement templated github action workflow generation. // Current reference - https://github.com/Azure/actions-workflow-templates const getJavaWarGithubActionWorkflowDefinition = ( siteName: string, slotName: string, branch: string, isLinuxApp: boolean, secretName: string, runtimeStackVersion: string ) => { const webAppName = slotName ? `${siteName}(${slotName})` : siteName; const slot = slotName || 'production'; return `# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy # More GitHub Actions for Azure: https://github.com/Azure/actions name: Build and deploy WAR app to Azure Web App - ${webAppName} on: push: branches: - ${branch} workflow_dispatch: jobs: build: runs-on: ${isLinuxApp ? 'ubuntu-latest' : 'windows-latest'} steps: - uses: actions/checkout@v2 - name: Set up Java version uses: actions/setup-java@v1 with: java-version: '${runtimeStackVersion}' - name: Build with Maven run: mvn clean install - name: Upload artifact for deployment job uses: actions/upload-artifact@v2 with: name: java-app path: '\${{ github.workspace }}/target/*.war' deploy: runs-on: ${isLinuxApp ? 'ubuntu-latest' : 'windows-latest'} needs: build environment: name: '${slot}' url: \${{ steps.deploy-to-webapp.outputs.webapp-url }} steps: - name: Download artifact from build job uses: actions/download-artifact@v2 with: name: java-app - name: Deploy to Azure Web App id: deploy-to-webapp uses: azure/webapps-deploy@v2 with: app-name: '${siteName}' slot-name: '${slot}' publish-profile: \${{ secrets.${secretName} }} package: '*.war'`; }; // TODO(michinoy): Need to implement templated github action workflow generation. // Current reference - https://github.com/Azure/actions-workflow-templates const getAspNetGithubActionWorkflowDefinition = ( siteName: string, slotName: string, branch: string, secretName: string, runtimeStackVersion: string ) => { const webAppName = slotName ? `${siteName}(${slotName})` : siteName; const slot = slotName || 'production'; return `# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy # More GitHub Actions for Azure: https://github.com/Azure/actions name: Build and deploy ASP app to Azure Web App - ${webAppName} on: push: branches: - ${branch} workflow_dispatch: jobs: build: runs-on: 'windows-latest' steps: - uses: actions/checkout@v2 - name: Setup MSBuild path uses: microsoft/setup-msbuild@v1.0.2 - name: Setup NuGet uses: NuGet/setup-nuget@v1.0.5 - name: Restore NuGet packages run: nuget restore - name: Publish to folder run: msbuild /nologo /verbosity:m /t:Build /t:pipelinePreDeployCopyAllFilesToOneFolder /p:_PackageTempDir="\\published\\" - name: Upload artifact for deployment job uses: actions/upload-artifact@v2 with: name: ASP-app path: '/published/**' deploy: runs-on: 'windows-latest' needs: build environment: name: '${slot}' url: \${{ steps.deploy-to-webapp.outputs.webapp-url }} steps: - name: Download artifact from build job uses: actions/download-artifact@v2 with: name: ASP-app - name: Deploy to Azure Web App id: deploy-to-webapp uses: azure/webapps-deploy@v2 with: app-name: '${siteName}' slot-name: '${slot}' publish-profile: \${{ secrets.${secretName} }} package: .`; }; const getPhpWindowsGithubActionWorkflowDefinition = ( siteName: string, slotName: string, branch: string, secretName: string, runtimeStackVersion: string ) => { const webAppName = slotName ? `${siteName}(${slotName})` : siteName; const slot = slotName || 'production'; return `# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy # More GitHub Actions for Azure: https://github.com/Azure/actions name: Build and deploy PHP app to Azure Web App - ${webAppName} on: push: branches: - ${branch} workflow_dispatch: jobs: build: runs-on: windows-latest steps: - uses: actions/checkout@v2 - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: '${runtimeStackVersion}' - name: Check if composer.json exists id: check_files uses: andstor/file-existence-action@v1 with: files: "composer.json" - name: Run composer install if composer.json exists if: steps.check_files.outputs.files_exists == 'true' run: composer validate --no-check-publish && composer install --prefer-dist --no-progress - name: Upload artifact for deployment job uses: actions/upload-artifact@v2 with: name: php-app path: . deploy: runs-on: ubuntu-latest needs: build environment: name: '${slot}' url: \${{ steps.deploy-to-webapp.outputs.webapp-url }} steps: - name: Download artifact from build job uses: actions/download-artifact@v2 with: name: php-app - name: 'Deploy to Azure Web App' uses: azure/webapps-deploy@v2 id: deploy-to-webapp with: app-name: '${siteName}' slot-name: '${slot}' publish-profile: \${{ secrets.${secretName} }} package: .`; }; const getPhpLinuxGithubActionWorkflowDefinition = ( siteName: string, slotName: string, branch: string, secretName: string, runtimeStackVersion: string ) => { const webAppName = slotName ? `${siteName}(${slotName})` : siteName; const slot = slotName || 'production'; return `# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy # More GitHub Actions for Azure: https://github.com/Azure/actions name: Build and deploy PHP app to Azure Web App - ${webAppName} on: push: branches: - ${branch} workflow_dispatch: jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: '${runtimeStackVersion}' - name: Check if composer.json exists id: check_files uses: andstor/file-existence-action@v1 with: files: "composer.json" - name: Run composer install if composer.json exists if: steps.check_files.outputs.files_exists == 'true' run: composer validate --no-check-publish && composer install --prefer-dist --no-progress - name: Upload artifact for deployment job uses: actions/upload-artifact@v2 with: name: php-app path: . deploy: runs-on: ubuntu-latest needs: build environment: name: '${slot}' url: \${{ steps.deploy-to-webapp.outputs.webapp-url }} steps: - name: Download artifact from build job uses: actions/download-artifact@v2 with: name: php-app - name: 'Deploy to Azure Web App' uses: azure/webapps-deploy@v2 id: deploy-to-webapp with: app-name: '${siteName}' slot-name: '${slot}' publish-profile: \${{ secrets.${secretName} }} package: .`; }; // TODO(michinoy): Need to implement templated github action workflow generation. // Current reference - https://github.com/Azure/actions-workflow-templates const getContainerGithubActionWorkflowDefinition = ( siteName: string, slotName: string, branch: string, publishingProfileSecretName: string, containerUsernameSecretName: string, containerPasswordSecretName: string, serverUrl: string, image: string ) => { const webAppName = slotName ? `${siteName}(${slotName})` : siteName; const slot = slotName || 'production'; const loginServer = serverUrl.toLocaleLowerCase(); // NOTE(michinoy): For dockerHub the server URL contains /v1 at the end. // The server used in the image should not have that part. const server = loginServer.indexOf(DeploymentCenterConstants.dockerHubServerUrlHost) > -1 ? DeploymentCenterConstants.dockerHubServerUrlHost : loginServer.replace('https://', ''); return `# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy # More GitHub Actions for Azure: https://github.com/Azure/actions name: Build and deploy container app to Azure Web App - ${webAppName} on: push: branches: - ${branch} workflow_dispatch: jobs: build: runs-on: 'ubuntu-latest' steps: - uses: actions/checkout@v2 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v1 - name: Log in to registry uses: docker/login-action@v1 with: registry: ${loginServer}/ username: \${{ secrets.${containerUsernameSecretName} }} password: \${{ secrets.${containerPasswordSecretName} }} - name: Build and push container image to registry uses: docker/build-push-action@v2 with: push: true tags: ${server}/\${{ secrets.${containerUsernameSecretName} }}/${image}:\${{ github.sha }} file: ./Dockerfile deploy: runs-on: ubuntu-latest needs: build environment: name: '${slot}' url: \${{ steps.deploy-to-webapp.outputs.webapp-url }} steps: - name: Deploy to Azure Web App id: deploy-to-webapp uses: azure/webapps-deploy@v2 with: app-name: '${siteName}' slot-name: '${slot}' publish-profile: \${{ secrets.${publishingProfileSecretName} }} images: '${server}/\${{ secrets.${containerUsernameSecretName} }}/${image}:\${{ github.sha }}'`; }; const getFunctionAppDotNetCoreWindowsWorkflow = ( siteName: string, slotName: string, branch: string, secretName: string, runtimeStackVersion: string ) => { const webAppName = slotName ? `${siteName}(${slotName})` : siteName; const slot = slotName || 'production'; return `# Docs for the Azure Web Apps Deploy action: https://github.com/azure/functions-action # More GitHub Actions for Azure: https://github.com/Azure/actions name: Build and deploy dotnet core app to Azure Function App - ${webAppName} on: push: branches: - ${branch} workflow_dispatch: env: AZURE_FUNCTIONAPP_PACKAGE_PATH: '.' # set this to the path to your web app project, defaults to the repository root DOTNET_VERSION: '${runtimeStackVersion}' # set this to the dotnet version to use jobs: build-and-deploy: runs-on: windows-latest steps: - name: 'Checkout GitHub Action' uses: actions/checkout@v2 - name: Setup DotNet \${{ env.DOTNET_VERSION }} Environment uses: actions/setup-dotnet@v1 with: dotnet-version: \${{ env.DOTNET_VERSION }} - name: 'Resolve Project Dependencies Using Dotnet' shell: pwsh run: | pushd './\${{ env.AZURE_FUNCTIONAPP_PACKAGE_PATH }}' dotnet build --configuration Release --output ./output popd - name: 'Run Azure Functions Action' uses: Azure/functions-action@v1 id: fa with: app-name: '${siteName}' slot-name: '${slot}' package: '\${{ env.AZURE_FUNCTIONAPP_PACKAGE_PATH }}/output' publish-profile: \${{ secrets.${secretName} }} `; }; const getFunctionAppDotNetCoreLinuxWorkflow = ( siteName: string, slotName: string, branch: string, secretName: string, runtimeStackVersion: string ) => { const webAppName = slotName ? `${siteName}(${slotName})` : siteName; const slot = slotName || 'production'; return `# Docs for the Azure Web Apps Deploy action: https://github.com/azure/functions-action # More GitHub Actions for Azure: https://github.com/Azure/actions name: Build and deploy dotnet core project to Azure Function App - ${webAppName} on: push: branches: - ${branch} workflow_dispatch: env: AZURE_FUNCTIONAPP_PACKAGE_PATH: '.' # set this to the path to your web app project, defaults to the repository root DOTNET_VERSION: '${runtimeStackVersion}' # set this to the dotnet version to use jobs: build-and-deploy: runs-on: ubuntu-latest steps: - name: 'Checkout GitHub Action' uses: actions/checkout@v2 - name: Setup DotNet \${{ env.DOTNET_VERSION }} Environment uses: actions/setup-dotnet@v1 with: dotnet-version: \${{ env.DOTNET_VERSION }} - name: 'Resolve Project Dependencies Using Dotnet' shell: bash run: | pushd './\${{ env.AZURE_FUNCTIONAPP_PACKAGE_PATH }}' dotnet build --configuration Release --output ./output popd - name: 'Run Azure Functions Action' uses: Azure/functions-action@v1 id: fa with: app-name: '${siteName}' slot-name: '${slot}' package: '\${{ env.AZURE_FUNCTIONAPP_PACKAGE_PATH }}/output' publish-profile: \${{ secrets.${secretName} }}`; }; const getFunctionAppNodeWindowsWorkflow = ( siteName: string, slotName: string, branch: string, secretName: string, runtimeStackVersion: string ) => { const webAppName = slotName ? `${siteName}(${slotName})` : siteName; const slot = slotName || 'production'; return `# Docs for the Azure Web Apps Deploy action: https://github.com/azure/functions-action # More GitHub Actions for Azure: https://github.com/Azure/actions name: Build and deploy Node.js project to Azure Function App - ${webAppName} on: push: branches: - ${branch} workflow_dispatch: env: AZURE_FUNCTIONAPP_PACKAGE_PATH: '.' # set this to the path to your web app project, defaults to the repository root NODE_VERSION: '${runtimeStackVersion}' # set this to the node version to use (supports 8.x, 10.x, 12.x) jobs: build-and-deploy: runs-on: windows-latest steps: - name: 'Checkout GitHub Action' uses: actions/checkout@v2 - name: Setup Node \${{ env.NODE_VERSION }} Environment uses: actions/setup-node@v1 with: node-version: \${{ env.NODE_VERSION }} - name: 'Resolve Project Dependencies Using Npm' shell: pwsh run: | pushd './\${{ env.AZURE_FUNCTIONAPP_PACKAGE_PATH }}' npm install npm run build --if-present npm run test --if-present popd - name: 'Run Azure Functions Action' uses: Azure/functions-action@v1 id: fa with: app-name: '${siteName}' slot-name: '${slot}' package: \${{ env.AZURE_FUNCTIONAPP_PACKAGE_PATH }} publish-profile: \${{ secrets.${secretName} }}`; }; const getFunctionAppNodeLinuxWorkflow = ( siteName: string, slotName: string, branch: string, secretName: string, runtimeStackVersion: string ) => { const webAppName = slotName ? `${siteName}(${slotName})` : siteName; const slot = slotName || 'production'; return `# Docs for the Azure Web Apps Deploy action: https://github.com/azure/functions-action # More GitHub Actions for Azure: https://github.com/Azure/actions name: Build and deploy Node.js project to Azure Function App - ${webAppName} on: push: branches: - ${branch} workflow_dispatch: env: AZURE_FUNCTIONAPP_PACKAGE_PATH: '.' # set this to the path to your web app project, defaults to the repository root NODE_VERSION: '${runtimeStackVersion}' # set this to the node version to use (supports 8.x, 10.x, 12.x) jobs: build-and-deploy: runs-on: ubuntu-latest steps: - name: 'Checkout GitHub Action' uses: actions/checkout@v2 - name: Setup Node \${{ env.NODE_VERSION }} Environment uses: actions/setup-node@v1 with: node-version: \${{ env.NODE_VERSION }} - name: 'Resolve Project Dependencies Using Npm' shell: bash run: | pushd './\${{ env.AZURE_FUNCTIONAPP_PACKAGE_PATH }}' npm install npm run build --if-present npm run test --if-present popd - name: 'Run Azure Functions Action' uses: Azure/functions-action@v1 id: fa with: app-name: '${siteName}' slot-name: '${slot}' package: \${{ env.AZURE_FUNCTIONAPP_PACKAGE_PATH }} publish-profile: \${{ secrets.${secretName} }}`; }; const getFunctionAppPowershellWindowsWorkflow = ( siteName: string, slotName: string, branch: string, secretName: string, runtimeStackVersion: string ) => { const webAppName = slotName ? `${siteName}(${slotName})` : siteName; const slot = slotName || 'production'; return `# Docs for the Azure Web Apps Deploy action: https://github.com/azure/functions-action # More GitHub Actions for Azure: https://github.com/Azure/actions name: Build and deploy Powershell project to Azure Function App - ${webAppName} on: push: branches: - ${branch} workflow_dispatch: env: AZURE_FUNCTIONAPP_PACKAGE_PATH: '.' # set this to the path to your web app project, defaults to the repository root jobs: build-and-deploy: runs-on: windows-latest steps: - name: 'Checkout GitHub Action' uses: actions/checkout@v2 - name: 'Run Azure Functions Action' uses: Azure/functions-action@v1 id: fa with: app-name: '${siteName}' slot-name: '${slot}' package: \${{ env.AZURE_FUNCTIONAPP_PACKAGE_PATH }} publish-profile: \${{ secrets.${secretName} }}`; }; const getFunctionAppJavaWindowsWorkflow = ( siteName: string, slotName: string, branch: string, secretName: string, runtimeStackVersion: string ) => { const webAppName = slotName ? `${siteName}(${slotName})` : siteName; const slot = slotName || 'production'; return `# Docs for the Azure Web Apps Deploy action: https://github.com/azure/functions-action # More GitHub Actions for Azure: https://github.com/Azure/actions name: Build and deploy Java project to Azure Function App - ${webAppName} on: push: branches: - ${branch} workflow_dispatch: env: AZURE_FUNCTIONAPP_NAME: ${webAppName} # set this to your function app name on Azure PACKAGE_DIRECTORY: '.' # set this to the directory which contains pom.xml file JAVA_VERSION: '${runtimeStackVersion}' # set this to the java version to use jobs: build-and-deploy: runs-on: windows-latest steps: - name: 'Checkout GitHub Action' uses: actions/checkout@v2 - name: Setup Java Sdk \${{ env.JAVA_VERSION }} uses: actions/setup-java@v1 with: java-version: \${{ env.JAVA_VERSION }} - name: 'Restore Project Dependencies Using Mvn' shell: pwsh run: | pushd './\${{ env.PACKAGE_DIRECTORY }}' mvn clean package popd - name: 'Run Azure Functions Action' uses: Azure/functions-action@v1 id: fa with: app-name: '${siteName}' slot-name: '${slot}' publish-profile: \${{ secrets.${secretName} }} package: '\${{ env.PACKAGE_DIRECTORY }}' respect-pom-xml: true`; }; const getFunctionAppJavaLinuxWorkflow = ( siteName: string, slotName: string, branch: string, secretName: string, runtimeStackVersion: string ) => { const webAppName = slotName ? `${siteName}(${slotName})` : siteName; const slot = slotName || 'production'; return `# Docs for the Azure Web Apps Deploy action: https://github.com/azure/functions-action # More GitHub Actions for Azure: https://github.com/Azure/actions name: Build and deploy Java project to Azure Function App - ${webAppName} on: push: branches: - ${branch} workflow_dispatch: env: AZURE_FUNCTIONAPP_NAME: ${webAppName} # set this to your function app name on Azure PACKAGE_DIRECTORY: '.' # set this to the directory which contains pom.xml file JAVA_VERSION: '${runtimeStackVersion}' # set this to the java version to use jobs: build-and-deploy: runs-on: ubuntu-latest steps: - name: 'Checkout GitHub Action' uses: actions/checkout@v2 - name: Setup Java Sdk \${{ env.JAVA_VERSION }} uses: actions/setup-java@v1 with: java-version: \${{ env.JAVA_VERSION }} - name: 'Restore Project Dependencies Using Mvn' shell: pwsh run: | pushd './\${{ env.PACKAGE_DIRECTORY }}' mvn clean package popd - name: 'Run Azure Functions Action' uses: Azure/functions-action@v1 id: fa with: app-name: '${siteName}' slot-name: '${slot}' publish-profile: \${{ secrets.${secretName} }} package: '\${{ env.PACKAGE_DIRECTORY }}' respect-pom-xml: true`; }; const getFunctionAppPythonLinuxWorkflow = ( siteName: string, slotName: string, branch: string, secretName: string, runtimeStackVersion: string ) => { const webAppName = slotName ? `${siteName}(${slotName})` : siteName; const slot = slotName || 'production'; return `# Docs for the Azure Web Apps Deploy action: https://github.com/azure/functions-action # More GitHub Actions for Azure: https://github.com/Azure/actions name: Build and deploy Python project to Azure Function App - ${webAppName} on: push: branches: - ${branch} workflow_dispatch: env: AZURE_FUNCTIONAPP_PACKAGE_PATH: '.' # set this to the path to your web app project, defaults to the repository root PYTHON_VERSION: '${runtimeStackVersion}' # set this to the python version to use (supports 3.6, 3.7, 3.8) jobs: build-and-deploy: runs-on: ubuntu-latest steps: - name: 'Checkout GitHub Action' uses: actions/checkout@v2 - name: Setup Python \${{ env.PYTHON_VERSION }} Environment uses: actions/setup-python@v1 with: python-version: \${{ env.PYTHON_VERSION }} - name: 'Resolve Project Dependencies Using Pip' shell: bash run: | pushd './\${{ env.AZURE_FUNCTIONAPP_PACKAGE_PATH }}' python -m pip install --upgrade pip pip install -r requirements.txt --target=".python_packages/lib/site-packages" popd - name: 'Run Azure Functions Action' uses: Azure/functions-action@v1 id: fa with: app-name: '${siteName}' slot-name: '${slot}' package: \${{ env.AZURE_FUNCTIONAPP_PACKAGE_PATH }} publish-profile: \${{ secrets.${secretName} }}`; };
the_stack
* The Storage Module provides storage for URL parameters, and an API for * getting and setting TensorBoard's stateful URI. * * It generates URI components like: events&runPrefix=train* * which TensorBoard uses after like localhost:8000/#events&runPrefix=train* * to store state in the URI. */ module TF.URIStorage { type StringDict = {[key: string]: string}; /** * A key that users cannot use, since TensorBoard uses this to store info * about the active tab. */ export let TAB = '__tab__'; /** * The name of the property for users to set on a Polymer component * in order for its stored properties to be stored in the URI unambiguously. * (No need to set this if you want mutliple instances of the component to * share URI state) * * Example: * <my-component disambiguator="0"></my-component> * * The disambiguator should be set to any unique value so that multiple * instances of the component can store properties in URI storage. * * Because it's hard to dereference this variable in HTML property bindings, * it is NOT safe to change the disambiguator string without find+replace * across the codebase. */ export let DISAMBIGUATOR = 'disambiguator'; /** * Return a boolean stored in the URI, given a corresponding key. * Undefined if not found. */ export function getBoolean(key: string): boolean { let items = _componentToDict(_readComponent()); let item = items[key]; return item === 'true' ? true : item === 'false' ? false : undefined; } /** * Store a boolean in the URI, with a corresponding key. */ export function setBoolean(key: string, value: boolean) { let items = _componentToDict(_readComponent()); items[key] = value.toString(); _writeComponent(_dictToComponent(items)); } /** * Return a string stored in the URI, given a corresponding key. * Undefined if not found. */ export function getString(key: string): string { let items = _componentToDict(_readComponent()); return items[key]; } /** * Store a string in the URI, with a corresponding key. */ export function setString(key: string, value: string) { let items = _componentToDict(_readComponent()); items[key] = value; _writeComponent(_dictToComponent(items)); } /** * Return a number stored in the URI, given a corresponding key. * Undefined if not found. */ export function getNumber(key: string): number { let items = _componentToDict(_readComponent()); return items[key] === undefined ? undefined : +items[key]; } /** * Store a number in the URI, with a corresponding key. */ export function setNumber(key: string, value: number) { let items = _componentToDict(_readComponent()); items[key] = '' + value; _writeComponent(_dictToComponent(items)); } /** * Return an object stored in the URI, given a corresponding key. * Undefined if not found. */ export function getObject(key: string): Object { let items = _componentToDict(_readComponent()); return items[key] === undefined ? undefined : JSON.parse(atob(items[key])); } /** * Store an object in the URI, with a corresponding key. */ export function setObject(key: string, value: Object) { let items = _componentToDict(_readComponent()); items[key] = btoa(JSON.stringify(value)); _writeComponent(_dictToComponent(items)); } /** * Get a unique storage name for a (Polymer component, propertyName) tuple. * * DISAMBIGUATOR must be set on the component, if other components use the * same propertyName. */ export function getURIStorageName( component: Object, propertyName: string): string { let d = component[DISAMBIGUATOR]; let components = d == null ? [propertyName] : [d, propertyName]; return components.join('.'); } /** * Return a function that: * (1) Initializes a Polymer boolean property with a default value, if its * value is not already set * (2) Sets up listener that updates Polymer property on hash change. */ export function getBooleanInitializer( propertyName: string, defaultVal: boolean): Function { return _getInitializer(getBoolean, propertyName, defaultVal); } /** * Return a function that: * (1) Initializes a Polymer string property with a default value, if its * value is not already set * (2) Sets up listener that updates Polymer property on hash change. */ export function getStringInitializer( propertyName: string, defaultVal: string): Function { return _getInitializer(getString, propertyName, defaultVal); } /** * Return a function that: * (1) Initializes a Polymer number property with a default value, if its * value is not already set * (2) Sets up listener that updates Polymer property on hash change. */ export function getNumberInitializer( propertyName: string, defaultVal: number): Function { return _getInitializer(getNumber, propertyName, defaultVal); } /** * Return a function that: * (1) Initializes a Polymer Object property with a default value, if its * value is not already set * (2) Sets up listener that updates Polymer property on hash change. * * Generates a deep clone of the defaultVal to avoid mutation issues. */ export function getObjectInitializer( propertyName: string, defaultVal: Object): Function { return _getInitializer(getObject, propertyName, defaultVal); } /** * Return a function that updates URIStorage when a string property changes. */ export function getBooleanObserver( propertyName: string, defaultVal: boolean): Function { return _getObserver(getBoolean, setBoolean, propertyName, defaultVal); } /** * Return a function that updates URIStorage when a string property changes. */ export function getStringObserver( propertyName: string, defaultVal: string): Function { return _getObserver(getString, setString, propertyName, defaultVal); } /** * Return a function that updates URIStorage when a number property changes. */ export function getNumberObserver( propertyName: string, defaultVal: number): Function { return _getObserver(getNumber, setNumber, propertyName, defaultVal); } /** * Return a function that updates URIStorage when an object property changes. * Generates a deep clone of the defaultVal to avoid mutation issues. */ export function getObjectObserver( propertyName: string, defaultVal: Object): Function { let clone = _.cloneDeep(defaultVal); return _getObserver(getObject, setObject, propertyName, clone); } /** * Read component from URI (e.g. returns "events&runPrefix=train*"). */ function _readComponent(): string { return TF.Globals.USE_HASH ? window.location.hash.slice(1) : TF.Globals.FAKE_HASH; } /** * Write component to URI. */ function _writeComponent(component: string) { if (TF.Globals.USE_HASH) { window.location.hash = component; } else { TF.Globals.FAKE_HASH = component; } } /** * Convert dictionary of strings into a URI Component. * All key value entries get added as key value pairs in the component, * with the exception of a key with the TAB value, which if present * gets prepended to the URI Component string for backwards comptability * reasons. */ function _dictToComponent(items: StringDict): string { let component = ''; // Add the tab name e.g. 'events', 'images', 'histograms' as a prefix // for backwards compatbility. if (items[TAB] !== undefined) { component += items[TAB]; } // Join other strings with &key=value notation let nonTab = _.pairs(items) .filter(function(pair) { return pair[0] !== TAB; }) .map(function(pair) { return encodeURIComponent(pair[0]) + '=' + encodeURIComponent(pair[1]); }) .join('&'); return nonTab.length > 0 ? (component + '&' + nonTab) : component; } /** * Convert a URI Component into a dictionary of strings. * Component should consist of key-value pairs joined by a delimiter * with the exception of the tabName. * Returns dict consisting of all key-value pairs and * dict[TAB] = tabName */ function _componentToDict(component: string): StringDict { let items = {} as StringDict; let tokens = component.split('&'); tokens.forEach(function(token) { let kv = token.split('='); // Special backwards compatibility for URI components like #events if (kv.length === 1 && _.contains(TF.Globals.TABS, kv[0])) { items[TAB] = kv[0]; } else if (kv.length === 2) { items[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]); } }); return items; } /** * Return a function that: * (1) Initializes a Polymer property with a default value, if its * value is not already set * (2) Sets up listener that updates Polymer property on hash change. */ function _getInitializer<T>( get: (name: string) => T, propertyName: string, defaultVal: T): Function { return function() { let URIStorageName = getURIStorageName(this, propertyName); // setComponentValue will be called every time the hash changes, and is // responsible for ensuring that new state in the hash will be propagated // to the component with that property. // It is important that this function does not re-assign needlessly, // to avoid Polymer observer churn. let setComponentValue = () => { let uriValue = get(URIStorageName); let currentValue = this[propertyName]; // if uriValue is undefined, we will ensure that the property has the // default value if (uriValue === undefined) { if (!_.isEqual(currentValue, defaultVal)) { // If we don't have an explicit URI value, then we need to ensure // the property value is equal to the default value. // We will assign a clone rather than the canonical default, because // the component receiving this property may mutate it, and we need // to keep a pristine copy of the default. this[propertyName] = _.clone(defaultVal); } // In this case, we have an explicit URI value, so we will ensure that // the component has an equivalent value. } else if (!_.isEqual(uriValue, currentValue)) { this[propertyName] = uriValue; } }; // Set the value on the property. setComponentValue(); // Update it when the hashchanges. window.addEventListener('hashchange', setComponentValue); }; } /** * Return a function that updates URIStorage when a property changes. */ function _getObserver<T>( get: (name: string) => T, set: (name: string, newVal: T) => void, propertyName: string, defaultVal: T): Function { return function() { let URIStorageName = getURIStorageName(this, propertyName); let newVal = this[propertyName]; if (!_.isEqual(newVal, get(URIStorageName))) { if (_.isEqual(newVal, defaultVal)) { _unset(URIStorageName); } else { set(URIStorageName, newVal); } } }; } /** * Delete a key from the URI. */ function _unset(key) { let items = _componentToDict(_readComponent()); delete items[key]; _writeComponent(_dictToComponent(items)); } }
the_stack
import type { TransformOptions, TransformResult, ModuleSource } from '../compiler/mod.ts' import type { APIHandler, Aleph as IAleph, DependencyDescriptor, ImportMap, LoadInput, LoadOutput, Module, RouterURL, ResolveResult, TransformInput, TransformOutput, SSRData, RenderOutput } from '../types.d.ts' import type { RequiredConfig } from './config.ts' import { dim } from 'https://deno.land/std@0.108.0/fmt/colors.ts' import { indexOf, copy, equals } from 'https://deno.land/std@0.108.0/bytes/mod.ts' import { ensureDir } from 'https://deno.land/std@0.108.0/fs/ensure_dir.ts' import { walk } from 'https://deno.land/std@0.108.0/fs/walk.ts' import { createHash } from 'https://deno.land/std@0.108.0/hash/mod.ts' import { basename, dirname, extname, join, resolve } from 'https://deno.land/std@0.108.0/path/mod.ts' import { Bundler, bundlerRuntimeCode, simpleJSMinify } from '../bundler/mod.ts' import { wasmChecksum, parseExportNames, SourceType, fastTransform, transform, stripSsrCode } from '../compiler/mod.ts' import { EventEmitter } from '../framework/core/events.ts' import { builtinModuleExts, toPagePath, trimBuiltinModuleExts } from '../framework/core/module.ts' import { Routing } from '../framework/core/routing.ts' import { frameworks } from '../framework/mod.ts' import { cssLoader } from '../plugins/css.ts' import { ensureTextFile, existsDir, existsFile, findFile, lazyRemove } from '../shared/fs.ts' import log, { Measure } from '../shared/log.ts' import util from '../shared/util.ts' import { VERSION } from '../version.ts' import { Analyzer } from './analyzer.ts' import { cache } from './cache.ts' import { defaultConfig, fixConfig, getDefaultImportMap, loadConfig, loadImportMap } from './config.ts' import { checkDenoVersion, clearBuildCache, decoder, encoder, formatBytesWithColor, getAlephPkgUri, getSourceType, isLocalhostUrl, moduleExclude, toLocalPath, toRelativePath, } from './helper.ts' import { getContentType } from './mime.ts' import { buildHtml, Renderer } from './renderer.ts' type CompileOptions = { source?: ModuleSource, forceRefresh?: boolean, ignoreDeps?: boolean, httpExternal?: boolean virtual?: boolean } type ResolveListener = { pluginId: number, test: RegExp, resolve(specifier: string): ResolveResult, } type LoadListener = { pluginId: number, test: RegExp, load(input: LoadInput): Promise<LoadOutput> | LoadOutput, } type TransformListener = { pluginId: number, test: RegExp | 'hmr' | 'main', transform(input: TransformInput): TransformOutput | void | Promise<TransformOutput | void>, } type RenderListener = (input: RenderOutput & { path: string }) => void | Promise<void> /** The class for Aleph server runtime. */ export class Aleph implements IAleph { #config: RequiredConfig #importMap: ImportMap #ready: Promise<void> #mode: 'development' | 'production' #workingDir: string #buildDir: string #modules: Map<string, Module> = new Map() #appModule: Module | null = null #pageRouting: Routing = new Routing() #apiRouting: Routing = new Routing() #analyzer: Analyzer = new Analyzer(this) #bundler: Bundler = new Bundler(this) #renderer: Renderer = new Renderer(this) #fsWatchListeners: Array<EventEmitter> = [] #pluginIndex: number = 0 #resolverListeners: Array<ResolveListener> = [] #loadListeners: Array<LoadListener> = [] #transformListeners: Array<TransformListener> = [] #renderListeners: Array<RenderListener> = [] #dists: Set<string> = new Set() #reload: boolean = false constructor( workingDir = '.', mode: 'development' | 'production' = 'production', reload = false ) { checkDenoVersion() this.#mode = mode this.#workingDir = resolve(workingDir) this.#buildDir = join(this.#workingDir, '.aleph', mode) this.#config = { ...defaultConfig() } this.#importMap = { imports: {}, scopes: {} } this.#reload = reload this.#ready = Deno.env.get('DENO_TESTING') ? Promise.resolve() : this.#init() } /** initiate runtime */ async #init() { const ms = new Measure() let [importMapFile, configFile] = await Promise.all([ findFile(this.#workingDir, ['import_map', 'import-map', 'importmap', 'importMap'].map(name => `${name}.json`)), findFile(this.#workingDir, ['ts', 'js', 'mjs', 'json'].map(ext => `aleph.config.${ext}`)) ]) if (importMapFile) { Object.assign(this.#importMap, await loadImportMap(importMapFile)) } else { Object.assign(this.#importMap, getDefaultImportMap()) } if (configFile) { Object.assign(this.#config, await loadConfig(configFile)) const { basePath, i18n, server: { rewrites } } = this.#config this.#pageRouting = new Routing({ basePath, i18n, rewrites, }) } await fixConfig(this.#workingDir, this.#config, this.#importMap) ms.stop('load config') Deno.env.set('ALEPH_VERSION', VERSION) Deno.env.set('ALEPH_ENV', this.#mode) Deno.env.set('ALEPH_FRAMEWORK', this.#config.framework) Deno.env.set('ALEPH_WORKING_DIR', this.#workingDir) const alephPkgUri = getAlephPkgUri() const srcDir = join(this.#workingDir, this.#config.srcDir) const apiDir = join(srcDir, 'api') const pagesDir = join(srcDir, 'pages') const manifestFile = join(this.#buildDir, 'build.manifest.json') const { browsers, target: buildTarget } = this.#config.build const buildBrowsers = Object.keys(browsers).sort().map(key => key + ':' + (browsers as any)[key]).join(' ') // remove the existent build dir when the compiler is updated, // or using a different aleph version, or build for different target/browsers. if (await existsFile(manifestFile)) { try { const v = JSON.parse(await Deno.readTextFile(manifestFile)) if ( util.isPlainObject(v) && ( v.compiler !== wasmChecksum || v.aleph !== VERSION || (this.mode === 'production' && ( v.buildTarget !== buildTarget || v.buildBrowsers !== buildBrowsers )) ) ) { if (await existsDir(this.#buildDir)) { await Deno.remove(this.#buildDir, { recursive: true }) } } } catch (e) { } } // write manifest ensureTextFile(manifestFile, JSON.stringify({ aleph: VERSION, deno: Deno.version.deno, compiler: wasmChecksum, buildTarget, buildBrowsers, }, undefined, 2)) // load .env[.*] files for await (const { path: p } of walk(this.workingDir, { match: [/(^|\/|\\)\.env(\.|$)/i], maxDepth: 1 })) { const text = await Deno.readTextFile(p) text.split('\n').forEach(line => { let [key, value] = util.splitBy(line, '=') key = key.trim() if (key) { Deno.env.set(key, value.trim()) } }) log.info('load env from', basename(p)) } ms.stop(`init env`) // apply plugins const { plugins } = this.#config for (let i = 0; i < this.#config.plugins.length; i++) { this.#pluginIndex = i await plugins[i].setup(this) } ms.stop('apply plugins') const mwsFile = await findFile(this.#workingDir, ['ts', 'js', 'mjs'].map(ext => `${this.#config.srcDir}/api/_middlewares.${ext}`)) if (mwsFile) { const mwMod = await this.compile(`/api/${basename(mwsFile)}`, { httpExternal: true }) const { default: _middlewares } = await import('file://' + join(this.#buildDir, mwMod.jsFile)) const middlewares = Array.isArray(_middlewares) ? _middlewares.filter(fn => util.isFunction(fn)) : [] this.#config.server.middlewares.push(...middlewares) ms.stop(`load API middlewares (${middlewares.length}) from 'api/${basename(mwsFile)}'`) } // init framework await frameworks[this.#config.framework].init(this) // compile and import framework renderer if (this.#config.ssr) { const mod = await this.compile(`${getAlephPkgUri()}/framework/${this.#config.framework}/renderer.ts`) const { render } = await this.importModule(mod) if (util.isFunction(render)) { this.#renderer.setFrameworkRenderer({ render }) } } ms.stop(`init ${this.#config.framework} framework`) const appFile = await findFile(srcDir, builtinModuleExts.map(ext => `app.${ext}`)) const modules: string[] = [] const moduleWalkOptions = { includeDirs: false, skip: moduleExclude } // pre-compile framework modules modules.push(`${alephPkgUri}/framework/${this.#config.framework}/bootstrap.ts`) if (this.isDev) { modules.push(`${alephPkgUri}/framework/core/hmr.ts`) modules.push(`${alephPkgUri}/framework/core/nomodule.ts`) } if (appFile) { modules.push(`/${basename(appFile)}`) } // create API routing if (await existsDir(apiDir)) { for await (const { path: p } of walk(apiDir, { ...moduleWalkOptions, exts: builtinModuleExts })) { const specifier = util.cleanPath('/api/' + util.trimPrefix(p, apiDir)) if (!specifier.startsWith('/api/_middlewares.')) { this.#apiRouting.update(...this.#createRouteUpdate(specifier)) } } } // create Page routing if (await existsDir(pagesDir)) { for await (const { path: p } of walk(pagesDir, moduleWalkOptions)) { const specifier = util.cleanPath('/pages/' + util.trimPrefix(p, pagesDir)) if (this.#isPageModule(specifier)) { this.#pageRouting.update(...this.#createRouteUpdate(specifier)) if (!this.isDev) { modules.push(specifier) } } } } // wait all compilation tasks are done await Promise.all(modules.map(specifier => this.compile(specifier))) // bundle modules in `production` mode if (!this.isDev) { await this.#bundle() } ms.stop('init project') if (this.isDev) { this.#watch() } } /** watch file changes, re-compile modules, and send HMR signal to client. */ async #watch() { const srcDir = join(this.#workingDir, this.#config.srcDir) const w = Deno.watchFs(srcDir, { recursive: true }) log.info('Start watching code changes...') for await (const event of w) { for (const path of event.paths) { const specifier = util.cleanPath(util.trimPrefix(path, srcDir)) if (this.#isScopedModule(specifier)) { util.debounceById( specifier, () => this.#watchHandler(path, specifier), 50 ) } } } } async #watchHandler(path: string, specifier: string): Promise<void> { if (await existsFile(path)) { if (this.#modules.has(specifier)) { try { const prevModule = this.#modules.get(specifier)! const module = await this.compile(specifier, { forceRefresh: true, ignoreDeps: true, httpExternal: prevModule.httpExternal }) const refreshPage = ( this.#config.ssr && ( (module.denoHooks !== undefined && JSON.stringify(prevModule.denoHooks) !== JSON.stringify(module.denoHooks)) || (module.ssrPropsFn !== undefined && prevModule.ssrPropsFn !== module.ssrPropsFn) ) ) const hmrable = this.#isHMRable(specifier) if (hmrable) { this.#fsWatchListeners.forEach(e => { e.emit('modify-' + module.specifier, { refreshPage: refreshPage || undefined }) }) } this.#applyCompilationSideEffect(module, () => { if (!hmrable && this.#isHMRable(specifier)) { log.debug(`compilation side-effect: ${specifier} ${dim('<-')} ${module.specifier}(${module.sourceHash.substr(0, 6)})`) this.#fsWatchListeners.forEach(e => { e.emit('modify-' + specifier, { refreshPage: refreshPage || undefined }) }) } this.#clearSSRCache(specifier) }) this.#clearSSRCache(specifier) log.debug('modify', specifier) } catch (err) { log.error(`compile(${specifier}):`, err.message) } } else { let routePath: string | undefined = undefined let isIndex: boolean | undefined = undefined let emitHMR = false if (this.#isPageModule(specifier)) { emitHMR = true this.#pageRouting.lookup(routes => { routes.forEach(({ module }) => { if (module === specifier) { emitHMR = false return false // break loop } }) }) if (emitHMR) { const [_routePath, _specifier, _isIndex] = this.#createRouteUpdate(specifier) routePath = _routePath specifier = _specifier isIndex = _isIndex this.#pageRouting.update(routePath, specifier, isIndex) } } else if (specifier.startsWith('/api/') && !specifier.startsWith('/api/_middlewares.')) { let routeExists = false this.#apiRouting.lookup(routes => { routes.forEach(({ module }) => { if (module === specifier) { routeExists = true return false // break loop } }) }) if (!routeExists) { this.#apiRouting.update(...this.#createRouteUpdate(specifier)) } } if (trimBuiltinModuleExts(specifier) === '/app') { await this.compile(specifier) emitHMR = true } if (emitHMR) { this.#fsWatchListeners.forEach(e => { e.emit('add', { specifier, routePath, isIndex }) }) log.debug('add', specifier) } } } else { if (this.#modules.has(specifier)) { this.#modules.delete(specifier) } if (trimBuiltinModuleExts(specifier) === '/app') { this.#fsWatchListeners.forEach(e => e.emit('remove', specifier)) } else if (this.#isPageModule(specifier)) { this.#pageRouting.removeRouteByModule(specifier) this.#fsWatchListeners.forEach(e => e.emit('remove', specifier)) } else if (specifier.startsWith('/api/')) { this.#apiRouting.removeRouteByModule(specifier) } this.#clearSSRCache(specifier) log.debug('remove', specifier) } } /** check the file whether it is a scoped module. */ #isScopedModule(specifier: string) { if (moduleExclude.some(r => r.test(specifier))) { return false } // is compiled module if (this.#modules.has(specifier)) { return true } // is page module by plugin if (this.#isPageModule(specifier)) { return true } // is api or app module for (const ext of builtinModuleExts) { if ( specifier.endsWith('.' + ext) && ( specifier.startsWith('/api/') || util.trimSuffix(specifier, '.' + ext) === '/app' ) ) { return true } } return false } get mode() { return this.#mode } get isDev() { return this.#mode === 'development' } get workingDir() { return this.#workingDir } get buildDir() { return this.#buildDir } get config() { return this.#config } get importMap() { return this.#importMap } get ready() { return this.#ready } get transformListeners() { return this.#transformListeners } /** get the module by given specifier. */ getModule(specifier: string): Module | null { if (specifier === 'app') { return this.#appModule } if (this.#modules.has(specifier)) { return this.#modules.get(specifier)! } return null } /** get the first module in the modules map where predicate is true, and null otherwise. */ findModule(predicate: (module: Module) => boolean): Module | null { for (const specifier of this.#modules.keys()) { const module = this.#modules.get(specifier)! if (predicate(module)) { return module } } return null } /** get api route by the given location. */ async getAPIRoute(location: { pathname: string, search?: string }): Promise<[RouterURL, APIHandler] | null> { const router = this.#apiRouting.createRouter(location) if (router !== null) { const [url, nestedModules] = router if (url.routePath !== '') { const specifier = nestedModules.pop()! const filepath = join(this.#workingDir, this.#config.srcDir, util.trimPrefix(specifier, 'file://')) const qs = this.isDev ? '?mtime=' + (await Deno.lstat(filepath)).mtime?.getTime() : '' const { handler } = await import(`file://${filepath}${qs}`) return [url, handler] } } return null } onResolve(test: RegExp, callback: (specifier: string) => ResolveResult): void { this.#resolverListeners.push({ pluginId: this.#pluginIndex, test, resolve: callback }) } onLoad(test: RegExp, callback: (input: LoadInput) => LoadOutput | Promise<LoadOutput>): void { this.#loadListeners.push({ pluginId: this.#pluginIndex, test, load: callback }) } onTransform(test: RegExp | 'hmr' | 'main', callback: (input: TransformOutput & { module: Module }) => TransformOutput | Promise<TransformOutput>): void { this.#transformListeners.push({ pluginId: this.#pluginIndex, test, transform: callback }) } onRender(callback: (input: RenderOutput & { path: string }) => void | Promise<void>): void { this.#renderListeners.push(callback) } /** add a module by given path and optional source code. */ async addModule(specifier: string, sourceCode: string, forceRefresh?: boolean): Promise<Module> { let sourceType = getSourceType(specifier) if (sourceType === SourceType.Unknown) { throw new Error("addModule: unknown source type") } const source = { code: sourceCode, type: sourceType, } const module = await this.compile(specifier, { source, forceRefresh, }) if (specifier.startsWith('pages/') || specifier.startsWith('api/')) { specifier = '/' + specifier } if (specifier.startsWith('/pages/') && this.#isPageModule(specifier)) { this.#pageRouting.update(...this.#createRouteUpdate(specifier)) } else if (specifier.startsWith('/api/') && !specifier.startsWith('/api/_middlewares.')) { this.#apiRouting.update(...this.#createRouteUpdate(specifier)) } Object.assign(module, { source }) return module } /** add a dist. */ async addDist(path: string, content: Uint8Array): Promise<void> { const pathname = util.cleanPath(path) const savePath = join(this.#buildDir, pathname) if (!await existsFile(savePath)) { const saveDir = dirname(savePath) await ensureDir(saveDir) await clearBuildCache(savePath, extname(savePath).slice(1)) await Deno.writeFile(savePath, content) } this.#dists.add(pathname) } /** get ssr data by the given location(page), return `null` if no data defined */ async getSSRData(request: Request, loc: { pathname: string, search?: string }): Promise<Record<string, SSRData> | null> { const [router, nestedModules] = this.#pageRouting.createRouter(loc) const { routePath } = router if (routePath === '' || !this.#isSSRable(router.pathname)) { return null } // pre-compile modules to check ssr options await Promise.all( nestedModules .filter(specifier => !this.#modules.has(specifier)) .map(specifier => this.compile(specifier)) ) if (!this.#isDataRoute(nestedModules)) { return null } const path = loc.pathname + (loc.search || '') const [_, data] = await this.#renderer.cache(routePath, path, async () => { return await this.#renderPage(request, router, nestedModules) }) return data } /* check whether the route has data by givan nested modules */ #isDataRoute(nestedModules: string[]) { const pageModule = this.getModule(nestedModules[nestedModules.length - 1]) if (pageModule && pageModule.ssrPropsFn) { return true } for (const specifier of ['app', ...nestedModules]) { const mod = this.getModule(specifier) if (mod) { if (mod.denoHooks?.length) { return true } let ok = false this.lookupDeps(mod.specifier, dep => { const depMod = this.getModule(dep.specifier) if (depMod?.denoHooks?.length) { ok = true return false // break loop } }) if (ok) { return } } } return false } /** render page to HTML by the given location */ async renderPage(request: Request, loc: { pathname: string, search?: string }): Promise<[number, string]> { const [router, nestedModules] = this.#pageRouting.createRouter(loc) const { routePath } = router const path = loc.pathname + (loc.search || '') if (!this.#isSSRable(loc.pathname)) { const [html] = await this.#renderer.cache('-', 'spa-index-html', async () => { return [await this.#createSPAIndexHtml(), null] }) return [200, html] } if (routePath === '') { const [html] = await this.#renderer.cache('404', path, async () => { const [_, nestedModules] = this.#pageRouting.createRouter({ pathname: '/404' }) return await this.#renderPage(request, router, nestedModules.slice(0, 1)) }) return [404, html] } const [html] = await this.#renderer.cache(routePath, path, async () => { return await this.#renderPage(request, router, nestedModules) }) return [200, html] } async #renderPage(request: Request, url: RouterURL, nestedModules: string[]): Promise<[string, Record<string, SSRData> | null]> { let [html, data] = await this.#renderer.renderPage(request, url, nestedModules) for (const callback of this.#renderListeners) { await callback({ path: url.toString(), html, data }) } return [buildHtml(html, !this.isDev), data] } /** create a fs watcher. */ createFSWatcher(): EventEmitter { const e = new EventEmitter() this.#fsWatchListeners.push(e) return e } /** remove the fs watcher. */ removeFSWatcher(e: EventEmitter) { e.removeAllListeners() const index = this.#fsWatchListeners.indexOf(e) if (index > -1) { this.#fsWatchListeners.splice(index, 1) } } /** create main bootstrap script in javascript. */ async createMainJS(bundleMode = false): Promise<string> { const alephPkgUri = getAlephPkgUri() const alephPkgPath = alephPkgUri.replace('https://', '').replace('http://localhost:', 'http_localhost_') const { framework, basePath, i18n, ssr, server: { rewrites } } = this.#config const { routes } = this.#pageRouting const config: Record<string, any> = { renderMode: ssr ? 'ssr' : 'spa', basePath, appModule: this.#appModule?.specifier, routes, i18n, rewrites: rewrites, } let code: string if (bundleMode) { config.dataRoutes = this.#pageRouting.paths.filter(pathname => { const [_, nestedModules] = this.#pageRouting.createRouter({ pathname }) return this.#isDataRoute(nestedModules) }) code = [ `__ALEPH__.basePath = ${JSON.stringify(basePath)};`, `__ALEPH__.pack["${alephPkgUri}/framework/${framework}/bootstrap.ts"].default(${JSON.stringify(config)});` ].join('') } else { code = [ `import bootstrap from "./-/${alephPkgPath}/framework/${framework}/bootstrap.js";`, this.isDev && `import { connect } from "./-/${alephPkgPath}/framework/core/hmr.js";`, this.isDev && `connect(${JSON.stringify(basePath)});`, `bootstrap(${JSON.stringify(config, undefined, this.isDev ? 2 : undefined)});` ].filter(Boolean).join('\n') } for (const { test, transform } of this.#transformListeners) { if (test === 'main') { let ret = await transform({ module: { specifier: '/main.js', deps: [], sourceHash: '', jsFile: '' }, code, }) if (util.isFilledString(ret?.code)) { code = ret!.code } } } return code } /** create the index html for SPA mode. */ async #createSPAIndexHtml(): Promise<string> { let html = { lang: this.#config.i18n.defaultLocale, head: [], scripts: this.getScripts(), body: '<div id="__aleph"></div>', bodyAttrs: {}, } for (const callback of this.#renderListeners) { await callback({ path: 'spa-index-html', html, data: null }) } return buildHtml(html, !this.isDev) } /** get scripts for html output */ getScripts(entryFile?: string) { const { framework } = this.#config const basePath = util.trimSuffix(this.#config.basePath, '/') const alephPkgPath = getAlephPkgUri().replace('https://', '').replace('http://localhost:', 'http_localhost_') const syncChunks = this.#bundler.getSyncChunks() if (this.isDev) { const preload: string[] = [ `/framework/core/module.js`, `/framework/core/events.js`, `/framework/core/routing.js`, `/framework/core/hmr.js`, `/framework/${framework}/bootstrap.js`, `/shared/util.js`, ].map(p => `${basePath}/_aleph/-/${alephPkgPath}${p}`) if (this.#appModule) { preload.push(`${basePath}/_aleph/app.js`) } if (entryFile) { preload.push(`${basePath}/_aleph${entryFile}`) } return [ ...preload.map(src => ({ src, type: 'module', preload: true })), { src: `${basePath}/_aleph/main.js`, type: 'module' }, { src: `${basePath}/_aleph/-/${alephPkgPath}/nomodule.js`, nomodule: true }, ] } return [ simpleJSMinify(bundlerRuntimeCode), ...syncChunks.map(filename => ({ src: `${basePath}/_aleph/${filename}` })) ] } computeModuleHash(module: Module) { const hasher = createHash('md5').update(module.sourceHash) this.lookupDeps(module.specifier, dep => { const depMod = this.getModule(dep.specifier) if (depMod) { hasher.update(depMod.sourceHash) } }) return hasher.toString() } /** parse the export names of the module. */ async parseModuleExportNames(specifier: string): Promise<string[]> { const { content, contentType } = await this.fetchModule(specifier) const sourceType = getSourceType(specifier, contentType || undefined) if (sourceType === SourceType.Unknown || sourceType === SourceType.CSS) { return [] } const code = decoder.decode(content) const names = await parseExportNames(specifier, code, { sourceType }) return (await Promise.all(names.map(async name => { if (name.startsWith('{') && name.endsWith('}')) { let dep = name.slice(1, -1) if (util.isLikelyHttpURL(specifier)) { const url = new URL(specifier) if (dep.startsWith('/')) { dep = url.protocol + '//' + url.host + dep } else { dep = url.protocol + '//' + url.host + join(url.pathname, dep) } } return await this.parseModuleExportNames(dep) } return name }))).flat() } /** common compiler options */ get commonCompilerOptions(): TransformOptions { return { alephPkgUri: getAlephPkgUri(), workingDir: this.#workingDir, importMap: this.#importMap, inlineStylePreprocess: async (key: string, type: string, tpl: string) => { if (type !== 'css') { for (const { test, load } of this.#loadListeners) { if (test.test(`.${type}`)) { const { code, type: codeType } = await load({ specifier: key, data: encoder.encode(tpl) }) if (codeType === 'css') { type = 'css' tpl = code break } } } } const { code } = await cssLoader({ specifier: key, data: encoder.encode(tpl) }, this) return code }, isDev: this.isDev, react: this.#config.react, } } analyze() { this.#analyzer.reset() this.#pageRouting.lookup(routes => { routes.forEach(({ module: specifier }) => { const module = this.getModule(specifier) if (module) { this.#analyzer.addEntry(module) } }) }) return this.#analyzer.entries } /** build the application to a static site(SSG) */ async build() { const start = performance.now() // wait for app ready await this.#ready const outputDir = join(this.#workingDir, this.#config.build.outputDir) const distDir = join(outputDir, '_aleph') // clean previous build if (await existsDir(outputDir)) { for await (const entry of Deno.readDir(outputDir)) { await Deno.remove(join(outputDir, entry.name), { recursive: entry.isDirectory }) } } // copy bundle dist await this.#bundler.copyDist() // ssg await this.#ssg() // copy public assets const publicDir = join(this.#workingDir, 'public') if (await existsDir(publicDir)) { for await (const { path: p } of walk(publicDir, { includeDirs: false, skip: [/(^|\/|\\)\./] })) { const rp = util.trimPrefix(p, publicDir) const fp = join(outputDir, rp) await ensureDir(dirname(fp)) await Deno.copyFile(p, fp) } } // copy custom dist files if (this.#dists.size > 0) { Promise.all(Array.from(this.#dists.values()).map(async path => { const src = join(this.#buildDir, path) if (await existsFile(src)) { const dest = join(distDir, path) await ensureDir(dirname(dest)) return Deno.copyFile(src, dest) } })) } log.info(`Done in ${Math.round(performance.now() - start)}ms`) } #createRouteUpdate(specifier: string): [string, string, boolean | undefined] { const isBuiltinModuleType = builtinModuleExts.some(ext => specifier.endsWith('.' + ext)) let routePath = isBuiltinModuleType ? toPagePath(specifier) : util.trimSuffix(specifier, '/pages') let isIndex: boolean | undefined = undefined if (!isBuiltinModuleType) { for (const { test, resolve } of this.#resolverListeners) { if (test.test(specifier)) { const { specifier: _specifier, asPage } = resolve(specifier) if (asPage) { const { path: pagePath, isIndex: _isIndex } = asPage if (util.isFilledString(pagePath)) { routePath = pagePath if (_specifier) { specifier = _specifier } if (_isIndex) { isIndex = true } break } } } } } else if (routePath !== '/') { for (const ext of builtinModuleExts) { if (specifier.endsWith(`/index.${ext}`)) { isIndex = true break } } } return [routePath, specifier, isIndex] } async importModule<T = any>(module: Module): Promise<T> { const path = join(this.#buildDir, module.jsFile) const hash = this.computeModuleHash(module) if (await existsFile(path)) { return await import(`file://${path}#${(hash).slice(0, 6)}`) } throw new Error(`import ${module.specifier}: file not found: ${path}`) } async getModuleJS(module: Module, injectHMRCode = false): Promise<Uint8Array | null> { const { specifier, jsFile, jsBuffer } = module if (!jsBuffer) { const jsFilePath = join(this.#buildDir, jsFile) if (await existsFile(jsFilePath)) { module.jsBuffer = await Deno.readFile(jsFilePath) log.debug(`load '${jsFile}'` + dim(' • ' + util.formatBytes(module.jsBuffer.length))) } } if (!module.jsBuffer) { return null } if (!injectHMRCode || !this.#isHMRable(specifier)) { return module.jsBuffer } let code = decoder.decode(module.jsBuffer) if (module.denoHooks?.length || module.ssrPropsFn || module.ssgPathsFn) { if ('csrCode' in module) { code = (module as any).csrCode } else { [code] = util.splitBy(code, '\n//# sourceMappingURL=', true) const { code: csrCode } = await stripSsrCode(specifier, code, { sourceMap: true, swcOptions: { sourceType: SourceType.JS } }) // cache csr code Object.assign(module, { csrCode }) code = csrCode // todo: merge source map } } for (const { test, transform } of this.#transformListeners) { if (test === 'hmr') { const { jsBuffer, ready, ...rest } = module const ret = await transform({ module: rest, code }) if (util.isFilledString(ret?.code)) { code = ret!.code } // todo: merge source map } } return encoder.encode([ `import.meta.hot = $createHotContext(${JSON.stringify(specifier)});`, '', code, '', 'import.meta.hot.accept();' ].join('\n')) } /** fetch module source by the specifier. */ async fetchModule(specifier: string): Promise<{ content: Uint8Array, contentType: string | null }> { if (!util.isLikelyHttpURL(specifier)) { const filepath = join(this.#workingDir, this.#config.srcDir, util.trimPrefix(specifier, 'file://')) if (await existsFile(filepath)) { const content = await Deno.readFile(filepath) return { content, contentType: getContentType(filepath) } } else { return Promise.reject(new Error(`No such file: ${util.trimPrefix(filepath, this.#workingDir + '/')}`)) } } // append `dev` query for development mode if (this.isDev && specifier.startsWith('https://esm.sh/')) { const u = new URL(specifier) if (!u.searchParams.has('dev')) { u.searchParams.set('dev', '') u.search = u.search.replace('dev=', 'dev') specifier = u.toString() } } return await cache(specifier, { forceRefresh: (() => { const key = 'cache:' + specifier const refresh = this.#reload && sessionStorage.getItem(key) === null if (refresh) { sessionStorage.setItem(key, '1') } return refresh })(), retryTimes: 10 }) } resolveImport({ jsFile, sourceHash }: Module, importer: string, bundleMode?: boolean, timeStamp?: boolean): string { const relPath = toRelativePath( dirname(toLocalPath(importer)), jsFile ) if (bundleMode) { return util.trimSuffix(relPath, '.js') + '.bundling.js' } let hash = '#' + sourceHash.slice(0, 8) if (timeStamp) { hash += '-' + Date.now() } return relPath + hash } async resolveModuleSource(specifier: string, data?: any): Promise<ModuleSource> { let sourceCode: string = '' let sourceType: SourceType = SourceType.Unknown let sourceMap: string | null = null let loader = this.#loadListeners.find(l => l.test.test(specifier)) if (loader) { const { code, type = 'js', map } = await loader.load({ specifier, data }) switch (type) { case 'js': sourceType = SourceType.JS break case 'jsx': sourceType = SourceType.JSX break case 'ts': sourceType = SourceType.TS break case 'tsx': sourceType = SourceType.TSX break case 'css': sourceType = SourceType.CSS break } sourceCode = code sourceMap = map || null } else { const source = await this.fetchModule(specifier) sourceType = getSourceType(specifier, source.contentType || undefined) if (sourceType !== SourceType.Unknown) { sourceCode = decoder.decode(source.content) } } return { code: sourceCode, type: sourceType, map: sourceMap ? sourceMap : undefined } } /** compile the module by given specifier */ async compile(specifier: string, options: CompileOptions = {}) { const [module, source] = await this.#initModule(specifier, options) if (!module.external) { await this.#transpileModule(module, source, options.ignoreDeps) } return module } /** init the module by given specifier, don't transpile the code when the returned `source` is equal to null */ async #initModule( specifier: string, { source: customSource, forceRefresh, httpExternal, virtual }: CompileOptions = {} ): Promise<[Module, ModuleSource | null]> { let external = false let data: any = null if (customSource === undefined) { for (const { test, resolve } of this.#resolverListeners) { if (test.test(specifier)) { const ret = resolve(specifier) if (ret.specifier) { specifier = ret.specifier } external = Boolean(ret.external) data = ret.data break } } } if (external) { return [{ specifier, deps: [], external, sourceHash: '', jsFile: '', ready: Promise.resolve() }, null] } let mod = this.#modules.get(specifier) if (mod && !forceRefresh && !(!httpExternal && mod.httpExternal)) { await mod.ready return [mod, null] } const localPath = toLocalPath(specifier) const jsFile = trimBuiltinModuleExts(localPath) + '.js' const jsFilePath = join(this.#buildDir, jsFile) const metaFilePath = jsFilePath.slice(0, -3) + '.meta.json' const isNew = !mod let defer = (err?: Error) => { } let source: ModuleSource | null = null mod = { specifier, deps: [], sourceHash: '', httpExternal, jsFile, ready: new Promise((resolve) => { defer = (err?: Error) => { if (err) { if (isNew) { this.#modules.delete(specifier) } log.error(err.message) // todo: send error to client } resolve() } }) } this.#modules.set(specifier, mod) if (trimBuiltinModuleExts(specifier) === '/app') { this.#appModule = mod } if (!forceRefresh && await existsFile(metaFilePath)) { try { const meta = JSON.parse(await Deno.readTextFile(metaFilePath)) if (meta.specifier === specifier && util.isFilledString(meta.sourceHash) && util.isArray(meta.deps)) { Object.assign(mod, meta) } else { log.warn(`removing invalid metadata of '${basename(specifier)}'...`) Deno.remove(metaFilePath) } } catch (e) { } } if (virtual) { defer() return [mod, null] } const isRemote = util.isLikelyHttpURL(specifier) && !isLocalhostUrl(specifier) const reload = this.#reload && sessionStorage.getItem('init:' + specifier) === null if ( !isRemote || // always check local file changes mod.sourceHash === '' || // first build reload || // reload !(await existsFile(jsFilePath)) // missing built js file ) { if (reload) { sessionStorage.setItem('init:' + specifier, '1') } try { const src = customSource || await this.resolveModuleSource(specifier, data) const hasher = createHash('sha1') const plugins = new Set<number>() const loader = this.#loadListeners.find(l => l.test.test(specifier)) hasher.update(src.code) hasher.update(Object.keys(this.#importMap.imports).sort().map(key => key + ':' + this.#importMap.imports[key]).join('\n')) if (loader) { plugins.add(loader.pluginId) } for (const { pluginId, test } of this.#transformListeners) { if (test instanceof RegExp && test.test(specifier)) { plugins.add(pluginId) } } if (plugins.size > 0) { plugins.forEach(index => { const p = this.#config.plugins[index] if (p.checksum) { hasher.update(p.name) hasher.update(p.checksum()) } }) } if (src.type === SourceType.CSS) { const { css } = this.#config hasher.update(JSON.stringify({ ...css, postcss: { plugins: css.postcss.plugins.map(v => util.isFunction(v) ? v.toString() : v) } })) } const sourceHash = hasher.toString() if (mod.sourceHash !== sourceHash) { mod.sourceHash = sourceHash source = src } } catch (err) { defer(err) return [mod, null] } } defer() return [mod, source] } async #transpileModule( module: Module, source: ModuleSource | null, ignoreDeps = false, __tracing: Set<string> = new Set() ): Promise<void> { const { specifier, jsFile, httpExternal } = module // ensure the module only be transppiled once in current compilation context, // to avoid dead-loop caused by cicular imports if (__tracing.has(specifier)) { return } __tracing.add(specifier) if (source) { if (source.type === SourceType.Unknown) { log.error(`Unsupported module '${specifier}'`) return } const ms = new Measure() if (source.type === SourceType.CSS) { const { code, map } = await cssLoader({ specifier, data: source.code }, this) source.code = code source.map = map source.type = SourceType.JS module.isStyle = true } let ret: TransformResult // use `fastTransform` when the module is remote non-jsx module if (util.isLikelyHttpURL(specifier) && source.type !== SourceType.JSX && source.type !== SourceType.TSX) { ret = await fastTransform(specifier, source, { react: this.#config.react }) } else { ret = await transform(specifier, source.code, { ...this.commonCompilerOptions, sourceMap: this.isDev, swcOptions: { sourceType: source.type }, httpExternal }) } const { code, deps = [], denoHooks, ssrPropsFn, ssgPathsFn, starExports, jsxStaticClassNames, map } = ret let jsCode = code let sourceMap = map // in production(bundle) mode we need to replace the star export with names if (!this.isDev && starExports && starExports.length > 0) { for (let index = 0; index < starExports.length; index++) { const exportSpecifier = starExports[index] const names = await this.parseModuleExportNames(exportSpecifier) jsCode = jsCode.replace( `export * from "[${exportSpecifier}]:`, `export {${names.filter(name => name !== 'default').join(',')}} from "` ) } } // revert external imports if (deps.length > 0 && this.#resolverListeners.length > 0) { deps.forEach(({ specifier }) => { if (specifier !== module.specifier && util.isLikelyHttpURL(specifier)) { let external = false for (const { test, resolve } of this.#resolverListeners) { if (test.test(specifier)) { const ret = resolve(specifier) if (ret.specifier) { specifier = ret.specifier } external = Boolean(ret.external) break } } if (external) { const importSpecifier = toRelativePath( dirname(toLocalPath(module.specifier)), toLocalPath(specifier) ) jsCode.replaceAll(`"${importSpecifier}"`, `"${specifier}"`) } } }) } Object.assign(module, { deps, ssrPropsFn, ssgPathsFn, jsxStaticClassNames }) if (util.isFilledArray(denoHooks)) { module.denoHooks = denoHooks.map(id => util.trimPrefix(id, 'useDeno-')) if (!this.#config.ssr) { log.error(`'useDeno' hook in SPA mode is illegal: ${specifier}`) } } let extraDeps: DependencyDescriptor[] = [] for (const { test, transform } of this.#transformListeners) { if (test instanceof RegExp && test.test(specifier)) { const { jsBuffer, ready, ...rest } = module const ret = await transform({ module: rest, code: jsCode, map: sourceMap }) if (util.isFilledString(ret?.code)) { jsCode = ret!.code } if (util.isFilledString(ret?.map)) { sourceMap = ret!.map } if (Array.isArray(ret?.extraDeps)) { extraDeps.push(...ret!.extraDeps) } } } // add source mapping url if (sourceMap) { jsCode += `\n//# sourceMappingURL=${basename(jsFile)}.map` } module.jsBuffer = encoder.encode(jsCode) module.deps = deps.filter(({ specifier }) => specifier !== module.specifier).map(({ specifier, resolved, isDynamic }) => { const dep: DependencyDescriptor = { specifier, } if (isDynamic) { dep.isDynamic = true } if (specifier.startsWith('/')) { const mark = encoder.encode(resolved) const idx = indexOf(module.jsBuffer!, mark) if (idx > 0) { dep.hashLoc = idx + mark.length - 6 } } return dep }).concat(extraDeps) ms.stop(`transpile '${specifier}'`) await this.#cacheModule(module, sourceMap) } if (module.deps.length > 0) { let fsync = false await Promise.all(module.deps.map(async ({ specifier, hashLoc, virtual }) => { let depModule: Module | null = null if (ignoreDeps || virtual) { depModule = this.getModule(specifier) if (depModule === null && virtual) { const [mod] = await this.#initModule(specifier, { virtual: true }) depModule = mod } } if (depModule === null) { const [mod, src] = await this.#initModule(specifier, { httpExternal }) if (!mod.external) { await this.#transpileModule(mod, src, false, __tracing) } depModule = mod } if (depModule) { if (hashLoc !== undefined) { const hash = this.computeModuleHash(depModule) if (await this.#replaceDepHash(module, hashLoc, hash)) { fsync = true } } } else { log.error(`transpile '${module.specifier}': missing dependency module '${specifier}'`) } })) if (fsync) { await this.#cacheModule(module) } } } /** apply compilation side-effect caused by updating dependency graph. */ async #applyCompilationSideEffect(by: Module, callback: (mod: Module) => void, __tracing = new Set<string>()) { if (__tracing.has(by.specifier)) { return } __tracing.add(by.specifier) let hash: string | null = null for (const mod of this.#modules.values()) { const { deps } = mod if (deps.length > 0) { let fsync = false for (const dep of deps) { const { specifier, hashLoc } = dep if (specifier === by.specifier && hashLoc !== undefined) { if (hash === null) { hash = this.computeModuleHash(by) } if (await this.#replaceDepHash(mod, hashLoc, hash)) { fsync = true } } } if (fsync) { callback(mod) this.#applyCompilationSideEffect(mod, callback) this.#cacheModule(mod) } } } } /** replace dep hash in the `jsBuffer` and remove `csrCode` cache if it exits */ async #replaceDepHash(module: Module, hashLoc: number, hash: string) { const hashData = encoder.encode(hash.substr(0, 6)) const jsBuffer = await this.getModuleJS(module) if (jsBuffer && !equals(hashData, jsBuffer.slice(hashLoc, hashLoc + 6))) { copy(hashData, jsBuffer, hashLoc) if ('csrCode' in module) { Reflect.deleteProperty(module, 'csrCode') } return true } return false } #clearSSRCache(specifier: string) { if (trimBuiltinModuleExts(specifier) === '/app') { this.#renderer.clearCache() } else if (this.#isPageModule(specifier)) { const [routePath] = this.#createRouteUpdate(specifier) this.#renderer.clearCache(routePath) } } async #cacheModule(module: Module, sourceMap?: string) { const { jsBuffer, jsFile, ready, ...rest } = module if (jsBuffer) { const jsFilePath = join(this.#buildDir, jsFile) const metaFilePath = jsFilePath.slice(0, -3) + '.meta.json' await ensureDir(dirname(jsFilePath)) await Promise.all([ Deno.writeFile(jsFilePath, jsBuffer), Deno.writeTextFile(metaFilePath, JSON.stringify({ ...rest }, undefined, 2)), sourceMap ? Deno.writeTextFile(`${jsFilePath}.map`, sourceMap) : Promise.resolve(), lazyRemove(jsFilePath.slice(0, -3) + '.bundling.js'), ]) } } /** create bundled chunks for production. */ async #bundle() { const entries = this.analyze() await this.#bundler.bundle(entries) } /** render all pages in routing. */ async #ssg() { const { ssr } = this.#config const outputDir = join(this.#workingDir, this.#config.build.outputDir) if (ssr === false) { const html = await this.#createSPAIndexHtml() await ensureTextFile(join(outputDir, 'index.html'), html) await ensureTextFile(join(outputDir, '404.html'), html) // todo: 500 page return } // lookup pages const paths: Set<{ pathname: string, search?: string }> = new Set(this.#pageRouting.paths.map(pathname => ({ pathname }))) const locales = this.#config.i18n.locales.filter(l => l !== this.#config.i18n.defaultLocale) for (const specifier of this.#modules.keys()) { const module = this.#modules.get(specifier)! if (module.ssgPathsFn) { const { ssr } = await this.importModule(module) let ssrPaths = ssr.paths if (util.isFunction(ssrPaths)) { ssrPaths = ssrPaths() if (ssrPaths instanceof Promise) { ssrPaths = await ssrPaths } } if (util.isFilledArray(ssrPaths)) { ssrPaths.forEach(path => { if (util.isFilledString(path)) { const parts = path.split('?') const pathname = util.cleanPath(parts.shift()!) const search = parts.length > 0 ? '?' + (new URLSearchParams('?' + parts.join('?'))).toString() : undefined const [router, nestedModules] = this.#pageRouting.createRouter({ pathname, search }) if (router.routePath !== '' && nestedModules.pop() === specifier) { paths.add({ pathname, search }) } else { log.warn(`Invalid SSG path '${path}'`) } } }) } } } // render route pages let pageIndex = 0 const req = new Request('http://localhost/') await Promise.all(Array.from(paths).map(loc => ([loc, ...locales.map(locale => ({ ...loc, pathname: '/' + locale + loc.pathname }))])).flat().map(async ({ pathname, search }) => { if (this.#isSSRable(pathname)) { const [router, nestedModules] = this.#pageRouting.createRouter({ pathname, search }) if (router.routePath !== '') { const ms = new Measure() const href = router.toString() const [html, data] = await this.#renderPage(req, router, nestedModules) await Promise.all([ ensureTextFile(join(outputDir, pathname, 'index.html' + (search || '')), html), data ? ensureTextFile(join(outputDir, `_aleph/data/${util.btoaUrl(href)}.json`), JSON.stringify(data)) : Promise.resolve() ]) ms.stop(`SSR ${href} (${formatBytesWithColor(html.length)})`) if (pageIndex == 0) { console.log('▲ SSG') } if (pageIndex <= 20) { console.log(' ', href, dim('•'), formatBytesWithColor(html.length)) } pageIndex++ } } })) if (pageIndex > 20) { console.log(` ... total ${pageIndex} pages`) } // render 404 page { const [router, nestedModules] = this.#pageRouting.createRouter({ pathname: '/404' }) if (nestedModules.length > 0) { await this.compile(nestedModules[0]) } const [html] = await this.#renderPage(req, router, nestedModules.slice(0, 1)) await ensureTextFile(join(outputDir, '404.html'), html) } } /** check the module whether it is page. */ #isPageModule(specifier: string): boolean { if (!specifier.startsWith('/pages/')) { return false } if (builtinModuleExts.some(ext => specifier.endsWith('.' + ext))) { return true } return this.#resolverListeners.some(({ test, resolve }) => test.test(specifier) && !!resolve(specifier).asPage) } /** check the module whether it is hmrable. */ #isHMRable(specifier: string): boolean { if (util.isLikelyHttpURL(specifier)) { return false } for (const ext of builtinModuleExts) { if (specifier.endsWith('.' + ext)) { return ( specifier.startsWith('/pages/') || specifier.startsWith('/components/') || util.trimSuffix(specifier, '.' + ext) === '/app' ) } } const mod = this.#modules.get(specifier) if (mod && mod.isStyle) { return true } return this.#resolverListeners.some(({ test, resolve }) => ( test.test(specifier) && this.#isAcceptHMR(resolve(specifier)) )) } #isAcceptHMR(ret: ResolveResult): boolean { return ret.acceptHMR || !!ret.asPage } /** check the page whether it supports SSR. */ #isSSRable(pathname: string): boolean { const { ssr } = this.#config if (util.isPlainObject(ssr)) { if (ssr.include) { for (let r of ssr.include) { if (!r.test(pathname)) { return false } } } if (ssr.exclude) { for (let r of ssr.exclude) { if (r.test(pathname)) { return false } } } return true } return ssr } /** lookup app deps recurively. */ lookupDeps( specifier: string, callback: (dep: DependencyDescriptor) => false | void, __tracing: Set<string> = new Set() ) { const mod = this.getModule(specifier) if (mod === null) { return } if (__tracing.has(specifier)) { return } __tracing.add(specifier) for (const dep of mod.deps) { if (callback(dep) === false) { return false } } for (const { specifier } of mod.deps) { if ((this.lookupDeps(specifier, callback, __tracing)) === false) { return false } } } }
the_stack
//#region Global Namespace /** * Global Namespace * This section includes members or types that extend the ECMAScript (JavaScript) Global object and other core objects. * @see {@link http://msdn.microsoft.com/en-us/library/bb310818(v=vs.100).aspx} */ //#region JavaScript Base Type Extensions /** * Provides extended reflection-like functionality to the base ECMAScript (JavaScript) Object object. * Object Type Extensions * @see {@link http://msdn.microsoft.com/en-us/library/bb397554(v=vs.100).aspx} */ interface ObjectConstructor { /** * Formats a number by using the invariant culture. */ getType(instance: any): Type; /** * Returns a string that identifies the run-time type name of an object. */ getTypeName(instance: any): string; } /** * Provides extensions to the base ECMAScript (JavaScript) Array functionality by adding static methods. * Array Type Extensions * @see {@link http://msdn.microsoft.com/en-us/library/bb383786(v=vs.100).aspx} */ interface ArrayConstructor { //#region Extensions /** * Adds an element to the end of an Array object. This function is static and is invoked without creating an instance of the object. * @param array * The array to add the item to. * @param item * */ add<T>(array: T[], element: T): void; /** * Copies all the elements of the specified array to the end of an Array object. */ addRange<T>(array: T[], items: T[]): void; /** * Removes all elements from an Array object. */ clear<T>(array: T[]): void; /** * Creates a shallow copy of an Array object. */ clone<T>(array: T[]): T[]; /** * Determines whether an element is in an Array object. */ contains<T>(array: T[], element: T): boolean; /** * Removes the first element from an Array object. */ dequeue<T>(array: T[]): T; /** * Adds an element to the end of an Array object. Use the add function instead of the Array.enqueue function. */ enqueue<T>(array: T[], element: T): void; /** * Performs a specified action on each element of an Array object. */ forEach<T>(array: T[], method: (element: T, index: number, array: T[]) => void, instance: any): void; /** * Searches for the specified element of an Array object and returns its index. */ indexOf<T>(array: T[], item: T, startIndex?: number): number; /** * Inserts a value at the specified location in an Array object. */ insert<T>(array: T[], index: number, item: T): void; /** * Creates an Array object from a string representation. */ parse<T>(value: string): T[]; /** * Removes the first occurrence of an element in an Array object. */ remove<T>(array: T[], item: T): boolean; /** * Removes an element at the specified location in an Array object. */ removeAt<T>(array: T[], index: number): void; //#endregion } /** * Extends the base ECMAScript (JavaScript) Number functionality with static and instance methods. * Number Type Extensions * @see {@link http://msdn.microsoft.com/en-us/library/bb310835(v=vs.100).aspx} */ interface Number { /** * Formats a number by using the invariant culture. */ format(format: string): string; /** * Formats a number by using the current culture. */ localeFormat(format: string): string; } interface NumberConstructor { /** * Returns a numeric value from a string representation of a number. This function is static and can be called without creating an instance of the object. */ parseInvariant(format: string): number; /** * Creates a numeric value from a locale-specific string. */ parseLocale(format: string): number; } /** * Provides extensions to the base ECMAScript (JavaScript) Date object. * Date Type Extensions * @see {@link http://msdn.microsoft.com/en-us/library/bb310850(v=vs.100).aspx} */ interface Date { /** * Formats a date by using the invariant (culture-independent) culture. */ format(format: string): string; /** * Formats a date by using the current culture. This function is static and can be invoked without creating an instance of the object. */ localeFormat(format: string): string; } interface DateConstructor { /** * Creates a date from a locale-specific string by using the current culture. This function is static and can be invoked without creating an instance of the object. * @exception (Debug) formats contains an invalid format. * @param value * A locale-specific string that represents a date. * @param formats * (Optional) An array of custom formats. */ parseLocale(value: string, formats?: string[]): Date; parseLocale(value: string, ...formats: string[]): Date; /** * Creates a date from a string by using the invariant culture. This function is static and can be invoked without creating an instance of the object. * @return If value is a valid string representation of a date in the invariant format, an object of type Date; otherwise, null. * @param value * A locale-specific string that represents a date. * @param formats * (Optional) An array of custom formats. */ parseInvariant(value: string, formats?: string[]): string; parseInvariant(value: string, ...formats: string[]): string; } /** * Provides static functions that extend the built-in ECMAScript (JavaScript) Function type by including exception * details and support for application-compilation modes (debug or release). * @see {@link http://msdn.microsoft.com/en-us/library/dd409270(v=vs.100).aspx} */ interface FunctionConstructor { //#region Extensions /** * Creates a delegate function that retains the context first used during an objects creation. * @see {@link http://msdn.microsoft.com/en-us/library/dd393582(v=vs.100).aspx } */ createCallback(method: Function, ...context: any[]): Function; /** * Creates a callback function that retains the parameter initially used during an object's creation. * @see {@link http://msdn.microsoft.com/en-us/library/dd409287(v=vs.100).aspx } */ createDelegate(instance: any, method: Function): Function; /** * A function that does nothing. * @see {@link http://msdn.microsoft.com/en-us/library/dd393667(v=vs.100).aspx } */ emptyMethod(): Function; /** * Validates the parameters to a method are as expected. * @see {@link http://msdn.microsoft.com/en-us/library/dd393712(v=vs.100).aspx } */ validateParameters(parameters: any, expectedParameters: Object[], validateParameterCount?: boolean): any; //#endregion } /** * Provides static functions that extend the built-in ECMAScript (JavaScript) Error type by including exception details and support for application-compilation modes (debug or release). * Error Type Extensions * @see {@link http://msdn.microsoft.com/en-us/library/bb310947(v=vs.100).aspx} */ interface ErrorConstructor { //#region Extensions /** * Creates an Error object that represents the Sys.ParameterCountException exception. */ parameterCount(message?: string): Error; /** * Creates an Error object that represents the Sys.NotImplementedException exception. */ notImplemented(message?: string): Error; /** * Creates an Error object that represents the Sys.ArgumentException exception. */ argument(paramName?: any, message?: string): Error; /** * Creates an Error object that represents the Sys.ArgumentNullException exception. */ argumentNull(paramName?: any, message?: string): Error; /** * Creates an Error object that represents the Sys.ArgumentOutOfRangeException exception. */ argumentOutOfRange(paramName?: string, actualValue?: any, message?: string): Error; /** * Creates an Error object that represents the Sys.ArgumentTypeException exception. */ argumentType(paramName?: string, actualType?: any, expectedType?: any, message?: string): Error; /** * Creates an Error object that represents the Sys.ArgumentUndefinedException exception. */ argumentUndefined(paramName?: string, message?: string): Error; /** * Creates an Error object that can contain additional error information. */ create(message?: string, errorInfo?: Object): Error; /** * Creates an Error object that represents the Sys.FormatException exception. */ format(message?: string): Error; /** * Creates an Error object that represents the Sys.InvalidOperationException exception. */ invalidOperation(message?: string): Error; //#endregion } interface Error { /** * Updates the fileName and lineNumber properties of an Error instance to indicate where the error was thrown instead of where the error was created. Use this function if you are creating custom error types. */ popStackFrame(): void; } interface String { //#region Extensions /** * Formats a number by using the invariant culture. * @returns true if the end of the String object matches suffix; otherwise, false. */ endsWith(suffix: string): boolean; /** * Removes leading and trailing white-space characters from a String object. * @returns A copy of the string with all white-space characters removed from the start and end of the string. */ trim(): string; /** * Removes trailing white-space characters from a String object. * @returns A copy of the string with all white-space characters removed from the end of the string. */ trimEnd(): string; /** * Removes leading white-space characters from a String object. * @returns A copy of the string with all white-space characters removed from the start of the string. */ trimStart(): string; //#endregion } /** * Provides extensions to the base ECMAScript (JavaScript) String object by including static and instance methods. * String Type Extensions * @see {@link http://msdn.microsoft.com/en-us/library/bb397472(v=vs.100).aspx} */ interface StringConstructor { /** * Replaces each format item in a String object with the text equivalent of a corresponding object's value. * @returns A copy of the string with the formatting applied. */ format(format: string, ...args: any[]): string; /** * Replaces the format items in a String object with the text equivalent of a corresponding object's value. The current culture is used to format dates and numbers. * @returns A copy of the string with the formatting applied. */ localeFormat(format: string, ...args: any[]): string; } /** * Provides extensions to the base ECMAScript (JavaScript) Boolean object. * Boolean Type Extensions * @see {@link http://msdn.microsoft.com/en-us/library/bb397557(v=vs.100).aspx} */ interface BooleanConstructor { //#region Extensions /** * Converts a string representation of a logical value to its Boolean object equivalent. */ parse(value: string): Boolean; //#endregion } //#endregion //#region ASP.NET Types /** * Provides a typing and type-reflection system for ECMAScript (JavaScript) object-oriented programming functionality. * Type Class * @see {@link http://msdn.microsoft.com/en-us/library/bb397568(v=vs.100).aspx} */ declare class Type { /** * Invokes a base method with specified arguments. * @returns A value of the class that the base method returns. If the base method does not return a value, no value is returned. */ callBaseMethod(instance: any, name: string, baseArguments?: any[]): any; /** * Creates a callback method, given the function to callback and the parameter to pass to it. * @return * The callback function. * * @param method * The function for which the callback method will be created. * @param context * The parameter to pass to the function. This parameter can be null, but it cannot be omitted. */ static createCallback(method: Function, context: Object): Function; /** * Creates a delegate function that keeps the context from its creation. The context defines the object instance to which the this keyword points. * @param instance * The object instance that will be the context for the function. This parameter can be null. * @param method * The function from which the delegate is created. * @return The delegate function. */ static createDelegate(instance: Object, method: Function): Function; /** * Returns the base implementation of a method from the base class of the specified instance. * @param instance * The instance for which the base method is requested. * @param name * The name of the method to retrieve as a reference. */ getBaseMethod(instance: Object, name: string): any; /** * Returns the base class of the instance. * Use the getBaseType method to retrieve the base class of the instance. */ getBaseType(): Type; /** * Returns an Array object that contains the list of interfaces that the type implements. * Use the getInterfaces function to return a list of objects that define the interfaces on a type object. * This enables you to enumerate the array to determine the object's interfaces. * * @return An Array object that contains the list of interfaces that the type implements. */ getInterfaces(): any[]; /** * Returns the name of the type of the instance. * @return A string representing the fully qualified name of the type of the instance. * @example Object.getType(c[i]).getName() */ getName(): string; /** * Returns an Array object containing references to all the root namespaces of the client application. This method is static and is invoked without creating an instance of the object. * Use the getRootNamespaces function to return an array containing references to all the root namespaces of the client application. * @return An object containing references to all the root namespaces of the client application. */ static getRootNamespaces(): any; /** * Determines whether a class implements a specified interface type. * @param interfaceType * The interface to test. * @return true if the class implements interfaceType; otherwise, false. */ implementsInterface(interfaceType: Type): boolean; /** * Determines whether an instance inherits from a specified class. * @param parentType * The fully qualified name of the class to test as a base class for the current instance. * @return true if the instance inherits from parentType; otherwise, false. */ inheritsFrom(parentType: string): boolean; /** * Initializes the base class and its members in the context of a given instance, which provides the model for inheritance and for initializing base members. * @param instance * The instance to initialize the base class for. Usually this. * @param baseArguments * (Optional) The arguments for the base constructor. Can be null. */ initializeBase(instance: any, baseArguments?: any[]): any; /** * Returns a value that indicates whether the specified type is a class. This method is static and can be invoked without creating an instance of the object. * @param type * The type to test. * @return true if the specified type is a class; otherwise, false. */ static isClass(type: any): boolean; /** * Indicates whether the specified type is an enumeration. * @param type * The type to test. * @return true if the type is an enumeration; otherwise, false. */ static isEnum(type: any): boolean; /** * Get a value that indicates whether the specified type is an integer of flags. * @param * The type to test. * @return true if the type is an integer of flags; otherwise, false. */ static isFlags(type: any): boolean; /** * Determines whether an instance implements an interface. * @param typeInstanceVar * The instance on which the interface is tested. * @return */ isImplementedBy(typeInstanceVar: any): boolean; /** * Returns a value that indicates whether an object is an instance of a specified class or of one of its derived classes. * @param instance * The object to test. * @return true if instance is an instance of the class; false if instance does not implement the interface, or if it is undefined or null. */ isInstanceOfType(instance: any): boolean; /** * Returns a value that indicates whether the specified type is an interface. This is a static member that is invoked directly without creating an instance of the class. * @param type * The type to test. * @return true if the specified type is an interface; otherwise, false. */ static isInterface(type: any): boolean; /** * Returns a value that indicates whether the specified object is a namespace. This is a static member that is invoked directly without creating an instance of the class. * @param object * The object to test. * @return true if the specified object is a namespace; otherwise, false. */ static isNamespace(object: any): boolean; /** * Returns an instance of the type specified by a type name. This is a static member that is invoked directly without creating an instance of its class. * @param typeName * A string that represents a fully qualified class name. Can be null. * @param ns * (Optional) The namespace that contains the class. * @return The class represented by typeName, or null if a class that matches typeName does not occur in the namespace. */ static parse(typeName: string, ns?: string): any; /** * Registers a class as defined by a constructor with an optional base type and interface type. * @param typeName * A string that represents the fully qualified name of the type. * @param baseType * (Optional) The base type. * @param interfaceTypes * (Optional) An unbounded array of interface type definitions that the type implements. * @return The registered type. */ registerClass(typeName: string, baseType?: any, interfaceTypes?: any[]): any; /** * Registers an enumeration. * @param name * The fully-qualified name of the enumeration. * @param flags * (Optional) true if the enumeration is a collection of flags; otherwise, false. */ registerEnum(name: string, flags?: boolean): void; /** * Registers an interface defined by a constructor. * @param typeName * A string that represents the fully qualified name of the class to be registered as an interface. * @return The registered interface. */ registerInterface(typeName: string): any; /** * Creates a namespace. This member is static and can be invoked without creating an instance of the class. * @param namespacePath * A string that represents the fully qualified namespace to register. */ static registerNamespace(namespacePath: string): void; /** * Copies members from the base class to the prototype associated with the derived class, and continues this process up the inheritance chain. This enables you to reflect on the inherited members of a derived type. * Use the resolveInheritance method to reflect on the inherited members of a derived type. * You invoke this method from the type that you want to reflect on. * The resolveInheritance method copies members from the base class to the prototype associated with the derived class, and continues this process up the inheritance chain. * If the derived type overrides a base type member, the base type member is not copied to the derived type's prototype. * After invoking a derived type's resolveInheritance method, you can examine the members of the derived type to discover all members, which includes inherited members. */ resolveInheritance(): void; } //#endregion //#region Shortcuts to commonly used APIs /** * Creates and initializes a component of the specified type. This method is static and can be called without creating an instance of the class. * @see {@link http://msdn.microsoft.com/en-us/library/bb397487(v=vs.100).aspx} * * @param type * The type of the component to create. * @param properties * (Optional) A JSON object that describes the properties and their values. * @param events * (Optional) A JSON object that describes the events and their handlers. * @param references * (Optional) A JSON object that describes the properties that are references to other components. * @param element * (Optional) The DOM element that the component should be attached to. * @returns A new instance of a component that uses the specified parameters. */ declare function $create(type: Type, properties?: any, events?: any, references?: any, element?: HTMLElement): Sys.Component; /** * Returns the specified Component object. This member is static and can be invoked without creating an instance of the class. * @see {@link http://msdn.microsoft.com/en-us/library/bb397441(v=vs.100).aspx} * @param id A string that contains the ID of the component to find. * @param parent (Optional) The component or element that contains the component to find. * @return A Component object that contains the component requested by ID, if found; otherwise, null. */ declare function $find(id: string, parent?: Sys.Component): Sys.Component; /** * Returns the specified Component object. This member is static and can be invoked without creating an instance of the class. * @see {@link http://msdn.microsoft.com/en-us/library/bb397441(v=vs.100).aspx} * @param id A string that contains the ID of the component to find. * @param parent (Optional) The component or element that contains the component to find. * @return A Component object that contains the component requested by ID, if found; otherwise, null. */ declare function $find(id: string, parent?: HTMLElement): Sys.Component; /* * Provides a shortcut to the addHandler method of the Sys.UI.DomEvent class. This member is static and can be invoked without creating an instance of the class. * @see {@link http://msdn.microsoft.com/en-us/library/bb311019(v=vs.100).aspx} * @param element The DOM element that exposes the event. * @param eventName The name of the event. * @param handler The event handler to add. * @param autoRemove (Optional) A boolean value that determines whether the handler should be removed automatically when the element is disposed. */ declare function $addHandler(element: HTMLElement, eventName: string, handler: (e: Sys.UI.DomEvent) => void, autoRemove?: boolean): void; /** * Provides a shortcut to the addHandlers method of the Sys.UI.DomEvent class. This member is static and can be invoked without creating an instance of the class. * @see {@link http://msdn.microsoft.com/en-us/library/bb384012(v=vs.100).aspx} * @param element The DOM element that exposes the event. * @param events A dictionary of events and their handlers. * @param handlerOwner (Optional) The object instance that is the context for the delegates that should be created from the handlers. * @param autoRemove (Optional) A boolean value that determines whether the handler should be removed automatically when the element is disposed. */ declare function $addHandlers(element: HTMLElement, events: { [event: string]: (e: Sys.UI.DomEvent) => void }, handlerOwner?: any, autoRemove?: boolean): void; /** * Provides a shortcut to the clearHandlers method of the Sys.UI.DomEvent class. This member is static and can be invoked without creating an instance of the class. * For details about the method that this shortcut represents, see Sys.UI.DomEvent clearHandlers Method. * @see {@link http://msdn.microsoft.com/en-us/library/bb310959(v=vs.100).aspx} * @param The DOM element that exposes the events. */ declare function $clearHandlers(element: HTMLElement): void; /** * Provides a shortcut to the getElementById method of the HTMLElement class. This member is static and can be invoked without creating an instance of the class. * @see {@link http://msdn.microsoft.com/en-us/library/bb397717(v=vs.100).aspx} * @param id * The ID of the DOM element to find. * @param element * The parent element to search. The default is the document element. * @return * The HTMLElement */ declare function $get(id: string, element?: HTMLElement): HTMLElement; /** * Provides a shortcut to the removeHandler method of the Sys.UI.DomEvent class. This member is static and can be invoked without creating an instance of the class. * @see {@link http://msdn.microsoft.com/en-us/library/bb397510(v=vs.100).aspx} * @param element The DOM element that exposes the event. * @param eventName The name of the DOM event. * @param handler The event handler to remove. */ declare function $removeHandler(element: HTMLElement, eventName: string, handler: (e: Sys.UI.DomEvent) => void): void; //#endregion //#endregion //#region Sys Namespace /** * Represents the root namespace for the Microsoft Ajax Library, which contains all fundamental classes and base classes. * @see {@link http://msdn.microsoft.com/en-us/library/bb397702(v=vs.100).aspx} */ declare module Sys { //#region Classes /** * Provides a run-time object that exposes client events and manages client components that are registered with the application. * The members of this object are available globally after the client application has been initialized. * The members can be invoked without creating an instance of the class. * @see {@link http://msdn.microsoft.com/en-us/library/bb384161(v=vs.100).aspx} */ interface Application extends Component, IContainer { //#region Constructors constructor(): void; //#endregion //#region Events /** * Raised after all scripts have been loaded but before objects are created. */ add_init(handler: (sender: Application, eventArgs: EventArgs) => void): void; /** * Raised after all scripts have been loaded but before objects are created. */ remove_init(handler: (sender: Application, eventArgs: EventArgs) => void): void; /** * Raised after all scripts have been loaded and after the objects in the application have been created and initialized. */ add_load(handler: (sender: Application, eventArgs: ApplicationLoadEventArgs) => void): void; /** * Raised after all scripts have been loaded and after the objects in the application have been created and initialized. */ remove_load(handler: (sender: Application, eventArgs: ApplicationLoadEventArgs) => void): void; /** * Occurs when the user clicks the browser's Back or Forward button. */ add_navigate(handler: (sender: Application, eventArgs: HistoryEventArgs) => void): void; /** * Occurs when the user clicks the browser's Back or Forward button. */ remove_navigate(handler: (sender: Application, eventArgs: HistoryEventArgs) => void): void; /** * Raised before all objects in the client application are disposed, typically when the DOM window.unload event is raised. */ add_unload(handler: Function): void; /** * Raised before all objects in the client application are disposed, typically when the DOM window.unload event is raised. */ remove_unload(handler: Function): void; //#endregion //#region Methods /** * Registers a component with the application and initializes it if the component is not already initialized. */ addComponent(component: any): void; /** * Instructs the application to start creating components. */ beginCreateComponents(): void; /** * Creates a history point and adds it to the browser's history stack. */ addHistoryPoint(state: Object, title?: string): void; /** * Called by the Sys.Application.beginUpdate Method to indicate that the process of setting component properties of the application has begun. */ beginUpdate(): void; /** * Releases resources and dependencies held by the client application. */ dispose(): void; /** * Releases resources and dependencies associated with an element and its child nodes. * @param element * The element to dispose. * @param childNodesOnly * A boolean value used to determine whether to dispose of the element and its child nodes or to dispose only its child nodes. */ disposeElement(element: Element, childNodesOnly: boolean): void; /** * Instructs the application to finalize component creation. */ endCreateComponents(): void; /** * Called by the Sys.Application.endCreateComponents Method to indicate that the process of updating the application has completed. */ endUpdate(): void; /** * Returns the specified Component object. This member is static and can be invoked without creating an instance of the class. * @return A Component object that contains the component requested by ID, if found; otherwise, null. */ findComponent(id: string, parent?: Sys.Component): Sys.Component; /** * Returns the specified Component object. This member is static and can be invoked without creating an instance of the class. * @return A Component object that contains the component requested by ID, if found; otherwise, null. */ findComponent(id: string, parent?: HTMLElement): Sys.Component; /** * Returns an array of all components that have been registered with the application by using the addComponent method. This member is static and can be invoked without creating an instance of the class. */ getComponents(): Sys.Component[]; /** * This function supports the client-script infrastructure and is not intended to be used directly from your code. */ initialize(): void; /** * Called by a referenced script to indicate that it has been loaded. This API is obsolete. You no longer need to call this method in order to notify the Microsoft Ajax Library that the JavaScript file has been loaded. */ notifyScriptLoaded(): void; /** * Raises the load event. This member is static and can be invoked without creating an instance of the class. */ raiseLoad(): void; /** * Raises the Sys.INotifyPropertyChange.propertyChanged event. */ raisePropertyChanged(propertyName: string): void; /** * Registers with the application an object that will require disposing. This member is static and can be invoked without creating an instance of the class. */ registerDisposableObject(object: any): void; /** * Removes the object from the application and disposes the object if it is disposable. This member is static and can be invoked without creating an instance of the class. */ removeComponent(component: Component): void; /** * Unregisters a disposable object from the application. This member is static and can be invoked without creating an instance of the class. */ unregisterDisposableObject(object: any): void; /** * Called by the Sys.Application.endUpdate method as a placeholder for additional logic. */ updated(): void; //#endregion //#region Properties /** * Gets or sets a value that indicates whether the Web application supports history point management. */ get_enableHistory(): boolean; /** * Gets or sets a value that indicates whether the Web application supports history point management. * @param value * true to allow the Web application to support history points, or false to not allow history points. */ set_enableHistory(value: boolean): void; /** * Gets a value that indicates whether the application is in the process of creating components. This member is static and can be invoked without creating an instance of the class. */ get_isCreatingComponents(): boolean; /** * Gets a value that indicates whether the application is in the process of disposing its resources. This member is static and can be invoked without creating an instance of the class. */ get_isDisposing(): boolean; //#endregion } var Application: Application; /** * Provides information about the current Web browser. * The Sys.Browser object determines which browser is being used and provides some information about it. You can use this object to help customize your code to the unique requirements or capabilities of the browser. * @see {@link http://msdn.microsoft.com/en-us/library/cc679064(v=vs.100).aspx} */ interface Browser { //#region Fields /** * Gets an object that represents the user agent of the browser. */ agent: any; /** * Gets a value that indicates the document compatibility mode of the browser. * @return * */ documentMode: number; /* * Gets a value that indicates whether the browser supports debug statements. * @return * True if the browser supports debug statements */ hasDebuggerStatement: boolean; /** * Gets the name of the browser. * @return * The name of the browser */ name: string; /* * Gets the version number of the browser. * @return * The version of the browser */ version: number; //#endregion } export function Browser(): Sys.Browser; /** * Provides the base class for the Control and Behavior classes, and for any other object whose lifetime should be managed by the ASP.NET AJAX client library. * @see {@link http://msdn.microsoft.com/en-us/library/bb397516(v=vs.100).aspx} */ class Component { //#region Constructors /** * When overridden in a derived class, initializes an instance of that class and registers it with the application as a disposable object. */ constructor(); //#endregion //#region Events /** * Raised when the dispose method is called for a component. */ add_disposing(handler: Function): void; /** * Raised when the dispose method is called for a component. */ remove_disposing(handler: Function): void; /** * Raised when the raisePropertyChanged method of the current Component object is called. */ add_propertyChanged(handler: Function): void; /** * Raised when the raisePropertyChanged method of the current Component object is called. */ remove_propertyChanged(handler: Function): void; //#endregion //#region Methods /** * Called by the create method to indicate that the process of setting properties of a component instance has begun. */ beginUpdate(): void; /** * Creates and initializes a component of the specified type. This method is static and can be called without creating an instance of the class. * @param type * The type of the component to create. * @param properties * (Optional) A JSON object that describes the properties and their values. * @param events * (Optional) A JSON object that describes the events and their handlers. * @param references * (Optional) A JSON object that describes the properties that are references to other components. * @param element * (Optional) The DOM element that the component should be attached to. * * @returns A new instance of a component that uses the specified parameters. */ static create(type: Type, properties?: any, events?: any, references?: any, element?: HTMLElement): Sys.Component; /** * Called by the create method to indicate that the process of setting properties of a component instance has finished. * This method is called by the create method ($create). * Sets the isUpdating property of the current Component object to false, calls the initialize method if it has not already been called, and then calls the updated method. */ endUpdate(): void; /** * Initializes the current Component object. * The initialize method sets the isInitialized property of the current Component object to true. This function is called by the create method ($create) and overridden in derived classes to initialize the component. */ initialize(): void; /** * Raises the propertyChanged event for the specified property. * @param propertyName * The name of the property that changed. */ raisePropertyChanged(propertyName: string): void; /** * Called by the endUpdate method as a placeholder for additional logic in derived classes. * Override the updated method in a derived class to add custom post-update logic. */ updated(): void; /** * Raises the disposing event of the current Component and removes the component from the application. */ dispose(): void; //#endregion //#region Properties /** * Gets an EventHandlerList object that contains references to all the event handlers that are mapped to the current component's events. * This member supports the client-script infrastructure and is not intended to be used directly from your code. * @return * An EventHandlerList object that contains references to all the events and handlers for this component. */ get_events(): any; /** * Gets the ID of the current Component object. * @return * The id */ get_id(): string; /** * Sets the ID of the current Component object. * @param value A string that contains the ID of the component. */ set_id(value: string): void; /** * Gets a value indicating whether the current Component object is initialized. * @return * true if the current Component is initialized; otherwise, false. */ get_isInitialized(): boolean; /** * Gets a value indicating whether the current Component object is updating. * @return * true if the current Component object is updating; otherwise, false. */ get_isUpdating(): boolean; //#endregion } /** * Represents a culture definition that can be applied to objects that accept a culture-related setting. * @see {@link http://msdn.microsoft.com/en-us/library/bb384004(v=vs.100).aspx} */ class CultureInfo { //#region Constructors /** * Initializes a new instance of the Sys.CultureInfo class. * @param name * The culture value (locale) that represents a language and region. * @param numberFormat * A culture-sensitive numeric formatting string. * @param dateTimeFormat * A culture-sensitive date formatting string. */ constructor(name: string, numberFormat: string, dateTimeFormat: string); //#endregion //#region Properties /** * Gets an object that contains an array of culture-sensitive formatting and parsing strings values that can be applied to Number type extensions. * Use the numberFormat field to retrieve an object that contains an array of formatting strings that are based on the current culture or on the invariant culture. * Each formatting string can be used to specify how to format Number type extensions. * @return An object that contains an array of culture-sensitive formatting strings. */ numberFormat: string[]; /** * Gets the culture value (locale) that represents a language and region. * @return The culture value (locale) that represents a language and region. */ name: string; /** * Gets the globalization values of the invariant culture as sent by the server. This member is static and can be invoked without creating an instance of the class. * The InvariantCulture field contains the following fields associated with the invariant (culture-independent) culture: name, dateTimeFormat, and numberFormat. * @return A CultureInfo object. */ static InvariantCulture: CultureInfo; /** * Gets the globalization values of the current culture as sent by the server. This member is static and can be invoked without creating an instance of the class. * The CurrentCulture field contains the following fields associated with the current culture: name, dateTimeFormat, and numberFormat. * @return A Sys.CultureInfo object. */ static CurrentCulture: CultureInfo; /** * Gets an object that contains an array of culture-sensitive formatting and parsing string values that can be applied to Date type extensions. * Use the dateTimeFormat field to retrieve an object that contains an array of formatting strings that are based on the current culture or on the invariant culture. * Each formatting string can be used to specify how to format Date type extensions. * @return An object that contains an array of culture-sensitive formatting strings. */ dateTimeFormat: string[]; //#endregion } /** * Provides debugging and tracing functionality for client ECMAScript (JavaScript) code. This class is static and can be invoked directly without creating an instance of the class. * @see {@link http://msdn.microsoft.com/en-us/library/bb397422(v=vs.100).aspx} */ class Debug { //#region Constructors /** * Initializes a new instance of the Sys.Debug class. */ constructor(); //#endregion //#region Methods /** * Checks for a condition, and if the condition is false, displays a message and prompts the user to break into the debugger. * When you call the assert method in your code, express the success of an operation as true or false and use that value for condition. If the operation fails (if condition is false), the assert logic is executed. * The assert method should be used to catch developer errors. To respond to user errors and to run-time error conditions such as network errors or permission failures, throw an exception. * Debugging behavior, requirements, and the output of trace messages vary with different browsers. For more information, see Debugging and Tracing Ajax Applications Overview. * * @param condition * true to continue to execute code; false to display message and break into the debugger. * @param message * (Optional) The message to display. The default is an empty string (""). * @param displayCaller * (Optional) true to indicate that the name of the function that is calling assert should be displayed in the message. The default is false. */ static assert(condition: boolean, message?: string, displayCaller?: boolean): void; /** * Clears all trace messages from the trace console. */ static clearTrace(): void; /** * Displays a message in the debugger's output window and breaks into the debugger. * @param message * The message to display. */ static fail(message: string): void; /** * Appends a text line to the debugger console and to the trace console, if available. * @param text * The text to display. */ static trace(text: string): void; /** * Dumps an object to the debugger console and to the trace console, if available. * @param object * The object to dump. * @param name * (Optional) The name of the object. */ static traceDump(object: any, name?: string): void; //#endregion } /** * Describes a change in a collection. * @see {@link http://msdn.microsoft.com/en-us/library/dd393798(v=vs.100).aspx} */ class CollectionChange { //#region Constructors /** * Creates a CollectionChange object based on the supplied parameters. * @param action * A NotifyCollectionChangedAction enumeration value. * @param newItems * (Optional) The items that were added when the action is add or replace. * @param newStartingIndex * (Optional) An integer that represents the index where new items have been inserted. * @param oldItems * (Optional) The items that were removed when the action is remove or replace. * @param oldStartingIndex * (Optional) An integer that represents the index where old items have been removed. */ constructor(action: NotifyCollectionChangedAction, newItems: any[], newStartingIndex: number, oldItems: any[], oldStartingIndex: number); //#endregion //#region Fields /** * Gets a NotifyCollectionChangedAction object that contains the change action enumeration value. * @return A NotifyCollectionChangedAction object. */ action: NotifyCollectionChangedAction; /** * @return An array of items that were added. */ newItems: any[]; /** * The index where new items have been inserted. * @return An integer that represents the index where new items have been inserted. */ newStartingIndex: number; /** * The items that were removed when the NotifyCollectionChangedAction object is set to remove. * @return An array containing the items that were removed. */ oldItems: any[]; /** * Gets the index where old items have been removed. * @return An integer that represents the index where old items have been removed. */ oldStartingIndex: number; //#endregion } /** * Adds update and management functionality to target objects such as arrays, DOM elements, and objects. * The Sys.Observer class is based on the Observer pattern. The Sys.Observer class maintains a list of interested dependents (observers) in a separate object (the subject). * All methods that are contained in the Sys.Observer class are static. * In order to be used with the Sys.Observer class, an object must be an object, array, or DOM element. * @see {@link http://msdn.microsoft.com/en-us/library/dd393710(v=vs.100).aspx} */ class Observer { //#region Methods /** * Adds an item to the collection in an observable manner. * @param target * The array to which an item will be added. * @param item * The item to add. */ static add(target: any[], item: any): void; /** * Adds an event handler to the target. * @param target The array to which an event handler will be added. * @param handler The event handler. */ static addCollectionChanged(target: any, handler: Function): void; /** * Adds an observable event handler to the target. * @param eventName A string that contains the event name. * @param handler The added function. */ static addEventHandler(target: any, eventName: string, handler: Function): void; /** * Adds a propertyChanged event handler to the target. * @param target The object to observe. * @param handler The function handler to add. */ static addPropertyChanged(target: any, handler: Function): void; /** * Adds items to the collection in an observable manner. * @param target The array to which items will be added. * @param items The array of items to add. */ static addRange(target: any[], items: any[]): void; /** * Begins the process of updating the target object. * @param target The object to update. */ static beginUpdate(target: any): void; /** * Clears the array of its elements in an observable manner. * @param target The array to clear. */ static clear(target: any): void; /** * Ends the process of updating the target object. * @param target The object being updated. */ static endUpdate(target: any): void; /** * Inserts an item at the specified index in an observable manner. * @param target The array to which the item is inserted. * @param index A number that represents the index where the item will be inserted. * @param item The item to insert. */ static insert(target: any, index: number, item: any): void; /** * Makes an object directly observable by adding observable methods to it. * @param target The object, array, or DOM element to make observable. * @return The observable object. * @see {@link http://msdn.microsoft.com/en-us/library/dd393633(v=vs.100).aspx} */ static makeObservable(target: any): any; /** * Raises the collectionChanged event. * @param target The collection to which an event is raised. * @param changes A Sys.CollectionChange object that contains the list of changes that were performed on the collection since the last event. */ static raiseCollectionChanged(target: any[], changes: Sys.CollectionChange): void; /** * Raises an observable event on the target. * @param target The target object. * @param eventName A string that contains the event name. * @param eventArgs A Sys.EventArgs object used to pass event argument information. */ static raiseEvent(target: any, eventName: string, eventArgs: Sys.EventArgs): void; /** * Raises a propertyChanged notification event. * @param target The object to which an event is raised. * @param propertyName The name of the property that changed. */ static raisePropertyChanged(target: any, propertyName: string): void; /** * Removes the first occurrence of an item from the array in an observable manner. * @param target The array to which the item will be removed. * @param item The item to remove. * @return true if the item is found in the array. Otherwise false. */ static remove(target: any[], item: any): boolean; /** * Removes the item at the specified index from the array in an observable manner. * @param target The array to which an item is removed. * @param index A number that represents the index of the item to remove. */ static removeAt(target: any[], index: number): void; /** * Removes the collectionChanged event handler from the target. * @param target The array from which the collectionChanged event handler is removed. * @param handler The function to remove. */ static removeCollectionChanged(target: any, handler: Function): void; /** * Removes a propertyChanged event handler from the target. * @param target The object to observe. * @param handler The event handler to remove. */ static removeEventHandler(target: any, handler: Function): void; /** * Sets a property or field on the target in an observable manner. * The raisePropertyChanged method is called after the setValue method set the value of the target object property. * @param target The object to which the property is set. * @param propertyName A string that contains the name of the property or field to set. * @param value The value to set. */ static setValue(target: any, propertyName: string, value: any): void; //#endregion //#region Properties /** * Indicates that the target is being updated. * @param target The target object to update. * @return true if given target argument is currently updating; otherwise false. */ static isUpdating(target: any): boolean; //#endregion } /** * Provides static, culture-neutral exception messages that are used by the Microsoft Ajax Library framework. * @see {@link http://msdn.microsoft.com/en-us/library/bb397705(v=vs.100).aspx} * This type supports the .NET Framework infrastructure and is not intended to be used directly from your code. */ class Res { //#region Fields /** * @return "Actual value was {0}." */ static actualValue: string; /** * @return "The application failed to load within the specified time out period." */ static appLoadTimedout: string; /** * @return "Value does not fall within the expected range." */ static argument: string; /** * @return "Value cannot be null." */ static argumentNull: string; /** * @return "Specified argument was out of the range of valid values. */ static argumentOutOfRange: string; /** * @return "Object cannot be converted to the required type." */ static argumentType: string; /** * @return "Object of type '{0}' cannot be converted to type '{1}'." */ static argumentTypeWithTypes: string; /** * @return "Value cannot be undefined." */ static argumentUndefined: string; /** * @return "Assertion Failed: {0}" */ static assertFailed: string; /** * @return "Assertion Failed: {0}\r\nat {1}" */ static assetFailedCaller: string; /** * @return "Base URL does not contain ://." */ static badBaseUrl1: string; /** * @return "Base URL does not contain another /." */ static badBaseUrl2: string; /** * @return "Cannot find last / in base URL." */ static badBaseUrl3: string; /** * @return "{0}\r\n\r\nBreak into debugger?" */ static breakIntoDebugger: string; /** * @return "Cannot abort when executor has not started." */ static cannotAbortBeforeStart: string; /** * @return "Cannot call {0} when responseAvailable is false." */ static cannotCallBeforeResponse: string; /** * @return "Cannot call {0} once started." */ static cannotCallOnceStarted: string; /** * @return "Cannot call {0} outside of a completed event handler." */ static cannotCallOutsideHandler: string; /** * @return "Cannot deserialize empty string." */ static cannotDeserializeEmptyString: string; /** * @return "Cannot serialize non-finite numbers." */ static cannotSerializeNonFiniteNumbers: string; /** * @return "The id property can't be set on a control." */ static controlCantSetId: string; /** * @return "'{0}' is not a valid value for enum {1}." */ static enumInvalidValue: string; /** * @return "Handler was not added through the Sys.UI.DomEvent.addHandler method. */ static eventHandlerInvalid: string; /** * @return "One of the identified items was in an invalid format." */ static format: string; /** * @return "The string was not recognized as a valid Date." */ static formatBadDate: string; /** * @return "Format specifier was invalid." */ static formatBadFormatSpecifier: string; /** * @return "Input string was not in a correct format." */ static formatInvalidString: string; /** * @return "Could not create a valid Sys.Net.WebRequestExecutor from: {0}." */ static invalidExecutorType: string; /** * @return "httpVerb cannot be set to an empty or null string." */ static invalidHttpVerb: string; /** * @return "Operation is not valid due to the current state of the object." */ static invalidOperation: string; /** * @return "Value must be greater than or equal to zero." */ static invalidTimeout: string; /** * @return "Cannot call invoke more than once." */ static invokeCalledTwice: string; /** * @return "The method or operation is not implemented." */ static notImplemented: string; /** * @return "Cannot call executeRequest with a null webRequest." */ static nullWebRequest: string; //#endregion } /** * Provides a mechanism to concatenate strings. * The StringBuilder class represents a mutable string of characters and provides a mechanism to concatenate a sequence of strings. * @see {@link http://msdn.microsoft.com/en-us/library/bb310852(v=vs.100).aspx} */ class StringBuilder { //#region Constructors /** * Creates a new instance of StringBuilder and optionally accepts initial text to concatenate. You can specify a string in the optional initialText parameter to initialize the value of the StringBuilder instance. * @param initialText * (Optional) The string that is used to initialize the value of the instance. If the value is null, the new StringBuilder instance will contain an empty string (""). */ constructor(initialText?: string); //#endregion //#region Methods /** * Appends a copy of a specified string to the end of the Sys.StringBuilder instance. * Use the append method to append a copy of a specified string to the end of a StringBuilder instance. If text is an empty string, null, or undefined, the StringBuilder instance remains unchanged. * @param text * The string to append to the end of the StringBuilder instance. */ append(text: string): void; /** * Appends a string with a line terminator to the end of the Sys.StringBuilder instance. * Use the appendLine method to append a specified string and a line terminator to the end of a Stringbuilder instance. The line terminator is a combination of a carriage return and a newline character. If no string is specified in text, only the line terminator is appended. * @param text * (Optional) The string to append with a line terminator to the end of the StringBuilder instance. */ appendLine(text: string): void; /** * Clears the contents of the Sys.StringBuilder instance. * Use the clear method to clear the StringBuilder instance of its current contents. */ clear(): void; /** * Determines whether the Sys.StringBuilder object has content. * Use the isEmpty method to determine whether a StringBuilder instance has any content. If you append an empty string, null, or an undefined value to an empty StringBuilder instance, the instance remains empty and unchanged. * @return true if the StringBuilder instance contains no elements; otherwise, false. */ isEmpty(): boolean; /** * Creates a string from the contents of a Sys.StringBuilder instance, and optionally inserts a delimiter between each element of the created string. * Use the toString method to create a string from the contents of a StringBuilder instance. Use the toString method with the optional separator parameter to insert a specified string delimiter between each element of the created string. * @param separator * (Optional) A string to append between each element of the string that is returned. * @return A string representation of the StringBuilder instance. If separator is specified, the delimiter string is inserted between each element of the returned string. */ toString(separator?: string): string; //#endregion } //#endregion //#region Enumerations /** * Describes how a collection has changed. * @see {@link http://msdn.microsoft.com/en-us/library/dd393774(v=vs.100).aspx} */ enum NotifyCollectionChangedAction { /** * The integer 0, indicating the changed action to the collection is add. */ add = 0, /** * The integer 1, indicating the changed action to the collection is remove. */ remove = 1, /** * The integer 2, indicating the changed action to the collection is reset. */ reset = 2 } //#endregion //#region Interfaces /** * Provides a common interface for all components that can contain other components. */ interface IContainer { //#region Methods /** * Adds a Component object to the current container. * Implement this method for an object that will contain one or more component objects in order to programmatically add components to that container. * @param component * The Component object to add. */ addComponent(component: Component): void; /** * Returns the specified Component instance. * Implement this method for an object that will contain one or more component objects to access components within that container. * @param id * The ID of the Component object to search for. * @return The Component instance with the specified ID. */ findComponent(id: string): Component; /** * Returns an array of all objects in the current container that inherit from Component. * Implement this method for an object that will contain one or more component objects so that the components in that container are available. Types that implement this method should return a copy of the list of components so that modifying the array does not change the contents of the container. * @return An array of all objects in the current container that inherit from Component. */ getComponents(): Component[]; /** * Removes a Component object from the current container. * @param component * The Component object to remove. */ removeComponent(component: Component): void; //#endregion } /** * Provides a common interface for the application-defined tasks of closing, releasing, or resetting resources held by instances of a registered Microsoft Ajax Library class. * Implement the IDisposable interface to provide a common interface for closing or releasing resources held by instances of your registered Microsoft Ajax Library class. * You register an interface by when you register the class by calling the Type.registerClass method. You specify IDisposable in the interfaceTypes parameter when you call Type.registerClass. */ interface IDisposable { //#region Methods /** * Releases resources held by an object that implements the Sys.IDisposable interface. * Implement the dispose method to close or release resources held by an object, or to prepare an object for reuse. */ dispose(): void; //#endregion } /** * Indicates that the type that implements the interface provides disposing notifications. * Implement this interface if the class must notify other objects when it is releasing resources. The base component class already implements this interface. Therefore, typically this interface is already available. */ interface INotifyDisposing { //#region Events /** * Occurs when an object's resources are released. * @param handler * The name of the event handler for the disposing event. */ add_disposing(handler: Function): void; /** * Occurs when an object's resources are released. * @param handler * The name of the event handler for the disposing event. */ remove_disposing(handler: Function): void; //#endregion } /** * Defines the propertyChanged event. */ interface INotifyPropertyChange { //#region Events /** * Occurs when a component property is set to a new value. * @param handler * The name of the event handler for the propertyChanged event. */ add_propertyChanged(handler: Function): void; /** * Occurs when a component property is set to a new value. * @param handler * The name of the event handler for the propertyChanged event. */ remove_propertyChanged(handler: Function): void; //#endregion } //#endregion //#region Event Args /* * Used by the Application class to hold event arguments for the load event. * @see {@link http://msdn.microsoft.com/en-us/library/bb383787(v=vs.100).aspx} */ class ApplicationLoadEventArgs { //#region Constructors /** * Initializes a new instance of the ApplicationLoadEventArgs class. * @param components * The list of components that were created since the last time the load event was raised. * @param isPartialLoad * true to indicate that the event is a partial-page update. */ constructor(components: any, isPartialLoad: boolean); //#endregion //#region Properties /** * Gets an array of all the components that were created since the last time the load event was raised. * @return An array of all the components that were created since the last time the load event was raised. */ get_components(): Component[]; /** * Returns a value that indicates whether the page is engaged in a partial-page update. * @return true if the page is engaged in a partial-page update; otherwise, false. */ get_isPartialLoad(): boolean; //#endregion } /** * Provides a base class for classes that are used by event sources to pass event argument information. * The EventArgs class is a base class and not intended to be used directly. Override this constructor to provide specific functionality. * @see {@link http://msdn.microsoft.com/en-us/library/bb383795(v=vs.100).aspx} */ class EventArgs { //#region Constructors /** * Initializes a new instance of the EventArgs class. */ constructor(); //#endregion //#region Fields /** * A static object of type EventArgs that is used as a convenient way to specify an empty EventArgs instance. */ static Empty: EventArgs; /** * An object of type EventArgs that is used as a convenient way to specify an empty EventArgs instance. */ Empty: EventArgs; //#endregion } /** * Provides a class for command events. * Event handlers can use the cancel property to cancel the operation in progress. The semantics of canceling an event depend on the event source. * @see {@link http://msdn.microsoft.com/en-us/library/dd393715(v=vs.100).aspx */ class CommandEventArgs extends EventArgs { //#region Constructors constructor(commandName: string, commandArgument: any, commandSource: any); //#endregion //#region Properties /** * Gets a string that specifies the command name. */ get_commandName(): string; /** * Gets a value that represents the command argument. */ get_commandArgument(): any; /** * Gets a value that represents the command source. */ get_commandSource(): any; //#endregion } /** * Provides the base class for events that can be canceled. * @see {@link http://msdn.microsoft.com/en-us/library/bb311009(v=vs.100).aspx} */ class CancelEventArgs extends EventArgs { //#region Constructors /** * Initializes a new instance of the CancelEventArgs class. */ constructor(); //#endregion //#region Properties /** * true to request that the event be canceled; otherwise, false. The default is false. */ set_cancel(value: boolean): void; /* * true to request that the event be canceled; otherwise, false. The default is false. * @return if the event is to be canceled; otherwise, false. */ get_cancel(): boolean; //#endregion } /** * This class is used by the Sys.Application Class to hold event arguments for the navigate event. * @see {@link http://msdn.microsoft.com/en-us/library/cc488008(v=vs.100).aspx} */ class HistoryEventArgs extends EventArgs { //#region Constructors /** * For a live code example that demonstrates this event in action, and for a view of how this event is used in code, see Managing Browser History Using Client Script. * @param state Object. A collection of key/value pairs that represent the state data. This data will be added to the main state to form the global state of the new history point. */ constructor(state: any); //#endregion //#region Methods /** * Object. A collection of name/value pairs that represent the state of a Web page. * The state object stores the data that is required in order to restore a Web page to a specified application state. * @return Object. A collection of name/value pairs that represent the state of a Web page. */ get_State(): any; //#endregion } /** * Describes how the collection was changed. * @see {@link http://msdn.microsoft.com/en-us/library/dd393665(v=vs.100).aspx} */ class NotifyCollectionChangedEventArgs extends EventArgs { //#region Constructors /** * Initializes a new instance of the CancelEventArgs class. * @param changes * A CollectionChange object that contains an array of changes that were performed on the collection since the last event. */ constructor(changes: CollectionChange); //#endregion //#region Properties /** * Gets an array of changes that were performed on the collection since the last event. * @return An array of CollectionChange objects that were performed on the collection since the last event. */ get_changes(): CollectionChange[]; //#endregion } /** * Used by the propertyChanged event to indicate which property has changed. * @see {@link http://msdn.microsoft.com/en-us/library/bb310957(v=vs.100).aspx} */ class PropertyChangedEventArgs extends EventArgs { //#region Constructors /** * Initializes a new instance of the PropertyChangedEventArgs class. * @param propertyName * The name of the property that changed. */ constructor(propertyName: string); //#endregion //#region Methods /** * Gets the name of the property that changed. * Use the propertyName property to determine the name of the property that changed. * @return A string that contains the name of the property that changed. */ propertyName(): string; //#endregion } //#endregion //#region Exception Types // Really not a types ///** //* Raised when a function or method is invoked and at least one of the passed arguments does not meet the parameter specification of the called function or method. //*/ //class ArgumentException { //} ///** //* Raised when an argument has an invalid value of null. //*/ //class ArgumentNullException { //} ///** //* Raised when an argument value is outside an acceptable range. //*/ //class ArgumentOutOfRangeException { //} ///** //* Raised when a parameter is not an allowed type. //*/ //class ArgumentTypeException { //} ///** //* Raised when an argument for a required method parameter is undefined. //*/ //class ArgumentUndefinedException { //} ///** //* //*/ //class FormatException { //} ///** //* Raised when a call to a method has failed, but the reason was not invalid arguments. //*/ //class InvalidOperationException { //} ///** //* Raised when a requested method is not supported by an object. //*/ //class NotImplementedException { //} ///** //* Raised when an invalid number of arguments have been passed to a function. //*/ //class ParameterCountException { //} ///** //* Raised by the Microsoft Ajax Library framework when a script does not load successfully. This exception should not be thrown by the developer. //*/ //class ScriptLoadFailedException { //} //#endregion //#region Sys.Net Namespace /** * The Sys.Net namespace contains classes that manage communication between AJAX-enabled ASP.NET client applications and Web services on the server. For more information, see Using Web Services in ASP.NET AJAX. The Sys.Net namespace is part of the Microsoft Ajax Library. * @see {@link http://msdn.microsoft.com/en-us/library/bb310860(v=vs.100).aspx} */ module Net { /** * Generated Proxy Classes * Enables your application to call Web services asynchronously by using ECMAScript (JavaScript). * @see {@link http://msdn.microsoft.com/en-us/library/bb310823(v=vs.100).aspx} */ class WebServiceProxy { static invoke( servicePath: string, methodName: string, useGet?: boolean, params?: any, onSuccess?: (result: string, eventArgs: EventArgs) => void, onFailure?: (error: WebServiceError) => void, userContext?: any, timeout?: number, enableJsonp?: boolean, jsonpCallbackParameter?: string): WebRequest; } class WebServiceError { get_errorObject(): any; get_exceptionType(): any; get_message(): string; get_stackTrace(): string; get_statusCode(): number; get_timedOut(): boolean; } /** * Contains information about a Web request that is ready to be sent to the current Sys.Net.WebRequestExecutor instance. * This class represents the type for the second parameter of the callback function added by the add_invokingRequest method. * The callback function is called before the Web request is routed to the current instance of the WebRequestExecutor class. * * @see {@link http://msdn.microsoft.com/en-us/library/bb397488(v=vs.100).aspx} */ class NetworkRequestEventArgs { //#region Constructors /** * Initializes a new instance of the Sys.Net.NetworkRequestEventArgs. class. * @param value * The current WebRequest instance. */ constructor(value: WebRequest); //#endregion //#region Methods //#endregion //#region Properties /** * Gets the Web request to be routed to the current Sys.Net.WebRequestExecutor instance. * Use this property to inspect the contents of a Web request before it is routed to the current instance of the Sys.Net.WebRequestExecutor class. * You can access the Web request instance from the handler that is called before the request is routed. * This event handler is added by using the add_invokingRequest method. * @return * The WebRequest. */ get_webRequest(): WebRequest; //#endregion } /** * Provides the script API to make a Web request. * @see {@link http://msdn.microsoft.com/en-us/library/bb310979(v=vs.100).aspx} */ class WebRequest { //#region Constructors /** * Initializes a new instance of the Sys.Net.WebRequest class. */ constructor(); //#endregion //#region Members get_url(): string; set_url(value: string): void; get_httpVerb(): string; set_httpVerb(value: string): void; get_timeout(): number; set_timeout(value: number): void; get_body(): string; set_body(value: string): void; get_headers(): { [key: string]: string; }; get_userContext(): any; set_userContext(value: any): void; get_executor(): WebRequestExecutor; set_executor(value: WebRequestExecutor): void; /** * Registers a handler for the completed request event of the Web request. * @see {@link http://msdn.microsoft.com/en-us/library/bb310841(v=vs.100).aspx} */ add_completed(handler: (reference: any, eventArgs: Sys.EventArgs) => void): void; /** * Removes the event handler added by the add_completed method. * @see {@link http://msdn.microsoft.com/en-us/library/bb397454(v=vs.100).aspx} */ remove_completed(handler: (reference: any, eventArgs: Sys.EventArgs) => void): void; /** * Gets the resolved URL of the Sys.Net.WebRequest instance. * @returns The resolved URL that the Web request is directed to. */ getResolvedUrl(): string; /** * Executes a Web request. */ invoke(): void; /** * Raises the completed event for the associated Sys.Net.WebRequest instance. * @param eventArgs * The value to pass to the Web request completed event handler. */ completed(eventArgs: Sys.EventArgs): void; //#endregion } /** * Provides the abstract base class from which network executors derive. * @see {@link http://msdn.microsoft.com/en-us/library/bb397434(v=vs.100).aspx} */ class WebRequestExecutor { //#region Constructors /** * Initializes a Sys.Net.WebRequestExecutor instance when implemented in a derived class. */ constructor(); //#endregion //#region Methods /** * Stops the pending network request issued by the executor. * The specifics of aborting a request vary depending on how an executor is implemented. * However, all executors that derive from WebRequestExecutor must set their state to aborted and must raise the completed event of the associated Sys.Net.WebRequest object. * The executor properties do not contain consistent data after abort has been called. */ abort(): void; /** * Instructs the executor to execute a Web request. * When this method is called, the executor packages the content of the Web request instance and initiates processing. * This method is intended to be used by a custom executor. If you are implementing a custom executor, you instantiate the executor, assign it to the Web request instance, and then invoke the method on the executor instance. * @see {@link http://msdn.microsoft.com/en-us/library/bb383834(v=vs.100).aspx} */ executeRequest(): void; /** * Gets all the response headers for the current request. * If a request finished successfully and with valid response data, this method returns all the response headers. * @return All the response headers * @see {@link http://msdn.microsoft.com/en-us/library/bb310805(v=vs.100).aspx} */ getAllResponseHeaders(): string; /** * Gets the value of the specified response header. * @return The specified response header. */ getResponseHeader(key: string): string; //#endregion //#region Properties /** * Gets the JSON-evaluated object from the response. * @return The JSON-evaluated response object. */ object(): any; /** * Gets a value indicating whether the request associated with the executor was aborted. * When the current instance of the Sys.Net.WebRequestExecutor class is aborted, it must set its state to aborted and it must raise the completed event of the associated request object. * @return true if the request associated with the executor was aborted; otherwise, false. */ get_aborted(): boolean; /** * Gets a value indicating whether the request completed successfully. * Successful completion usually means a well-formed response was received by the executor. * If a response was received, the current instance of the Sys.Net.WebRequestExecutor class must set its state to completed. * It must also raise the completed event of the associated request object. * @return true if the request completed successfully; otherwise, false. */ get_responseAvailable(): boolean; /** * Gets the text representation of the response body. When a request has completed successfully with valid response data, this property returns the text that is contained in the response body. * @return The text representation of the response body. */ get_responseData(): string; /** * Returns a value indicating whether the executor has started processing the request. * The executor returns true if substantial processing of the request has started. For executors that make network calls, substantial processing means that a network call has been started. * @return true if the executor has started processing the request; otherwise, false. */ get_started(): boolean; /** * Gets a success status code. * The statusCode property returns an integer that specifies that a request completed successfully and with valid response data. * @return An integer that represents a status code. */ get_statusCode(): number; /** * Gets status information about a request that completed successfully. * The statusText property returns status information if a request completed successfully and with valid response data. * @return the status text */ get_statusText(): string; /** * Gets a value indicating whether the request timed out. * Executors use the time-out information associated with the request to raise the completed event on the associated WebRequest object. * @return true if the request timed out; otherwise, false. */ get_timedOut(): boolean; /** * Attempts to get the response to the current request as an XMLDOM object. * If a request finished successfully with valid response data, this method tries to get the response as an XMLDOM object. */ get_xml(): XMLDocument; /** * Gets the WebRequest object associated with the executor. * @return The WebRequest object associated with the current executor instance. */ get_webRequest(): Sys.Net.WebRequest; //#endregion } /** * Manages the flow of the Web requests issued by the Sys.Net.WebRequest object to the associated executor object. * @see {@link http://msdn.microsoft.com/en-us/library/bb397435(v=vs.100).aspx} */ class IWebRequestManager { //#region Constructor /** * Initializes a new instance of the Sys.Net.WebRequestManager class when implemented in a derived class. */ constructor(); //#endregion //#region Methods /** * Registers a handler for the completed request event of the WebRequestManager. * @param handler * The function registered to handle the completed request event. */ add_completedRequest(handler: (sender: WebRequestExecutor, eventArgs: EventArgs) => void): void; /** * Registers a handler for processing the invoking request event of the WebRequestManager. * @param handler * The function registered to handle the invoking request event. */ add_invokingRequest(handler: (sender: WebRequestExecutor, networkRequestEventArgs: NetworkRequestEventArgs) => void): void; /** * Sends Web requests to the default network executor. * This member supports the client-script infrastructure and is not intended to be used directly from your code. * @param WebRequest * An instance of the Sys.Net.WebRequest class. */ executeRequest(WebRequest: Sys.Net.WebRequest): void; /** * Removes the event handler set by the add_completedRequest method. * Use the remove_ completedRequest method to remove the event handler you set using the add_ completedRequest method. * @param handler * The function that handles the completed request event. */ remove_completedRequest(handler: (sender: WebRequestExecutor, eventArgs: EventArgs) => void): void; /** * Removes the event handler set by the add_invokingRequest method. * Use the remove_invokingRequest method to remove the event handler you set using the add_invokingRequest method. * @param handler * The function that handles the invoking request event. */ remove_invokingRequest(handler: (sender: WebRequestExecutor, networkRequestEventArgs: NetworkRequestEventArgs) => void): void; //#endregion //#region Properties /** * Gets or sets the default network executor type that is used to make network requests. * @return * The object that represents the default Web request executor. */ get_defaultExecutorType(): Sys.Net.WebRequestExecutor; /** * Gets or sets the default network executor type that is used to make network requests. * @param value * A reference to an implementation of the WebRequestExecutor class. */ set_defaultExecutorType(value: Sys.Net.WebRequestExecutor): void; /** * Gets or sets the time-out for the default network executor. * @return * An integer value that indicates the current time-out for the default executor. */ get_defaultTimeout(): number; /** * Gets or sets the time-out for the default network executor. * * @throws Sys.ArgumentOutOfRangeException An invalid parameter was passed. * @param value * The time in milliseconds that the default executor should wait before timing out a Web request. This value must be 0 or a positive integer. */ set_defaultTimeout(value: number): void; //#endregion } export var WebRequestManager: IWebRequestManager; } //#endregion //#region Sys.Serialization Namespace /** * Contains classes related to data serialization for AJAX client functionality in ASP.NET. For more information, see Using Web Services in ASP.NET AJAX. * @see {@link http://msdn.microsoft.com/en-us/library/bb310840(v=vs.100).aspx} */ module Serialization { /** * Serializes JavaScript types into JSON-formatted data and deserializes JSON-formatted data into JavaScript types * The JavaScriptSerializer class contains only static methods. * @see {@link http://msdn.microsoft.com/en-us/library/bb310857(v=vs.100).aspx} */ class JavaScriptSerializer { //#region Constructors /** * Initializes a new instance of the Sys.Serialization.JavaScriptSerializer class. */ constructor(); //#endregion //#region Methods /** * Converts an ECMAScript (JavaScript) object graph into a JSON string. This member is static and can be invoked without creating an instance of the class. * @static * @param value * The JavaScript object graph to serialize. * @exception Sys.ArgumentException * value contains a value that cannot be serialized. */ static serialize(value: any): string; /** * Converts a JSON string into an ECMAScript (JavaScript) object graph. This member is static and can be invoked without creating an instance of the class. * @static * @param value * The JSON string to deserialize. */ static deserialize(value: string): any; //#endregion } } //#endregion //#region Sys.Services Namespace /** * Contains types that provide script access in AJAX-enabled ASP.NET client applications to the ASP.NET authentication service, profile service, and other application services. * The Sys.Services namespace is part of the Microsoft Ajax Library. * For more information @{see Using Web Services in ASP.NET AJAX {@link http://msdn.microsoft.com/en-us/library/bb515101(v=vs.100).aspx}} * @see {@link http://msdn.microsoft.com/en-us/library/bb311017(v=vs.100).aspx} */ module Services { /** * Provides the client proxy class for the authentication service. * The AuthenticationService class is a singleton; it has only one instance with a global point of access. * It is always available to your application and you do not have to instantiate it. * The AuthenticationService class provides script access to user authentication. * It calls methods of the authentication service through the same infrastructure used to call any other Web service method. * @see {@link http://msdn.microsoft.com/en-us/library/bb310861(v=vs.100).aspx} */ class AuthenticationService { //#region Constructors /** * Initializes a new instance of the Sys.Services.AuthenticationService class. */ constructor(); //#endregion //#region Fields /** * Specifies the path of the default authentication service. */ DefaultWebServicePath: string; //#endregion //#region Methods /** * Authenticates the user's credentials. * @param userName (required) The user name to authenticate. * @param password * The user's password. The default is null. * @param isPersistent * true if the issued authentication ticket should be persistent across browser sessions; otherwise, false. The default is false. * @param redirctUrl * The URL to redirect the browser to on successful login. The default is null. * @param customInfo * * @param loginCompletedCallback * The function to call when the login has finished successfully. The default is null. * @param failedCallback * The function to call if the login fails. The default is null. * @param userContext * User context information that you are passing to the callback functions. * @exception Sys.ArgumentNullException - username is null. */ login(userName: string, password: string, isPersistent: boolean, customInfo: any, redirectUrl: string, loginCompletedCallback: Function, failedCallback: Function, userContext: any): void; /** * Logs out the currently authenticated user. * * If redirectUrl is null or is an empty string, the page is redirected to itself after the call to the authentication Web service finishes and the completed callback function is called. * This makes sure that any user-related data is cleared from the page. If redirectUrl is not null or is a non-empty string, the page is redirected to the specified URL after a successful call to the Web service. * This URL can be an absolute virtual path, a relative virtual path, or a fully qualified domain name and a path. * If the call to the Web service fails, the page is not redirected or refreshed. Instead, the failed callback function is called. * * @param redirectUrl * The URL to redirect the browser to on successful logout. The default is null. * @param logoutCompletedCallback * The function that is called when the logout has finished. The default is null. * @param failedCallback * The function that is called if the logout has failed. The default is null. * @param userContext * User context information that you are passing to the callback functions. */ logout(redirectUrl: string, logoutCompletedCallback: Function, failedCallback: Function, userContext: any): void; //#endregion //#region Properties /** * Gets or sets the name of the default failure callback function. */ get_defaultFailedCallback(): Function; /** * Gets or sets the name of the default failure callback function. * @param value * A string that contains the name of the default failure callback function. */ set_defaultFailedCallback(value: string): void; /** * Gets or sets the default succeeded callback function for the service. * @return A reference to the succeeded callback function for the service. */ defaultSucceededCallback(): Function; /** * Gets or sets the default succeeded callback function for the service. * @param value * A reference to the succeeded callback function for the service. */ defaultSucceededCallback(value: Function): void; /** * Gets or sets the default user context for the service. * @return A reference to the user context for the service. */ defaultUserContext(): Object /** * Gets or sets the default user context for the service. * @param value * A reference to the user context for the service. */ defaultUserContext(value: Object): void; /** * Gets the authentication state of the current user. * The value of this property is set by the ScriptManager object during a page request. * @return true if the current user is logged in; otherwise, false. */ get_isLoggedIn(): boolean; /** * Gets or sets the authentication service path. * You usually set the path property in declarative markup. This value can be an absolute virtual path, a relative virtual path, or a fully qualified domain name and a path. * By default, the path property is set to an empty string. If you do not set the path property, the internal default path is used, which points to the built-in authentication service. * @param value * The authentication service path. */ set_path(value: string): void; /** * Gets or sets the authentication service path. * By default, the path property is set to an empty string. If you do not set the path property, the internal default path is used, which points to the built-in authentication service. */ get_path(): string; /** * Gets or sets the authentication service time-out value. * The timeout property represents the time in milliseconds that the current instance of the Sys.Net.WebRequestExecutor class should wait before timing out the request. * By setting a time-out interval, you can make sure that a pending request returns based on a time interval that you specify, instead of waiting for the asynchronous communication layer to time out. * @param value * The time-out value in milliseconds. */ set_timeout(value: number): void; /** * Gets or sets the authentication service time-out value. * The timeout property represents the time in milliseconds that the current instance of the Sys.Net.WebRequestExecutor class should wait before timing out the request. * The timeout in milliseconds * @return * The timeout */ get_timeout(): number; //#endregion } /** * Defines a profile group. * The ProfileGroup class defines the type of an element as a group in the properties collection of the Sys.Services.ProfileService class. * Profile group properties are accessed as subproperties of the related group, as shown in the following ECMAScript (JavaScript) example: * @see {@link http://msdn.microsoft.com/en-us/library/bb310801(v=vs.100).aspx} */ class ProfileGroup { //#region Constructors constructor(); /** * Initializes a new instance of the Sys.Services.ProfileGroup class. * @param properties * (Optional) An object that contains the settings for this profile group. This parameter can be null. */ constructor(properties: Object); //#endregion //#region Methods //#endregion } /** * Provides the client proxy class for the role service. * @see {@link http://msdn.microsoft.com/en-us/library/bb513880(v=vs.100).aspx} */ class RoleService { } /** * Provides the client proxy class for the profile service. * @see {@link http://msdn.microsoft.com/en-us/library/bb383800(v=vs.100).aspx} */ class ProfileService { new(): ProfileService; //#region Fields /** * Specifies the path of the default profile service. */ static DefaultWebServicePath: string; /** * Contains the loaded profile data. You can access the loaded profile data directly from the properties field. * An element in the properties field can be a property group of type ProfileGroup. If it is, the related properties appear as sub-properties. For more information, see Sys.Services.ProfileGroup Class. */ static properties: any; //#endregion //#region Methods /** * Loads the specified profile properties. * * If propertyNames is not supplied, all profile properties enabled for read access are loaded from the server. * The loaded profile can then be accessed directly from the properties field. * This enables your application to access the profile properties by using simple field syntax, as shown in the following example: * @example * Sys.Services.ProfileService.load(null, LoadCompletedCallback, ProfileFailedCallback, null); * * @param propertyName * A string array that contains the profile properties to load. * @param loadCompletedCallback * The function that is called when loading has completed. The default is null. * @param failedCallback * The function that is called when loading has failed. The default is null. * @param userContext * User context information passed to the callback functions. */ static load(propertyNames: string[], loadCompletedCallback: Function, failedCallback: Function, userContext: any): void; /** * @param propertyNames * A string array that contains the profile properties to save. * @param saveCompletedCallback * The function that is called when the save method has finished. The default is null. * @param failedCallback * The function that is called if the save method has failed. The default is null. * @param userContext * User context information passed to the callback functions. */ static save(propertyNames: string[], saveCompletedCallback: Function, failedCallback: Function, userContext: any): void; //#endregion //#region Properties /** * Gets or sets the name of the default failure callback function. * @param value * A string that contains the name of the default failure callback function. */ static set_defaultFailedCallback(value: string): void; static get_defaultFailedCallback(): Function; /** * Gets or sets the name of the default load-completed callback function. * * @param value * A string that contains the name of the default load-completed callback function. */ static set_defaultLoadCompletedCallback(value: string): void; static get_defaultLoadCompletedCallback(): Function; /** * Gets or sets the name of the default save-completed callback function. * @param value * A string that contains the name of the default save-completed callback function. */ static set_defaultSaveCompletedCallback(value: string): void; static get_defaultSaveCompletedCallback(): Function; /** * Gets or sets the default succeeded callback function for the service. * @return * A reference to the succeeded callback function for the service. */ static defaultSucceededCallback(): Function; static defaultSucceededCallback(value: Function): void; /** * Gets or sets the default user context for the service. * @return * A reference to the user context for the service. */ static defaultUserContext(): Object; /** * Gets or sets the default user context for the service. */ static defaultUserContext(value: Object): void; /** * Gets or sets the profile service path. * @param value * A string that contains the profile service path. */ static set_path(value: string): void; /** * Gets or sets the profile service path. * @return * The profile path */ static get_path(): string; /** * Gets or sets the profile service time-out value. * The timeout property represents the time in milliseconds that the current instance of the Sys.Net.WebRequestExecutor class should wait before timing out the request. * By setting a time-out interval, you can make sure that a pending request returns based on a time interval that you specify, instead of waiting for the asynchronous communication layer to time out. * * @param value * The time-out value in milliseconds. */ static set_timeout(value: number): void; /** * Gets or sets the profile service time-out value. */ static get_timeout(): number; //#endregion } } //#endregion //#region Sys.UI Namespace /** * Contains types related to the user interface (UI), such as controls, events, and UI properties in the Microsoft Ajax Library. * @see {@link http://msdn.microsoft.com/en-us/library/bb397431(v=vs.100).aspx} */ module UI { /** * Provides a base class for all ASP.NET AJAX client behaviors. * @see {@link http://msdn.microsoft.com/en-us/library/bb311020(v=vs.100).aspx} */ class Behavior extends Sys.Component { //#region Methods /** * Gets a Sys.UI.Behavior instance with the specified name property from the specified HTML Document Object Model (DOM) element. This member a static member and can be invoked without creating an instance of the class. * @return The specified Behavior object, if found; otherwise, null. */ static getBehaviorByName(element: HTMLElement, name: string): Behavior; /** * Gets an array of Sys.UI.Behavior objects that are of the specified type from the specified HTML Document Object Model (DOM) element. This method is static and can be invoked without creating an instance of the class. * @return An array of all Behavior objects of the specified type that are associated with the specified DOM element, if found; otherwise, an empty array. */ static getBehaviorsByType(element: HTMLElement, type: Sys.UI.Behavior): Behavior[]; /** * Gets the Sys.UI.Behavior objects that are associated with the specified HTML Document Object Model (DOM) element. This member is static and can be invoked without creating an instance of the class. * @param element * The HTMLElement object to search. * @return An array of references to Behavior objects, or null if no references exist. */ static getBehaviors(element: DomElement): Behavior[]; /** * Removes the current Behavior object from the application. * The dispose method releases all resources from the Sys.UI.Behavior object, unbinds it from its associated HTML Document Object Model (DOM) element, and unregisters it from the application. */ dispose(): void; //#endregion //#region Properties /** * Gets the HTML Document Object Model (DOM) element that the current Sys.UI.Behavior object is associated with. * @return The DOM element that the current Behavior object is associated with. */ get_element(): HTMLElement; /** * Gets or sets the identifier for the Sys.UI.Behavior object. * A generated identifier that consists of the ID of the associated HTMLElement, the "$" character, and the name value of the Behavior object. */ get_id(): string; /** * Gets or sets the identifier for the Sys.UI.Behavior object. * @param value * The string value to use as the identifier. */ set_id(value: string): void; /* * Gets or sets the name of the Sys.UI.Behavior object. * If you do not explicitly set the name property, getting the property value sets it to its default value, which is equal to the type of the Behavior object. The name property remains null until it is accessed. * @param value * A string value to use as the name. */ set_name(value: string): void; /** * Gets or sets the name of the Sys.UI.Behavior object. */ get_name(): string; //#endregion } /** * Creates an object that contains a set of integer coordinates representing position, width, and height. * @see {@link http://msdn.microsoft.com/en-us/library/bb397698(v=vs.100).aspx} */ class Bounds { //#region Constructors /** * Initializes a new instance of the Sys.UI.Bounds class. */ constructor(); //#endregion //#region Fields /** * Gets the height of an object in pixels. This property is read-only. * @return A number that represents the height of an object in pixels. */ height: number; /** * Gets the width of an object in pixels. This property is read-only. * @return A number that represents the width of an object in pixels. */ width: number; /** * Gets the x-coordinate of an object in pixels. * @return A number that represents the x-coordinate of an object in pixels. */ x: number; /** * Gets the y-coordinate of anobject in pixels. * @return A number that represents the y-coordinate of an object in pixels. */ y: number; //#endregion } /** * Provides the base class for all all ASP.NET AJAX client controls. */ class Control extends Sys.Component { //#region Constructors /** * When called from a derived class, initializes a new instance of that class. * The Control constructor is a complete constructor function. However, because the Control class is an abstract base class, the constructor should be called only from derived classes. * @param element * The HTMLElement object that the control will be associated with. * * @throws Error.invalidOperation Function */ constructor(element: HTMLElement); //#endregion //#region Methods /** * Adds a CSS class to the HTML Document Object Model (DOM) element that the control is attached to. * Use the addCssClass method to add a CSS class to a control. If the CSS class has already been added to the control, addCssClass makes no changes to the control. * @param className * A string that contains the name of the CSS class to add. */ addCssClass(className: string): void; /** * Removes the current control from the application. * The dispose method releases all resources from the Sys.UI.Control object, unbinds it from its associated HTML Document Object Model (DOM) element, and unregisters it from the application. */ dispose(): void; /** * Initializes the current Sys.UI.Control object. * The initialize method initializes the control and sets the base Sys.Component.isInitialized property to true. You can override this method to include additional initialization logic for your derived class. */ initialize(): void; /** * Called when an event is raised by the raiseBubbleEvent method. * * The onBubbleEvent method returns false to make sure that unhandled events propagate (bubble) to the parent control. * In derived classes, you should override the onBubbleEvent method and return true when events are handled to prevent the events from bubbling further. * For an explanation of bubbling, see Sys.UI.Control raiseBubbleEvent Method. * * @param source * The object that triggered the event. * @param args * The event arguments. * @return * false in all cases. */ onBubbleEvent(source: any, args: any): boolean; /** * Calls the onBubbleEvent method of the parent control. * * When the raiseBubbleEvent method is called, the source object and args values are sent to the onBubbleEvent handler of the current control. * If onBubbleEvent returns false, they are sent to the onBubbleEvent handler of the parent control. * This process continues until an onBubbleEvent event handler returns true, which indicates that the event has been handled. * Any event that bubbles to the Sys.Application instance without being handled is ignored. * * @param source * The object that triggered the event. * @param args * The event arguments. */ raiseBubbleEvent(source: any, args: any): void; /** * Removes a CSS class from the HTML Document Object Model (DOM) element that the control is attached to. * Use the removeCssClass method to remove a CSS class from a control. If the CSS class has already been removed from the control, removeCssClass makes no changes to the control. * * @param className * A string that contains the name of the CSS class to remove. */ removeCssClass(className: string): void; /** * Toggles a CSS class of the HTML Document Object Model (DOM) element that the control is attached to. * @param className * A string that contains the name of the CSS class to toggle. */ toggleCssClass(className: string): void; //#endregion //#region Properties /** * Gets the HTML Document Object Model (DOM) element that the current Sys.UI.Control object is associated with. * @return The DOM element that the current Control object is associated with. */ get_element(): HTMLElement; /** * Gets or sets the identifier for the Sys.UI.Control object. * A generated identifier that consists of the ID of the associated HTMLElement, the "$" character, and the name value of the Control object. */ get_id(): string; /** * Gets or sets the identifier for the Sys.UI.Control object. * @param value * The string value to use as the identifier. */ set_id(value: string): void; /* * Gets or sets the name of the Sys.UI.Control object. * If you do not explicitly set the name property, getting the property value sets it to its default value, which is equal to the type of the Control object. The name property remains null until it is accessed. * @param value * A string value to use as the name. */ //#endregion } /** * Defines static methods and properties that provide helper APIs for manipulating and inspecting DOM elements. * @see {@link http://msdn.microsoft.com/en-us/library/bb383788(v=vs.100).aspx} */ interface DomElement { //#region Constructors //#endregion //#region Methods /** * Adds a CSS class to a DOM element if the class is not already part of the DOM element. This member is static and can be invoked without creating an instance of the class. * If the element does not support a CSS class, no change is made to the element. * @param element * The HTMLElement object to add the CSS class to. * @param className * The name of the CSS class to add. */ addCssClass(element: HTMLElement, className: string): void; /** * Gets a value that indicates whether the DOM element contains the specified CSS class. This member is static and can be invoked without creating an instance of the class. * @param element * The HTMLElement object to test for the CSS class. * @param className * The name of the CSS class to test for. * @return * true if the element contains the specified CSS class; otherwise, false. */ containsCssClass(element: HTMLElement, className: string): boolean; /** * Gets a set of integer coordinates that represent the position, width, and height of a DOM element. This member is static and can be invoked without creating an instance of the class. * * @param element * The HTMLElement instance to get the coordinates of. * @return * An object of the JavaScript type Object that contains the x-coordinate and y-coordinate of the upper-left corner, the width, and the height of the element in pixels. */ getBounds(element: HTMLElement): { x: number; y: number; width: number; height: number; }; /** * @param id * The ID of the element to find. * @param element * (optional) The parent element to search in. The default is the document element. */ getElementById(id: string): HTMLElement; getElementById(id: string, element?: HTMLElement): HTMLElement; getElementById(id: string, element?: HTMLElement): HTMLElement; getElementById(id: string, element: any): any; /** * Gets the absolute position of a DOM element relative to the upper-left corner of the owner frame or window. This member is static and can be invoked without creating an instance of the class. * * @param element * The target element. * * @return * An object of the JavaScript type Object that contains the x-coordinate and y-coordinate of the element in pixels. */ getLocation(element: HTMLElement): Sys.UI.Point; /* * Returns a value that represents the layout characteristics of a DOM element when it is hidden by invoking the HTMLElement.setVisible method. This member is static and can be invoked without creating an instance of the class. * @param element * The target DOM element. * @return * A Sys.UI.VisibilityMode enumeration value that indicates the layout characteristics of element when it is hidden by invoking the setVisible method. */ getVisibilityMode(element: HTMLElement): Sys.UI.VisibilityMode; /** * Gets a value that indicates whether a DOM element is currently visible on the Web page. This member is static and can be invoked without creating an instance of the class. * @param element * The target DOM element. * @return * true if element is visible on the Web page; otherwise, false */ getVisible(element: any): boolean; /** * Determines whether the specified object is a DOM element. * @param obj * An object * @return * true if the object is a DOM element; otherwise, false. */ isDomElement(obj: any): boolean; /** * Raises a bubble event. A bubble event causes an event to be raised and then propagated up the control hierarchy until it is handled. * @param source * The DOM element that triggers the event. * @param args * The event arguments */ raiseBubbleEvent(source: HTMLElement, args: EventArgs): void; /** * Removes a CSS class from a DOM element. This member is static and can be invoked without creating an instance of the class. If the element does not include a CSS class, no change is made to the element. * @param element * The HTMLElement object to remove the CSS class from. * @param className * The name of the CSS class to remove. */ removeCssClass(element: HTMLElement, className: string): void; removeCssClass(element: HTMLElement, className: string): void; removeCssClass(element: any, className: string): void; /** * Returns the element that has either the specified ID in the specified container, or is the specified element itself. * The resolveElement method is used to verify that an ID or an object can be resolved as an element. * * @param elementOrElementId * The element to resolve, or the ID of the element to resolve. This parameter can be null. * @param containerElement * (Optional) The specified container. * @return * A DOM element. */ resolveElement(elementOrElementId: string|HTMLElement, containerElement?: HTMLElement): HTMLElement; /** * Sets the position of a DOM element. This member is static and can be invoked without creating an instance of the class. * he left and top style attributes (upper-left corner) of an element specify the relative position of an element. * The actual position will depend on the offsetParent property of the target element and the positioning mode of the element. * * @param element The target element. * @param x The x-coordinate in pixels. * @param y The y-coordinate in pixels. */ setLocation(element: HTMLElement, x: number, y: number): void; /** * Sets the layout characteristics of a DOM element when it is hidden by invoking the HTMLElement.setVisible method. * This member is static and can be invoked without creating an instance of the class. * * Use the setVisibilityMode method to set the layout characteristics of a DOM element when it is hidden by invoking the HTMLElement.setVisible method. * For example, if value is set to Sys.UI.VisibilityMode.collapse, the element uses no space on the page when the setVisible method is called to hide the element. * * @param element * The target DOM element. * @param value * A Sys.UI.VisibilityMode enumeration value. */ setVisibilityMode(element: HTMLElement, value: Sys.UI.VisibilityMode): void; /** * Sets a DOM element to be visible or hidden. This member is static and can be invoked without creating an instance of the class. * * Use the setVisible method to set a DOM element as visible or hidden on the Web page. * If you invoke this method with value set to false for an element whose visibility mode is set to "hide," the element will not be visible. * However, it will occupy space on the page. If the element's visibility mode is set to "collapse," the element will occupy no space in the page. * For more information about how to set the layout characteristics of hidden DOM elements, see HTMLElement setVisibilityMode Method. * * @param element * The target DOM element. * @param value * true to make element visible on the Web page; false to hide element. */ setVisible(element: HTMLElement, value: boolean): void; /** * Toggles a CSS class in a DOM element. This member is static and can be invoked without creating an instance of the class. * Use the toggleCssClass method to hide a CSS class of an element if it is shown, or to show a CSS class of an element if it is hidden. * * @param element * The HTMLElement object to toggle. * @param className * The name of the CSS class to toggle. */ toggleCssClass(element: HTMLElement, className: string): void; //#endregion } var DomElement: DomElement; /** * Provides cross-browser access to DOM event properties and helper APIs that are used to attach handlers to DOM element events. * @see {@link http://msdn.microsoft.com/en-us/library/bb310935(v=vs.100).aspx} */ class DomEvent { //#region Constructors /** * Initializes a new instance of the Sys.UI.DomEvent class and associates it with the specified HTMLElement object. * @param domElement * The HTMLElement object to associate with the event. */ constructor(domElement: HTMLElement); //#endregion //#region Methods /** * Provides a method to add a DOM event handler to the DOM element that exposes the event. This member is static and can be invoked without creating an instance of the class. * Use the addHandler method to add a DOM event handler to the element that exposes the event. The eventName parameter should not include the "on" prefix. For example, specify "click" instead of "onclick". * This method can be accessed through the $addHandler shortcut method. * * @param element * The element that exposes the event. * @param eventName * The name of the event. * @param handler * The client function that is called when the event occurs. * @param autoRemove * (Optional) A boolean value that determines whether the handler should be removed automatically when the element is disposed. */ static addHandler(element: HTMLElement, eventName: string, handler: (e: DomEvent) => void, autoRemove?: boolean): void; /** * Adds a list of DOM event handlers to the DOM element that exposes the events. This member is static and can be invoked without creating an instance of the class. * Use the addHandlers method to add a list of DOM event handlers to the element that exposes the event. * The events parameter takes a comma-separated list of name/value pairs in the format name:value, where name is the name of the DOM event and value is the name of the handler function. * If there is more than one name/value pair, the list must be enclosed in braces ({}) to identify it as a single parameter. Multiple name/value pairs are separated with commas. * Event names should not include the "on" prefix. For example, specify "click" instead of "onclick". * If handlerOwner is specified, delegates are created for each handler. These delegates are attached to the specified object instance, and the this pointer from the delegate handler will refer to the handlerOwner object. * This method can be accessed through the $addHandlers shortcut method. * * @param element * The DOM element that exposes the events. * @param events * A dictionary of event handlers. * @param handlerOwner * (Optional) The object instance that is the context for the delegates that should be created from the handlers. * @param autoRemove * (Optional) A boolean value that determines whether the handler should be removed automatically when the element is disposed. * * @throws Error.invalidOperation - (Debug) One of the handlers specified in events is not a function. * */ static addHandlers(element: HTMLElement, events: { [event: string]: (e: DomEvent) => void }, handlerOwner?: any, autoRemove?: boolean): void; /** * Removes all DOM event handlers from a DOM element that were added through the Sys.UI.DomEvent addHandler or the Sys.UI.DomEvent addHandlers methods. * This member is static and can be invoked without creating an instance of the class. * This method can be accessed through the $clearHandlers shortcut method. * * @param element * The element that exposes the events. */ static clearHandlers(element: HTMLElement): void; /** * Removes a DOM event handler from the DOM element that exposes the event. This member is static and can be invoked without creating an instance of the class. * * @param element * The element that exposes the event. * @param eventName * The name of the event. * @param handler * The event handler to remove. */ static removeHandler(element: HTMLElement, eventName: string, handler: (e: DomEvent) => void): void; /** * Prevents the default DOM event action from happening. * Use the preventDefault method to prevent the default event action for the browser from occurring. * For example, if you prevent the keydown event of an input element from occurring, the character typed by the user is not automatically appended to the input element's value. */ preventDefault(): void; /** * Prevents an event from being propagated (bubbled) to parent elements. * By default, event notification is bubbled from a child object to parent objects until it reaches the document object. * The event notification stops if the event is handled during the propagation process. * Use the stopPropagation method to prevent an event from being propagated to parent elements. */ stopPropagation(): void; //#endregion //#region Fields /** * Gets a Boolean value that indicates the state of the ALT key when the associated event occurred. * Use the altKey field to determine whether the ALT key is pressed when the event occurred. * * @return true if the ALT key was pressed when the event occurred; otherwise, false. */ altKey: boolean; /** * Gets a Sys.UI.MouseButton enumeration value that indicates the button state of the mouse when the related event occurred. * Use the button field to determine which mouse button was pressed when the related event occurred. * @return A MouseButton value */ button: Sys.UI.MouseButton; /** * Gets the character code of the key that raised the associated keyPress event. * Use the charCode field to get the character code of a pressed key or key combination that raised a keyPress event. * The keyPress event provides a single character code that identifies key combinations. * The keyPress event is not raised for single modifier keys such as ALT, CTRL, and SHIFT. * * @return An integer value that represents the character code of the key or key combination that was pressed to raise the keyPress event. */ charCode: number; /** * Gets the x-coordinate of the mouse pointer's position relative to the client area of the browser window, excluding window scroll bars. * @return An integer that represents the x-coordinate in pixels. */ clientX: number; /** * Gets the y-coordinate of the mouse pointer's position relative to the client area of the browser window, excluding window scroll bars. * @return An integer that represents the y-coordinate in pixels. */ clientY: number; /** * Gets a Boolean value that indicates the state of the CTRL key when the associated event occurred. * @return true if the CTRL key was pressed when the event occurred; otherwise, false. */ ctrlKey: boolean; /** * Gets the key code of the key that raised the keyUp or keyDown event. * @return An integer value that represents the key code of the key that was pressed to raise the keyUp or keyDown event. */ keyCode: number; /** * Gets the x-coordinate of the mouse pointer's position relative to the object that raised the event. * @return An integer that represents the x-coordinate in pixels. */ offsetX: number; /** * Gets the y-coordinate of the mouse pointer's position relative to the object that raised the event. * @return An integer that represents the y-coordinate in pixels. */ offsetY: number; /** * Gets the x-coordinate of the mouse pointer's position relative to the user's screen. * @return An integer that represents the x-coordinate in pixels. */ screenX: number; /** * Gets the y-coordinate of the mouse pointer's position relative to the user's screen. * @return An integer that represents the y-coordinate in pixels. */ screenY: number; /** * Gets a Boolean value that indicates the state of the SHIFT key when the associated event occurred. * @return true if the SHIFT key was pressed when the event occurred; otherwise, false. */ shiftKey: boolean; /** * Gets the object that the event acted on. * @return An object that represents the target that the event acted on. */ target: any; /** * Gets the name of the event that was raised. * @return A string that represents the name of the event that was raised. */ type: string; //#endregion } /** * Describes key codes. * The values correspond to values in the Document Object Model (DOM). */ enum Key { /** * Represents the BACKSPACE key. */ backspace, /* * Represents the TAB key. */ tab, /** * Represents the ENTER key. */ enter, /** * Represents the ESC key. */ esc, /* * Represents the SPACEBAR key. */ space, /** * Represents the PAGE UP key. */ pageUp, /** * Represents the PAGE DOWN key. */ pageDown, /** * Represents the END key. */ end, /** * Represents the HOME key. */ home, /** * Represents the LEFT ARROW key. */ left, /** * Represents the UP ARROW key. */ up, /** * Represents the RIGHT ARROW key. */ right, /** * Represents the DOWN ARROW key. */ down, /** * Represents DELETE key. */ del } /** * Describes mouse button locations. */ enum MouseButton { /** * Represents the left mouse button. */ leftButton, /** * Represents the middle mouse button. */ middleButton, /** * Represents the right mouse button. */ rightButton } /** * Creates an object that contains a set of integer coordinates that represent a position. The getLocation method of the HTMLElement class returns a Point object. * @see {@link http://msdn.microsoft.com/en-us/library/bb383992(v=vs.100).aspx} * */ class Point { //#region Constructors /** * Creates an object that contains a set of integer coordinates that represent a position. * @param x The number of pixels between the location and the left edge of the parent frame. * @param y The number of pixels between the location and the top edge of the parent frame. */ constructor(x: number, y: number); //#endregion //#region Fields /** * Gets the x-coordinate of a Sys.UI.Point object in pixels. This property is read-only. * @return A number that represents the x-coordinate of the Point object in pixels. */ x: number; /** * Gets the y-coordinate of a Sys.UI.Point object in pixels. This property is read-only. * @return A number that represents the y-coordinate of the Point object in pixels. */ y: number; //#endregion } /** * Describes the layout of a DOM element in the page when the element's visible property is set to false. * @see {@link http://msdn.microsoft.com/en-us/library/bb397498(v=vs.100).aspx} */ enum VisibilityMode { /** * The element is not visible, but it occupies space on the page. */ hide, /** * The element is not visible, and the space it occupies is collapsed. */ collapse } } //#endregion //#region Sys.WebForms Namespace /** * The Sys.WebForms namespace contains classes related to partial-page rendering in the Microsoft Ajax Library. * @see {@link http://msdn.microsoft.com/en-us/library/bb397566(v=vs.100).aspx} */ module WebForms { /** * Used by the beginRequest event of the PageRequestManager class to pass argument information to event handlers. * @see {@link http://msdn.microsoft.com/en-us/library/bb384003(v=vs.100).aspx} */ class BeginRequestEventArgs extends EventArgs { //#region Constructors /** * Initializes a new instance of the BeginRequestEventArgs class. * @param request * A Sys.Net.WebRequest representing the web request for the EventArgs. * @param postBackElement * The postback element that initiated the async postback. * @param updatePanelsToUpdate * (Optional) A list of UniqueIDs for UpdatePanel controls that are requested to update their rendering by the client. Server-side processing may update additional UpdatePanels. */ constructor(request: Sys.Net.WebRequest, postBackElement: any, updatePanelsToUpdate: string[]); //#endregion //#region Properties /** * Gets the postback element that initiated the asynchronous postback. This property is read-only. * @readonly * @return An HTML DOM element. */ get_postBackElement(): HTMLElement; /** * Gets the request object that represents the current postback. * @return An instance of the Sys.Net.WebRequest class. */ get_request(): Sys.Net.WebRequest; /** * Gets a list of UniqueID values for UpdatePanel controls that should re-render their content, as requested by the client. * Server-side processing might update additional UpdatePanel controls. * @return An array of UniqueID values for UpdatePanel controls. */ get_updatePanelsToUpdate(): string[]; //#endregion } /** * Used by the endRequest event of the PageRequestManager class to pass argument information to event handlers. * @see {@link http://msdn.microsoft.com/en-us/library/bb397499.aspx} */ class EndRequestEventArgs extends EventArgs { //#region Constructors /** * Initializes a new instance of the EndRequestEventArgs class. * @param error * An error object. * @param dataItems * An object containing data items. * @param response * An object of type Sys.Net.WebRequestExecutor. */ constructor(error: Error, dataItems: any, response: Sys.Net.WebRequestExecutor); //#endregion //#region Properties /** * Gets a JSON data structure that contains data items that were registered by using the RegisterDataItem method of the ScriptManager class. * The JavaScript Error object exposes several properties that define the error. The Microsoft Ajax Library provides additional functions for the Error object. * @return A JSON data structure that contains name/value pairs that were registered as data items by using the RegisterDataItem method of the ScriptManager class. */ get_dataItems(): any; /** * Gets the Error object. * @return A base ECMAScript (JavaScript) Error object. */ get_error(): Error; /** * Get or sets a value that indicates whether the error has been handled. * Use this property to determine whether an asynchronous postback error has already been handled. If it has not and if you want to take action on the error, you can set the error as handled. * @return true if the error has been handled; otherwise false. */ get_errorHandled(): boolean; /** * Get or sets a value that indicates whether the error has been handled. * Use this property to determine whether an asynchronous postback error has already been handled. If it has not and if you want to take action on the error, you can set the error as handled. * @param value * true or false. */ set_errorHandled(value: boolean): void; /** * Gets a response object that is represented by the Sys.Net.WebRequestExecutor class. * @return A response object that is represented by the WebRequestExecutor class. */ get_response(): Sys.Net.WebRequestExecutor; //#endregion } /** * Used by the initializeRequest event of the PageRequestManager class to pass argument information to event handlers. * This class contains private members that support the client-script infrastructure and are not intended to be used directly from your code. Names of private members begin with an underscore ( _ ). * @see {@link http://msdn.microsoft.com/en-us/library/bb311030(v=vs.100).aspx} */ class InitializeRequestEventArgs extends EventArgs { //#region Constructors /** * Initializes a new instance of the EndRequestEventArgs class. * @param request * A Sys.Net.WebRequest object that represents the Web request for the EventArgs object. * @param datapostBackElementItems * The postback element that initiated the asynchronous postback. * @param updatePanelsToUpdate * (Optional) A list of UniqueID values for UpdatePanel controls that are being requested to update their rendering by the client. Server-side processing might update additional UpdatePanel controls. */ constructor(request: Sys.Net.WebRequest, postBackElement: any, updatePanelsToUpdate: string[]); //#endregion //#region Properties /** * Gets the postback element that initiated the asynchronous postback. * @return An HTML DOM element. */ get_postBackElement(): HTMLElement; /** * Gets the request object that represents the current postback. * @return A request object that is represented by the Sys.Net.WebRequestExecutor class. */ get_request(): Sys.Net.WebRequestExecutor; /** * Gets or sets a list of UniqueID values for UpdatePanel controls that should re-render their content, as requested by the client. * The returned array can be modified by a client event handler to add or remove UpdatePanel controls that should re-render their content dynamically. Server processing can also modify the array. * @return An array of UniqueID values for UpdatePanel controls. */ get_updatePanelsToUpdate(): string[]; //#endregion } /** * Used by the pageLoaded event of the PageRequestManager class to send event data that represents the UpdatePanel controls that were updated and created in the most recent postback. * @see {@link http://msdn.microsoft.com/en-us/library/bb397476(v=vs.100).aspx} */ class PageLoadedEventArgs extends EventArgs { //#region Constructors /** * Initializes a new instance of the PageLoadedEventArgs class. */ constructor(); //#endregion //#region Properties /** * Gets a JSON data structure that contains data items that were registered by using the RegisterDataItem method of the ScriptManager class. * A page or control must be in partial-page rendering mode to register data items that use the RegisterDataItem method of the ScriptManager class * Use the IsInAsyncPostBack property to check whether the page is in partial-page rendering mode.The dataItems property returns a JSON data structure that contains name/value pairs. * The name is the unique ID of the control that is used in the control parameter of the RegisterDataItem method. The value is the dataItem parameter of the RegisterDataItem method. * * @return A JSON data structure that contains name/value pairs that were registered as data items that use the RegisterDataItem method of the ScriptManager class. */ get_dataItems(): any; /** * Gets an array of HTML div elements that represent UpdatePanel controls that were created when the DOM was updated during the last asynchronous postback. * If an UpdatePanel control is updated as a result of a partial-page update, the array referenced in the panelsCreated property of the PageLoadedEventArgs class contains a reference to the corresponding div element. * The pageLoaded event of the Sys.WebForms.PageRequestManager class uses a PageLoadedEventArgs object to return its event data. * @return An array of div elements that were created during the DOM manipulation that was caused by the last asynchronous postback. If no elements were created, the property returns null. */ get_panelsCreated(): HTMLDivElement[]; /** * Gets an array of HTML <div> elements that represent UpdatePanel controls that were updated when the DOM was updated during the last asynchronous postback. * If an UpdatePanel control is updated as a result of a partial-page update, the array referenced in the panelsUpdated property of the PageLoadedEventArgs class contains a reference to the corresponding <div> element. * The pageLoaded event of the Sys.WebForms.PageRequestManager class uses a PageLoadedEventArgs object to return its event data. * @return An array of <div> elements that were updated during the DOM manipulation that was the result of the last asynchronous postback. If no elements were created, the property returns null. */ get_panelsUpdated(): HTMLDivElement[]; //#endregion } /** * Used by the pageLoading event of the PageRequestManager class to send event data that represents the UpdatePanel controls that are being updated and deleted as a result of the most recent postback. * @see {@link http://msdn.microsoft.com/en-us/library/bb310960(v=vs.100).aspx} */ class PageLoadingEventArgs extends EventArgs { //#region Constructors /** * Initializes a new instance of the PageLoadingEventArgs class. */ constructor(); //#endregion //#region Properties /** * Gets a JSON data structure that contains data items that were registered by using the RegisterDataItem method of the ScriptManager class. * page or control must be in partial-page rendering mode to register data items that use the RegisterDataItem method of the ScriptManager class. * Use the IsInAsyncPostBack property to check whether the page is in partial-page rendering mode. * The dataItems property returns a JSON data structure that contains name/value pairs. * The name is the unique ID of the control that is used in the control parameter of the RegisterDataItem method. The value is the dataItem parameter of the RegisterDataItem method. * @return A JSON data structure that contains name/value pairs that were registered as data items by using the RegisterDataItem method of the ScriptManager class. */ get_dataItems(): any; /** * Gets an array of HTML <div> elements that represent UpdatePanel controls that will be deleted from the DOM as a result of the current asynchronous postback. * If the contents of an UpdatePanel control will be deleted as the result of a partial-page update, the array that is referenced in the panelsDeleting property of the PageLoadingEventArgs class contains a reference to the corresponding <div> element. * The pageLoading event of the Sys.WebForms.PageRequestManager class uses a PageLoadingEventArgs object to return its event data. * @return An array of <div> elements that will be deleted from the DOM. If no elements will be deleted, the property returns null. */ get_panelsDeleting(): HTMLDivElement[]; /** * Gets an array of HTML <div> elements that represent UpdatePanel controls that will be updated in the DOM as a result of the current asynchronous postback. * If the contents of any UpdatePanel controls will be updated as the result of a partial-page update, the panelsUpdating property contains an array that references the corresponding <div> elements. * The pageLoading event of the Sys.WebForms.PageRequestManager class uses a PageLoadingEventArgs object to return its event data. * @return An array of <div> elements that will be updated in the DOM. If no elements will be updated, the property returns null. */ get_panelsUpdating(): HTMLDivElement[]; //#endregion } /** * Manages client partial-page updates of server UpdatePanel controls. In addition, defines properties, events, and methods that can be used to customize a Web page with client script. * @see {@link http://msdn.microsoft.com/en-us/library/bb311028(v=vs.100).aspx} */ class PageRequestManager { //#region Constructors /** * Initializes a new instance of the Sys.WebForms.PageRequestManager Class. */ constructor(); //#endregion //#region Events /** * Raised before the processing of an asynchronous postback starts and the postback request is sent to the server. * @param beginRequestHandler * The name of the handler method that will be called. */ add_beginRequest(beginRequestHandler: (sender: any, args: BeginRequestEventArgs) => void): void; /** * Raised before the processing of an asynchronous postback starts and the postback request is sent to the server. * @param beginRequestHandler * The handler method that will be removed. */ remove_beginRequest(beginRequestHandler: Function): void; /** * Raised after an asynchronous postback is finished and control has been returned to the browser. * @param endRequestHandler * The name of the handler method that will be called. */ add_endRequest(endRequestHandler: (sender: any, args: Sys.WebForms.EndRequestEventArgs) => void): void; /** * Raised after an asynchronous postback is finished and control has been returned to the browser. * @param endRequestHandler * The name of the handler method that will be removed. */ remove_endRequest(endRequestHandler: (sender: any, args: Sys.WebForms.EndRequestEventArgs) => void): void; /** * Raised during the initialization of the asynchronous postback. * @param initializeRequestHandler * The name of the handler method that will be called. */ add_initializeRequest(initializeRequestHandler: (sender: any, args: InitializeRequestEventArgs) => void): void; /** * Raised during the initialization of the asynchronous postback. * @param initializeRequestHandler * The name of the handler method that will be called. */ remove_initializeRequest(initializeRequestHandler: (sender: any, args: InitializeRequestEventArgs) => void): void; /** * Raised after all content on the page is refreshed as a result of either a synchronous or an asynchronous postback. * @param pageLoadedHandler * The name of the handler method that will be called. */ add_pageLoaded(pageLoadedHandler: (sender: any, args: PageLoadedEventArgs) => void): void; /** * Raised after all content on the page is refreshed as a result of either a synchronous or an asynchronous postback. * @param pageLoadedHandler * The name of the handler method that will be called. */ remove_pageLoaded(pageLoadedHandler: (sender: any, args: PageLoadedEventArgs) => void): void; /** * Raised after the response from the server to an asynchronous postback is received but before any content on the page is updated. * @param pageLoadedHandler * The name of the handler method that will be called. */ add_pageLoading(pageLoadingHandler: (sender: any, args: PageLoadingEventArgs) => void): void; /** * Raised after the response from the server to an asynchronous postback is received but before any content on the page is updated. * @param pageLoadedHandler * The name of the handler method that will be called. */ remove_pageLoading(pageLoadingHandler: (sender: any, args: PageLoadingEventArgs) => void): void; //#endregion //#region Methods /** * Returns the instance of the PageRequestManager class for the page. * @return The current instance of the PageRequestManager class. You do not create a new instance of the PageRequestManager class directly. Instead, an instance is available when partial-page rendering is enabled. */ static getInstance(): PageRequestManager; /** * Stops all updates that would occur as a result of an asynchronous postback. * The abortPostBack method stops the currently executing postback. To cancel a new postback, provide an event handler for the initializeRequest event and use the cancel event of the Sys.CancelEventArgs class. */ abortPostBack(): void; /** * Begins an asynchronous postback. * @param updatePanelsToUpdate * (Optional) An array of UniqueID values or ClientID values for UpdatePanel controls that must be re-rendered. * @param eventTarget * (Optional) A string that contains the target of the event. * @param eventArgument * (Optional) A string that contains an argument for the event. * @param causesValidation * (Optional) true to cause validation. * @param validationGroup * (Optional) A string that contains the name of the validation group. */ beginAsyncPostBack(updatePanelsToUpdate?: string[], eventTarget?: string, eventArgument?: string, causesValidation?: boolean, validationGroup?: string): void; /** * Releases ECMAScript (JavaScript) resources and detaches events. * the dispose method to free client resources. The PageRequestManager instance calls the dispose method during the window.unload event of the browser. * If you call the dispose method and then reference members of the PageRequestManager class, an error occurs. In typical page developer scenarios, you do not have to call the dispose method. */ dispose(): void; //#endregion //#region Properties get_isInAsyncPostBack(): boolean; //#endregion } //#region Exceptions: Defines exceptions that can occur during partial-page updates. /** * Raised when an error occurs while processing the response from the server. * If the response to an asynchronous postback returns without an error but there is an error processing the response in the client, the Sys.WebForms.PageRequestManagerParserErrorException is raised. * For information about how to handle this error condition, see Debugging and Tracing Ajax Applications Overview. * @see {@link http://msdn.microsoft.com/en-us/library/bb397466(v=vs.100).aspx} */ class PageRequestManagerParserErrorException { // Nothing to define } /** * Raised when an error occurs on the server. * If an error occurs on the server while the request is being processed, an error response is returned to the browser and the Sys.WebForms.PageRequestManagerServerErrorException exception is raised. * To customize error handling and to display more information about the server error, handle the AsyncPostBackError event and use the AsyncPostBackErrorMessage and AllowCustomErrorsRedirect properties. * For an example of how to provide custom error handling during partial-page updates, see Customizing Error Handling for ASP.NET UpdatePanel Controls. * @see {@link http://msdn.microsoft.com/en-us/library/bb397466(v=vs.100).aspx} * */ class PageRequestManagerServerErrorException { // Nothing to define } /** * Raised when the request times out. * A partial-page update is initiated by a client request (an asynchronous postback) to the server. The server processes the request and returns a response to the client. * If the browser does not receive a response in a specified time, the Sys.WebForms.PageRequestManagerTimeoutException is raised. * To change the interval that elapses before asynchronous postbacks time out, set the AsyncPostBackTimeout property of the ScriptManager control. * @see {@link http://msdn.microsoft.com/en-us/library/bb397466(v=vs.100).aspx} */ class PageRequestManagerTimeoutException { // Nothing to define } //#endregion } //#endregion } //#endregion
the_stack
import { createElement } from '@syncfusion/ej2-base'; import { Diagram } from '../../../src/diagram/diagram'; import { NodeModel, BpmnShapeModel } from '../../../src/diagram/objects/node-model'; import { ShapeAnnotationModel } from '../../../src/diagram/objects/annotation-model'; import { PointPortModel } from '../../../src/diagram/objects/port-model'; import { HorizontalAlignment, VerticalAlignment } from '../../../src/diagram/enum/enum'; import { TextStyleModel, } from '../../../src/diagram/core/appearance-model'; import { BpmnDiagrams } from '../../../src/diagram/objects/bpmn'; import { ConnectorModel, BpmnFlowModel } from '../../../src/diagram/objects/connector-model'; import { Segments, DecoratorShapes } from '../../../src/diagram/enum/enum'; import { DiagramElement } from '../../../src/diagram/core/elements/diagram-element'; import { profile, inMB, getMemoryProfile } from '../../../spec/common.spec'; Diagram.Inject(BpmnDiagrams); /** * BPMN Shapes property change */ describe('Diagram Control', () => { describe('BPMN Shape property Changes ', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'bpmna1' }); document.body.appendChild(ele); let node: NodeModel = { id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100, shape: { type: 'Bpmn', shape: 'DataObject', dataObject: { collection: false, type: 'Input' } } as BpmnShapeModel }; let node1: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 300, offsetY: 100, shape: { type: 'Bpmn', shape: 'Gateway', gateway: { type: 'Exclusive' } }, }; let node2: NodeModel = { id: 'node2', width: 100, height: 100, offsetX: 500, offsetY: 100, shape: { type: 'Bpmn', shape: 'Gateway', gateway: { type: 'EventBased' } }, }; let node3: NodeModel = { id: 'node3', width: 100, height: 100, offsetX: 700, offsetY: 100, shape: { type: 'Bpmn', shape: 'Gateway', gateway: { type: 'Inclusive' } }, }; let node4: NodeModel = { id: 'node4', width: 100, height: 100, offsetX: 900, offsetY: 100, shape: { type: 'Bpmn', shape: 'Event', event: { event: 'Start', trigger: 'None' } } }; let node5: NodeModel = { id: 'node5', width: 100, height: 100, offsetX: 100, offsetY: 300, shape: { type: 'Bpmn', shape: 'DataObject', dataObject: { collection: false, type: 'Input' } } as BpmnShapeModel }; let node6: NodeModel = { id: 'node6', width: 100, height: 100, offsetX: 300, offsetY: 300, shape: { type: 'Bpmn', shape: 'Gateway', gateway: { type: 'Exclusive' } }, }; let node7: NodeModel = { id: 'node7', width: 100, height: 100, offsetX: 500, offsetY: 300, shape: { type: 'Bpmn', shape: 'Gateway', gateway: { type: 'EventBased' } }, }; let node8: NodeModel = { id: 'node8', width: 100, height: 100, offsetX: 700, offsetY: 300, shape: { type: 'Bpmn', shape: 'Message' } as BpmnShapeModel }; diagram = new Diagram({ width: '1500px', height: '600px', nodes: [node, node1, node2, node3, node4, node5, node6, node7, node8] }); diagram.appendTo('#bpmna1'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking data object to gateway', (done: Function) => { // gateway ((diagram.nodes[0] as NodeModel).shape as BpmnShapeModel).shape = 'Gateway'; ((diagram.nodes[0] as NodeModel).shape as BpmnShapeModel).gateway.type = 'Complex'; diagram.dataBind(); expect((((diagram.nodes[0] as NodeModel).shape as BpmnShapeModel).shape === 'Gateway') && (((diagram.nodes[0] as NodeModel).shape as BpmnShapeModel).gateway.type === 'Complex')).toBe(true); done(); }); it('Checking gateway to data object', (done: Function) => { ((diagram.nodes[1] as NodeModel).shape as BpmnShapeModel).shape = 'DataObject'; ((diagram.nodes[1] as NodeModel).shape as BpmnShapeModel).dataObject.type = 'Output'; ((diagram.nodes[1] as NodeModel).shape as BpmnShapeModel).dataObject.collection = true; diagram.dataBind(); // dataobject expect((((diagram.nodes[1] as NodeModel).shape as BpmnShapeModel).shape === 'DataObject') && (((diagram.nodes[1] as NodeModel).shape as BpmnShapeModel).dataObject.type === 'Output') && (((diagram.nodes[1] as NodeModel).shape as BpmnShapeModel).dataObject.collection === true) ).toBe(true); done(); }); it('Checking gateway to event', (done: Function) => { ((diagram.nodes[2] as NodeModel).shape as BpmnShapeModel).shape = 'Event'; ((diagram.nodes[2] as NodeModel).shape as BpmnShapeModel).event.event = 'Intermediate'; ((diagram.nodes[2] as NodeModel).shape as BpmnShapeModel).event.trigger = 'Error'; // //events diagram.dataBind(); expect((((diagram.nodes[2] as NodeModel).shape as BpmnShapeModel).shape === 'Event') && (((diagram.nodes[2] as NodeModel).shape as BpmnShapeModel).event.event === 'Intermediate') && (((diagram.nodes[2] as NodeModel).shape as BpmnShapeModel).event.trigger === 'Error') ).toBe(true); done(); }); it('Checking gateway, event to activity', (done: Function) => { ((diagram.nodes[3] as NodeModel).shape as BpmnShapeModel).shape = 'Activity'; ((diagram.nodes[3] as NodeModel).shape as BpmnShapeModel).activity.task.type = 'Service'; //activity - task ((diagram.nodes[4] as NodeModel).shape as BpmnShapeModel).shape = 'Activity'; ((diagram.nodes[4] as NodeModel).shape as BpmnShapeModel).activity.task.type = 'Service'; ((diagram.nodes[4] as NodeModel).shape as BpmnShapeModel).activity.task.loop = 'ParallelMultiInstance'; //activity- task with loop type diagram.dataBind(); expect(((diagram.nodes[3] as NodeModel).shape as BpmnShapeModel).shape === 'Activity' && ((diagram.nodes[3] as NodeModel).shape as BpmnShapeModel).activity.task.type === 'Service' ).toBe(true); done(); }); it('Checking data object to message shape', (done: Function) => { ((diagram.nodes[5] as NodeModel).shape as BpmnShapeModel).shape = 'Message'; // message diagram.dataBind(); expect(((diagram.nodes[5] as NodeModel).shape as BpmnShapeModel).shape === 'Message').toBe(true); done(); }); it('Gateway to Data source property change', (done: Function) => { ((diagram.nodes[6] as NodeModel).shape as BpmnShapeModel).shape = 'DataSource'; diagram.dataBind(); expect(((diagram.nodes[6] as NodeModel).shape as BpmnShapeModel).shape === 'DataSource').toBe(true); done(); }); it('Checking message to activity', (done: Function) => { ((diagram.nodes[8] as NodeModel).shape as BpmnShapeModel).shape = 'Activity'; ((diagram.nodes[8] as NodeModel).shape as BpmnShapeModel).activity.task.type = 'Service'; ((diagram.nodes[8] as NodeModel).shape as BpmnShapeModel).activity.task.loop = 'ParallelMultiInstance'; diagram.dataBind(); expect(((diagram.nodes[8] as NodeModel).shape as BpmnShapeModel).shape === 'Activity').toBe(true); done(); }); }); describe('Change the bpmn shapes ', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'bpmna2' }); document.body.appendChild(ele); let node9: NodeModel = { id: 'node9', width: 100, height: 100, offsetX: 100, offsetY: 300, shape: { type: 'Bpmn', shape: 'DataSource' } as BpmnShapeModel }; let node11: NodeModel = { id: 'node11', width: 100, height: 100, offsetX: 700, offsetY: 500, shape: { type: 'Bpmn', shape: 'Activity', activity: { activity: 'Task', task: { type: 'Service', compensation: false, } } } as BpmnShapeModel, }; let node13: NodeModel = { id: 'node13', width: 100, height: 100, offsetX: 500, offsetY: 500, shape: { type: 'Bpmn', shape: 'Activity', activity: { activity: 'SubProcess', subProcess: { type: 'Event', loop: 'ParallelMultiInstance', compensation: true, adhoc: false, boundary: 'Event', collapsed: true, events: [{ height: 20, width: 20, offset: { x: 0, y: 0 }, annotations: [{ id: 'label3', horizontalAlignment: 'Center', verticalAlignment: 'Center', content: 'Text', offset: { x: 0, y: 0 }, style: { color: 'black', fill: 'red', fontFamily: 'Fantasy', fontSize: 12, strokeColor: 'white', } as TextStyleModel } as ShapeAnnotationModel], ports: [{ shape: 'Square', id: 'port4', horizontalAlignment: 'Right', verticalAlignment: 'Bottom', width: 6, height: 6, offset: { x: 1, y: 1 }, style: { fill: 'red', strokeColor: 'black', strokeWidth: 2, opacity: 1 } } as PointPortModel], event: 'Intermediate', trigger: 'Error' }] } } } as BpmnShapeModel }; diagram = new Diagram({ width: '1500px', height: '600px', nodes: [node9, node11, node13] }); diagram.appendTo('#bpmna2'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking data source to event', (done: Function) => { ((diagram.nodes[0] as NodeModel).shape as BpmnShapeModel).shape = 'Event'; ((diagram.nodes[0] as NodeModel).shape as BpmnShapeModel).event.event = 'Intermediate'; ((diagram.nodes[0] as NodeModel).shape as BpmnShapeModel).event.trigger = 'Error'; diagram.dataBind(); expect(((diagram.nodes[0] as NodeModel).shape as BpmnShapeModel).shape === 'Event' && ((diagram.nodes[0] as NodeModel).shape as BpmnShapeModel).event.event === 'Intermediate' && ((diagram.nodes[0] as NodeModel).shape as BpmnShapeModel).event.trigger === 'Error').toBe(true); done(); }); it('Checking activity to message', (done: Function) => { ((diagram.nodes[2] as NodeModel).shape as BpmnShapeModel).shape = 'Message'; diagram.dataBind(); expect((((diagram.nodes[2] as NodeModel).shape as BpmnShapeModel).shape === 'Message')).toBe(true); done(); }); }); describe('Change the bpmn subprocess shapes ', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'bpmnsubprocess' }); document.body.appendChild(ele); let node9: NodeModel = { id: 'node9', width: 100, height: 100, offsetX: 100, offsetY: 300, shape: { type: 'Bpmn', shape: 'Activity', activity: { activity: 'SubProcess', subProcess: { type: 'Event', loop: 'ParallelMultiInstance', compensation: true, adhoc: false, boundary: 'Event', collapsed: true, events: [{ height: 20, width: 20, offset: { x: 0, y: 0 }, annotations: [{ id: 'label3', horizontalAlignment: 'Center', verticalAlignment: 'Center', content: 'Text', offset: { x: 0, y: 0 }, style: { color: 'black', fill: 'red', fontFamily: 'Fantasy', fontSize: 12, strokeColor: 'white', } as TextStyleModel } as ShapeAnnotationModel], ports: [{ shape: 'Square', id: 'port4', horizontalAlignment: 'Right', verticalAlignment: 'Bottom', width: 6, height: 6, offset: { x: 1, y: 1 }, style: { fill: 'red', strokeColor: 'black', strokeWidth: 2, opacity: 1 } } as PointPortModel], event: 'Intermediate', trigger: 'Error' }] } } } as BpmnShapeModel }; let node10: NodeModel = { id: 'node10', width: 100, height: 100, offsetX: 500, offsetY: 300, shape: { type: 'Bpmn', shape: 'Activity', activity: { activity: 'SubProcess', subProcess: { type: 'Event', loop: 'ParallelMultiInstance', compensation: true, adhoc: false, boundary: 'Event', collapsed: true, events: [{ height: 20, width: 20, offset: { x: 0, y: 0 }, annotations: [{ id: 'label3', horizontalAlignment: 'Center', verticalAlignment: 'Center', content: 'Text', offset: { x: 0, y: 0 }, style: { color: 'black', fill: 'red', fontFamily: 'Fantasy', fontSize: 12, strokeColor: 'white', } as TextStyleModel } as ShapeAnnotationModel], ports: [{ shape: 'Square', id: 'port4', horizontalAlignment: 'Right', verticalAlignment: 'Bottom', width: 6, height: 6, offset: { x: 1, y: 1 }, style: { fill: 'red', strokeColor: 'black', strokeWidth: 2, opacity: 1 } } as PointPortModel], event: 'Intermediate', trigger: 'Error' }] } } } as BpmnShapeModel }; let node11: NodeModel = { id: 'node11', width: 100, height: 100, offsetX: 700, offsetY: 500, shape: { type: 'Bpmn', shape: 'Activity', activity: { activity: 'SubProcess', subProcess: { type: 'Event', loop: 'ParallelMultiInstance', compensation: true, adhoc: false, boundary: 'Event', collapsed: true, events: [{ height: 20, width: 20, offset: { x: 0, y: 0 }, annotations: [{ id: 'label3', horizontalAlignment: 'Center', verticalAlignment: 'Center', content: 'Text', offset: { x: 0, y: 0 }, style: { color: 'black', fill: 'red', fontFamily: 'Fantasy', fontSize: 12, strokeColor: 'white', } as TextStyleModel } as ShapeAnnotationModel], ports: [{ shape: 'Square', id: 'port4', horizontalAlignment: 'Right', verticalAlignment: 'Bottom', width: 6, height: 6, offset: { x: 1, y: 1 }, style: { fill: 'red', strokeColor: 'black', strokeWidth: 2, opacity: 1 } } as PointPortModel], event: 'Intermediate', trigger: 'Error' }] } } } as BpmnShapeModel, }; diagram = new Diagram({ width: '1500px', height: '600px', nodes: [node9, node10, node11,] }); diagram.appendTo('#bpmnsubprocess'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking subprocess changes compensation, adhoc enabling', (done: Function) => { ((diagram.nodes[0] as NodeModel).shape as BpmnShapeModel).activity.subProcess.loop = 'SequenceMultiInstance'; ((diagram.nodes[0] as NodeModel).shape as BpmnShapeModel).activity.subProcess.compensation = true; ((diagram.nodes[0] as NodeModel).shape as BpmnShapeModel).activity.subProcess.adhoc = true; ((diagram.nodes[0] as NodeModel).shape as BpmnShapeModel).activity.subProcess.boundary = 'Call'; ((diagram.nodes[0] as NodeModel).shape as BpmnShapeModel).activity.subProcess.collapsed = false; diagram.dataBind(); expect(((diagram.nodes[0] as NodeModel).shape as BpmnShapeModel).activity.subProcess.loop === 'SequenceMultiInstance' && ((diagram.nodes[0] as NodeModel).shape as BpmnShapeModel).activity.subProcess.compensation === true && ((diagram.nodes[0] as NodeModel).shape as BpmnShapeModel).activity.subProcess.adhoc === true).toBe(true); done(); }); it('Checking subprocess changes compensation, adhoc disabling', (done: Function) => { ((diagram.nodes[1] as NodeModel).shape as BpmnShapeModel).activity.subProcess.loop = 'ParallelMultiInstance'; ((diagram.nodes[1] as NodeModel).shape as BpmnShapeModel).activity.subProcess.compensation = false; ((diagram.nodes[1] as NodeModel).shape as BpmnShapeModel).activity.subProcess.adhoc = false; ((diagram.nodes[1] as NodeModel).shape as BpmnShapeModel).activity.subProcess.boundary = 'Default'; ((diagram.nodes[1] as NodeModel).shape as BpmnShapeModel).activity.subProcess.collapsed = true; diagram.dataBind(); expect(((diagram.nodes[1] as NodeModel).shape as BpmnShapeModel).activity.subProcess.compensation === false && ((diagram.nodes[1] as NodeModel).shape as BpmnShapeModel).activity.subProcess.boundary === 'Default').toBe(true); done(); }); it('Checking subprocess boundary as event', (done: Function) => { ((diagram.nodes[2] as NodeModel).shape as BpmnShapeModel).activity.subProcess.boundary = 'Event'; diagram.dataBind(); expect((((diagram.nodes[2] as NodeModel).shape as BpmnShapeModel).activity.subProcess.boundary === 'Event')).toBe(true); done(); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }) }); });
the_stack
import { ExtractResult, RegExpUtility, Match, StringUtility } from "@microsoft/recognizers-text"; import { Constants, TimeTypeConstants } from "./constants"; import { Constants as NumberConstants } from "@microsoft/recognizers-text-number"; import { BaseNumberExtractor, BaseNumberParser } from "@microsoft/recognizers-text-number"; import { Token, DateTimeFormatUtil, DateTimeResolutionResult, IDateTimeUtilityConfiguration, AgoLaterUtil, AgoLaterMode, DateUtils, DayOfWeek, MatchingUtil } from "./utilities"; import { IDateTimeExtractor } from "./baseDateTime"; import { BaseDurationExtractor, BaseDurationParser } from "./baseDuration"; import { IDateTimeParser, DateTimeParseResult } from "./parsers"; import toNumber = require("lodash.tonumber"); export interface IDateExtractorConfiguration { dateRegexList: RegExp[], implicitDateList: RegExp[], monthEnd: RegExp, ofMonth: RegExp, dateUnitRegex: RegExp, forTheRegex: RegExp, weekDayAndDayOfMonthRegex: RegExp, relativeMonthRegex: RegExp, strictRelativeRegex: RegExp, weekDayRegex: RegExp, dayOfWeek: ReadonlyMap<string, number>; ordinalExtractor: BaseNumberExtractor, integerExtractor: BaseNumberExtractor, numberParser: BaseNumberParser, durationExtractor: IDateTimeExtractor, utilityConfiguration: IDateTimeUtilityConfiguration, rangeConnectorSymbolRegex: RegExp, } export class BaseDateExtractor implements IDateTimeExtractor { protected readonly extractorName = Constants.SYS_DATETIME_DATE; protected readonly config: IDateExtractorConfiguration; constructor(config: IDateExtractorConfiguration) { this.config = config; } extract(source: string, refDate: Date): ExtractResult[] { if (!refDate) { refDate = new Date(); } let referenceDate = refDate; let tokens: Token[] = new Array<Token>(); tokens = tokens.concat(this.basicRegexMatch(source)); tokens = tokens.concat(this.implicitDate(source)); tokens = tokens.concat(this.numberWithMonth(source, referenceDate)); tokens = tokens.concat(this.durationWithBeforeAndAfter(source, referenceDate)); let result = Token.mergeAllTokens(tokens, source, this.extractorName); return result; } protected basicRegexMatch(source: string): Token[] { let ret = []; this.config.dateRegexList.forEach(regexp => { let matches = RegExpUtility.getMatches(regexp, source); matches.forEach(match => { if (this.ValidateMatch(match, source)) { let preText = source.substring(0, match.index); let relativeRegex = RegExpUtility.getMatchEnd(this.config.strictRelativeRegex, preText, true); if (relativeRegex.success) { ret.push(new Token(relativeRegex.match.index, match.index + match.length)); } else { ret.push(new Token(match.index, match.index + match.length)); } } }); }); return ret; } // this method is to validate whether the match is part of date range and is a correct split // For example: in case "10-1 - 11-7", "10-1 - 11" can be matched by some of the Regexes, but the full text is a date range, so "10-1 - 11" is not a correct split protected ValidateMatch(match: Match, text: string): boolean { // If the match doesn't contains "year" part, it will not be ambiguous and it's a valid match let isValidMatch = match.groups('year') === undefined; if (!isValidMatch) { let yearGroup = match.groups("year"); // If the "year" part is not at the end of the match, it's a valid match if (yearGroup.index + yearGroup.length != match.index + match.length) { isValidMatch = true; } else { let subText = text.substring(yearGroup.index); // If the following text (include the "year" part) doesn't start with a Date entity, it's a valid match if (!this.StartsWithBasicDate(subText)) { isValidMatch = true; } else { // If the following text (include the "year" part) starts with a Date entity, but the following text (doesn't include the "year" part) also starts with a valid Date entity, the current match is still valid // For example, "10-1-2018-10-2-2018". Match "10-1-2018" is valid because though "2018-10-2" a valid match (indicates the first year "2018" might belongs to the second Date entity), but "10-2-2018" is also a valid match. subText = text.substring(yearGroup.index + yearGroup.length).trim(); subText = this.TrimStartRangeConnectorSymbols(subText); isValidMatch = this.StartsWithBasicDate(subText); } } // Expressions with mixed separators are not considered valid dates e.g. "30/4.85" (unless one is a comma "30/4, 2016") if (match.groups("day") !== undefined && match.groups("month") !== undefined) { let noDateText = match.value.replace(match.groups("year").value, "") .replace(match.groups("month").value, "") .replace(match.groups("day").value, ""); let separators = [ '/', '\\', '-', '.' ]; if (separators.filter(separator => noDateText.indexOf(separator) >= 0).length > 1) { isValidMatch = false; } } } return isValidMatch; } // TODO: Simplify this method to improve its performance protected TrimStartRangeConnectorSymbols(text: string): string { let rangeConnectorSymbolMatches = RegExpUtility.getMatches(this.config.rangeConnectorSymbolRegex, text); rangeConnectorSymbolMatches.forEach( symbolMatch => { let startSymbolLength = -1; if (symbolMatch && symbolMatch.index === 0 && symbolMatch.length > startSymbolLength) { startSymbolLength = symbolMatch.length; } if (startSymbolLength > 0) { text = text.substring(startSymbolLength); } }); return text.trim(); } // TODO: Simplify this method to improve its performance protected StartsWithBasicDate(text: string): boolean { this.config.dateRegexList.forEach(regex => { let match = RegExpUtility.getMatches(regex, text.trim()).pop(); if (match && match.index === 0) { return true; } }); return false; } protected implicitDate(source: string): Token[] { let ret = []; this.config.implicitDateList.forEach(regexp => { let matches = RegExpUtility.getMatches(regexp, source); matches.forEach(match => { ret.push(new Token(match.index, match.index + match.length)); }); }); return ret; } private numberWithMonth(source: string, refDate: Date): Token[] { let ret = []; let er = this.config.ordinalExtractor.extract(source).concat(this.config.integerExtractor.extract(source)); er.forEach(result => { let num = toNumber(this.config.numberParser.parse(result).value); if (num < 1 || num > 31) { return; } if (result.start >= 0) { let frontString = source.substring(0, result.start | 0); // Check that the extracted number is not part of a decimal number, time expression or currency // (e.g. '123.24', '12:24', '$12') if (MatchingUtil.isInvalidDayNumberPrefix(frontString)) { return; } let match = RegExpUtility.getMatches(this.config.monthEnd, frontString)[0]; if (match && match.length) { ret.push(new Token(match.index, match.index + match.length + result.length)); return; } // handling cases like 'for the 25th' let matches = RegExpUtility.getMatches(this.config.forTheRegex, source); let isFound = false; matches.forEach(matchCase => { if (matchCase) { let ordinalNum = matchCase.groups('DayOfMonth').value; if (ordinalNum === result.text) { let length = matchCase.groups('end').value.length; ret.push(new Token(matchCase.index, matchCase.index + matchCase.length - length)); isFound = true; } } }); if (isFound) { return; } // handling cases like 'Thursday the 21st', which both 'Thursday' and '21st' refer to a same date matches = RegExpUtility.getMatches(this.config.weekDayAndDayOfMonthRegex, source); matches.forEach(matchCase => { if (matchCase) { let ordinalNum = matchCase.groups('DayOfMonth').value; if (ordinalNum === result.text) { let month = refDate.getMonth(); let year = refDate.getFullYear(); // get week of day for the ordinal number which is regarded as a date of reference month let date = DateUtils.safeCreateFromMinValue(year, month, num); let numWeekDayStr = DayOfWeek[date.getDay()].toString().toLowerCase(); // get week day from text directly, compare it with the weekday generated above // to see whether they refer to a same week day let extractedWeekDayStr = matchCase.groups("weekday").value.toString().toLowerCase(); if (date !== DateUtils.minValue() && this.config.dayOfWeek.get(numWeekDayStr) === this.config.dayOfWeek.get(extractedWeekDayStr)) { ret.push(new Token(matchCase.index, result.start + result.length)); isFound = true; } } } }); if (isFound) { return; } // handling cases like '20th of next month' let suffixStr = source.substr(result.start + result.length).toLowerCase(); match = RegExpUtility.getMatches(this.config.relativeMonthRegex, suffixStr.trim()).pop(); if (match && match.index === 0) { let spaceLen = suffixStr.length - suffixStr.trim().length; ret.push(new Token(result.start, result.start + result.length + spaceLen + match.length)); } // handling cases like 'second Sunday' match = RegExpUtility.getMatches(this.config.weekDayRegex, suffixStr.trim()).pop(); if (match && match.index === 0 && num >= 1 && num <= 5 && result.type === NumberConstants.SYS_NUM_ORDINAL) { let weekDayStr = match.groups('weekday').value; if (this.config.dayOfWeek.has(weekDayStr)) { let spaceLen = suffixStr.length - suffixStr.trim().length; ret.push(new Token(result.start, result.start + result.length + spaceLen + match.length)); } } } if (result.start + result.length < source.length) { let afterString = source.substring(result.start + result.length); let match = RegExpUtility.getMatches(this.config.ofMonth, afterString)[0]; if (match && match.length) { ret.push(new Token(result.start, result.start + result.length + match.length)); return; } } }); return ret; } protected durationWithBeforeAndAfter(source: string, refDate: Date): Token[] { let ret = []; let durEx = this.config.durationExtractor.extract(source, refDate); durEx.forEach(er => { let match = RegExpUtility.getMatches(this.config.dateUnitRegex, er.text).pop(); if (!match) { return; } ret = AgoLaterUtil.extractorDurationWithBeforeAndAfter(source, er, ret, this.config.utilityConfiguration); }); return ret; } } export interface IDateParserConfiguration { ordinalExtractor: BaseNumberExtractor integerExtractor: BaseNumberExtractor cardinalExtractor: BaseNumberExtractor durationExtractor: IDateTimeExtractor durationParser: IDateTimeParser numberParser: BaseNumberParser monthOfYear: ReadonlyMap<string, number> dayOfMonth: ReadonlyMap<string, number> dayOfWeek: ReadonlyMap<string, number> unitMap: ReadonlyMap<string, string> cardinalMap: ReadonlyMap<string, number> dateRegex: RegExp[] onRegex: RegExp specialDayRegex: RegExp specialDayWithNumRegex: RegExp nextRegex: RegExp unitRegex: RegExp monthRegex: RegExp weekDayRegex: RegExp lastRegex: RegExp thisRegex: RegExp weekDayOfMonthRegex: RegExp forTheRegex: RegExp weekDayAndDayOfMonthRegex: RegExp relativeMonthRegex: RegExp strictRelativeRegex: RegExp relativeWeekDayRegex: RegExp utilityConfiguration: IDateTimeUtilityConfiguration dateTokenPrefix: string getSwiftDay(source: string): number getSwiftMonthOrYear(source: string): number isCardinalLast(source: string): boolean } export class BaseDateParser implements IDateTimeParser { protected readonly parserName = Constants.SYS_DATETIME_DATE; protected readonly config: IDateParserConfiguration; constructor(config: IDateParserConfiguration) { this.config = config; } parse(extractorResult: ExtractResult, referenceDate?: Date): DateTimeParseResult | null { if (!referenceDate) { referenceDate = new Date(); } let resultValue; if (extractorResult.type === this.parserName) { let source = extractorResult.text.toLowerCase(); let innerResult = this.parseBasicRegexMatch(source, referenceDate); if (!innerResult.success) { innerResult = this.parseImplicitDate(source, referenceDate); } if (!innerResult.success) { innerResult = this.parseWeekdayOfMonth(source, referenceDate); } if (!innerResult.success) { innerResult = this.parserDurationWithAgoAndLater(source, referenceDate); } if (!innerResult.success) { innerResult = this.parseNumberWithMonth(source, referenceDate); } if (!innerResult.success) { innerResult = this.parseSingleNumber(source, referenceDate); } if (innerResult.success) { innerResult.futureResolution = {}; innerResult.futureResolution[TimeTypeConstants.DATE] = DateTimeFormatUtil.formatDate(innerResult.futureValue); innerResult.pastResolution = {}; innerResult.pastResolution[TimeTypeConstants.DATE] = DateTimeFormatUtil.formatDate(innerResult.pastValue); resultValue = innerResult; } } let result = new DateTimeParseResult(extractorResult); result.value = resultValue; result.timexStr = resultValue ? resultValue.timex : ''; result.resolutionStr = ''; return result; } protected parseBasicRegexMatch(source: string, referenceDate: Date): DateTimeResolutionResult { let trimmedSource = source.trim(); let result = new DateTimeResolutionResult(); this.config.dateRegex.some(regex => { let offset = 0; let relativeStr = null; let match = RegExpUtility.getMatches(regex, trimmedSource).pop(); if (!match) { match = RegExpUtility.getMatches(regex, this.config.dateTokenPrefix + trimmedSource).pop(); if (match) { offset = this.config.dateTokenPrefix.length; relativeStr = match.groups('order').value; } } if (match) { let relativeRegex = RegExpUtility.getMatchEnd(this.config.strictRelativeRegex, source.substring(0, match.index), true); let isContainRelative = relativeRegex.success && match.index + match.length === trimmedSource.length; if ((match.index === offset && match.length === trimmedSource.length) || isContainRelative) { if (match.index !== offset) { relativeStr = relativeRegex.match.value; } result = this.matchToDate(match, referenceDate, relativeStr); return true; } } }); return result; } protected parseImplicitDate(source: string, referenceDate: Date): DateTimeResolutionResult { let trimmedSource = source.trim(); let result = new DateTimeResolutionResult(); // handle "on 12" let match = RegExpUtility.getMatches(this.config.onRegex, this.config.dateTokenPrefix + trimmedSource).pop(); if (match && match.index === this.config.dateTokenPrefix.length && match.length === trimmedSource.length) { let day = 0; let month = referenceDate.getMonth(); let year = referenceDate.getFullYear(); let dayStr = match.groups('day').value; day = this.config.dayOfMonth.get(dayStr); result.timex = DateTimeFormatUtil.luisDate(-1, -1, day); let tryStr = DateTimeFormatUtil.luisDate(year, month, day); let tryDate = Date.parse(tryStr); let futureDate: Date; let pastDate: Date; if (tryDate && !isNaN(tryDate)) { futureDate = DateUtils.safeCreateFromMinValue(year, month, day); pastDate = DateUtils.safeCreateFromMinValue(year, month, day); if (futureDate < referenceDate) { futureDate.setMonth(futureDate.getMonth() + 1); } if (pastDate >= referenceDate) { pastDate.setMonth(pastDate.getMonth() - 1); } } else { futureDate = DateUtils.safeCreateFromMinValue(year, month + 1, day); pastDate = DateUtils.safeCreateFromMinValue(year, month - 1, day); } result.futureValue = futureDate; result.pastValue = pastDate; result.success = true; return result; } // handle "today", "the day before yesterday" match = RegExpUtility.getMatches(this.config.specialDayRegex, trimmedSource).pop(); if (match && match.index === 0 && match.length === trimmedSource.length) { let swift = this.config.getSwiftDay(match.value); let today = DateUtils.safeCreateFromMinValue(referenceDate.getFullYear(), referenceDate.getMonth(), referenceDate.getDate()); let value = DateUtils.addDays(today, swift); result.timex = DateTimeFormatUtil.luisDateFromDate(value); result.futureValue = value; result.pastValue = value; result.success = true; return result; } // handle "two days from tomorrow" match = RegExpUtility.getMatches(this.config.specialDayWithNumRegex, trimmedSource).pop(); if (match && match.index === 0 && match.length === trimmedSource.length) { let swift = this.config.getSwiftDay(match.groups('day').value); let numErs = this.config.integerExtractor.extract(trimmedSource); let numOfDays = Number.parseInt(this.config.numberParser.parse(numErs[0]).value); let value = DateUtils.addDays(referenceDate, swift + numOfDays); result.timex = DateTimeFormatUtil.luisDateFromDate(value); result.futureValue = value; result.pastValue = value; result.success = true; return result; } // handle "two sundays from now" match = RegExpUtility.getMatches(this.config.relativeWeekDayRegex, trimmedSource).pop(); if (match && match.index === 0 && match.length === trimmedSource.length) { let numErs = this.config.integerExtractor.extract(trimmedSource); let num = Number.parseInt(this.config.numberParser.parse(numErs[0]).value); let weekdayStr = match.groups('weekday').value.toLowerCase(); let value = referenceDate; // Check whether the determined day of this week has passed. if (value.getDay() > this.config.dayOfWeek.get(weekdayStr)) { num--; } while (num-- > 0) { value = DateUtils.next(value, this.config.dayOfWeek.get(weekdayStr)); } result.timex = DateTimeFormatUtil.luisDateFromDate(value); result.futureValue = value; result.pastValue = value; result.success = true; return result; } // handle "next Sunday" match = RegExpUtility.getMatches(this.config.nextRegex, trimmedSource).pop(); if (match && match.index === 0 && match.length === trimmedSource.length) { let weekdayStr = match.groups('weekday').value; let value = DateUtils.next(referenceDate, this.config.dayOfWeek.get(weekdayStr)); result.timex = DateTimeFormatUtil.luisDateFromDate(value); result.futureValue = value; result.pastValue = value; result.success = true; return result; } // handle "this Friday" match = RegExpUtility.getMatches(this.config.thisRegex, trimmedSource).pop(); if (match && match.index === 0 && match.length === trimmedSource.length) { let weekdayStr = match.groups('weekday').value; let value = DateUtils.this(referenceDate, this.config.dayOfWeek.get(weekdayStr)); result.timex = DateTimeFormatUtil.luisDateFromDate(value); result.futureValue = value; result.pastValue = value; result.success = true; return result; } // handle "last Friday", "last mon" match = RegExpUtility.getMatches(this.config.lastRegex, trimmedSource).pop(); if (match && match.index === 0 && match.length === trimmedSource.length) { let weekdayStr = match.groups('weekday').value; let value = DateUtils.last(referenceDate, this.config.dayOfWeek.get(weekdayStr)); result.timex = DateTimeFormatUtil.luisDateFromDate(value); result.futureValue = value; result.pastValue = value; result.success = true; return result; } // handle "Friday" match = RegExpUtility.getMatches(this.config.weekDayRegex, trimmedSource).pop(); if (match && match.index === 0 && match.length === trimmedSource.length) { let weekdayStr = match.groups('weekday').value; let weekday = this.config.dayOfWeek.get(weekdayStr); let value = DateUtils.this(referenceDate, this.config.dayOfWeek.get(weekdayStr)); if (weekday === 0) { weekday = 7; } if (weekday < referenceDate.getDay()) { value = DateUtils.next(referenceDate, weekday); } result.timex = 'XXXX-WXX-' + weekday; let futureDate = new Date(value); let pastDate = new Date(value); if (futureDate < referenceDate) { futureDate.setDate(value.getDate() + 7); } if (pastDate >= referenceDate) { pastDate.setDate(value.getDate() - 7); } result.futureValue = futureDate; result.pastValue = pastDate; result.success = true; return result; } // handle "for the 27th." match = RegExpUtility.getMatches(this.config.forTheRegex, trimmedSource).pop(); if (match) { let dayStr = match.groups('DayOfMonth').value; let er = ExtractResult.getFromText(dayStr); let day = Number.parseInt(this.config.numberParser.parse(er).value); let month = referenceDate.getMonth(); let year = referenceDate.getFullYear(); result.timex = DateTimeFormatUtil.luisDate(-1, -1, day); let date = new Date(year, month, day); result.futureValue = date; result.pastValue = date; result.success = true; return result; } // handling cases like 'Thursday the 21st', which both 'Thursday' and '21st' refer to a same date match = RegExpUtility.getMatches(this.config.weekDayAndDayOfMonthRegex, trimmedSource).pop(); if (match) { let dayStr = match.groups('DayOfMonth').value; let er = ExtractResult.getFromText(dayStr); let day = Number.parseInt(this.config.numberParser.parse(er).value); let month = referenceDate.getMonth(); let year = referenceDate.getFullYear(); // the validity of the phrase is guaranteed in the Date Extractor result.timex = DateTimeFormatUtil.luisDate(year, month, day); result.futureValue = new Date(year, month, day); result.pastValue = new Date(year, month, day); result.success = true; return result; } return result; } private parseNumberWithMonth(source: string, referenceDate: Date): DateTimeResolutionResult { let trimmedSource = source.trim(); let ambiguous = true; let result = new DateTimeResolutionResult(); let ers = this.config.ordinalExtractor.extract(trimmedSource); if (!ers || ers.length === 0) { ers = this.config.integerExtractor.extract(trimmedSource); } if (!ers || ers.length === 0) { return result; } let num = Number.parseInt(this.config.numberParser.parse(ers[0]).value); let day = 1; let month = 0; let match = RegExpUtility.getMatches(this.config.monthRegex, trimmedSource).pop(); if (match) { month = this.config.monthOfYear.get(match.value) - 1; day = num; } else { // handling relative month match = RegExpUtility.getMatches(this.config.relativeMonthRegex, trimmedSource).pop(); if (match) { let monthStr = match.groups('order').value; let swift = this.config.getSwiftMonthOrYear(monthStr); let date = new Date(referenceDate); date.setMonth(referenceDate.getMonth() + swift); month = date.getMonth(); day = num; ambiguous = false; } } // handling casesd like 'second Sunday' if (!match) { match = RegExpUtility.getMatches(this.config.weekDayRegex, trimmedSource).pop(); if (match) { month = referenceDate.getMonth(); // resolve the date of wanted week day let wantedWeekDay = this.config.dayOfWeek.get(match.groups('weekday').value); let firstDate = DateUtils.safeCreateFromMinValue(referenceDate.getFullYear(), referenceDate.getMonth(), 1); let firstWeekday = firstDate.getDay(); let firstWantedWeekDay = new Date(firstDate); firstWantedWeekDay.setDate(firstDate.getDate() + ((wantedWeekDay > firstWeekday) ? wantedWeekDay - firstWeekday : wantedWeekDay - firstWeekday + 7)); day = firstWantedWeekDay.getDate() + ((num - 1) * 7); ambiguous = false; } } if (!match) { return result; } let year = referenceDate.getFullYear(); // for LUIS format value string let futureDate = DateUtils.safeCreateFromMinValue(year, month, day); let pastDate = DateUtils.safeCreateFromMinValue(year, month, day); if (ambiguous) { result.timex = DateTimeFormatUtil.luisDate(-1, month, day); if (futureDate < referenceDate) { futureDate.setFullYear(year + 1); } if (pastDate >= referenceDate) { pastDate.setFullYear(year - 1); } } else { result.timex = DateTimeFormatUtil.luisDate(year, month, day); } result.futureValue = futureDate; result.pastValue = pastDate; result.success = true; return result; } // handle cases like "the 27th". In the extractor, only the unmatched weekday and date will output this date. private parseSingleNumber(source: string, referenceDate: Date): DateTimeResolutionResult { let trimmedSource = source.trim(); let result = new DateTimeResolutionResult(); let er = this.config.ordinalExtractor.extract(trimmedSource).pop(); if (!er || StringUtility.isNullOrEmpty(er.text)) { er = this.config.integerExtractor.extract(trimmedSource).pop(); } if (!er || StringUtility.isNullOrEmpty(er.text)) { return result; } let day = Number.parseInt(this.config.numberParser.parse(er).value); let month = referenceDate.getMonth(); let year = referenceDate.getFullYear(); result.timex = DateTimeFormatUtil.luisDate(-1, -1, day); let pastDate = DateUtils.safeCreateFromMinValue(year, month, day); let futureDate = DateUtils.safeCreateFromMinValue(year, month, day); if (futureDate !== DateUtils.minValue() && futureDate < referenceDate) { futureDate.setMonth(month + 1); } if (pastDate !== DateUtils.minValue() && pastDate >= referenceDate) { pastDate.setMonth(month - 1); } result.futureValue = futureDate; result.pastValue = pastDate; result.success = true; return result; } protected parserDurationWithAgoAndLater(source: string, referenceDate: Date): DateTimeResolutionResult { return AgoLaterUtil.parseDurationWithAgoAndLater( source, referenceDate, this.config.durationExtractor, this.config.durationParser, this.config.unitMap, this.config.unitRegex, this.config.utilityConfiguration, AgoLaterMode.Date ); } protected parseWeekdayOfMonth(source: string, referenceDate: Date): DateTimeResolutionResult { let trimmedSource = source.trim(); let result = new DateTimeResolutionResult(); let match = RegExpUtility.getMatches(this.config.weekDayOfMonthRegex, trimmedSource).pop(); if (!match) { return result; } let cardinalStr = match.groups('cardinal').value; let weekdayStr = match.groups('weekday').value; let monthStr = match.groups('month').value; let noYear = false; let cardinal = this.config.isCardinalLast(cardinalStr) ? 5 : this.config.cardinalMap.get(cardinalStr); let weekday = this.config.dayOfWeek.get(weekdayStr); let month = referenceDate.getMonth(); let year = referenceDate.getFullYear(); if (StringUtility.isNullOrEmpty(monthStr)) { let swift = this.config.getSwiftMonthOrYear(trimmedSource); let temp = new Date(referenceDate); temp.setMonth(referenceDate.getMonth() + swift); month = temp.getMonth(); year = temp.getFullYear(); } else { month = this.config.monthOfYear.get(monthStr) - 1; noYear = true; } let value = this.computeDate(cardinal, weekday, month, year); if (value.getMonth() !== month) { cardinal -= 1; value.setDate(value.getDate() - 7); } let futureDate = value; let pastDate = value; if (noYear && futureDate < referenceDate) { futureDate = this.computeDate(cardinal, weekday, month, year + 1); if (futureDate.getMonth() !== month) { futureDate.setDate(futureDate.getDate() - 7); } } if (noYear && pastDate >= referenceDate) { pastDate = this.computeDate(cardinal, weekday, month, year - 1); if (pastDate.getMonth() !== month) { pastDate.setDate(pastDate.getDate() - 7); } } result.timex = ['XXXX', DateTimeFormatUtil.toString(month + 1, 2), 'WXX', weekday, '#' + cardinal].join('-'); result.futureValue = futureDate; result.pastValue = pastDate; result.success = true; return result; } protected matchToDate(match: Match, referenceDate: Date, relativeStr: string): DateTimeResolutionResult { let result = new DateTimeResolutionResult(); let yearStr = match.groups('year').value; let monthStr = match.groups('month').value; let dayStr = match.groups('day').value; let weekdayStr = match.groups('weekday').value; let month = 0; let day = 0; let year = 0; if (this.config.monthOfYear.has(monthStr) && this.config.dayOfMonth.has(dayStr)) { month = this.config.monthOfYear.get(monthStr) - 1; day = this.config.dayOfMonth.get(dayStr); if (!StringUtility.isNullOrEmpty(yearStr)) { year = Number.parseInt(yearStr, 10); if (year < 100 && year >= Constants.MinTwoDigitYearPastNum) { year += 1900; } else if (year >= 0 && year < Constants.MaxTwoDigitYearFutureNum) { year += 2000; } } } let noYear = false; if (year === 0) { year = referenceDate.getFullYear(); result.timex = DateTimeFormatUtil.luisDate(-1, month, day); if (!StringUtility.isNullOrEmpty(relativeStr)) { let swift = this.config.getSwiftMonthOrYear(relativeStr); if (!StringUtility.isNullOrEmpty(weekdayStr)) { swift = 0; } year += swift; } else { noYear = true; } } else { result.timex = DateTimeFormatUtil.luisDate(year, month, day); } let futurePastDates = DateUtils.generateDates(noYear, referenceDate, year, month, day); result.futureValue = futurePastDates.future; result.pastValue = futurePastDates.past; result.success = true; return result; } private computeDate(cardinal: number, weekday: number, month: number, year: number) { let firstDay = new Date(year, month, 1); let firstWeekday = DateUtils.this(firstDay, weekday); let dayOfWeekOfFirstDay = firstDay.getDay(); if (weekday === 0) { weekday = 7; } if (dayOfWeekOfFirstDay === 0) { dayOfWeekOfFirstDay = 7; } if (weekday < dayOfWeekOfFirstDay) { firstWeekday = DateUtils.next(firstDay, weekday); } firstWeekday.setDate(firstWeekday.getDate() + (7 * (cardinal - 1))); return firstWeekday; } }
the_stack
import destination from '@turf/destination'; import bearing from '@turf/bearing'; import pointToLineDistance from '@turf/point-to-line-distance'; import { flattenEach } from '@turf/meta'; import { point, MultiLineString } from '@turf/helpers'; import { getCoords } from '@turf/invariant'; import WebMercatorViewport from 'viewport-mercator-project'; import { Viewport, Pick, EditHandleFeature, EditHandleType } from './types'; import { Geometry, Position, Point, LineString, FeatureOf, FeatureWithProps, } from './geojson-types'; export type NearestPointType = FeatureWithProps<Point, { dist: number; index: number }>; export function toDeckColor( color?: [number, number, number, number] | number, defaultColor: [number, number, number, number] = [255, 0, 0, 255] ): [number, number, number, number] { if (!Array.isArray(color)) { return defaultColor; } return [color[0] * 255, color[1] * 255, color[2] * 255, color[3] * 255]; } // // a GeoJSON helper function that calls the provided function with // an argument that is the most deeply-nested array having elements // that are arrays of primitives as an argument, e.g. // // { // "type": "MultiPolygon", // "coordinates": [ // [ // [[30, 20], [45, 40], [10, 40], [30, 20]] // ], // [ // [[15, 5], [40, 10], [10, 20], [5, 10], [15, 5]] // ] // ] // } // // the function would be called on: // // [[30, 20], [45, 40], [10, 40], [30, 20]] // // and // // [[15, 5], [40, 10], [10, 20], [5, 10], [15, 5]] // export function recursivelyTraverseNestedArrays( array: Array<any>, prefix: Array<number>, fn: Function ) { if (!Array.isArray(array[0])) { return true; } for (let i = 0; i < array.length; i++) { if (recursivelyTraverseNestedArrays(array[i], [...prefix, i], fn)) { fn(array, prefix); break; } } return false; } export function generatePointsParallelToLinePoints( p1: Position, p2: Position, mapCoords: Position ): Position[] { const lineString: LineString = { type: 'LineString', coordinates: [p1, p2], }; const pt = point(mapCoords); const ddistance = pointToLineDistance(pt, lineString); const lineBearing = bearing(p1, p2); // Check if current point is to the left or right of line // Line from A=(x1,y1) to B=(x2,y2) a point P=(x,y) // then (x−x1)(y2−y1)−(y−y1)(x2−x1) const isPointToLeftOfLine = (mapCoords[0] - p1[0]) * (p2[1] - p1[1]) - (mapCoords[1] - p1[1]) * (p2[0] - p1[0]); // Bearing to draw perpendicular to the line string const orthogonalBearing = isPointToLeftOfLine < 0 ? lineBearing - 90 : lineBearing - 270; // Get coordinates for the point p3 and p4 which are perpendicular to the lineString // Add the distance as the current position moves away from the lineString const p3 = destination(p2, ddistance, orthogonalBearing); const p4 = destination(p1, ddistance, orthogonalBearing); return [p3.geometry.coordinates, p4.geometry.coordinates] as Position[]; } export function distance2d(x1: number, y1: number, x2: number, y2: number): number { const dx = x1 - x2; const dy = y1 - y2; return Math.sqrt(dx * dx + dy * dy); } export function mix(a: number, b: number, ratio: number): number { return b * ratio + a * (1 - ratio); } export function nearestPointOnProjectedLine( line: FeatureOf<LineString>, inPoint: FeatureOf<Point>, viewport: Viewport ): NearestPointType { const wmViewport = new WebMercatorViewport(viewport); // Project the line to viewport, then find the nearest point const coordinates: Array<Array<number>> = line.geometry.coordinates as any; const projectedCoords = coordinates.map(([x, y, z = 0]) => wmViewport.project([x, y, z])); // @ts-ignore const [x, y] = wmViewport.project(inPoint.geometry.coordinates); // console.log('projectedCoords', JSON.stringify(projectedCoords)); let minDistance = Infinity; let minPointInfo = {}; projectedCoords.forEach(([x2, y2], index) => { if (index === 0) { return; } const [x1, y1] = projectedCoords[index - 1]; // line from projectedCoords[index - 1] to projectedCoords[index] // convert to Ax + By + C = 0 const A = y1 - y2; const B = x2 - x1; const C = x1 * y2 - x2 * y1; // https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line const div = A * A + B * B; const distance = Math.abs(A * x + B * y + C) / Math.sqrt(div); // TODO: Check if inside bounds if (distance < minDistance) { minDistance = distance; minPointInfo = { index, x0: (B * (B * x - A * y) - A * C) / div, y0: (A * (-B * x + A * y) - B * C) / div, }; } }); // @ts-ignore const { index, x0, y0 } = minPointInfo; const [x1, y1, z1 = 0] = projectedCoords[index - 1]; const [x2, y2, z2 = 0] = projectedCoords[index]; // calculate what ratio of the line we are on to find the proper z const lineLength = distance2d(x1, y1, x2, y2); const startToPointLength = distance2d(x1, y1, x0, y0); const ratio = startToPointLength / lineLength; const z0 = mix(z1, z2, ratio); return { type: 'Feature', geometry: { type: 'Point', coordinates: wmViewport.unproject([x0, y0, z0]), }, properties: { // TODO: calculate the distance in proper units dist: minDistance, index: index - 1, }, }; } export function nearestPointOnLine<G extends LineString | MultiLineString>( lines: FeatureOf<LineString>, inPoint: FeatureOf<Point>, viewport?: Viewport ): NearestPointType { let mercator; if (viewport) { mercator = new WebMercatorViewport(viewport); } let closestPoint: any = point([Infinity, Infinity], { dist: Infinity, }); if (!lines.geometry?.coordinates.length || lines.geometry?.coordinates.length < 2) { return closestPoint; } // @ts-ignore flattenEach(lines, (line: any) => { const coords: any = getCoords(line); // @ts-ignore const pointCoords: any = getCoords(inPoint); let minDist; let to; let from; let x; let y; let segmentIdx; let dist; if (coords.length > 1 && pointCoords.length) { let lineCoordinates; let pointCoordinate; // If viewport is given, then translate these coordinates to pixels to increase precision if (mercator) { lineCoordinates = coords.map((lineCoordinate) => mercator.project(lineCoordinate)); pointCoordinate = mercator.project(pointCoords); } else { lineCoordinates = coords; pointCoordinate = pointCoords; } for (let n = 1; n < lineCoordinates.length; n++) { if (lineCoordinates[n][0] !== lineCoordinates[n - 1][0]) { const slope = (lineCoordinates[n][1] - lineCoordinates[n - 1][1]) / (lineCoordinates[n][0] - lineCoordinates[n - 1][0]); const inverseSlope = lineCoordinates[n][1] - slope * lineCoordinates[n][0]; dist = Math.abs(slope * pointCoordinate[0] + inverseSlope - pointCoordinate[1]) / Math.sqrt(slope * slope + 1); } else dist = Math.abs(pointCoordinate[0] - lineCoordinates[n][0]); // length^2 of line segment const rl2 = Math.pow(lineCoordinates[n][1] - lineCoordinates[n - 1][1], 2) + Math.pow(lineCoordinates[n][0] - lineCoordinates[n - 1][0], 2); // distance^2 of pt to end line segment const ln2 = Math.pow(lineCoordinates[n][1] - pointCoordinate[1], 2) + Math.pow(lineCoordinates[n][0] - pointCoordinate[0], 2); // distance^2 of pt to begin line segment const lnm12 = Math.pow(lineCoordinates[n - 1][1] - pointCoordinate[1], 2) + Math.pow(lineCoordinates[n - 1][0] - pointCoordinate[0], 2); // minimum distance^2 of pt to infinite line const dist2 = Math.pow(dist, 2); // calculated length^2 of line segment const calcrl2 = ln2 - dist2 + lnm12 - dist2; // redefine minimum distance to line segment (not infinite line) if necessary if (calcrl2 > rl2) { dist = Math.sqrt(Math.min(ln2, lnm12)); } if (minDist === null || minDist === undefined || minDist > dist) { // eslint-disable-next-line max-depth if (calcrl2 > rl2) { // eslint-disable-next-line max-depth if (lnm12 < ln2) { to = 0; // nearer to previous point from = 1; } else { from = 0; // nearer to current point to = 1; } } else { // perpendicular from point intersects line segment to = Math.sqrt(lnm12 - dist2) / Math.sqrt(rl2); from = Math.sqrt(ln2 - dist2) / Math.sqrt(rl2); } minDist = dist; segmentIdx = n; } } const dx = lineCoordinates[segmentIdx - 1][0] - lineCoordinates[segmentIdx][0]; const dy = lineCoordinates[segmentIdx - 1][1] - lineCoordinates[segmentIdx][1]; x = lineCoordinates[segmentIdx - 1][0] - dx * to; y = lineCoordinates[segmentIdx - 1][1] - dy * to; } // index needs to be -1 because we have to account for the shift from initial backscan let snapPoint = { x, y, idx: segmentIdx - 1, to, from }; if (mercator) { const pixelToLatLong = mercator.unproject([snapPoint.x, snapPoint.y]); snapPoint = { x: pixelToLatLong[0], y: pixelToLatLong[1], idx: segmentIdx - 1, to, from, }; } closestPoint = point([snapPoint.x, snapPoint.y], { dist: Math.abs(snapPoint.from - snapPoint.to), index: snapPoint.idx, }); }); return closestPoint; } export function getPickedEditHandle( picks: Pick[] | null | undefined ): EditHandleFeature | null | undefined { const handles = getPickedEditHandles(picks); return handles.length ? handles[0] : null; } export function getPickedSnapSourceEditHandle( picks: Pick[] | null | undefined ): EditHandleFeature | null | undefined { const handles = getPickedEditHandles(picks); return handles.find((handle) => handle.properties.editHandleType === 'snap-source'); } export function getNonGuidePicks(picks: Pick[]): Pick[] { return picks && picks.filter((pick) => !pick.isGuide); } export function getPickedExistingEditHandle( picks: Pick[] | null | undefined ): EditHandleFeature | null | undefined { const handles = getPickedEditHandles(picks); return handles.find( ({ properties }) => properties.featureIndex >= 0 && properties.editHandleType === 'existing' ); } export function getPickedIntermediateEditHandle( picks: Pick[] | null | undefined ): EditHandleFeature | null | undefined { const handles = getPickedEditHandles(picks); return handles.find( ({ properties }) => properties.featureIndex >= 0 && properties.editHandleType === 'intermediate' ); } export function getPickedEditHandles(picks: Pick[] | null | undefined): EditHandleFeature[] { const handles = (picks && picks .filter((pick) => pick.isGuide && pick.object.properties.guideType === 'editHandle') .map((pick) => pick.object)) || []; return handles; } export function getEditHandlesForGeometry( geometry: Geometry, featureIndex: number, editHandleType: EditHandleType = 'existing' ): EditHandleFeature[] { let handles: EditHandleFeature[] = []; switch (geometry.type) { case 'Point': // positions are not nested handles = [ { type: 'Feature', properties: { guideType: 'editHandle', editHandleType, positionIndexes: [], featureIndex, }, geometry: { type: 'Point', coordinates: geometry.coordinates, }, }, ]; break; case 'MultiPoint': case 'LineString': // positions are nested 1 level handles = handles.concat( getEditHandlesForCoordinates(geometry.coordinates, [], featureIndex, editHandleType) ); break; case 'Polygon': case 'MultiLineString': // positions are nested 2 levels for (let a = 0; a < geometry.coordinates.length; a++) { handles = handles.concat( getEditHandlesForCoordinates(geometry.coordinates[a], [a], featureIndex, editHandleType) ); if (geometry.type === 'Polygon') { // Don't repeat the first/last handle for Polygons handles = handles.slice(0, -1); } } break; case 'MultiPolygon': // positions are nested 3 levels for (let a = 0; a < geometry.coordinates.length; a++) { for (let b = 0; b < geometry.coordinates[a].length; b++) { handles = handles.concat( getEditHandlesForCoordinates( geometry.coordinates[a][b], [a, b], featureIndex, editHandleType ) ); // Don't repeat the first/last handle for Polygons handles = handles.slice(0, -1); } } break; default: // @ts-ignore throw Error(`Unhandled geometry type: ${geometry.type}`); } return handles; } function getEditHandlesForCoordinates( coordinates: any[], positionIndexPrefix: number[], featureIndex: number, editHandleType: EditHandleType = 'existing' ): EditHandleFeature[] { const editHandles = []; for (let i = 0; i < coordinates.length; i++) { const position = coordinates[i]; editHandles.push({ type: 'Feature', properties: { guideType: 'editHandle', positionIndexes: [...positionIndexPrefix, i], featureIndex, editHandleType, }, geometry: { type: 'Point', coordinates: position, }, }); } return editHandles; }
the_stack
import * as path from 'path'; import * as fs from 'fs-extra'; import { Chain, events as chainEvents, GenesisBlock, Block, blockSchema, blockHeaderSchema, Account, AccountSchema, readGenesisBlockJSON, Transaction, transactionSchema, getAccountSchemaWithDefault, getRegisteredBlockAssetSchema, AccountDefaultProps, RawBlockHeader, } from '@liskhq/lisk-chain'; import { EVENT_BFT_BLOCK_FINALIZED, BFT } from '@liskhq/lisk-bft'; import { getNetworkIdentifier, hash } from '@liskhq/lisk-cryptography'; import { TransactionPool, events as txPoolEvents } from '@liskhq/lisk-transaction-pool'; import { KVStore, NotFoundError } from '@liskhq/lisk-db'; import { jobHandlers } from '@liskhq/lisk-utils'; import { codec } from '@liskhq/lisk-codec'; import { APP_EVENT_BLOCK_DELETE, APP_EVENT_BLOCK_NEW, APP_EVENT_CHAIN_VALIDATORS_CHANGE, APP_EVENT_NETWORK_EVENT, APP_EVENT_NETWORK_READY, } from '../constants'; import { Forger } from './forger'; import { Transport, handlePostTransactionReturn } from './transport'; import { Synchronizer, BlockSynchronizationMechanism, FastChainSwitchingMechanism, } from './synchronizer'; import { Processor } from './processor'; import { Logger } from '../logger'; import { ApplicationConfig, EventPostTransactionData, ForgingStatus, RegisteredModule, RegisteredSchema, UpdateForgingStatusInput, } from '../types'; import { InMemoryChannel } from '../controller/channels'; import { ActionsDefinition } from '../controller/action'; import { EVENT_PROCESSOR_BROADCAST_BLOCK, EVENT_PROCESSOR_SYNC_REQUIRED, } from './processor/processor'; import { EVENT_SYNCHRONIZER_SYNC_REQUIRED } from './synchronizer/base_synchronizer'; import { Network } from './network'; import { BaseAsset, BaseModule } from '../modules'; import { Bus } from '../controller/bus'; const forgeInterval = 1000; const { EVENT_NEW_BLOCK, EVENT_DELETE_BLOCK, EVENT_VALIDATORS_CHANGED } = chainEvents; const { EVENT_TRANSACTION_REMOVED } = txPoolEvents; const MINIMUM_MODULE_ID = 2; export type NodeOptions = Omit<ApplicationConfig, 'plugins'>; interface NodeConstructor { readonly options: NodeOptions; } interface NodeInitInput { readonly dataPath: string; readonly genesisBlockJSON: Record<string, unknown>; readonly logger: Logger; readonly channel: InMemoryChannel; readonly forgerDB: KVStore; readonly blockchainDB: KVStore; readonly nodeDB: KVStore; readonly bus: Bus; } interface ForgingStatusResponse extends Omit<ForgingStatus, 'address'> { readonly address: string; } const compiledGenesisBlockFileName = 'genesis_block_compiled'; export class Node { private readonly _options: NodeOptions; private readonly _registeredModules: BaseModule[] = []; private _bus!: Bus; private _channel!: InMemoryChannel; private _logger!: Logger; private _nodeDB!: KVStore; private _forgerDB!: KVStore; private _blockchainDB!: KVStore; private _networkIdentifier!: Buffer; private _registeredAccountSchemas: { [moduleName: string]: AccountSchema } = {}; private _networkModule!: Network; private _chain!: Chain; private _bft!: BFT; private _processor!: Processor; private _synchronizer!: Synchronizer; private _transactionPool!: TransactionPool; private _transport!: Transport; private _forger!: Forger; private _forgingJob!: jobHandlers.Scheduler<void>; public constructor({ options }: NodeConstructor) { this._options = options; if (this._options.forging.waitThreshold >= this._options.genesisConfig.blockTime) { throw Error( `forging.waitThreshold=${this._options.forging.waitThreshold} is greater or equal to genesisConfig.blockTime=${this._options.genesisConfig.blockTime}. It impacts the forging and propagation of blocks. Please use a smaller value for forging.waitThreshold`, ); } } public getSchema(): RegisteredSchema { const transactionsAssets: RegisteredSchema['transactionsAssets'] = []; for (const customModule of this._registeredModules) { for (const customAsset of customModule.transactionAssets) { transactionsAssets.push({ moduleID: customModule.id, moduleName: customModule.name, assetID: customAsset.id, assetName: customAsset.name, schema: customAsset.schema, }); } } const { default: defaultAccount, ...accountSchema } = getAccountSchemaWithDefault( this._registeredAccountSchemas, ); const blockHeadersAssets = getRegisteredBlockAssetSchema(accountSchema); return { account: accountSchema, block: blockSchema, blockHeader: blockHeaderSchema, blockHeadersAssets, transaction: transactionSchema, transactionsAssets, }; } public getDefaultAccount(): Record<string, unknown> { const { default: defaultAccount } = getAccountSchemaWithDefault(this._registeredAccountSchemas); return defaultAccount; } public getRegisteredModules(): RegisteredModule[] { return this._registeredModules.reduce<RegisteredModule[]>((prev, current) => { const assets = current.transactionAssets.map(asset => ({ id: asset.id, name: asset.name })); prev.push({ id: current.id, name: current.name, actions: Object.keys(current.actions).map(key => `${current.name}:${key}`), events: current.events.map(key => `${current.name}:${key}`), reducers: Object.keys(current.reducers).map(key => `${current.name}:${key}`), transactionAssets: assets, }); return prev; }, []); } public registerModule(customModule: BaseModule): void { const exist = this._registeredModules.find(rm => rm.id === customModule.id); if (exist) { throw new Error(`Custom module with id ${customModule.id} already exists.`); } if (!customModule.name || !customModule.id) { throw new Error( `Custom module '${customModule.constructor.name}' is missing either one or both of the required properties: 'id', 'name'.`, ); } if (customModule.id < MINIMUM_MODULE_ID) { throw new Error(`Custom module must have id greater than ${MINIMUM_MODULE_ID}.`); } if (customModule.accountSchema) { this._registeredAccountSchemas[customModule.name] = { ...customModule.accountSchema, fieldNumber: customModule.id, }; } for (const asset of customModule.transactionAssets) { if (!(asset instanceof BaseAsset)) { throw new Error('Custom module contains asset which does not extend `BaseAsset` class.'); } if (typeof asset.name !== 'string' || asset.name === '') { throw new Error('Custom module contains asset with invalid `name` property.'); } if (typeof asset.id !== 'number') { throw new Error('Custom module contains asset with invalid `id` property.'); } if (typeof asset.schema !== 'object') { throw new Error('Custom module contains asset with invalid `schema` property.'); } if (typeof asset.apply !== 'function') { throw new Error('Custom module contains asset with invalid `apply` property.'); } } this._registeredModules.push(customModule); } public async init({ genesisBlockJSON, dataPath: configPath, bus, channel, blockchainDB, forgerDB, logger, nodeDB, }: NodeInitInput): Promise<void> { this._channel = channel; this._logger = logger; this._blockchainDB = blockchainDB; this._forgerDB = forgerDB; this._nodeDB = nodeDB; this._bus = bus; // read from compiled genesis block if exist const genesisBlock = this._readGenesisBlock(genesisBlockJSON, configPath); this._networkIdentifier = getNetworkIdentifier( genesisBlock.header.id, this._options.genesisConfig.communityIdentifier, ); this._initModules(genesisBlock); for (const customModule of this._registeredModules) { this._processor.register(customModule); const customModuleChannel = new InMemoryChannel( customModule.name, customModule.events, (customModule.actions as unknown) as ActionsDefinition, ); await customModuleChannel.registerToBus(this._bus); // Give limited access of channel to custom module to publish events customModule.init({ channel: { publish: (name: string, data?: Record<string, unknown>) => customModuleChannel.publish(name, data), }, dataAccess: { getChainState: async (key: string) => this._chain.dataAccess.getChainState(key), getAccountByAddress: async <T = AccountDefaultProps>(address: Buffer) => this._chain.dataAccess.getAccountByAddress<T>(address), getLastBlockHeader: async () => this._chain.dataAccess.getLastBlockHeader(), }, logger: this._logger, }); } // Initialize callable P2P endpoints this._networkModule.registerEndpoint('getTransactions', async ({ data, peerId }) => this._transport.handleRPCGetTransactions(data, peerId), ); this._networkModule.registerEndpoint('getLastBlock', ({ peerId }) => this._transport.handleRPCGetLastBlock(peerId), ); this._networkModule.registerEndpoint('getBlocksFromId', async ({ data, peerId }) => this._transport.handleRPCGetBlocksFromId(data, peerId), ); this._networkModule.registerEndpoint('getHighestCommonBlock', async ({ data, peerId }) => this._transport.handleRPCGetHighestCommonBlockID(data, peerId), ); // Network needs to be initialized first to call events await this._networkModule.bootstrap(this.networkIdentifier); // Start subscribing to events, so that genesis block will also be included in event this._subscribeToEvents(); // After binding, it should immediately load blockchain await this._processor.init(genesisBlock); // Check if blocks are left in temp_blocks table await this._synchronizer.init(); this._networkModule.applyNodeInfo({ height: this._chain.lastBlock.header.height, lastBlockID: this._chain.lastBlock.header.id, // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access maxHeightPrevoted: // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access this._chain.lastBlock.header.asset.maxHeightPrevoted ?? 0, blockVersion: this._chain.lastBlock.header.version, }); await this._transactionPool.start(); await this._startForging(); this._logger.info('Node ready and launched'); this._networkModule.events.on( APP_EVENT_NETWORK_READY, // eslint-disable-next-line @typescript-eslint/no-misused-promises async () => { await this._startLoader(); }, ); // Avoid receiving blocks/transactions from the network during snapshotting process this._networkModule.events.on( APP_EVENT_NETWORK_EVENT, // eslint-disable-next-line @typescript-eslint/no-misused-promises async (eventData?: Record<string, unknown>) => { const { event, data, peerId } = eventData as { event: string; data: Buffer | undefined; peerId: string; }; try { if (event === 'postTransactionsAnnouncement') { await this._transport.handleEventPostTransactionsAnnouncement(data, peerId); return; } if (event === 'postBlock') { await this._transport.handleEventPostBlock(data, peerId); return; } } catch (err) { this._logger.warn( // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment { err, event }, 'Received invalid event message', ); } }, ); } public get networkIdentifier(): Buffer { return this._networkIdentifier; } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types,@typescript-eslint/explicit-function-return-type public get actions() { return { getValidators: async (): Promise< ReadonlyArray<{ address: string; nextForgingTime: number; minActiveHeight: number; isConsensusParticipant: boolean; }> > => { const validators = await this._chain.getValidators(); const slot = this._chain.slots.getSlotNumber(); const startTime = this._chain.slots.getSlotTime(slot); let nextForgingTime = startTime; const slotInRound = slot % this._chain.numberOfValidators; const blockTime = this._chain.slots.blockTime(); const forgersInfo = []; for (let i = slotInRound; i < slotInRound + this._chain.numberOfValidators; i += 1) { const validator = validators[i % validators.length]; forgersInfo.push({ ...validator, address: validator.address.toString('hex'), nextForgingTime, }); nextForgingTime += blockTime; } return forgersInfo; }, updateForgingStatus: async ( params: UpdateForgingStatusInput, ): Promise<ForgingStatusResponse> => { const result = await this._forger.updateForgingStatus( Buffer.from(params.address, 'hex'), params.password, params.forging, params.height, params.maxHeightPreviouslyForged, params.maxHeightPrevoted, params.overwrite, ); return { address: result.address.toString('hex'), forging: result.forging, }; }, getAccount: async (params: { address: string }): Promise<string> => { const account = await this._chain.dataAccess.getAccountByAddress( Buffer.from(params.address, 'hex'), ); return this._chain.dataAccess.encodeAccount(account).toString('hex'); }, getAccounts: async (params: { address: readonly string[] }): Promise<readonly string[]> => { const accounts = await this._chain.dataAccess.getAccountsByAddress( params.address.map(address => Buffer.from(address, 'hex')), ); return accounts.map(account => this._chain.dataAccess.encodeAccount(account).toString('hex'), ); }, getBlockByID: async (params: { id: string }): Promise<string | undefined> => { const block = await this._chain.dataAccess.getBlockByID(Buffer.from(params.id, 'hex')); return this._chain.dataAccess.encode(block).toString('hex'); }, getBlocksByIDs: async (params: { ids: readonly string[] }): Promise<readonly string[]> => { const blocks = []; try { for (const id of params.ids) { const block = await this._chain.dataAccess.getBlockByID(Buffer.from(id, 'hex')); blocks.push(block); } } catch (error) { if (!(error instanceof NotFoundError)) { throw error; } } return blocks.map(block => this._chain.dataAccess.encode(block).toString('hex')); }, getBlockByHeight: async (params: { height: number }): Promise<string | undefined> => { const block = await this._chain.dataAccess.getBlockByHeight(params.height); return this._chain.dataAccess.encode(block).toString('hex'); }, getBlocksByHeightBetween: async (params: { from: number; to: number; }): Promise<readonly string[]> => { const blocks = await this._chain.dataAccess.getBlocksByHeightBetween( params.from, params.to, ); return blocks.map(b => this._chain.dataAccess.encode(b).toString('hex')); }, getTransactionByID: async (params: { id: string }): Promise<string> => { const transaction = await this._chain.dataAccess.getTransactionByID( Buffer.from(params.id, 'hex'), ); // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition return transaction.getBytes().toString('hex'); }, getTransactionsByIDs: async (params: { ids: readonly string[] }): Promise<string[]> => { const transactions = []; try { for (const id of params.ids) { const transaction = await this._chain.dataAccess.getTransactionByID( Buffer.from(id, 'hex'), ); transactions.push(transaction); } } catch (error) { if (!(error instanceof NotFoundError)) { throw error; } } return transactions.map(tx => tx.getBytes().toString('hex')); }, getForgingStatus: async (): Promise<ForgingStatusResponse[] | undefined> => { const forgingStatus = await this._forger.getForgingStatusOfAllDelegates(); if (forgingStatus) { return forgingStatus.map(({ address, ...forgingStatusWithoutAddress }) => ({ address: address.toString('hex'), ...forgingStatusWithoutAddress, })); } return undefined; }, getTransactionsFromPool: (): string[] => this._transactionPool.getAll().map(tx => tx.getBytes().toString('hex')), postTransaction: async ( params: EventPostTransactionData, ): Promise<handlePostTransactionReturn> => this._transport.handleEventPostTransaction(params), // eslint-disable-next-line @typescript-eslint/require-await getLastBlock: (): string => this._chain.dataAccess.encode(this._chain.lastBlock).toString('hex'), getSchema: () => this.getSchema(), getRegisteredModules: () => this.getRegisteredModules(), getNodeInfo: () => ({ version: this._options.version, networkVersion: this._options.networkVersion, networkIdentifier: this._networkIdentifier.toString('hex'), lastBlockID: this._chain.lastBlock.header.id.toString('hex'), height: this._chain.lastBlock.header.height, genesisHeight: this._chain.genesisHeight, finalizedHeight: this._bft.finalityManager.finalizedHeight, syncing: this._synchronizer.isActive, unconfirmedTransactions: this._transactionPool.getAll().length, genesisConfig: { ...this._options.genesisConfig, }, registeredModules: this.getRegisteredModules(), network: { port: this._options.network.port, hostIp: this._options.network.hostIp, seedPeers: this._options.network.seedPeers, blacklistedIPs: this._options.network.blacklistedIPs, fixedPeers: this._options.network.fixedPeers, whitelistedPeers: this._options.network.whitelistedPeers, }, }), getConnectedPeers: () => this._networkModule.getConnectedPeers(), getDisconnectedPeers: () => this._networkModule.getDisconnectedPeers(), getNetworkStats: () => this._networkModule.getNetworkStats(), }; } // eslint-disable-next-line @typescript-eslint/require-await public async cleanup(): Promise<void> { this._logger.info('Node cleanup started'); this._transactionPool.stop(); this._unsubscribeToEvents(); if (this._forgingJob) { this._forgingJob.stop(); } await this._synchronizer.stop(); await this._processor.stop(); this._logger.info('Node cleanup completed'); await this._networkModule.cleanup(); } private _initModules(genesisBlock: GenesisBlock): void { this._networkModule = new Network({ networkVersion: this._options.networkVersion, options: this._options.network, logger: this._logger, channel: this._channel, nodeDB: this._nodeDB, }); this._chain = new Chain({ db: this._blockchainDB, genesisBlock, networkIdentifier: this._networkIdentifier, maxPayloadLength: this._options.genesisConfig.maxPayloadLength, rewardDistance: this._options.genesisConfig.rewards.distance, rewardOffset: this._options.genesisConfig.rewards.offset, rewardMilestones: this._options.genesisConfig.rewards.milestones.map(s => BigInt(s)), blockTime: this._options.genesisConfig.blockTime, accountSchemas: this._registeredAccountSchemas, minFeePerByte: this._options.genesisConfig.minFeePerByte, baseFees: this._options.genesisConfig.baseFees, }); this._bft = new BFT({ chain: this._chain, threshold: this._options.genesisConfig.bftThreshold, genesisHeight: genesisBlock.header.height, }); this._processor = new Processor({ channel: this._channel, logger: this._logger, chainModule: this._chain, bftModule: this._bft, }); this._transactionPool = new TransactionPool({ baseFees: this._options.genesisConfig.baseFees.map(fees => ({ ...fees, baseFee: BigInt(fees.baseFee), })), minFeePerByte: this._options.genesisConfig.minFeePerByte, applyTransactions: async (transactions: Transaction[]) => { const stateStore = await this._chain.newStateStore(); return this._processor.verifyTransactions(transactions, stateStore); }, ...this._options.transactionPool, minEntranceFeePriority: BigInt(this._options.transactionPool.minEntranceFeePriority), minReplacementFeeDifference: BigInt( this._options.transactionPool.minReplacementFeeDifference, ), }); const blockSyncMechanism = new BlockSynchronizationMechanism({ logger: this._logger, bft: this._bft, channel: this._channel, chain: this._chain, processorModule: this._processor, networkModule: this._networkModule, }); const fastChainSwitchMechanism = new FastChainSwitchingMechanism({ logger: this._logger, channel: this._channel, chain: this._chain, bft: this._bft, processor: this._processor, networkModule: this._networkModule, }); this._synchronizer = new Synchronizer({ channel: this._channel, logger: this._logger, chainModule: this._chain, bftModule: this._bft, processorModule: this._processor, transactionPoolModule: this._transactionPool, mechanisms: [blockSyncMechanism, fastChainSwitchMechanism], networkModule: this._networkModule, }); blockSyncMechanism.events.on( EVENT_SYNCHRONIZER_SYNC_REQUIRED, ({ block, peerId }: { block: Block; peerId: string }) => { this._synchronizer.run(block, peerId).catch(err => { this._logger.error({ err: err as Error }, 'Error occurred during synchronization.'); }); }, ); fastChainSwitchMechanism.events.on( EVENT_SYNCHRONIZER_SYNC_REQUIRED, ({ block, peerId }: { block: Block; peerId: string }) => { this._synchronizer.run(block, peerId).catch(err => { this._logger.error({ err: err as Error }, 'Error occurred during synchronization.'); }); }, ); this._forger = new Forger({ logger: this._logger, // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment db: this._forgerDB, bftModule: this._bft, transactionPoolModule: this._transactionPool, processorModule: this._processor, chainModule: this._chain, forgingDelegates: this._options.forging.delegates.map(delegate => ({ ...delegate, address: Buffer.from(delegate.address, 'hex'), hashOnion: { ...delegate.hashOnion, hashes: delegate.hashOnion.hashes.map(h => Buffer.from(h, 'hex')), }, })), forgingForce: this._options.forging.force, forgingDefaultPassword: this._options.forging.defaultPassword, forgingWaitThreshold: this._options.forging.waitThreshold, }); this._transport = new Transport({ channel: this._channel, logger: this._logger, synchronizer: this._synchronizer, transactionPoolModule: this._transactionPool, processorModule: this._processor, chainModule: this._chain, networkModule: this._networkModule, }); } private async _startLoader(): Promise<void> { return this._synchronizer.loadUnconfirmedTransactions(); } private async _forgingTask(): Promise<void> { try { if (!this._forger.delegatesEnabled()) { this._logger.trace('No delegates are enabled'); return; } if (this._synchronizer.isActive) { this._logger.debug('Client not ready to forge'); return; } await this._forger.forge(); } catch (err) { this._logger.error({ err: err as Error }); } } private async _startForging(): Promise<void> { try { await this._forger.loadDelegates(); } catch (err) { this._logger.error({ err: err as Error }, 'Failed to load delegates for forging'); } this._forgingJob = new jobHandlers.Scheduler(async () => this._forgingTask(), forgeInterval); // eslint-disable-next-line @typescript-eslint/no-floating-promises this._forgingJob.start(); } private _subscribeToEvents(): void { this._chain.events.on( EVENT_NEW_BLOCK, // eslint-disable-next-line @typescript-eslint/no-misused-promises async (eventData: { block: Block; accounts: Account[]; // eslint-disable-next-line @typescript-eslint/require-await }): Promise<void> => { const { block } = eventData; // Publish to the outside this._channel.publish(APP_EVENT_BLOCK_NEW, { block: this._chain.dataAccess.encode(block).toString('hex'), accounts: eventData.accounts.map(acc => this._chain.dataAccess.encodeAccount(acc).toString('hex'), ), }); // Remove any transactions from the pool on new block if (block.payload.length) { for (const transaction of block.payload) { this._transactionPool.remove(transaction); } } if (!this._synchronizer.isActive) { this._networkModule.applyNodeInfo({ height: block.header.height, lastBlockID: block.header.id, // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access maxHeightPrevoted: block.header.asset.maxHeightPrevoted, blockVersion: block.header.version, }); } this._logger.info( { id: block.header.id, height: block.header.height, numberOfTransactions: block.payload.length, }, 'New block added to the chain', ); }, ); // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access this._chain.events.on( EVENT_DELETE_BLOCK, // eslint-disable-next-line @typescript-eslint/no-misused-promises async (eventData: { block: Block; accounts: Account[] }) => { const { block } = eventData; // Publish to the outside this._channel.publish(APP_EVENT_BLOCK_DELETE, { block: this._chain.dataAccess.encode(block).toString('hex'), accounts: eventData.accounts.map(acc => this._chain.dataAccess.encodeAccount(acc).toString('hex'), ), }); if (block.payload.length) { for (const transaction of block.payload) { try { await this._transactionPool.add(transaction); } catch (err) { this._logger.error( { err: err as Error }, 'Failed to add transaction back to the pool', ); } } } this._logger.info( { id: block.header.id, height: block.header.height }, 'Deleted a block from the chain', ); }, ); this._chain.events.on( EVENT_VALIDATORS_CHANGED, (eventData: { validators: [ { address: Buffer; isConsensusParticipant: boolean; minActiveHeight: number; }, ]; }): void => { const updatedValidatorsList = eventData.validators.map(aValidator => ({ ...aValidator, address: aValidator.address.toString('hex'), })); this._channel.publish(APP_EVENT_CHAIN_VALIDATORS_CHANGE, { validators: updatedValidatorsList, }); }, ); this._processor.events.on( EVENT_PROCESSOR_BROADCAST_BLOCK, // eslint-disable-next-line @typescript-eslint/no-misused-promises async ({ block }) => { await this._transport.handleBroadcastBlock(block); }, ); this._processor.events.on( EVENT_PROCESSOR_SYNC_REQUIRED, ({ block, peerId }: { block: Block; peerId: string }) => { this._synchronizer.run(block, peerId).catch(err => { this._logger.error({ err: err as Error }, 'Error occurred during synchronization.'); }); }, ); this._transactionPool.events.on(EVENT_TRANSACTION_REMOVED, event => { this._logger.debug(event, 'Transaction was removed from the pool.'); }); } private _unsubscribeToEvents(): void { this._bft.removeAllListeners(EVENT_BFT_BLOCK_FINALIZED); } private _readGenesisBlock( genesisBlockJSON: Record<string, unknown>, configPath: string, ): GenesisBlock { const compiledGenesisPath = path.join(configPath, compiledGenesisBlockFileName); const { default: defaultAccount, ...schema } = getAccountSchemaWithDefault( this._registeredAccountSchemas, ); const genesisAssetSchema = getRegisteredBlockAssetSchema(schema)[0]; // check local file for compiled const compiled = fs.existsSync(compiledGenesisPath); if (compiled) { const genesisBlockBytes = fs.readFileSync(compiledGenesisPath); // cannot use chain yet, so manually decode genesis block const blockHeader = codec.decode<RawBlockHeader>(blockHeaderSchema, genesisBlockBytes); const asset = codec.decode<GenesisBlock['header']['asset']>( genesisAssetSchema, blockHeader.asset, ); const id = hash(genesisBlockBytes); return { header: { ...blockHeader, asset, id, }, payload: [], }; } // decode from JSON file and store the encoded genesis block const genesisBlock = readGenesisBlockJSON(genesisBlockJSON, this._registeredAccountSchemas); const assetBytes = codec.encode(genesisAssetSchema, genesisBlock.header.asset); const headerBytes = codec.encode(blockHeaderSchema, { ...genesisBlock.header, asset: assetBytes, }); fs.writeFileSync(compiledGenesisPath, headerBytes); // encode genesis block and return genesisBlock; } }
the_stack
import * as React from 'react'; import styles from './EventRecurrenceInfoYearly.module.scss'; import * as strings from 'CalendarWebPartStrings'; import { IEventRecurrenceInfoYearlyProps } from './IEventRecurrenceInfoYearlyProps'; import { IEventRecurrenceInfoYearlyState } from './IEventRecurrenceInfoYearlyState'; import { escape } from '@microsoft/sp-lodash-subset'; import * as moment from 'moment'; import { parseString, Builder } from "xml2js"; import { ChoiceGroup, IChoiceGroupOption, Dropdown, IDropdownOption, Label, MaskedTextField } from 'office-ui-fabric-react'; import { DatePicker, DayOfWeek, IDatePickerStrings } from 'office-ui-fabric-react/lib/DatePicker'; import { toLocaleShortDateString } from '../../utils/dateUtils'; import spservices from '../../services/spservices'; const DayPickerStrings: IDatePickerStrings = { months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], shortDays: ['S', 'M', 'T', 'W', 'T', 'F', 'S'], goToToday: 'Go to today', prevMonthAriaLabel: 'Go to previous month', nextMonthAriaLabel: 'Go to next month', prevYearAriaLabel: 'Go to previous year', nextYearAriaLabel: 'Go to next year', closeButtonAriaLabel: 'Close date picker' }; /** * * * @export * @class EventRecurrenceInfoDaily * @extends {React.Component<IEventRecurrenceInfoYearlyProps, IEventRecurrenceInfoYearlyState>} */ export class EventRecurrenceInfoYearly extends React.Component<IEventRecurrenceInfoYearlyProps, IEventRecurrenceInfoYearlyState> { private spService: spservices = null; public constructor(props) { super(props); this.onPaternChange = this.onPaternChange.bind(this); this.state = { selectedKey: 'daily', selectPatern: 'yearly', startDate: this.props.startDate ? this.props.startDate : moment().toDate(), endDate: moment().endOf('month').toDate(), numberOcurrences: '1', disableDayOfMonth: false, disableNumberOcurrences: true, selectdateRangeOption: 'noDate', disableEndDate: true, selectedRecurrenceRule: 'yearly', dayOfMonth: this.props.startDate ? moment(this.props.startDate).format('D') : moment().format('D'), isLoading: false, errorMessageDayOfMonth: '', selectedWeekOrderMonth: 'first', selectedWeekDay: 'day', selectedMonth: moment().format('M'), selectedYearlyByDayMonth: moment().format('M'), }; // this.onDayOfMonthChange = this.onDayOfMonthChange.bind(this); this.onNumberOfOcurrencesChange = this.onNumberOfOcurrencesChange.bind(this); this.onDataRangeOptionChange = this.onDataRangeOptionChange.bind(this); this.onEndDateChange = this.onEndDateChange.bind(this); this.onStartDateChange = this.onStartDateChange.bind(this); this.onApplyRecurrence = this.onApplyRecurrence.bind(this); this.onYearlyByDayMonthChange = this.onYearlyByDayMonthChange.bind(this); this.onSelectedWeekDayChange = this.onSelectedWeekDayChange.bind(this); this.onWeekOrderMonthChange = this.onWeekOrderMonthChange.bind(this); this.onMonthChange = this.onMonthChange.bind(this); this.spService = new spservices(this.props.context); } /** * * * @private * @param {Date} date * @memberof EventRecurrenceInfoDaily */ private onStartDateChange(date: Date) { this.setState({ startDate: date }); this.applyRecurrence(); } /** * * * @private * @param {Date} date * @memberof EventRecurrenceInfoDaily */ private onEndDateChange(date: Date) { this.setState({ endDate: date }); this.applyRecurrence(); } /** * * * @private * @param {React.SyntheticEvent<HTMLElement>} ev * @param {string} value * @memberof EventRecurrenceInfoDaily */ private onDayOfMonthChange(ev: React.SyntheticEvent<HTMLElement>, value: string) { ev.preventDefault(); setTimeout(() => { let errorMessage = ''; if (Number(value.trim()) < 1 || Number(value.trim()) > 31) { value = '1 '; errorMessage = 'Allowed values 1 to 31'; } this.setState({ dayOfMonth: value, errorMessageDayOfMonth: errorMessage }); this.applyRecurrence(); }, 3000); } private onMonthChange(ev: React.SyntheticEvent<HTMLElement>, item: IDropdownOption) { this.setState({ selectedMonth: item.key }); this.applyRecurrence(); } /** * * * @private * @param {React.SyntheticEvent<HTMLElement>} ev * @param {string} value * @memberof EventRecurrenceInfoDaily */ private onNumberOfOcurrencesChange(ev: React.SyntheticEvent<HTMLElement>, value: string) { ev.preventDefault(); this.setState({ numberOcurrences: value }); this.applyRecurrence(); } /** * * * @private * @param {React.SyntheticEvent<HTMLElement>} ev * @param {IChoiceGroupOption} option * @memberof EventRecurrenceInfoDaily */ private onDataRangeOptionChange(ev: React.SyntheticEvent<HTMLElement>, option: IChoiceGroupOption): void { ev.preventDefault(); this.setState({ selectdateRangeOption: option.key, disableNumberOcurrences: option.key == 'endAfter' ? false : true, disableEndDate: option.key == 'endDate' ? false : true, }); this.applyRecurrence(); } /** * * * @private * @param {React.SyntheticEvent<HTMLElement>} ev * @param {IChoiceGroupOption} option * @memberof EventRecurrenceInfoYearly */ private onPaternChange(ev: React.SyntheticEvent<HTMLElement>, option: IChoiceGroupOption): void { ev.preventDefault(); this.setState({ selectPatern: option.key, disableDayOfMonth: option.key == 'yearly' ? false : true, }); this.applyRecurrence(); } public async componentDidMount() { } public async componentWillMount() { await this.load(); } /** * * * @private * @param {React.FormEvent<HTMLDivElement>} ev * @param {IDropdownOption} item * @memberof EventRecurrenceInfoYearly */ private onWeekOrderMonthChange(ev: React.FormEvent<HTMLDivElement>, item: IDropdownOption): void { this.setState({ selectedWeekOrderMonth: item.key.toString() }); this.applyRecurrence(); } /** * * * @private * @param {React.FormEvent<HTMLDivElement>} ev * @param {IDropdownOption} item * @memberof EventRecurrenceInfoYearly */ private onYearlyByDayMonthChange(ev: React.FormEvent<HTMLDivElement>, item: IDropdownOption): void { this.setState({ selectedYearlyByDayMonth: item.key }); this.applyRecurrence(); } /** * * * @private * @param {React.FormEvent<HTMLDivElement>} ev * @param {IDropdownOption} item * @memberof EventRecurrenceInfoYearly */ private onSelectedWeekDayChange(ev: React.FormEvent<HTMLDivElement>, item: IDropdownOption): void { this.setState({ selectedWeekDay: item.key.toString() }); this.applyRecurrence(); } public async componentDidUpdate(prevProps: IEventRecurrenceInfoYearlyProps, prevState: IEventRecurrenceInfoYearlyState) { } /** * * * @private * @memberof EventRecurrenceInfoYearly */ private async load() { let patern: any = {}; let dateRange: { repeatForever?: string, repeatInstances?: string, windowEnd?: Date } = {}; let yearlyPatern: { yearFrequency?: string, day?: string, month?: string } = {}; let yearlyByDayPatern: { yearFrequency?: string, weekdayOfMonth?: string, weekDay?: string, month?: string } = {}; let recurrenceRule: string; if (this.props.recurrenceData) { parseString(this.props.recurrenceData, { explicitArray: false }, (error, result) => { if (result.recurrence.rule.repeat) { patern = result.recurrence.rule.repeat; } // if (result.recurrence.rule.repeatForever) { dateRange = { repeatForever: result.recurrence.rule.repeatForever }; } if (result.recurrence.rule.repeatInstances) { dateRange = { repeatInstances: result.recurrence.rule.repeatInstances }; } if (result.recurrence.rule.windowEnd) { dateRange = { windowEnd: result.recurrence.rule.windowEnd }; } }); // yearly Patern if (patern.yearly) { recurrenceRule = 'yearly'; if (patern.yearly.$.yearFrequency && patern.yearly.$.day) { yearlyPatern = { yearFrequency: patern.yearly.$.yearFrequency, day: patern.yearly.$.day, month: patern.yearly.$.month }; } } // yearlyByDay Patern if (patern.yearlyByDay) { recurrenceRule = 'yearly'; let weekDay = 'day'; if (patern.yearlyByDay.$.su) weekDay = 'sunday'; if (patern.yearlyByDay.$.mo) weekDay = 'monday'; if (patern.yearlyByDay.$.tu) weekDay = 'tuesday'; if (patern.yearlyByDay.$.we) weekDay = 'wednesday'; if (patern.yearlyByDay.$.th) weekDay = 'thursday'; if (patern.yearlyByDay.$.fr) weekDay = 'friday'; if (patern.yearlyByDay.$.sa) weekDay = 'saturday'; if (patern.yearlyByDay.$.day) weekDay = 'day'; if (patern.yearlyByDay.$.weekday) weekDay = 'weekday'; if (patern.yearlyByDay.$.weekend_day) weekDay = 'weekdendday'; yearlyByDayPatern = { yearFrequency: patern.yearlyByDay.$.yearFrequency, weekdayOfMonth: patern.yearlyByDay.$.weekdayOfMonth, weekDay: weekDay, month: patern.yearlyByDay.$.month, }; } let selectDateRangeOption: string = 'noDate'; if (dateRange.repeatForever) { selectDateRangeOption = 'noDate'; } else if (dateRange.repeatInstances) { selectDateRangeOption = 'endAfter'; } else if (dateRange.windowEnd) { selectDateRangeOption = 'endDate'; } // weekday patern this.setState({ selectedRecurrenceRule: recurrenceRule, selectPatern: patern.yearly ? 'yearly' : 'yearlyByDay', dayOfMonth: yearlyPatern.day ? yearlyPatern.day : '1', selectedMonth: yearlyPatern.month ? yearlyPatern.month : moment().month(), selectedYearlyByDayMonth: yearlyByDayPatern.month ? yearlyByDayPatern.month : moment().format('M'), selectedWeekOrderMonth: yearlyByDayPatern.weekdayOfMonth ? yearlyByDayPatern.weekdayOfMonth : 'first', selectedWeekDay: yearlyByDayPatern.weekDay ? yearlyByDayPatern.weekDay : 'day', disableDayOfMonth: patern.yearly ? false : true, selectdateRangeOption: selectDateRangeOption, numberOcurrences: dateRange.repeatInstances ? dateRange.repeatInstances : '10', disableNumberOcurrences: dateRange.repeatInstances ? false : true, endDate: dateRange.windowEnd ? new Date(moment(dateRange.windowEnd).format('YYYY/MM/DD')) : this.state.endDate, disableEndDate: dateRange.windowEnd ? false : true, isLoading: false, }); } await this.applyRecurrence(); } /** * * * @private * @param {React.MouseEvent<HTMLButtonElement>} ev * @memberof EventRecurrenceInfoYearly */ private async onApplyRecurrence(ev: React.MouseEvent<HTMLButtonElement>) { await this.applyRecurrence(); } /** * * * @private * @param {React.MouseEvent<HTMLButtonElement>} ev * @memberof EventRecurrenceInfoDaily */ private async applyRecurrence() { const endDate = await this.spService.getUtcTime(this.state.endDate); let selectDateRangeOption; switch (this.state.selectdateRangeOption) { case 'noDate': selectDateRangeOption = `<repeatForever>FALSE</repeatForever>`; break; case 'endAfter': selectDateRangeOption = `<repeatInstances>${this.state.numberOcurrences}</repeatInstances>`; break; case 'endDate': selectDateRangeOption = `<windowEnd>${endDate}</windowEnd>`; break; default: break; } let recurrencePatern: string = ''; if (this.state.selectPatern == 'yearly') { recurrencePatern = `<yearly yearFrequency="1" day="${this.state.dayOfMonth}" month="${this.state.selectedMonth}" /></repeat>${selectDateRangeOption}</rule></recurrence>`; } if (this.state.selectPatern == 'yearlyByDay') { recurrencePatern = `<yearlyByDay weekdayOfMonth="${this.state.selectedWeekOrderMonth}" month="${this.state.selectedYearlyByDayMonth}"`; switch (this.state.selectedWeekDay) { case 'day': recurrencePatern = recurrencePatern + `day="TRUE"`; break; case 'weekday': recurrencePatern = recurrencePatern + `weekday="TRUE"`; break; case 'weekendday': recurrencePatern = recurrencePatern + `weekend_day="TRUE"`; break; case 'sunday': recurrencePatern = recurrencePatern + `su="TRUE"`; break; case 'monday': recurrencePatern = recurrencePatern + `mo="TRUE"`; break; case 'tuesday': recurrencePatern = recurrencePatern + `tu="TRUE"`; break; case 'wednesday': recurrencePatern = recurrencePatern + `we="TRUE"`; break; case 'thursday': recurrencePatern = recurrencePatern + `th="TRUE"`; break; case 'friday': recurrencePatern = recurrencePatern + `fr="TRUE"`; break; case 'saturday': recurrencePatern = recurrencePatern + `sa="TRUE"`; break; default: break; } recurrencePatern = recurrencePatern + ` yearFrequency="1" /></repeat>${selectDateRangeOption}</rule></recurrence>`; } const recurrenceXML = `<recurrence><rule><firstDayOfWeek>su</firstDayOfWeek><repeat>` + recurrencePatern; this.props.returnRecurrenceData(this.state.startDate, recurrenceXML); } /** * * * @returns {React.ReactElement<IEventRecurrenceInfoDailyProps>} * @memberof EventRecurrenceInfoDaily */ public render(): React.ReactElement<IEventRecurrenceInfoYearlyProps> { return ( <div > { <div> <div style={{ display: 'inline-block', float: 'right', paddingTop: '10px', height: '40px' }}> </div> <div style={{ width: '100%', paddingTop: '10px' }}> <Label>{strings.PaternLabel}</Label> <ChoiceGroup selectedKey={this.state.selectPatern} options={[ { key: 'yearly', text: strings.every, ariaLabel: strings.every, onRenderField: (props, render) => { return ( <div > {render!(props)} <div style={{ display: 'inline-block', verticalAlign: 'top', width: '100px', paddingLeft: '10px' }}> <Dropdown selectedKey={this.state.selectedMonth} onChange={this.onMonthChange} disabled={this.state.disableDayOfMonth} options={[ { key: '1', text: strings.January }, { key: '2', text: strings.February }, { key: '3', text: strings.March }, { key: '4', text: strings.April }, { key: '5', text: strings.May }, { key: '6', text: strings.June }, { key: '7', text: strings.July }, { key: '8', text: strings.August }, { key: '9', text: strings.September }, { key: '10', text: strings.October }, { key: '11', text: strings.November }, { key: '12', text: strings.December }, ]} /> </div> <MaskedTextField styles={{ root: { display: 'inline-block', verticalAlign: 'top', width: '100px', paddingLeft: '10px' } }} mask="99" maskChar=' ' disabled={this.state.disableDayOfMonth} value={this.state.dayOfMonth} errorMessage={this.state.errorMessageDayOfMonth} onChange={this.onDayOfMonthChange} /> </div> ); } }, { key: 'yearlyByDay', text: strings.theLabel, onRenderField: (props, render) => { return ( <div > {render!(props)} <div style={{ display: 'inline-block', verticalAlign: 'top', width: '80px', paddingLeft: '10px' }}> <Dropdown selectedKey={this.state.selectedWeekOrderMonth} onChange={this.onWeekOrderMonthChange} disabled={!this.state.disableDayOfMonth} options={[ { key: 'first', text: strings.firstLabel }, { key: 'second', text: strings.secondLabel }, { key: 'third', text: strings.thirdLabel }, { key: 'fourth', text: strings.fourthLabel }, { key: 'last', text: strings.lastLabel }, ]} /> </div> <div style={{ display: 'inline-block', verticalAlign: 'top', width: '100px', paddingLeft: '5px' }}> <Dropdown selectedKey={this.state.selectedWeekDay} disabled={!this.state.disableDayOfMonth} onChange={this.onSelectedWeekDayChange} options={[ { key: 'day', text: strings.dayLable }, { key: 'weekday', text: strings.weekDayLabel }, { key: 'weekendday', text: strings.weekEndDay }, { key: 'sunday', text: strings.Sunday }, { key: 'monday', text: strings.Monday }, { key: 'tuesday', text: strings.Tuesday }, { key: 'wednesday', text: strings.Wednesday }, { key: 'thursday', text: strings.Thursday }, { key: 'friday', text: strings.Friday }, { key: 'saturday', text: strings.Saturday }, ]} /> </div> <Label styles={{ root: { display: 'inline-block', verticalAlign: 'top', width: '30px', paddingLeft: '10px' } }}>{ strings.ofMonthLabel} </Label> <div style={{ display: 'inline-block', verticalAlign: 'top', width: '100px', paddingLeft: '5px' }}> <Dropdown selectedKey={this.state.selectedYearlyByDayMonth} onChange={this.onYearlyByDayMonthChange} disabled={!this.state.disableDayOfMonth} options={[ { key: '1', text: strings.January }, { key: '2', text: strings.February }, { key: '3', text: strings.March }, { key: '4', text: strings.April }, { key: '5', text: strings.May }, { key: '6', text: strings.June }, { key: '7', text: strings.July }, { key: '8', text: strings.August }, { key: '9', text: strings.September }, { key: '10', text: strings.October }, { key: '11', text: strings.November }, { key: '12', text: strings.December }, ]} /> </div> </div> ); } } ]} onChange={this.onPaternChange} required={true} /> </div> <div style={{ paddingTop: '22px' }}> <Label>{ strings.dateRangeLabel }</Label> <div style={{ display: 'inline-block', verticalAlign: 'top', paddingRight: '35px', paddingTop: '10px' }}> <DatePicker firstDayOfWeek={DayOfWeek.Sunday} strings={DayPickerStrings} placeholder={strings.StartDatePlaceHolder} ariaLabel={strings.StartDatePlaceHolder} label={strings.StartDateLabel} value={this.state.startDate} onSelectDate={this.onStartDateChange} formatDate={toLocaleShortDateString} /> </div> <div style={{ display: 'inline-block', verticalAlign: 'top', paddingTop: '10px' }}> <ChoiceGroup selectedKey={this.state.selectdateRangeOption} onChange={this.onDataRangeOptionChange} options={[ { key: 'noDate', text: strings.noEndDate, }, { key: 'endDate', text: strings.EndByLabel, onRenderField: (props, render) => { return ( <div > {render!(props)} <DatePicker firstDayOfWeek={DayOfWeek.Sunday} strings={DayPickerStrings} placeholder={strings.StartDatePlaceHolder} ariaLabel={strings.StartDatePlaceHolder} style={{ display: 'inline-block', verticalAlign: 'top', paddingLeft: '22px', }} onSelectDate={this.onEndDateChange} formatDate={toLocaleShortDateString} value={this.state.endDate} disabled={this.state.disableEndDate} /> </div> ); } }, { key: 'endAfter', text: strings.EndAfterLabel, onRenderField: (props, render) => { return ( <div > {render!(props)} <MaskedTextField styles={{ root: { display: 'inline-block', verticalAlign: 'top', width: '100px', paddingLeft: '10px' } }} mask="999" maskChar=' ' value={this.state.numberOcurrences} disabled={this.state.disableNumberOcurrences} onChange={this.onNumberOfOcurrencesChange} /> <Label styles={{ root: { display: 'inline-block', verticalAlign: 'top', paddingLeft: '10px' } }}>{strings.OcurrencesLabel}</Label> </div> ); } }, ]} required={true} /> </div> </div> </div> } </div> ); } }
the_stack
import { ErrorCohortStats, IErrorAnalysisMatrixNode, MetricCohortStats, Metrics } from "@responsible-ai/core-ui"; /** * Temporary abstract class for cohort statistics. */ export abstract class BaseStats { public metricName: string; public constructor(metricName: string) { this.metricName = metricName; } public abstract updateCohort(value: IErrorAnalysisMatrixNode): void; public abstract updateGlobal(value: IErrorAnalysisMatrixNode): void; public abstract createCohortStats(): MetricCohortStats; } /** * Temporary abstract class for aggregating cohort stats. */ export abstract class BaseStatsAggregator extends BaseStats { public totalCohortCount = 0; public totalGlobalCount = 0; public existsSelectedCell = false; public updateCohort(value: IErrorAnalysisMatrixNode): void { this.updateCohortStats(value); this.updateCohortCount(value.count); this.existsSelectedCell = true; } public updateGlobal(value: IErrorAnalysisMatrixNode): void { this.updateGlobalStats(value); this.updateGlobalCount(value.count); } protected updateCohortCount(count: number): void { this.totalCohortCount += count; } protected updateGlobalCount(count: number): void { this.totalGlobalCount += count; } protected abstract updateCohortStats(value: IErrorAnalysisMatrixNode): void; protected abstract updateGlobalStats(value: IErrorAnalysisMatrixNode): void; } /** * Temporary class for aggregating cohort stats for error rate. */ export class ErrorRateStatsAggregator extends BaseStatsAggregator { public falseCohortCount = 0; public falseGlobalCount = 0; public updateCohortStats(value: IErrorAnalysisMatrixNode): void { if (value.falseCount !== undefined) { this.falseCohortCount += value.falseCount; } } public updateGlobalStats(value: IErrorAnalysisMatrixNode): void { if (value.falseCount !== undefined) { this.falseGlobalCount += value.falseCount; } } public createCohortStats(): MetricCohortStats { if (this.existsSelectedCell) { const metricValue = (this.falseCohortCount / this.totalCohortCount) * 100; return new ErrorCohortStats( this.falseCohortCount, this.totalCohortCount, this.falseGlobalCount, this.totalGlobalCount, metricValue, this.metricName ); } const metricValue = (this.falseGlobalCount / this.totalGlobalCount) * 100; return new ErrorCohortStats( this.falseGlobalCount, this.totalGlobalCount, this.falseGlobalCount, this.totalGlobalCount, metricValue, this.metricName ); } } /** * Temporary class for aggregating cohort stats for metrics. */ export class MetricStatsAggregator extends BaseStatsAggregator { public totalCohortError = 0; public totalGlobalError = 0; public updateCohortStats(value: IErrorAnalysisMatrixNode): void { if (value.metricValue !== undefined) { this.totalCohortError += value.metricValue * value.count; } } public updateGlobalStats(value: IErrorAnalysisMatrixNode): void { if (value.metricValue !== undefined) { this.totalGlobalError += value.metricValue * value.count; } } public createCohortStats(): MetricCohortStats { if (this.existsSelectedCell) { const metricValue = this.totalCohortError / this.totalCohortCount; const coverage = (this.totalCohortError / this.totalGlobalError) * 100; return new MetricCohortStats( this.totalCohortCount, this.totalGlobalCount, metricValue, this.metricName, coverage ); } const metricValue = this.totalGlobalError / this.totalGlobalCount; const coverage = 100; return new MetricCohortStats( this.totalCohortCount, this.totalGlobalCount, metricValue, this.metricName, coverage ); } } /** * Temporary class for aggregating cohort stats for precision. */ export class PrecisionStatsAggregator extends BaseStatsAggregator { public totalCohortError = 0; public totalGlobalError = 0; public tpCohort: number[] = []; public tpGlobal: number[] = []; public fpCohort: number[] = []; public fpGlobal: number[] = []; public updateCohortStats(value: IErrorAnalysisMatrixNode): void { if (value.error !== undefined) { this.totalCohortError += value.error; if (this.tpCohort.length === 0) { this.tpCohort = [...value.tp]; } else { this.tpCohort = this.tpCohort.map((num, idx) => num + value.tp[idx]); } if (this.fpCohort.length === 0) { this.fpCohort = [...value.fp]; } else { this.fpCohort = this.fpCohort.map((num, idx) => num + value.fp[idx]); } } } public updateGlobalStats(value: IErrorAnalysisMatrixNode): void { if (value.error !== undefined) { this.totalGlobalError += value.error; } if (this.tpGlobal.length === 0) { this.tpGlobal = [...value.tp]; } else { this.tpGlobal = this.tpGlobal.map((num, idx) => num + value.tp[idx]); } if (this.fpGlobal.length === 0) { this.fpGlobal = [...value.fp]; } else { this.fpGlobal = this.fpGlobal.map((num, idx) => num + value.fp[idx]); } } public createCohortStats(): MetricCohortStats { let metricValue = 0; let coverage = 0; if (this.existsSelectedCell) { metricValue = this.computeMetricValue(this.tpCohort, this.fpCohort); coverage = (this.totalCohortError / this.totalGlobalError) * 100; } else { metricValue = this.computeMetricValue(this.tpGlobal, this.fpGlobal); coverage = 100; } return new MetricCohortStats( this.totalCohortCount, this.totalGlobalCount, metricValue, this.metricName, coverage ); } private computeMetricValue(tp: number[], fp: number[]) { let metricValue = 0; if (this.metricName === Metrics.PrecisionScore) { if (tp.length === 2) { // For binary case where negative and positive labels exist metricValue = tp[1] / (tp[1] + fp[1]); } else { // For binary case where only positive labels specified metricValue = tp[0] / (tp[0] + fp[0]); } } else if (this.metricName === Metrics.MicroPrecisionScore) { // Take aggregate across all classes const tpSum = tp.reduce((sum, value) => sum + value, 0); const fpSum = fp.reduce((sum, value) => sum + value, 0); metricValue = tpSum / (tpSum + fpSum); } else if (this.metricName === Metrics.MacroPrecisionScore) { // Compute per class and then average const perClassMetrics: number[] = []; tp.map((num, idx) => perClassMetrics.push(num / (num + fp[idx]))); metricValue = perClassMetrics.reduce((sum, value) => sum + value, 0) / perClassMetrics.length; } return metricValue; } } /** * Temporary class for aggregating cohort stats for recall. */ export class RecallStatsAggregator extends BaseStatsAggregator { public totalCohortError = 0; public totalGlobalError = 0; public tpCohort: number[] = []; public tpGlobal: number[] = []; public fnCohort: number[] = []; public fnGlobal: number[] = []; public updateCohortStats(value: IErrorAnalysisMatrixNode): void { if (value.error !== undefined) { this.totalCohortError += value.error; if (this.tpCohort.length === 0) { this.tpCohort = [...value.tp]; } else { this.tpCohort = this.tpCohort.map((num, idx) => num + value.tp[idx]); } if (this.fnCohort.length === 0) { this.fnCohort = [...value.fn]; } else { this.fnCohort = this.fnCohort.map((num, idx) => num + value.fn[idx]); } } } public updateGlobalStats(value: IErrorAnalysisMatrixNode): void { if (value.error !== undefined) { this.totalGlobalError += value.error; } if (this.tpGlobal.length === 0) { this.tpGlobal = [...value.tp]; } else { this.tpGlobal = this.tpGlobal.map((num, idx) => num + value.tp[idx]); } if (this.fnGlobal.length === 0) { this.fnGlobal = [...value.fn]; } else { this.fnGlobal = this.fnGlobal.map((num, idx) => num + value.fn[idx]); } } public createCohortStats(): MetricCohortStats { let metricValue = 0; let coverage = 0; if (this.existsSelectedCell) { metricValue = this.computeMetricValue(this.tpCohort, this.fnCohort); coverage = (this.totalCohortError / this.totalGlobalError) * 100; } else { metricValue = this.computeMetricValue(this.tpGlobal, this.fnGlobal); coverage = 100; } return new MetricCohortStats( this.totalCohortCount, this.totalGlobalCount, metricValue, this.metricName, coverage ); } private computeMetricValue(tp: number[], fn: number[]) { let metricValue = 0; if (this.metricName === Metrics.RecallScore) { if (tp.length === 2) { // For binary case where negative and positive labels exist metricValue = tp[1] / (tp[1] + fn[1]); } else { // For binary case where only positive labels specified metricValue = tp[0] / (tp[0] + fn[0]); } } else if (this.metricName === Metrics.MicroRecallScore) { // Take aggregate across all classes const tpSum = tp.reduce((sum, value) => sum + value, 0); const fnSum = fn.reduce((sum, value) => sum + value, 0); metricValue = tpSum / (tpSum + fnSum); } else if (this.metricName === Metrics.MacroRecallScore) { // Compute per class and then average const perClassMetrics: number[] = []; tp.map((num, idx) => perClassMetrics.push(num / (num + fn[idx]))); metricValue = perClassMetrics.reduce((sum, value) => sum + value, 0) / perClassMetrics.length; } return metricValue; } } /** * Temporary class for aggregating cohort stats for F1 score. */ export class F1ScoreStatsAggregator extends BaseStats { public precisionAggregator: PrecisionStatsAggregator; public recallAggregator: RecallStatsAggregator; public constructor(metricName: string) { super(metricName); let precisionMetric: string = Metrics.PrecisionScore; let recallMetric: string = Metrics.RecallScore; if (metricName === Metrics.MicroF1Score) { precisionMetric = Metrics.MicroPrecisionScore; recallMetric = Metrics.MicroRecallScore; } else if (metricName === Metrics.MacroF1Score) { precisionMetric = Metrics.MacroPrecisionScore; recallMetric = Metrics.MacroRecallScore; } this.precisionAggregator = new PrecisionStatsAggregator(precisionMetric); this.recallAggregator = new RecallStatsAggregator(recallMetric); } public updateCohort(value: IErrorAnalysisMatrixNode): void { this.precisionAggregator.updateCohort(value); this.recallAggregator.updateCohort(value); } public updateGlobal(value: IErrorAnalysisMatrixNode): void { this.precisionAggregator.updateGlobal(value); this.recallAggregator.updateGlobal(value); } public createCohortStats(): MetricCohortStats { let metricValue = 0; const precisionCohortStats = this.precisionAggregator.createCohortStats(); const recallCohortStats = this.recallAggregator.createCohortStats(); if (this.metricName !== Metrics.MacroF1Score) { const precisionMetric = precisionCohortStats.metricValue; const recallMetric = recallCohortStats.metricValue; metricValue = (2 * (precisionMetric * recallMetric)) / (precisionMetric + recallMetric); } else if (this.precisionAggregator.existsSelectedCell) { metricValue = this.computeMacroF1MetricValue( this.precisionAggregator.tpCohort, this.precisionAggregator.fpCohort, this.recallAggregator.fnCohort ); } else { metricValue = this.computeMacroF1MetricValue( this.precisionAggregator.tpGlobal, this.precisionAggregator.fpGlobal, this.recallAggregator.fnGlobal ); } return new MetricCohortStats( precisionCohortStats.totalCohort, precisionCohortStats.totalAll, metricValue, this.metricName, precisionCohortStats.errorCoverage ); } public computeMacroF1MetricValue( tp: number[], fp: number[], fn: number[] ): number { const perClassPrecision: number[] = []; tp.map((num, idx) => perClassPrecision.push(num / (num + fp[idx]))); const perClassRecall: number[] = []; tp.map((num, idx) => perClassRecall.push(num / (num + fn[idx]))); const perClassF1Score: number[] = []; perClassPrecision.forEach((precision, idx) => { const recall = perClassRecall[idx]; const f1Score = (2 * precision * recall) / (precision + recall); perClassF1Score.push(f1Score); }); return ( perClassF1Score.reduce((sum, value) => sum + value, 0) / perClassF1Score.length ); } } /** * Temporary class for aggregating cohort stats for accuracy. */ export class AccuracyStatsAggregator extends BaseStatsAggregator { public totalCohortError = 0; public totalGlobalError = 0; public tpCohort: number[] = []; public tpGlobal: number[] = []; public tnCohort: number[] = []; public tnGlobal: number[] = []; public fpCohort: number[] = []; public fpGlobal: number[] = []; public fnCohort: number[] = []; public fnGlobal: number[] = []; public updateCohortStats(value: IErrorAnalysisMatrixNode): void { if (value.error !== undefined) { this.totalCohortError += value.error; if (this.tpCohort.length === 0) { this.tpCohort = [...value.tp]; } else { this.tpCohort = this.tpCohort.map((num, idx) => num + value.tp[idx]); } if (this.tnCohort.length === 0) { this.tnCohort = [...value.tn]; } else { this.tnCohort = this.tnCohort.map((num, idx) => num + value.tn[idx]); } if (this.fpCohort.length === 0) { this.fpCohort = [...value.fp]; } else { this.fpCohort = this.fpCohort.map((num, idx) => num + value.fp[idx]); } if (this.fnCohort.length === 0) { this.fnCohort = [...value.fn]; } else { this.fnCohort = this.fnCohort.map((num, idx) => num + value.fn[idx]); } } } public updateGlobalStats(value: IErrorAnalysisMatrixNode): void { if (value.error !== undefined) { this.totalGlobalError += value.error; } if (this.tpGlobal.length === 0) { this.tpGlobal = [...value.tp]; } else { this.tpGlobal = this.tpGlobal.map((num, idx) => num + value.tp[idx]); } if (this.tnGlobal.length === 0) { this.tnGlobal = [...value.tn]; } else { this.tnGlobal = this.tnGlobal.map((num, idx) => num + value.tn[idx]); } if (this.fpGlobal.length === 0) { this.fpGlobal = [...value.fp]; } else { this.fpGlobal = this.fpGlobal.map((num, idx) => num + value.fp[idx]); } if (this.fnGlobal.length === 0) { this.fnGlobal = [...value.fn]; } else { this.fnGlobal = this.fnGlobal.map((num, idx) => num + value.fn[idx]); } } public createCohortStats(): MetricCohortStats { let metricValue = 0; let coverage = 0; if (this.existsSelectedCell) { metricValue = this.computeMetricValue( this.tpCohort, this.tnCohort, this.fpCohort, this.fnCohort ); coverage = (this.totalCohortError / this.totalGlobalError) * 100; } else { metricValue = this.computeMetricValue( this.tpGlobal, this.tnGlobal, this.fpGlobal, this.fnGlobal ); coverage = 100; } return new MetricCohortStats( this.totalCohortCount, this.totalGlobalCount, metricValue, this.metricName, coverage ); } private computeMetricValue( tp: number[], tn: number[], fp: number[], fn: number[] ) { let metricValue = 0; if (tp.length === 1) { // For binary case where only positive labels specified metricValue = (tp[0] + tn[0]) / (tp[0] + tn[0] + fp[0] + fn[0]); } else { // When all labels specified const tpSum = tp.reduce((sum, value) => sum + value, 0); metricValue = tpSum / (tp[0] + tn[0] + fp[0] + fn[0]); } return metricValue; } }
the_stack
import * as assert from 'assert'; import { VSBuffer } from 'vs/base/common/buffer'; import { DisposableStore, toDisposable } from 'vs/base/common/lifecycle'; import { IFileService } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { IUserDataProfilesService } from 'vs/platform/userDataProfile/common/userDataProfile'; import { getKeybindingsContentFromSyncContent, KeybindingsSynchroniser } from 'vs/platform/userDataSync/common/keybindingsSync'; import { IUserDataSyncStoreService, SyncResource, UserDataSyncError, UserDataSyncErrorCode } from 'vs/platform/userDataSync/common/userDataSync'; import { UserDataSyncClient, UserDataSyncTestServer } from 'vs/platform/userDataSync/test/common/userDataSyncClient'; suite('KeybindingsSync', () => { const disposableStore = new DisposableStore(); const server = new UserDataSyncTestServer(); let client: UserDataSyncClient; let testObject: KeybindingsSynchroniser; setup(async () => { client = disposableStore.add(new UserDataSyncClient(server)); await client.setUp(true); testObject = client.getSynchronizer(SyncResource.Keybindings) as KeybindingsSynchroniser; disposableStore.add(toDisposable(() => client.instantiationService.get(IUserDataSyncStoreService).clear())); }); teardown(() => disposableStore.clear()); test('when keybindings file does not exist', async () => { const fileService = client.instantiationService.get(IFileService); const keybindingsResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.keybindingsResource; assert.deepStrictEqual(await testObject.getLastSyncUserData(), null); let manifest = await client.manifest(); server.reset(); await testObject.sync(manifest); assert.deepStrictEqual(server.requests, [ { type: 'GET', url: `${server.url}/v1/resource/${testObject.resource}/latest`, headers: {} }, ]); assert.ok(!await fileService.exists(keybindingsResource)); const lastSyncUserData = await testObject.getLastSyncUserData(); const remoteUserData = await testObject.getRemoteUserData(null); assert.deepStrictEqual(lastSyncUserData!.ref, remoteUserData.ref); assert.deepStrictEqual(lastSyncUserData!.syncData, remoteUserData.syncData); assert.strictEqual(lastSyncUserData!.syncData, null); manifest = await client.manifest(); server.reset(); await testObject.sync(manifest); assert.deepStrictEqual(server.requests, []); manifest = await client.manifest(); server.reset(); await testObject.sync(manifest); assert.deepStrictEqual(server.requests, []); }); test('when keybindings file is empty and remote has no changes', async () => { const fileService = client.instantiationService.get(IFileService); const keybindingsResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.keybindingsResource; await fileService.writeFile(keybindingsResource, VSBuffer.fromString('')); await testObject.sync(await client.manifest()); const lastSyncUserData = await testObject.getLastSyncUserData(); const remoteUserData = await testObject.getRemoteUserData(null); assert.strictEqual(getKeybindingsContentFromSyncContent(lastSyncUserData!.syncData!.content!, true, client.instantiationService.get(ILogService)), '[]'); assert.strictEqual(getKeybindingsContentFromSyncContent(remoteUserData!.syncData!.content!, true, client.instantiationService.get(ILogService)), '[]'); assert.strictEqual((await fileService.readFile(keybindingsResource)).value.toString(), ''); }); test('when keybindings file is empty and remote has changes', async () => { const client2 = disposableStore.add(new UserDataSyncClient(server)); await client2.setUp(true); const content = JSON.stringify([ { 'key': 'shift+cmd+w', 'command': 'workbench.action.closeAllEditors', } ]); await client2.instantiationService.get(IFileService).writeFile(client2.instantiationService.get(IUserDataProfilesService).defaultProfile.keybindingsResource, VSBuffer.fromString(content)); await client2.sync(); const fileService = client.instantiationService.get(IFileService); const keybindingsResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.keybindingsResource; await fileService.writeFile(keybindingsResource, VSBuffer.fromString('')); await testObject.sync(await client.manifest()); const lastSyncUserData = await testObject.getLastSyncUserData(); const remoteUserData = await testObject.getRemoteUserData(null); assert.strictEqual(getKeybindingsContentFromSyncContent(lastSyncUserData!.syncData!.content!, true, client.instantiationService.get(ILogService)), content); assert.strictEqual(getKeybindingsContentFromSyncContent(remoteUserData!.syncData!.content!, true, client.instantiationService.get(ILogService)), content); assert.strictEqual((await fileService.readFile(keybindingsResource)).value.toString(), content); }); test('when keybindings file is empty with comment and remote has no changes', async () => { const fileService = client.instantiationService.get(IFileService); const keybindingsResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.keybindingsResource; const expectedContent = '// Empty Keybindings'; await fileService.writeFile(keybindingsResource, VSBuffer.fromString(expectedContent)); await testObject.sync(await client.manifest()); const lastSyncUserData = await testObject.getLastSyncUserData(); const remoteUserData = await testObject.getRemoteUserData(null); assert.strictEqual(getKeybindingsContentFromSyncContent(lastSyncUserData!.syncData!.content!, true, client.instantiationService.get(ILogService)), expectedContent); assert.strictEqual(getKeybindingsContentFromSyncContent(remoteUserData!.syncData!.content!, true, client.instantiationService.get(ILogService)), expectedContent); assert.strictEqual((await fileService.readFile(keybindingsResource)).value.toString(), expectedContent); }); test('when keybindings file is empty and remote has keybindings', async () => { const client2 = disposableStore.add(new UserDataSyncClient(server)); await client2.setUp(true); const content = JSON.stringify([ { 'key': 'shift+cmd+w', 'command': 'workbench.action.closeAllEditors', } ]); await client2.instantiationService.get(IFileService).writeFile(client2.instantiationService.get(IUserDataProfilesService).defaultProfile.keybindingsResource, VSBuffer.fromString(content)); await client2.sync(); const fileService = client.instantiationService.get(IFileService); const keybindingsResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.keybindingsResource; await fileService.writeFile(keybindingsResource, VSBuffer.fromString('// Empty Keybindings')); await testObject.sync(await client.manifest()); const lastSyncUserData = await testObject.getLastSyncUserData(); const remoteUserData = await testObject.getRemoteUserData(null); assert.strictEqual(getKeybindingsContentFromSyncContent(lastSyncUserData!.syncData!.content!, true, client.instantiationService.get(ILogService)), content); assert.strictEqual(getKeybindingsContentFromSyncContent(remoteUserData!.syncData!.content!, true, client.instantiationService.get(ILogService)), content); assert.strictEqual((await fileService.readFile(keybindingsResource)).value.toString(), content); }); test('when keybindings file is empty and remote has empty array', async () => { const client2 = disposableStore.add(new UserDataSyncClient(server)); await client2.setUp(true); const content = `// Place your key bindings in this file to override the defaults [ ]`; await client2.instantiationService.get(IFileService).writeFile(client2.instantiationService.get(IUserDataProfilesService).defaultProfile.keybindingsResource, VSBuffer.fromString(content)); await client2.sync(); const fileService = client.instantiationService.get(IFileService); const keybindingsResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.keybindingsResource; const expectedLocalContent = '// Empty Keybindings'; await fileService.writeFile(keybindingsResource, VSBuffer.fromString(expectedLocalContent)); await testObject.sync(await client.manifest()); const lastSyncUserData = await testObject.getLastSyncUserData(); const remoteUserData = await testObject.getRemoteUserData(null); assert.strictEqual(getKeybindingsContentFromSyncContent(lastSyncUserData!.syncData!.content!, true, client.instantiationService.get(ILogService)), content); assert.strictEqual(getKeybindingsContentFromSyncContent(remoteUserData!.syncData!.content!, true, client.instantiationService.get(ILogService)), content); assert.strictEqual((await fileService.readFile(keybindingsResource)).value.toString(), expectedLocalContent); }); test('when keybindings file is created after first sync', async () => { const fileService = client.instantiationService.get(IFileService); const keybindingsResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.keybindingsResource; await testObject.sync(await client.manifest()); await fileService.createFile(keybindingsResource, VSBuffer.fromString('[]')); let lastSyncUserData = await testObject.getLastSyncUserData(); const manifest = await client.manifest(); server.reset(); await testObject.sync(manifest); assert.deepStrictEqual(server.requests, [ { type: 'POST', url: `${server.url}/v1/resource/${testObject.resource}`, headers: { 'If-Match': lastSyncUserData?.ref } }, ]); lastSyncUserData = await testObject.getLastSyncUserData(); const remoteUserData = await testObject.getRemoteUserData(null); assert.deepStrictEqual(lastSyncUserData!.ref, remoteUserData.ref); assert.deepStrictEqual(lastSyncUserData!.syncData, remoteUserData.syncData); assert.strictEqual(getKeybindingsContentFromSyncContent(lastSyncUserData!.syncData!.content!, true, client.instantiationService.get(ILogService)), '[]'); }); test('test apply remote when keybindings file does not exist', async () => { const fileService = client.instantiationService.get(IFileService); const keybindingsResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.keybindingsResource; if (await fileService.exists(keybindingsResource)) { await fileService.del(keybindingsResource); } const preview = (await testObject.preview(await client.manifest(), {}))!; server.reset(); const content = await testObject.resolveContent(preview.resourcePreviews[0].remoteResource); await testObject.accept(preview.resourcePreviews[0].remoteResource, content); await testObject.apply(false); assert.deepStrictEqual(server.requests, []); }); test('sync throws invalid content error - content is an object', async () => { await client.instantiationService.get(IFileService).writeFile(client.instantiationService.get(IUserDataProfilesService).defaultProfile.keybindingsResource, VSBuffer.fromString('{}')); try { await testObject.sync(await client.manifest()); assert.fail('should fail with invalid content error'); } catch (e) { assert.ok(e instanceof UserDataSyncError); assert.deepStrictEqual((<UserDataSyncError>e).code, UserDataSyncErrorCode.LocalInvalidContent); } }); });
the_stack
import { EventEmitter } from 'events'; import * as socketClusterClient from 'socketcluster-client'; import { SCServerSocket } from 'socketcluster-server'; import { codec } from '@liskhq/lisk-codec'; import { DEFAULT_PRODUCTIVITY, DEFAULT_PRODUCTIVITY_RESET_INTERVAL, FORBIDDEN_CONNECTION, FORBIDDEN_CONNECTION_REASON, INTENTIONAL_DISCONNECT_CODE, INVALID_PEER_INFO_PENALTY, INVALID_PEER_LIST_PENALTY, INVALID_PEER_INFO_LIST_REASON, DEFAULT_MESSAGE_ENCODING_FORMAT, } from '../constants'; import { InvalidPeerInfoError, InvalidPeerInfoListError, RPCResponseError, InvalidNodeInfoError, } from '../errors'; import { EVENT_BAN_PEER, EVENT_DISCOVERED_PEER, EVENT_FAILED_PEER_INFO_UPDATE, EVENT_FAILED_TO_FETCH_PEERS, EVENT_FAILED_TO_FETCH_PEER_INFO, EVENT_INVALID_MESSAGE_RECEIVED, EVENT_INVALID_REQUEST_RECEIVED, EVENT_MESSAGE_RECEIVED, EVENT_REQUEST_RECEIVED, EVENT_UPDATED_PEER_INFO, PROTOCOL_EVENTS_TO_RATE_LIMIT, REMOTE_EVENT_POST_NODE_INFO, REMOTE_EVENT_RPC_GET_NODE_INFO, REMOTE_EVENT_RPC_GET_PEERS_LIST, REMOTE_SC_EVENT_MESSAGE, REMOTE_SC_EVENT_RPC_REQUEST, } from '../events'; import { P2PRequest } from '../p2p_request'; import { P2PInternalState, P2PMessagePacket, P2PNodeInfo, P2PPeerInfo, P2PRequestPacket, RPCSchemas, P2PSharedState, P2PMessagePacketBufferData, P2PRequestPacketBufferData, P2PResponsePacketBufferData, P2PRawRequestPacket, P2PRawMessagePacket, ProtocolPeerInfo, BaseRequestResponsePacket, PeerConfig, } from '../types'; import { assignInternalInfo, sanitizeIncomingPeerInfo, validatePeerCompatibility, validatePeerInfo, validatePeerInfoList, validateProtocolMessage, validateRPCRequest, validatePayloadSize, } from '../utils'; import { decodeNodeInfo } from '../utils/codec'; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment export const socketErrorStatusCodes: { [key: number]: string | undefined } = { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-explicit-any ...(socketClusterClient.SCClientSocket as any).errorStatuses, 1000: 'Intentionally disconnected', }; // Can be used to convert a rate which is based on the rateCalculationInterval into a per-second rate. export const RATE_NORMALIZATION_FACTOR = 1000; // Peer status message rate to be checked in every 10 seconds and reset const PEER_STATUS_MESSAGE_RATE_INTERVAL = 10000; export type SCClientSocket = socketClusterClient.SCClientSocket; export type SCServerSocketUpdated = { // eslint-disable-next-line @typescript-eslint/method-signature-style destroy(code?: number, data?: string | object): void; // eslint-disable-next-line @typescript-eslint/method-signature-style on(event: string | unknown, listener: (packet?: unknown) => void): void; // eslint-disable-next-line @typescript-eslint/method-signature-style,@typescript-eslint/no-explicit-any on(event: string, listener: (packet: any, respond: any) => void): void; } & SCServerSocket; export enum ConnectionState { CONNECTING = 'connecting', OPEN = 'open', CLOSED = 'closed', } export interface ConnectedPeerInfo extends P2PPeerInfo { internalState: P2PInternalState; } export class Peer extends EventEmitter { // protected variables & handlers protected readonly _handleRawRPC: ( packet: P2PRawRequestPacket, respond: (responseError?: Error, responseData?: unknown) => void, ) => void; protected readonly _handleWSMessage: (message: string) => void; protected readonly _handleRawMessage: (packet: unknown) => void; protected _socket: SCServerSocketUpdated | SCClientSocket | undefined; protected _peerInfo: ConnectedPeerInfo; protected readonly _peerConfig: PeerConfig; protected _serverNodeInfo: P2PNodeInfo | undefined; protected _rateInterval: number; // private variables private readonly _rpcSchemas: RPCSchemas; private readonly _discoveryMessageCounter: { getPeers: number; getNodeInfo: number; postNodeInfo: number; }; private readonly _peerStatusMessageRate: number; private readonly _peerStatusRateInterval: NodeJS.Timer; private readonly _counterResetInterval: NodeJS.Timer; private readonly _productivityResetInterval: NodeJS.Timer; public constructor(peerInfo: P2PPeerInfo, peerConfig: PeerConfig) { super(); this._peerConfig = peerConfig; this._rpcSchemas = peerConfig.rpcSchemas; this._peerInfo = this._initializeInternalState(peerInfo) as ConnectedPeerInfo; this._rateInterval = this._peerConfig.rateCalculationInterval; this._counterResetInterval = setInterval(() => { this._resetCounters(); }, this._rateInterval); this._productivityResetInterval = setInterval(() => { this._resetProductivity(); }, DEFAULT_PRODUCTIVITY_RESET_INTERVAL); this._serverNodeInfo = peerConfig.serverNodeInfo; this._discoveryMessageCounter = { getPeers: 0, getNodeInfo: 0, postNodeInfo: 0, }; this._peerStatusMessageRate = peerConfig.peerStatusMessageRate; this._peerStatusRateInterval = setInterval(() => { this._resetStatusMessageRate(); }, PEER_STATUS_MESSAGE_RATE_INTERVAL); // This needs to be an arrow function so that it can be used as a listener. this._handleRawRPC = ( packet: unknown, respond: (responseError?: Error, responseData?: unknown) => void, ): void => { try { validateRPCRequest(packet); } catch (error) { respond(error); this.emit(EVENT_INVALID_REQUEST_RECEIVED, { packet, peerId: this._peerInfo.peerId, }); return; } const rawRequestPacket = packet as P2PRawRequestPacket; // Apply penalty when you receive getNodeInfo RPC more than once if (rawRequestPacket.procedure === REMOTE_EVENT_RPC_GET_NODE_INFO) { this._discoveryMessageCounter.getNodeInfo += 1; if (this._discoveryMessageCounter.getNodeInfo > 1) { this.applyPenalty(10); } } // Apply penalty when you receive getPeers RPC more than once if (rawRequestPacket.procedure === REMOTE_EVENT_RPC_GET_PEERS_LIST) { this._discoveryMessageCounter.getPeers += 1; if (this._discoveryMessageCounter.getPeers > 1) { this.applyPenalty(10); } } // Discovery requests are only allowed once per second. If it exceeds that, we prevent the request from propagating. if ( PROTOCOL_EVENTS_TO_RATE_LIMIT.has(rawRequestPacket.procedure) && this._peerInfo.internalState.rpcCounter.has(rawRequestPacket.procedure) ) { this._updateRPCCounter(rawRequestPacket); return; } // Protocol RCP request limiter LIP-0004 this._updateRPCCounter(rawRequestPacket); const rate = this._getRPCRate(rawRequestPacket); // Each P2PRequest contributes to the Peer's productivity. // A P2PRequest can mutate this._productivity from the current Peer instance. const request = new P2PRequest( { procedure: rawRequestPacket.procedure, data: rawRequestPacket.data, id: this.peerInfo.peerId, rate, productivity: this.internalState.productivity, }, respond, ); this.emit(EVENT_REQUEST_RECEIVED, request); }; this._handleWSMessage = (): void => { this._peerInfo.internalState.wsMessageCount += 1; }; // This needs to be an arrow function so that it can be used as a listener. this._handleRawMessage = (packet: unknown): void => { try { validateProtocolMessage(packet); } catch (error) { this.emit(EVENT_INVALID_MESSAGE_RECEIVED, { packet, peerId: this._peerInfo.peerId, }); return; } const message = packet as P2PRawMessagePacket; this._updateMessageCounter(message); const rate = this._getMessageRate(message); const messageBufferData = this._getBufferData(message.data); if (message.event === REMOTE_EVENT_POST_NODE_INFO) { this._discoveryMessageCounter.postNodeInfo += 1; if (this._discoveryMessageCounter.postNodeInfo > this._peerStatusMessageRate) { this.applyPenalty(10); } this._handleUpdateNodeInfo({ ...message, data: messageBufferData }); } const messageWithRateInfo = { ...message, data: messageBufferData, peerId: this._peerInfo.peerId, rate, }; this.emit(EVENT_MESSAGE_RECEIVED, messageWithRateInfo); }; } // Getters public get id(): string { return this._peerInfo.peerId; } public get ipAddress(): string { return this._peerInfo.ipAddress; } public get port(): number { return this._peerInfo.port; } public get internalState(): P2PInternalState { return this.peerInfo.internalState; } public get peerInfo(): ConnectedPeerInfo { return this._peerInfo; } public get state(): ConnectionState { // eslint-disable-next-line no-nested-ternary const state = this._socket ? this._socket.state === this._socket.OPEN ? ConnectionState.OPEN : ConnectionState.CLOSED : ConnectionState.CLOSED; return state; } public updateInternalState(internalState: P2PInternalState): void { this._peerInfo = { ...this._peerInfo, internalState, }; } public updatePeerInfo(newPeerInfo: P2PPeerInfo): void { // The ipAddress and port properties cannot be updated after the initial discovery. this._peerInfo = { sharedState: newPeerInfo.sharedState, internalState: this._peerInfo.internalState, ipAddress: this.ipAddress, port: this.port, peerId: this.id, }; } public connect(): void { if (!this._socket) { throw new Error('Peer socket does not exist'); } } public disconnect(code: number = INTENTIONAL_DISCONNECT_CODE, reason?: string): void { clearInterval(this._counterResetInterval); clearInterval(this._productivityResetInterval); clearInterval(this._peerStatusRateInterval); if (this._socket) { this._socket.destroy(code, reason); } } public send(packet: P2PMessagePacketBufferData): void { if (!this._socket) { throw new Error('Peer socket does not exist'); } const data = this._getBase64Data(packet.data); this._socket.emit(REMOTE_SC_EVENT_MESSAGE, { event: packet.event, data, }); } public async request(packet: P2PRequestPacketBufferData): Promise<P2PResponsePacketBufferData> { return new Promise<P2PResponsePacketBufferData>( ( resolve: (result: P2PResponsePacketBufferData) => void, reject: (result: Error) => void, ): void => { if (!this._socket) { throw new Error('Peer socket does not exist'); } const data = this._getBase64Data(packet.data); this._socket.emit( REMOTE_SC_EVENT_RPC_REQUEST, { procedure: packet.procedure, data, }, (error: Error | undefined, responseData: unknown) => { if (error) { reject(error); return; } const response = responseData as BaseRequestResponsePacket | undefined; if (response) { const responseBufferData = { peerId: response.peerId, data: this._getBufferData(response.data), }; resolve(responseBufferData); return; } reject( new RPCResponseError( `Failed to handle response for procedure ${packet.procedure}`, `${this.ipAddress}:${this.port}`, ), ); }, ); }, ); } public async fetchPeers(): Promise<ReadonlyArray<P2PPeerInfo>> { try { const response = await this.request({ procedure: REMOTE_EVENT_RPC_GET_PEERS_LIST, }); if (!response.data) { throw new InvalidPeerInfoListError(INVALID_PEER_INFO_LIST_REASON); } const { peers } = codec.decode<{ peers: Buffer[] }>( this._rpcSchemas.peerRequestResponse, response.data, ); const sanitizedPeersList = peers.map<P2PPeerInfo>((peerInfoBuffer: Buffer) => { const peerInfo = codec.decode<ProtocolPeerInfo>(this._rpcSchemas.peerInfo, peerInfoBuffer); return sanitizeIncomingPeerInfo(peerInfo); }); validatePeerInfoList( sanitizedPeersList, this._peerConfig.maxPeerDiscoveryResponseLength, this._peerConfig.maxPeerInfoSize, ); return sanitizedPeersList.map(peerInfo => ({ ...peerInfo, sourceAddress: this.ipAddress, })); } catch (error) { if (error instanceof InvalidPeerInfoError || error instanceof InvalidPeerInfoListError) { this.applyPenalty(INVALID_PEER_LIST_PENALTY); } this.emit(EVENT_FAILED_TO_FETCH_PEERS, error); throw new RPCResponseError('Failed to fetch peer list of peer', this.ipAddress); } } public async discoverPeers(): Promise<ReadonlyArray<P2PPeerInfo>> { const discoveredPeerInfoList = await this.fetchPeers(); discoveredPeerInfoList.forEach(peerInfo => { this.emit(EVENT_DISCOVERED_PEER, peerInfo); }); return discoveredPeerInfoList; } public async fetchAndUpdateStatus(): Promise<P2PPeerInfo> { let response: P2PResponsePacketBufferData; try { response = await this.request({ procedure: REMOTE_EVENT_RPC_GET_NODE_INFO, }); } catch (error) { this.emit(EVENT_FAILED_TO_FETCH_PEER_INFO, error); throw new RPCResponseError( 'Failed to fetch peer info of peer', `${this.ipAddress}:${this.port}`, ); } try { const receivedNodeInfo = decodeNodeInfo(this._rpcSchemas.nodeInfo, response.data); this._updateFromProtocolPeerInfo(receivedNodeInfo); } catch (error) { this.emit(EVENT_FAILED_PEER_INFO_UPDATE, error); // Apply penalty for malformed PeerInfo if (error instanceof InvalidNodeInfoError) { this.applyPenalty(INVALID_PEER_INFO_PENALTY); } throw new RPCResponseError( 'Failed to update peer info of peer due to validation of peer compatibility', `${this.ipAddress}:${this.port}`, ); } this.emit(EVENT_UPDATED_PEER_INFO, this._peerInfo); // Return the updated detailed peer info. return this._peerInfo; } public applyPenalty(penalty: number): void { this.peerInfo.internalState.reputation -= penalty; if (this.internalState.reputation <= 0) { this._banPeer(); } } private _resetCounters(): void { this._peerInfo.internalState.wsMessageRate = (this.peerInfo.internalState.wsMessageCount * RATE_NORMALIZATION_FACTOR) / this._rateInterval; this._peerInfo.internalState.wsMessageCount = 0; if (this.peerInfo.internalState.wsMessageRate > this._peerConfig.wsMaxMessageRate) { // Allow to increase penalty based on message rate limit exceeded const messageRateExceedCoefficient = Math.floor( this.peerInfo.internalState.wsMessageRate / this._peerConfig.wsMaxMessageRate, ); const penaltyRateMultiplier = messageRateExceedCoefficient > 1 ? messageRateExceedCoefficient : 1; this.applyPenalty(this._peerConfig.wsMaxMessageRatePenalty * penaltyRateMultiplier); } this._peerInfo.internalState.rpcRates = new Map( [...this.internalState.rpcCounter.entries()].map(([key, value]) => { const rate = value / this._rateInterval; // Protocol RCP request limiter LIP-0004 if (PROTOCOL_EVENTS_TO_RATE_LIMIT.has(key) && value > 1) { this.applyPenalty(this._peerConfig.wsMaxMessageRatePenalty); } // eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-explicit-any return [key, rate] as any; }), ); this._peerInfo.internalState.rpcCounter = new Map<string, number>(); this._peerInfo.internalState.messageRates = new Map( [...this.internalState.messageCounter.entries()].map(([key, value]) => { const rate = value / this._rateInterval; // eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-explicit-any return [key, rate] as any; }), ); this._peerInfo.internalState.messageCounter = new Map<string, number>(); } private _resetProductivity(): void { // If peer has not recently responded, reset productivity to 0 if ( this.peerInfo.internalState.productivity.lastResponded < Date.now() - DEFAULT_PRODUCTIVITY_RESET_INTERVAL ) { this._peerInfo.internalState.productivity = { ...DEFAULT_PRODUCTIVITY }; } } private _resetStatusMessageRate(): void { // Reset only postNodeInfo counter to zero after every 10 seconds this._discoveryMessageCounter.postNodeInfo = 0; // Reset getPeers RPC request count to zero this._discoveryMessageCounter.getPeers = 0; } private _updateFromProtocolPeerInfo(rawPeerInfo: unknown): void { if (!this._serverNodeInfo) { throw new Error('Missing server node info.'); } // Sanitize and validate PeerInfo const peerInfo = validatePeerInfo( sanitizeIncomingPeerInfo({ ...(rawPeerInfo as object), ipAddress: this.ipAddress, port: this.port, }), this._peerConfig.maxPeerInfoSize, ); const result = validatePeerCompatibility(peerInfo, this._serverNodeInfo); if (!result.success && result.error) { throw new Error(`${result.error} : ${peerInfo.ipAddress}:${peerInfo.port}`); } this.updatePeerInfo(peerInfo); } private _handleUpdateNodeInfo(message: P2PMessagePacketBufferData): void { // Update peerInfo with the latest values from the remote peer. try { // Check incoming nodeInfo size before decoding validatePayloadSize(message.data, this._peerConfig.maxPeerInfoSize); const decodedNodeInfo = decodeNodeInfo(this._rpcSchemas.nodeInfo, message.data); // Only update options object const { options } = decodedNodeInfo; // Only update options property this._peerInfo = { ...this._peerInfo, sharedState: { ...this._peerInfo.sharedState, options: { ...this._peerInfo.sharedState?.options, ...options }, } as P2PSharedState, }; } catch (error) { // Apply penalty for malformed nodeInfo update if (error instanceof InvalidNodeInfoError) { this.applyPenalty(INVALID_PEER_INFO_PENALTY); } this.emit(EVENT_FAILED_PEER_INFO_UPDATE, error); return; } this.emit(EVENT_UPDATED_PEER_INFO, this.peerInfo); } private _banPeer(): void { this.emit(EVENT_BAN_PEER, this.id); this.disconnect(FORBIDDEN_CONNECTION, FORBIDDEN_CONNECTION_REASON); } private _updateRPCCounter(packet: P2PRequestPacket): void { const key = packet.procedure; const count = (this.internalState.rpcCounter.get(key) ?? 0) + 1; this.peerInfo.internalState.rpcCounter.set(key, count); } private _getRPCRate(packet: P2PRequestPacket): number { const rate = this.peerInfo.internalState.rpcRates.get(packet.procedure) ?? 0; return rate * RATE_NORMALIZATION_FACTOR; } private _updateMessageCounter(packet: P2PMessagePacket): void { const key = packet.event; const count = (this.internalState.messageCounter.get(key) ?? 0) + 1; this.peerInfo.internalState.messageCounter.set(key, count); } private _getMessageRate(packet: P2PMessagePacket): number { const rate = this.internalState.messageRates.get(packet.event) ?? 0; return rate * RATE_NORMALIZATION_FACTOR; } private _initializeInternalState(peerInfo: P2PPeerInfo): P2PPeerInfo { return peerInfo.internalState ? peerInfo : { ...peerInfo, internalState: assignInternalInfo(peerInfo, this._peerConfig.secret), }; } // All the inbound and outbound messages communication to socket // Should be converted to base64 string // eslint-disable-next-line class-methods-use-this private _getBase64Data(data?: Buffer): string | undefined { if (data === undefined) { return undefined; } if (Buffer.isBuffer(data)) { return data.toString(DEFAULT_MESSAGE_ENCODING_FORMAT); } return data; } // eslint-disable-next-line class-methods-use-this private _getBufferData(data?: string): Buffer | undefined { if (data === undefined) { return undefined; } return Buffer.from(data, DEFAULT_MESSAGE_ENCODING_FORMAT); } }
the_stack
import { Tag, defineTag } from "@esfx/internal-tag"; import { WaitQueue } from "@esfx/async-waitqueue"; import { LockHandle, UpgradeableLockHandle, AsyncLockable } from "@esfx/async-lockable"; import { Cancelable } from "@esfx/cancelable"; import { Disposable } from "@esfx/disposable"; export { LockHandle, UpgradeableLockHandle } from "@esfx/async-lockable"; const disposablePrototype: object = Object.getPrototypeOf(Disposable.create(() => { })); const lockHandlePrototype: object = { get mutex() { return this; }, async [AsyncLockable.lock](this: LockHandle, cancelable?: Cancelable) { await this.lock(cancelable); return this; }, [AsyncLockable.unlock](this: LockHandle) { this.unlock(); }, [Disposable.dispose](this: LockHandle) { if (this.ownsLock) { this.unlock(); } } }; defineTag(lockHandlePrototype, "LockHandle"); Object.setPrototypeOf(lockHandlePrototype, disposablePrototype); const readerPrototype: object = {}; defineTag(readerPrototype, "AsyncReaderWriterLockReader"); Object.setPrototypeOf(readerPrototype, lockHandlePrototype); const writerPrototype: object = {}; defineTag(writerPrototype, "AsyncReaderWriterLockWriter"); Object.setPrototypeOf(writerPrototype, lockHandlePrototype); const upgradeableReaderPrototype: object = {}; defineTag(upgradeableReaderPrototype, "AsyncReaderWriterLockUpgradeableReader"); Object.setPrototypeOf(upgradeableReaderPrototype, readerPrototype); const upgradedWriterPrototype: object = {}; defineTag(upgradedWriterPrototype, "AsyncReaderWriterLockUpgradedWriter"); Object.setPrototypeOf(upgradedWriterPrototype, writerPrototype); /** * Coordinates readers and writers for a resource. */ @Tag() export class AsyncReaderWriterLock { private _readerQueue = new WaitQueue<void>(); private _writerQueue = new WaitQueue<void>(); private _readers = new Set<LockHandle>(); private _writer: LockHandle | undefined; private _upgradeable: LockHandle | undefined; /** * Creates a `AsyncReaderWriterLockReader` that can be used to take and release "read" locks on a resource. */ createReader() { const owner = this; const handle: AsyncReaderWriterLockReader = Object.setPrototypeOf({ get owner() { return owner; }, get ownsLock() { return owner._readers.has(handle); }, async lock(cancelable?: Cancelable) { await owner._lockReader(handle, false, cancelable); return handle; }, unlock() { owner._unlockReader(handle); } }, readerPrototype); return handle; } /** * Creates a `AsyncReaderWriterLockUpgradeableReader` that can be used to take and release "read" locks on a resource * and can be later upgraded to take and release "write" locks. */ createUpgradeableReader() { const owner = this; const handle: AsyncReaderWriterLockUpgradeableReader = Object.setPrototypeOf({ get owner() { return handle; }, get ownsLock() { return owner._readers.has(handle); }, async lock(cancelable?: Cancelable) { await owner._lockReader(handle, true, cancelable); return handle; }, unlock() { owner._unlockReader(handle); }, createWriter() { return owner._createUpgradedWriter(handle); }, async upgrade(cancelable?: Cancelable) { const upgradedWriter = this.createWriter(); await upgradedWriter.lock(cancelable); return upgradedWriter; } }, upgradeableReaderPrototype); return handle; } /** * Creates a `AsyncReaderWriterLockWriter` that can be used to take and release "write" locks on a resource. */ createWriter() { const owner = this; const handle: AsyncReaderWriterLockWriter = Object.setPrototypeOf({ get owner() { return owner; }, get ownsLock() { return owner._writer === handle; }, async lock(cancelable?: Cancelable) { await owner._lockWriter(handle, undefined, cancelable); return handle; }, unlock() { owner._unlockWriter(handle); } }, writerPrototype); return handle; } private _createUpgradedWriter(upgradeable: AsyncReaderWriterLockUpgradeableReader) { const owner = this; const handle: AsyncReaderWriterLockWriter = Object.setPrototypeOf({ get owner() { return owner; }, get ownsLock() { return owner._writer === handle; }, async lock(cancelable?: Cancelable) { await owner._lockWriter(handle, upgradeable, cancelable); return handle; }, unlock() { owner._unlockWriter(handle); } }, upgradedWriterPrototype); return handle; } /** * Asynchronously waits for and takes a read lock on a resource. * * @param cancelable A `Cancelable` used to cancel the request. */ async read(cancelable?: Cancelable) { const reader = this.createReader(); await reader.lock(cancelable); return reader; } /** * Asynchronously waits for and takes a read lock on a resource * that can later be upgraded to a write lock. * * @param cancelable A `Cancelable` used to cancel the request. */ async upgradeableRead(cancelable?: Cancelable) { const upgradeableReader = this.createUpgradeableReader(); await upgradeableReader.lock(cancelable); return upgradeableReader; } /** * Asynchronously waits for and takes a write lock on a resource. * * @param cancelable A `Cancelable` used to cancel the request. */ async write(cancelable?: Cancelable) { const writer = this.createWriter(); await writer.lock(cancelable); return writer; } private _processLockRequests(): void { if (this._processWriteRequest()) return; this._processReadRequests(); } private _processWriteRequest(): boolean { if (this._canTakeWriteLock()) { if (this._writerQueue.resolveOne()) { return true; } } return false; } private _processReadRequests(): void { if (this._canTakeReadLock()) { this._readerQueue.resolveAll(); } } private _canTakeReadLock() { return !this._writer && this._writerQueue.size === 0; } private _canTakeWriteLock() { return !this._writer && this._readers.size === 0; } private async _lockReader(handle: LockHandle, upgradeable: boolean, cancelable?: Cancelable) { Cancelable.throwIfSignaled(cancelable); while (true) { if (this._readers.has(handle)) { throw new Error("Lock already taken."); } if (this._canTakeReadLock() && !(upgradeable && this._upgradeable)) { this._readers.add(handle); if (upgradeable) { this._upgradeable = handle; } return; } await this._readerQueue.wait(cancelable); } } private _unlockReader(handle: LockHandle): void { if (!this._readers.has(handle)) { throw new Error("Lock already released."); } if (handle === this._upgradeable) { if (this._writer) { throw new Error("Cannot unlock an upgraded lock."); } this._upgradeable = undefined; } this._readers.delete(handle); this._processLockRequests(); } private async _lockWriter(handle: LockHandle, upgradeable: LockHandle | undefined, cancelable?: Cancelable) { Cancelable.throwIfSignaled(cancelable); while (true) { if (this._writer === handle) { throw new Error("Lock already taken."); } if (this._upgradeable !== upgradeable) { throw new Error("Lock already released."); } if (this._canTakeWriteLock()) { this._writer = handle; return; } await this._writerQueue.wait(cancelable); } } private _unlockWriter(handle: LockHandle): void { if (this._writer !== handle) { throw new Error("Lock already released."); } this._writer = undefined; this._processLockRequests(); } } export interface AsyncReaderWriterLockReader extends LockHandle<AsyncReaderWriterLockReader> { /** * Gets the `AsyncReaderWriterLock` that owns this object. */ readonly owner: AsyncReaderWriterLock; } export interface AsyncReaderWriterLockWriter extends LockHandle<AsyncReaderWriterLockWriter> { /** * Gets the `AsyncReaderWriterLock` that owns this object. */ readonly owner: AsyncReaderWriterLock; } export interface AsyncReaderWriterLockUpgradedWriter extends LockHandle<AsyncReaderWriterLockUpgradedWriter> { /** * Gets the `AsyncReaderWriterLock` that owns this object. */ readonly owner: AsyncReaderWriterLock; } export interface AsyncReaderWriterLockUpgradeableReader extends UpgradeableLockHandle<AsyncReaderWriterLockUpgradeableReader, AsyncReaderWriterLockUpgradedWriter> { /** * Gets the `AsyncReaderWriterLock` that owns this object. */ readonly owner: AsyncReaderWriterLock; /** * Creates a `AsyncReaderWriterLockUpgradedWriter` that can be used to take and release "write" locks on a resource. */ createWriter(): AsyncReaderWriterLockUpgradedWriter; /** * Asynchronously waits for and takes a write lock on a resource. * * @param cancelable A `Cancelable` used to cancel the request. */ upgrade(cancelable?: Cancelable): Promise<AsyncReaderWriterLockUpgradedWriter>; }
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class CloudDirectory extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: CloudDirectory.Types.ClientConfiguration) config: Config & CloudDirectory.Types.ClientConfiguration; /** * Adds a new Facet to an object. An object can have more than one facet applied on it. */ addFacetToObject(params: CloudDirectory.Types.AddFacetToObjectRequest, callback?: (err: AWSError, data: CloudDirectory.Types.AddFacetToObjectResponse) => void): Request<CloudDirectory.Types.AddFacetToObjectResponse, AWSError>; /** * Adds a new Facet to an object. An object can have more than one facet applied on it. */ addFacetToObject(callback?: (err: AWSError, data: CloudDirectory.Types.AddFacetToObjectResponse) => void): Request<CloudDirectory.Types.AddFacetToObjectResponse, AWSError>; /** * Copies the input published schema, at the specified version, into the Directory with the same name and version as that of the published schema. */ applySchema(params: CloudDirectory.Types.ApplySchemaRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ApplySchemaResponse) => void): Request<CloudDirectory.Types.ApplySchemaResponse, AWSError>; /** * Copies the input published schema, at the specified version, into the Directory with the same name and version as that of the published schema. */ applySchema(callback?: (err: AWSError, data: CloudDirectory.Types.ApplySchemaResponse) => void): Request<CloudDirectory.Types.ApplySchemaResponse, AWSError>; /** * Attaches an existing object to another object. An object can be accessed in two ways: Using the path Using ObjectIdentifier */ attachObject(params: CloudDirectory.Types.AttachObjectRequest, callback?: (err: AWSError, data: CloudDirectory.Types.AttachObjectResponse) => void): Request<CloudDirectory.Types.AttachObjectResponse, AWSError>; /** * Attaches an existing object to another object. An object can be accessed in two ways: Using the path Using ObjectIdentifier */ attachObject(callback?: (err: AWSError, data: CloudDirectory.Types.AttachObjectResponse) => void): Request<CloudDirectory.Types.AttachObjectResponse, AWSError>; /** * Attaches a policy object to a regular object. An object can have a limited number of attached policies. */ attachPolicy(params: CloudDirectory.Types.AttachPolicyRequest, callback?: (err: AWSError, data: CloudDirectory.Types.AttachPolicyResponse) => void): Request<CloudDirectory.Types.AttachPolicyResponse, AWSError>; /** * Attaches a policy object to a regular object. An object can have a limited number of attached policies. */ attachPolicy(callback?: (err: AWSError, data: CloudDirectory.Types.AttachPolicyResponse) => void): Request<CloudDirectory.Types.AttachPolicyResponse, AWSError>; /** * Attaches the specified object to the specified index. */ attachToIndex(params: CloudDirectory.Types.AttachToIndexRequest, callback?: (err: AWSError, data: CloudDirectory.Types.AttachToIndexResponse) => void): Request<CloudDirectory.Types.AttachToIndexResponse, AWSError>; /** * Attaches the specified object to the specified index. */ attachToIndex(callback?: (err: AWSError, data: CloudDirectory.Types.AttachToIndexResponse) => void): Request<CloudDirectory.Types.AttachToIndexResponse, AWSError>; /** * Attaches a typed link to a specified source and target object. For more information, see Typed Links. */ attachTypedLink(params: CloudDirectory.Types.AttachTypedLinkRequest, callback?: (err: AWSError, data: CloudDirectory.Types.AttachTypedLinkResponse) => void): Request<CloudDirectory.Types.AttachTypedLinkResponse, AWSError>; /** * Attaches a typed link to a specified source and target object. For more information, see Typed Links. */ attachTypedLink(callback?: (err: AWSError, data: CloudDirectory.Types.AttachTypedLinkResponse) => void): Request<CloudDirectory.Types.AttachTypedLinkResponse, AWSError>; /** * Performs all the read operations in a batch. */ batchRead(params: CloudDirectory.Types.BatchReadRequest, callback?: (err: AWSError, data: CloudDirectory.Types.BatchReadResponse) => void): Request<CloudDirectory.Types.BatchReadResponse, AWSError>; /** * Performs all the read operations in a batch. */ batchRead(callback?: (err: AWSError, data: CloudDirectory.Types.BatchReadResponse) => void): Request<CloudDirectory.Types.BatchReadResponse, AWSError>; /** * Performs all the write operations in a batch. Either all the operations succeed or none. */ batchWrite(params: CloudDirectory.Types.BatchWriteRequest, callback?: (err: AWSError, data: CloudDirectory.Types.BatchWriteResponse) => void): Request<CloudDirectory.Types.BatchWriteResponse, AWSError>; /** * Performs all the write operations in a batch. Either all the operations succeed or none. */ batchWrite(callback?: (err: AWSError, data: CloudDirectory.Types.BatchWriteResponse) => void): Request<CloudDirectory.Types.BatchWriteResponse, AWSError>; /** * Creates a Directory by copying the published schema into the directory. A directory cannot be created without a schema. You can also quickly create a directory using a managed schema, called the QuickStartSchema. For more information, see Managed Schema in the Amazon Cloud Directory Developer Guide. */ createDirectory(params: CloudDirectory.Types.CreateDirectoryRequest, callback?: (err: AWSError, data: CloudDirectory.Types.CreateDirectoryResponse) => void): Request<CloudDirectory.Types.CreateDirectoryResponse, AWSError>; /** * Creates a Directory by copying the published schema into the directory. A directory cannot be created without a schema. You can also quickly create a directory using a managed schema, called the QuickStartSchema. For more information, see Managed Schema in the Amazon Cloud Directory Developer Guide. */ createDirectory(callback?: (err: AWSError, data: CloudDirectory.Types.CreateDirectoryResponse) => void): Request<CloudDirectory.Types.CreateDirectoryResponse, AWSError>; /** * Creates a new Facet in a schema. Facet creation is allowed only in development or applied schemas. */ createFacet(params: CloudDirectory.Types.CreateFacetRequest, callback?: (err: AWSError, data: CloudDirectory.Types.CreateFacetResponse) => void): Request<CloudDirectory.Types.CreateFacetResponse, AWSError>; /** * Creates a new Facet in a schema. Facet creation is allowed only in development or applied schemas. */ createFacet(callback?: (err: AWSError, data: CloudDirectory.Types.CreateFacetResponse) => void): Request<CloudDirectory.Types.CreateFacetResponse, AWSError>; /** * Creates an index object. See Indexing and search for more information. */ createIndex(params: CloudDirectory.Types.CreateIndexRequest, callback?: (err: AWSError, data: CloudDirectory.Types.CreateIndexResponse) => void): Request<CloudDirectory.Types.CreateIndexResponse, AWSError>; /** * Creates an index object. See Indexing and search for more information. */ createIndex(callback?: (err: AWSError, data: CloudDirectory.Types.CreateIndexResponse) => void): Request<CloudDirectory.Types.CreateIndexResponse, AWSError>; /** * Creates an object in a Directory. Additionally attaches the object to a parent, if a parent reference and LinkName is specified. An object is simply a collection of Facet attributes. You can also use this API call to create a policy object, if the facet from which you create the object is a policy facet. */ createObject(params: CloudDirectory.Types.CreateObjectRequest, callback?: (err: AWSError, data: CloudDirectory.Types.CreateObjectResponse) => void): Request<CloudDirectory.Types.CreateObjectResponse, AWSError>; /** * Creates an object in a Directory. Additionally attaches the object to a parent, if a parent reference and LinkName is specified. An object is simply a collection of Facet attributes. You can also use this API call to create a policy object, if the facet from which you create the object is a policy facet. */ createObject(callback?: (err: AWSError, data: CloudDirectory.Types.CreateObjectResponse) => void): Request<CloudDirectory.Types.CreateObjectResponse, AWSError>; /** * Creates a new schema in a development state. A schema can exist in three phases: Development: This is a mutable phase of the schema. All new schemas are in the development phase. Once the schema is finalized, it can be published. Published: Published schemas are immutable and have a version associated with them. Applied: Applied schemas are mutable in a way that allows you to add new schema facets. You can also add new, nonrequired attributes to existing schema facets. You can apply only published schemas to directories. */ createSchema(params: CloudDirectory.Types.CreateSchemaRequest, callback?: (err: AWSError, data: CloudDirectory.Types.CreateSchemaResponse) => void): Request<CloudDirectory.Types.CreateSchemaResponse, AWSError>; /** * Creates a new schema in a development state. A schema can exist in three phases: Development: This is a mutable phase of the schema. All new schemas are in the development phase. Once the schema is finalized, it can be published. Published: Published schemas are immutable and have a version associated with them. Applied: Applied schemas are mutable in a way that allows you to add new schema facets. You can also add new, nonrequired attributes to existing schema facets. You can apply only published schemas to directories. */ createSchema(callback?: (err: AWSError, data: CloudDirectory.Types.CreateSchemaResponse) => void): Request<CloudDirectory.Types.CreateSchemaResponse, AWSError>; /** * Creates a TypedLinkFacet. For more information, see Typed Links. */ createTypedLinkFacet(params: CloudDirectory.Types.CreateTypedLinkFacetRequest, callback?: (err: AWSError, data: CloudDirectory.Types.CreateTypedLinkFacetResponse) => void): Request<CloudDirectory.Types.CreateTypedLinkFacetResponse, AWSError>; /** * Creates a TypedLinkFacet. For more information, see Typed Links. */ createTypedLinkFacet(callback?: (err: AWSError, data: CloudDirectory.Types.CreateTypedLinkFacetResponse) => void): Request<CloudDirectory.Types.CreateTypedLinkFacetResponse, AWSError>; /** * Deletes a directory. Only disabled directories can be deleted. A deleted directory cannot be undone. Exercise extreme caution when deleting directories. */ deleteDirectory(params: CloudDirectory.Types.DeleteDirectoryRequest, callback?: (err: AWSError, data: CloudDirectory.Types.DeleteDirectoryResponse) => void): Request<CloudDirectory.Types.DeleteDirectoryResponse, AWSError>; /** * Deletes a directory. Only disabled directories can be deleted. A deleted directory cannot be undone. Exercise extreme caution when deleting directories. */ deleteDirectory(callback?: (err: AWSError, data: CloudDirectory.Types.DeleteDirectoryResponse) => void): Request<CloudDirectory.Types.DeleteDirectoryResponse, AWSError>; /** * Deletes a given Facet. All attributes and Rules that are associated with the facet will be deleted. Only development schema facets are allowed deletion. */ deleteFacet(params: CloudDirectory.Types.DeleteFacetRequest, callback?: (err: AWSError, data: CloudDirectory.Types.DeleteFacetResponse) => void): Request<CloudDirectory.Types.DeleteFacetResponse, AWSError>; /** * Deletes a given Facet. All attributes and Rules that are associated with the facet will be deleted. Only development schema facets are allowed deletion. */ deleteFacet(callback?: (err: AWSError, data: CloudDirectory.Types.DeleteFacetResponse) => void): Request<CloudDirectory.Types.DeleteFacetResponse, AWSError>; /** * Deletes an object and its associated attributes. Only objects with no children and no parents can be deleted. The maximum number of attributes that can be deleted during an object deletion is 30. For more information, see Amazon Cloud Directory Limits. */ deleteObject(params: CloudDirectory.Types.DeleteObjectRequest, callback?: (err: AWSError, data: CloudDirectory.Types.DeleteObjectResponse) => void): Request<CloudDirectory.Types.DeleteObjectResponse, AWSError>; /** * Deletes an object and its associated attributes. Only objects with no children and no parents can be deleted. The maximum number of attributes that can be deleted during an object deletion is 30. For more information, see Amazon Cloud Directory Limits. */ deleteObject(callback?: (err: AWSError, data: CloudDirectory.Types.DeleteObjectResponse) => void): Request<CloudDirectory.Types.DeleteObjectResponse, AWSError>; /** * Deletes a given schema. Schemas in a development and published state can only be deleted. */ deleteSchema(params: CloudDirectory.Types.DeleteSchemaRequest, callback?: (err: AWSError, data: CloudDirectory.Types.DeleteSchemaResponse) => void): Request<CloudDirectory.Types.DeleteSchemaResponse, AWSError>; /** * Deletes a given schema. Schemas in a development and published state can only be deleted. */ deleteSchema(callback?: (err: AWSError, data: CloudDirectory.Types.DeleteSchemaResponse) => void): Request<CloudDirectory.Types.DeleteSchemaResponse, AWSError>; /** * Deletes a TypedLinkFacet. For more information, see Typed Links. */ deleteTypedLinkFacet(params: CloudDirectory.Types.DeleteTypedLinkFacetRequest, callback?: (err: AWSError, data: CloudDirectory.Types.DeleteTypedLinkFacetResponse) => void): Request<CloudDirectory.Types.DeleteTypedLinkFacetResponse, AWSError>; /** * Deletes a TypedLinkFacet. For more information, see Typed Links. */ deleteTypedLinkFacet(callback?: (err: AWSError, data: CloudDirectory.Types.DeleteTypedLinkFacetResponse) => void): Request<CloudDirectory.Types.DeleteTypedLinkFacetResponse, AWSError>; /** * Detaches the specified object from the specified index. */ detachFromIndex(params: CloudDirectory.Types.DetachFromIndexRequest, callback?: (err: AWSError, data: CloudDirectory.Types.DetachFromIndexResponse) => void): Request<CloudDirectory.Types.DetachFromIndexResponse, AWSError>; /** * Detaches the specified object from the specified index. */ detachFromIndex(callback?: (err: AWSError, data: CloudDirectory.Types.DetachFromIndexResponse) => void): Request<CloudDirectory.Types.DetachFromIndexResponse, AWSError>; /** * Detaches a given object from the parent object. The object that is to be detached from the parent is specified by the link name. */ detachObject(params: CloudDirectory.Types.DetachObjectRequest, callback?: (err: AWSError, data: CloudDirectory.Types.DetachObjectResponse) => void): Request<CloudDirectory.Types.DetachObjectResponse, AWSError>; /** * Detaches a given object from the parent object. The object that is to be detached from the parent is specified by the link name. */ detachObject(callback?: (err: AWSError, data: CloudDirectory.Types.DetachObjectResponse) => void): Request<CloudDirectory.Types.DetachObjectResponse, AWSError>; /** * Detaches a policy from an object. */ detachPolicy(params: CloudDirectory.Types.DetachPolicyRequest, callback?: (err: AWSError, data: CloudDirectory.Types.DetachPolicyResponse) => void): Request<CloudDirectory.Types.DetachPolicyResponse, AWSError>; /** * Detaches a policy from an object. */ detachPolicy(callback?: (err: AWSError, data: CloudDirectory.Types.DetachPolicyResponse) => void): Request<CloudDirectory.Types.DetachPolicyResponse, AWSError>; /** * Detaches a typed link from a specified source and target object. For more information, see Typed Links. */ detachTypedLink(params: CloudDirectory.Types.DetachTypedLinkRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Detaches a typed link from a specified source and target object. For more information, see Typed Links. */ detachTypedLink(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Disables the specified directory. Disabled directories cannot be read or written to. Only enabled directories can be disabled. Disabled directories may be reenabled. */ disableDirectory(params: CloudDirectory.Types.DisableDirectoryRequest, callback?: (err: AWSError, data: CloudDirectory.Types.DisableDirectoryResponse) => void): Request<CloudDirectory.Types.DisableDirectoryResponse, AWSError>; /** * Disables the specified directory. Disabled directories cannot be read or written to. Only enabled directories can be disabled. Disabled directories may be reenabled. */ disableDirectory(callback?: (err: AWSError, data: CloudDirectory.Types.DisableDirectoryResponse) => void): Request<CloudDirectory.Types.DisableDirectoryResponse, AWSError>; /** * Enables the specified directory. Only disabled directories can be enabled. Once enabled, the directory can then be read and written to. */ enableDirectory(params: CloudDirectory.Types.EnableDirectoryRequest, callback?: (err: AWSError, data: CloudDirectory.Types.EnableDirectoryResponse) => void): Request<CloudDirectory.Types.EnableDirectoryResponse, AWSError>; /** * Enables the specified directory. Only disabled directories can be enabled. Once enabled, the directory can then be read and written to. */ enableDirectory(callback?: (err: AWSError, data: CloudDirectory.Types.EnableDirectoryResponse) => void): Request<CloudDirectory.Types.EnableDirectoryResponse, AWSError>; /** * Returns current applied schema version ARN, including the minor version in use. */ getAppliedSchemaVersion(params: CloudDirectory.Types.GetAppliedSchemaVersionRequest, callback?: (err: AWSError, data: CloudDirectory.Types.GetAppliedSchemaVersionResponse) => void): Request<CloudDirectory.Types.GetAppliedSchemaVersionResponse, AWSError>; /** * Returns current applied schema version ARN, including the minor version in use. */ getAppliedSchemaVersion(callback?: (err: AWSError, data: CloudDirectory.Types.GetAppliedSchemaVersionResponse) => void): Request<CloudDirectory.Types.GetAppliedSchemaVersionResponse, AWSError>; /** * Retrieves metadata about a directory. */ getDirectory(params: CloudDirectory.Types.GetDirectoryRequest, callback?: (err: AWSError, data: CloudDirectory.Types.GetDirectoryResponse) => void): Request<CloudDirectory.Types.GetDirectoryResponse, AWSError>; /** * Retrieves metadata about a directory. */ getDirectory(callback?: (err: AWSError, data: CloudDirectory.Types.GetDirectoryResponse) => void): Request<CloudDirectory.Types.GetDirectoryResponse, AWSError>; /** * Gets details of the Facet, such as facet name, attributes, Rules, or ObjectType. You can call this on all kinds of schema facets -- published, development, or applied. */ getFacet(params: CloudDirectory.Types.GetFacetRequest, callback?: (err: AWSError, data: CloudDirectory.Types.GetFacetResponse) => void): Request<CloudDirectory.Types.GetFacetResponse, AWSError>; /** * Gets details of the Facet, such as facet name, attributes, Rules, or ObjectType. You can call this on all kinds of schema facets -- published, development, or applied. */ getFacet(callback?: (err: AWSError, data: CloudDirectory.Types.GetFacetResponse) => void): Request<CloudDirectory.Types.GetFacetResponse, AWSError>; /** * Retrieves attributes that are associated with a typed link. */ getLinkAttributes(params: CloudDirectory.Types.GetLinkAttributesRequest, callback?: (err: AWSError, data: CloudDirectory.Types.GetLinkAttributesResponse) => void): Request<CloudDirectory.Types.GetLinkAttributesResponse, AWSError>; /** * Retrieves attributes that are associated with a typed link. */ getLinkAttributes(callback?: (err: AWSError, data: CloudDirectory.Types.GetLinkAttributesResponse) => void): Request<CloudDirectory.Types.GetLinkAttributesResponse, AWSError>; /** * Retrieves attributes within a facet that are associated with an object. */ getObjectAttributes(params: CloudDirectory.Types.GetObjectAttributesRequest, callback?: (err: AWSError, data: CloudDirectory.Types.GetObjectAttributesResponse) => void): Request<CloudDirectory.Types.GetObjectAttributesResponse, AWSError>; /** * Retrieves attributes within a facet that are associated with an object. */ getObjectAttributes(callback?: (err: AWSError, data: CloudDirectory.Types.GetObjectAttributesResponse) => void): Request<CloudDirectory.Types.GetObjectAttributesResponse, AWSError>; /** * Retrieves metadata about an object. */ getObjectInformation(params: CloudDirectory.Types.GetObjectInformationRequest, callback?: (err: AWSError, data: CloudDirectory.Types.GetObjectInformationResponse) => void): Request<CloudDirectory.Types.GetObjectInformationResponse, AWSError>; /** * Retrieves metadata about an object. */ getObjectInformation(callback?: (err: AWSError, data: CloudDirectory.Types.GetObjectInformationResponse) => void): Request<CloudDirectory.Types.GetObjectInformationResponse, AWSError>; /** * Retrieves a JSON representation of the schema. See JSON Schema Format for more information. */ getSchemaAsJson(params: CloudDirectory.Types.GetSchemaAsJsonRequest, callback?: (err: AWSError, data: CloudDirectory.Types.GetSchemaAsJsonResponse) => void): Request<CloudDirectory.Types.GetSchemaAsJsonResponse, AWSError>; /** * Retrieves a JSON representation of the schema. See JSON Schema Format for more information. */ getSchemaAsJson(callback?: (err: AWSError, data: CloudDirectory.Types.GetSchemaAsJsonResponse) => void): Request<CloudDirectory.Types.GetSchemaAsJsonResponse, AWSError>; /** * Returns the identity attribute order for a specific TypedLinkFacet. For more information, see Typed Links. */ getTypedLinkFacetInformation(params: CloudDirectory.Types.GetTypedLinkFacetInformationRequest, callback?: (err: AWSError, data: CloudDirectory.Types.GetTypedLinkFacetInformationResponse) => void): Request<CloudDirectory.Types.GetTypedLinkFacetInformationResponse, AWSError>; /** * Returns the identity attribute order for a specific TypedLinkFacet. For more information, see Typed Links. */ getTypedLinkFacetInformation(callback?: (err: AWSError, data: CloudDirectory.Types.GetTypedLinkFacetInformationResponse) => void): Request<CloudDirectory.Types.GetTypedLinkFacetInformationResponse, AWSError>; /** * Lists schema major versions applied to a directory. If SchemaArn is provided, lists the minor version. */ listAppliedSchemaArns(params: CloudDirectory.Types.ListAppliedSchemaArnsRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListAppliedSchemaArnsResponse) => void): Request<CloudDirectory.Types.ListAppliedSchemaArnsResponse, AWSError>; /** * Lists schema major versions applied to a directory. If SchemaArn is provided, lists the minor version. */ listAppliedSchemaArns(callback?: (err: AWSError, data: CloudDirectory.Types.ListAppliedSchemaArnsResponse) => void): Request<CloudDirectory.Types.ListAppliedSchemaArnsResponse, AWSError>; /** * Lists indices attached to the specified object. */ listAttachedIndices(params: CloudDirectory.Types.ListAttachedIndicesRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListAttachedIndicesResponse) => void): Request<CloudDirectory.Types.ListAttachedIndicesResponse, AWSError>; /** * Lists indices attached to the specified object. */ listAttachedIndices(callback?: (err: AWSError, data: CloudDirectory.Types.ListAttachedIndicesResponse) => void): Request<CloudDirectory.Types.ListAttachedIndicesResponse, AWSError>; /** * Retrieves each Amazon Resource Name (ARN) of schemas in the development state. */ listDevelopmentSchemaArns(params: CloudDirectory.Types.ListDevelopmentSchemaArnsRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListDevelopmentSchemaArnsResponse) => void): Request<CloudDirectory.Types.ListDevelopmentSchemaArnsResponse, AWSError>; /** * Retrieves each Amazon Resource Name (ARN) of schemas in the development state. */ listDevelopmentSchemaArns(callback?: (err: AWSError, data: CloudDirectory.Types.ListDevelopmentSchemaArnsResponse) => void): Request<CloudDirectory.Types.ListDevelopmentSchemaArnsResponse, AWSError>; /** * Lists directories created within an account. */ listDirectories(params: CloudDirectory.Types.ListDirectoriesRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListDirectoriesResponse) => void): Request<CloudDirectory.Types.ListDirectoriesResponse, AWSError>; /** * Lists directories created within an account. */ listDirectories(callback?: (err: AWSError, data: CloudDirectory.Types.ListDirectoriesResponse) => void): Request<CloudDirectory.Types.ListDirectoriesResponse, AWSError>; /** * Retrieves attributes attached to the facet. */ listFacetAttributes(params: CloudDirectory.Types.ListFacetAttributesRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListFacetAttributesResponse) => void): Request<CloudDirectory.Types.ListFacetAttributesResponse, AWSError>; /** * Retrieves attributes attached to the facet. */ listFacetAttributes(callback?: (err: AWSError, data: CloudDirectory.Types.ListFacetAttributesResponse) => void): Request<CloudDirectory.Types.ListFacetAttributesResponse, AWSError>; /** * Retrieves the names of facets that exist in a schema. */ listFacetNames(params: CloudDirectory.Types.ListFacetNamesRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListFacetNamesResponse) => void): Request<CloudDirectory.Types.ListFacetNamesResponse, AWSError>; /** * Retrieves the names of facets that exist in a schema. */ listFacetNames(callback?: (err: AWSError, data: CloudDirectory.Types.ListFacetNamesResponse) => void): Request<CloudDirectory.Types.ListFacetNamesResponse, AWSError>; /** * Returns a paginated list of all the incoming TypedLinkSpecifier information for an object. It also supports filtering by typed link facet and identity attributes. For more information, see Typed Links. */ listIncomingTypedLinks(params: CloudDirectory.Types.ListIncomingTypedLinksRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListIncomingTypedLinksResponse) => void): Request<CloudDirectory.Types.ListIncomingTypedLinksResponse, AWSError>; /** * Returns a paginated list of all the incoming TypedLinkSpecifier information for an object. It also supports filtering by typed link facet and identity attributes. For more information, see Typed Links. */ listIncomingTypedLinks(callback?: (err: AWSError, data: CloudDirectory.Types.ListIncomingTypedLinksResponse) => void): Request<CloudDirectory.Types.ListIncomingTypedLinksResponse, AWSError>; /** * Lists objects attached to the specified index. */ listIndex(params: CloudDirectory.Types.ListIndexRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListIndexResponse) => void): Request<CloudDirectory.Types.ListIndexResponse, AWSError>; /** * Lists objects attached to the specified index. */ listIndex(callback?: (err: AWSError, data: CloudDirectory.Types.ListIndexResponse) => void): Request<CloudDirectory.Types.ListIndexResponse, AWSError>; /** * Lists the major version families of each managed schema. If a major version ARN is provided as SchemaArn, the minor version revisions in that family are listed instead. */ listManagedSchemaArns(params: CloudDirectory.Types.ListManagedSchemaArnsRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListManagedSchemaArnsResponse) => void): Request<CloudDirectory.Types.ListManagedSchemaArnsResponse, AWSError>; /** * Lists the major version families of each managed schema. If a major version ARN is provided as SchemaArn, the minor version revisions in that family are listed instead. */ listManagedSchemaArns(callback?: (err: AWSError, data: CloudDirectory.Types.ListManagedSchemaArnsResponse) => void): Request<CloudDirectory.Types.ListManagedSchemaArnsResponse, AWSError>; /** * Lists all attributes that are associated with an object. */ listObjectAttributes(params: CloudDirectory.Types.ListObjectAttributesRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListObjectAttributesResponse) => void): Request<CloudDirectory.Types.ListObjectAttributesResponse, AWSError>; /** * Lists all attributes that are associated with an object. */ listObjectAttributes(callback?: (err: AWSError, data: CloudDirectory.Types.ListObjectAttributesResponse) => void): Request<CloudDirectory.Types.ListObjectAttributesResponse, AWSError>; /** * Returns a paginated list of child objects that are associated with a given object. */ listObjectChildren(params: CloudDirectory.Types.ListObjectChildrenRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListObjectChildrenResponse) => void): Request<CloudDirectory.Types.ListObjectChildrenResponse, AWSError>; /** * Returns a paginated list of child objects that are associated with a given object. */ listObjectChildren(callback?: (err: AWSError, data: CloudDirectory.Types.ListObjectChildrenResponse) => void): Request<CloudDirectory.Types.ListObjectChildrenResponse, AWSError>; /** * Retrieves all available parent paths for any object type such as node, leaf node, policy node, and index node objects. For more information about objects, see Directory Structure. Use this API to evaluate all parents for an object. The call returns all objects from the root of the directory up to the requested object. The API returns the number of paths based on user-defined MaxResults, in case there are multiple paths to the parent. The order of the paths and nodes returned is consistent among multiple API calls unless the objects are deleted or moved. Paths not leading to the directory root are ignored from the target object. */ listObjectParentPaths(params: CloudDirectory.Types.ListObjectParentPathsRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListObjectParentPathsResponse) => void): Request<CloudDirectory.Types.ListObjectParentPathsResponse, AWSError>; /** * Retrieves all available parent paths for any object type such as node, leaf node, policy node, and index node objects. For more information about objects, see Directory Structure. Use this API to evaluate all parents for an object. The call returns all objects from the root of the directory up to the requested object. The API returns the number of paths based on user-defined MaxResults, in case there are multiple paths to the parent. The order of the paths and nodes returned is consistent among multiple API calls unless the objects are deleted or moved. Paths not leading to the directory root are ignored from the target object. */ listObjectParentPaths(callback?: (err: AWSError, data: CloudDirectory.Types.ListObjectParentPathsResponse) => void): Request<CloudDirectory.Types.ListObjectParentPathsResponse, AWSError>; /** * Lists parent objects that are associated with a given object in pagination fashion. */ listObjectParents(params: CloudDirectory.Types.ListObjectParentsRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListObjectParentsResponse) => void): Request<CloudDirectory.Types.ListObjectParentsResponse, AWSError>; /** * Lists parent objects that are associated with a given object in pagination fashion. */ listObjectParents(callback?: (err: AWSError, data: CloudDirectory.Types.ListObjectParentsResponse) => void): Request<CloudDirectory.Types.ListObjectParentsResponse, AWSError>; /** * Returns policies attached to an object in pagination fashion. */ listObjectPolicies(params: CloudDirectory.Types.ListObjectPoliciesRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListObjectPoliciesResponse) => void): Request<CloudDirectory.Types.ListObjectPoliciesResponse, AWSError>; /** * Returns policies attached to an object in pagination fashion. */ listObjectPolicies(callback?: (err: AWSError, data: CloudDirectory.Types.ListObjectPoliciesResponse) => void): Request<CloudDirectory.Types.ListObjectPoliciesResponse, AWSError>; /** * Returns a paginated list of all the outgoing TypedLinkSpecifier information for an object. It also supports filtering by typed link facet and identity attributes. For more information, see Typed Links. */ listOutgoingTypedLinks(params: CloudDirectory.Types.ListOutgoingTypedLinksRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListOutgoingTypedLinksResponse) => void): Request<CloudDirectory.Types.ListOutgoingTypedLinksResponse, AWSError>; /** * Returns a paginated list of all the outgoing TypedLinkSpecifier information for an object. It also supports filtering by typed link facet and identity attributes. For more information, see Typed Links. */ listOutgoingTypedLinks(callback?: (err: AWSError, data: CloudDirectory.Types.ListOutgoingTypedLinksResponse) => void): Request<CloudDirectory.Types.ListOutgoingTypedLinksResponse, AWSError>; /** * Returns all of the ObjectIdentifiers to which a given policy is attached. */ listPolicyAttachments(params: CloudDirectory.Types.ListPolicyAttachmentsRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListPolicyAttachmentsResponse) => void): Request<CloudDirectory.Types.ListPolicyAttachmentsResponse, AWSError>; /** * Returns all of the ObjectIdentifiers to which a given policy is attached. */ listPolicyAttachments(callback?: (err: AWSError, data: CloudDirectory.Types.ListPolicyAttachmentsResponse) => void): Request<CloudDirectory.Types.ListPolicyAttachmentsResponse, AWSError>; /** * Lists the major version families of each published schema. If a major version ARN is provided as SchemaArn, the minor version revisions in that family are listed instead. */ listPublishedSchemaArns(params: CloudDirectory.Types.ListPublishedSchemaArnsRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListPublishedSchemaArnsResponse) => void): Request<CloudDirectory.Types.ListPublishedSchemaArnsResponse, AWSError>; /** * Lists the major version families of each published schema. If a major version ARN is provided as SchemaArn, the minor version revisions in that family are listed instead. */ listPublishedSchemaArns(callback?: (err: AWSError, data: CloudDirectory.Types.ListPublishedSchemaArnsResponse) => void): Request<CloudDirectory.Types.ListPublishedSchemaArnsResponse, AWSError>; /** * Returns tags for a resource. Tagging is currently supported only for directories with a limit of 50 tags per directory. All 50 tags are returned for a given directory with this API call. */ listTagsForResource(params: CloudDirectory.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListTagsForResourceResponse) => void): Request<CloudDirectory.Types.ListTagsForResourceResponse, AWSError>; /** * Returns tags for a resource. Tagging is currently supported only for directories with a limit of 50 tags per directory. All 50 tags are returned for a given directory with this API call. */ listTagsForResource(callback?: (err: AWSError, data: CloudDirectory.Types.ListTagsForResourceResponse) => void): Request<CloudDirectory.Types.ListTagsForResourceResponse, AWSError>; /** * Returns a paginated list of all attribute definitions for a particular TypedLinkFacet. For more information, see Typed Links. */ listTypedLinkFacetAttributes(params: CloudDirectory.Types.ListTypedLinkFacetAttributesRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListTypedLinkFacetAttributesResponse) => void): Request<CloudDirectory.Types.ListTypedLinkFacetAttributesResponse, AWSError>; /** * Returns a paginated list of all attribute definitions for a particular TypedLinkFacet. For more information, see Typed Links. */ listTypedLinkFacetAttributes(callback?: (err: AWSError, data: CloudDirectory.Types.ListTypedLinkFacetAttributesResponse) => void): Request<CloudDirectory.Types.ListTypedLinkFacetAttributesResponse, AWSError>; /** * Returns a paginated list of TypedLink facet names for a particular schema. For more information, see Typed Links. */ listTypedLinkFacetNames(params: CloudDirectory.Types.ListTypedLinkFacetNamesRequest, callback?: (err: AWSError, data: CloudDirectory.Types.ListTypedLinkFacetNamesResponse) => void): Request<CloudDirectory.Types.ListTypedLinkFacetNamesResponse, AWSError>; /** * Returns a paginated list of TypedLink facet names for a particular schema. For more information, see Typed Links. */ listTypedLinkFacetNames(callback?: (err: AWSError, data: CloudDirectory.Types.ListTypedLinkFacetNamesResponse) => void): Request<CloudDirectory.Types.ListTypedLinkFacetNamesResponse, AWSError>; /** * Lists all policies from the root of the Directory to the object specified. If there are no policies present, an empty list is returned. If policies are present, and if some objects don't have the policies attached, it returns the ObjectIdentifier for such objects. If policies are present, it returns ObjectIdentifier, policyId, and policyType. Paths that don't lead to the root from the target object are ignored. For more information, see Policies. */ lookupPolicy(params: CloudDirectory.Types.LookupPolicyRequest, callback?: (err: AWSError, data: CloudDirectory.Types.LookupPolicyResponse) => void): Request<CloudDirectory.Types.LookupPolicyResponse, AWSError>; /** * Lists all policies from the root of the Directory to the object specified. If there are no policies present, an empty list is returned. If policies are present, and if some objects don't have the policies attached, it returns the ObjectIdentifier for such objects. If policies are present, it returns ObjectIdentifier, policyId, and policyType. Paths that don't lead to the root from the target object are ignored. For more information, see Policies. */ lookupPolicy(callback?: (err: AWSError, data: CloudDirectory.Types.LookupPolicyResponse) => void): Request<CloudDirectory.Types.LookupPolicyResponse, AWSError>; /** * Publishes a development schema with a major version and a recommended minor version. */ publishSchema(params: CloudDirectory.Types.PublishSchemaRequest, callback?: (err: AWSError, data: CloudDirectory.Types.PublishSchemaResponse) => void): Request<CloudDirectory.Types.PublishSchemaResponse, AWSError>; /** * Publishes a development schema with a major version and a recommended minor version. */ publishSchema(callback?: (err: AWSError, data: CloudDirectory.Types.PublishSchemaResponse) => void): Request<CloudDirectory.Types.PublishSchemaResponse, AWSError>; /** * Allows a schema to be updated using JSON upload. Only available for development schemas. See JSON Schema Format for more information. */ putSchemaFromJson(params: CloudDirectory.Types.PutSchemaFromJsonRequest, callback?: (err: AWSError, data: CloudDirectory.Types.PutSchemaFromJsonResponse) => void): Request<CloudDirectory.Types.PutSchemaFromJsonResponse, AWSError>; /** * Allows a schema to be updated using JSON upload. Only available for development schemas. See JSON Schema Format for more information. */ putSchemaFromJson(callback?: (err: AWSError, data: CloudDirectory.Types.PutSchemaFromJsonResponse) => void): Request<CloudDirectory.Types.PutSchemaFromJsonResponse, AWSError>; /** * Removes the specified facet from the specified object. */ removeFacetFromObject(params: CloudDirectory.Types.RemoveFacetFromObjectRequest, callback?: (err: AWSError, data: CloudDirectory.Types.RemoveFacetFromObjectResponse) => void): Request<CloudDirectory.Types.RemoveFacetFromObjectResponse, AWSError>; /** * Removes the specified facet from the specified object. */ removeFacetFromObject(callback?: (err: AWSError, data: CloudDirectory.Types.RemoveFacetFromObjectResponse) => void): Request<CloudDirectory.Types.RemoveFacetFromObjectResponse, AWSError>; /** * An API operation for adding tags to a resource. */ tagResource(params: CloudDirectory.Types.TagResourceRequest, callback?: (err: AWSError, data: CloudDirectory.Types.TagResourceResponse) => void): Request<CloudDirectory.Types.TagResourceResponse, AWSError>; /** * An API operation for adding tags to a resource. */ tagResource(callback?: (err: AWSError, data: CloudDirectory.Types.TagResourceResponse) => void): Request<CloudDirectory.Types.TagResourceResponse, AWSError>; /** * An API operation for removing tags from a resource. */ untagResource(params: CloudDirectory.Types.UntagResourceRequest, callback?: (err: AWSError, data: CloudDirectory.Types.UntagResourceResponse) => void): Request<CloudDirectory.Types.UntagResourceResponse, AWSError>; /** * An API operation for removing tags from a resource. */ untagResource(callback?: (err: AWSError, data: CloudDirectory.Types.UntagResourceResponse) => void): Request<CloudDirectory.Types.UntagResourceResponse, AWSError>; /** * Does the following: Adds new Attributes, Rules, or ObjectTypes. Updates existing Attributes, Rules, or ObjectTypes. Deletes existing Attributes, Rules, or ObjectTypes. */ updateFacet(params: CloudDirectory.Types.UpdateFacetRequest, callback?: (err: AWSError, data: CloudDirectory.Types.UpdateFacetResponse) => void): Request<CloudDirectory.Types.UpdateFacetResponse, AWSError>; /** * Does the following: Adds new Attributes, Rules, or ObjectTypes. Updates existing Attributes, Rules, or ObjectTypes. Deletes existing Attributes, Rules, or ObjectTypes. */ updateFacet(callback?: (err: AWSError, data: CloudDirectory.Types.UpdateFacetResponse) => void): Request<CloudDirectory.Types.UpdateFacetResponse, AWSError>; /** * Updates a given typed link’s attributes. Attributes to be updated must not contribute to the typed link’s identity, as defined by its IdentityAttributeOrder. */ updateLinkAttributes(params: CloudDirectory.Types.UpdateLinkAttributesRequest, callback?: (err: AWSError, data: CloudDirectory.Types.UpdateLinkAttributesResponse) => void): Request<CloudDirectory.Types.UpdateLinkAttributesResponse, AWSError>; /** * Updates a given typed link’s attributes. Attributes to be updated must not contribute to the typed link’s identity, as defined by its IdentityAttributeOrder. */ updateLinkAttributes(callback?: (err: AWSError, data: CloudDirectory.Types.UpdateLinkAttributesResponse) => void): Request<CloudDirectory.Types.UpdateLinkAttributesResponse, AWSError>; /** * Updates a given object's attributes. */ updateObjectAttributes(params: CloudDirectory.Types.UpdateObjectAttributesRequest, callback?: (err: AWSError, data: CloudDirectory.Types.UpdateObjectAttributesResponse) => void): Request<CloudDirectory.Types.UpdateObjectAttributesResponse, AWSError>; /** * Updates a given object's attributes. */ updateObjectAttributes(callback?: (err: AWSError, data: CloudDirectory.Types.UpdateObjectAttributesResponse) => void): Request<CloudDirectory.Types.UpdateObjectAttributesResponse, AWSError>; /** * Updates the schema name with a new name. Only development schema names can be updated. */ updateSchema(params: CloudDirectory.Types.UpdateSchemaRequest, callback?: (err: AWSError, data: CloudDirectory.Types.UpdateSchemaResponse) => void): Request<CloudDirectory.Types.UpdateSchemaResponse, AWSError>; /** * Updates the schema name with a new name. Only development schema names can be updated. */ updateSchema(callback?: (err: AWSError, data: CloudDirectory.Types.UpdateSchemaResponse) => void): Request<CloudDirectory.Types.UpdateSchemaResponse, AWSError>; /** * Updates a TypedLinkFacet. For more information, see Typed Links. */ updateTypedLinkFacet(params: CloudDirectory.Types.UpdateTypedLinkFacetRequest, callback?: (err: AWSError, data: CloudDirectory.Types.UpdateTypedLinkFacetResponse) => void): Request<CloudDirectory.Types.UpdateTypedLinkFacetResponse, AWSError>; /** * Updates a TypedLinkFacet. For more information, see Typed Links. */ updateTypedLinkFacet(callback?: (err: AWSError, data: CloudDirectory.Types.UpdateTypedLinkFacetResponse) => void): Request<CloudDirectory.Types.UpdateTypedLinkFacetResponse, AWSError>; /** * Upgrades a single directory in-place using the PublishedSchemaArn with schema updates found in MinorVersion. Backwards-compatible minor version upgrades are instantaneously available for readers on all objects in the directory. Note: This is a synchronous API call and upgrades only one schema on a given directory per call. To upgrade multiple directories from one schema, you would need to call this API on each directory. */ upgradeAppliedSchema(params: CloudDirectory.Types.UpgradeAppliedSchemaRequest, callback?: (err: AWSError, data: CloudDirectory.Types.UpgradeAppliedSchemaResponse) => void): Request<CloudDirectory.Types.UpgradeAppliedSchemaResponse, AWSError>; /** * Upgrades a single directory in-place using the PublishedSchemaArn with schema updates found in MinorVersion. Backwards-compatible minor version upgrades are instantaneously available for readers on all objects in the directory. Note: This is a synchronous API call and upgrades only one schema on a given directory per call. To upgrade multiple directories from one schema, you would need to call this API on each directory. */ upgradeAppliedSchema(callback?: (err: AWSError, data: CloudDirectory.Types.UpgradeAppliedSchemaResponse) => void): Request<CloudDirectory.Types.UpgradeAppliedSchemaResponse, AWSError>; /** * Upgrades a published schema under a new minor version revision using the current contents of DevelopmentSchemaArn. */ upgradePublishedSchema(params: CloudDirectory.Types.UpgradePublishedSchemaRequest, callback?: (err: AWSError, data: CloudDirectory.Types.UpgradePublishedSchemaResponse) => void): Request<CloudDirectory.Types.UpgradePublishedSchemaResponse, AWSError>; /** * Upgrades a published schema under a new minor version revision using the current contents of DevelopmentSchemaArn. */ upgradePublishedSchema(callback?: (err: AWSError, data: CloudDirectory.Types.UpgradePublishedSchemaResponse) => void): Request<CloudDirectory.Types.UpgradePublishedSchemaResponse, AWSError>; } declare namespace CloudDirectory { export interface AddFacetToObjectRequest { /** * The Amazon Resource Name (ARN) that is associated with the Directory where the object resides. For more information, see arns. */ DirectoryArn: Arn; /** * Identifiers for the facet that you are adding to the object. See SchemaFacet for details. */ SchemaFacet: SchemaFacet; /** * Attributes on the facet that you are adding to the object. */ ObjectAttributeList?: AttributeKeyAndValueList; /** * A reference to the object you are adding the specified facet to. */ ObjectReference: ObjectReference; } export interface AddFacetToObjectResponse { } export interface ApplySchemaRequest { /** * Published schema Amazon Resource Name (ARN) that needs to be copied. For more information, see arns. */ PublishedSchemaArn: Arn; /** * The Amazon Resource Name (ARN) that is associated with the Directory into which the schema is copied. For more information, see arns. */ DirectoryArn: Arn; } export interface ApplySchemaResponse { /** * The applied schema ARN that is associated with the copied schema in the Directory. You can use this ARN to describe the schema information applied on this directory. For more information, see arns. */ AppliedSchemaArn?: Arn; /** * The ARN that is associated with the Directory. For more information, see arns. */ DirectoryArn?: Arn; } export type Arn = string; export type Arns = Arn[]; export interface AttachObjectRequest { /** * Amazon Resource Name (ARN) that is associated with the Directory where both objects reside. For more information, see arns. */ DirectoryArn: Arn; /** * The parent object reference. */ ParentReference: ObjectReference; /** * The child object reference to be attached to the object. */ ChildReference: ObjectReference; /** * The link name with which the child object is attached to the parent. */ LinkName: LinkName; } export interface AttachObjectResponse { /** * The attached ObjectIdentifier, which is the child ObjectIdentifier. */ AttachedObjectIdentifier?: ObjectIdentifier; } export interface AttachPolicyRequest { /** * The Amazon Resource Name (ARN) that is associated with the Directory where both objects reside. For more information, see arns. */ DirectoryArn: Arn; /** * The reference that is associated with the policy object. */ PolicyReference: ObjectReference; /** * The reference that identifies the object to which the policy will be attached. */ ObjectReference: ObjectReference; } export interface AttachPolicyResponse { } export interface AttachToIndexRequest { /** * The Amazon Resource Name (ARN) of the directory where the object and index exist. */ DirectoryArn: Arn; /** * A reference to the index that you are attaching the object to. */ IndexReference: ObjectReference; /** * A reference to the object that you are attaching to the index. */ TargetReference: ObjectReference; } export interface AttachToIndexResponse { /** * The ObjectIdentifier of the object that was attached to the index. */ AttachedObjectIdentifier?: ObjectIdentifier; } export interface AttachTypedLinkRequest { /** * The Amazon Resource Name (ARN) of the directory where you want to attach the typed link. */ DirectoryArn: Arn; /** * Identifies the source object that the typed link will attach to. */ SourceObjectReference: ObjectReference; /** * Identifies the target object that the typed link will attach to. */ TargetObjectReference: ObjectReference; /** * Identifies the typed link facet that is associated with the typed link. */ TypedLinkFacet: TypedLinkSchemaAndFacetName; /** * A set of attributes that are associated with the typed link. */ Attributes: AttributeNameAndValueList; } export interface AttachTypedLinkResponse { /** * Returns a typed link specifier as output. */ TypedLinkSpecifier?: TypedLinkSpecifier; } export interface AttributeKey { /** * The Amazon Resource Name (ARN) of the schema that contains the facet and attribute. */ SchemaArn: Arn; /** * The name of the facet that the attribute exists within. */ FacetName: FacetName; /** * The name of the attribute. */ Name: AttributeName; } export interface AttributeKeyAndValue { /** * The key of the attribute. */ Key: AttributeKey; /** * The value of the attribute. */ Value: TypedAttributeValue; } export type AttributeKeyAndValueList = AttributeKeyAndValue[]; export type AttributeKeyList = AttributeKey[]; export type AttributeName = string; export interface AttributeNameAndValue { /** * The attribute name of the typed link. */ AttributeName: AttributeName; /** * The value for the typed link. */ Value: TypedAttributeValue; } export type AttributeNameAndValueList = AttributeNameAndValue[]; export type AttributeNameList = AttributeName[]; export interface BatchAddFacetToObject { /** * Represents the facet being added to the object. */ SchemaFacet: SchemaFacet; /** * The attributes to set on the object. */ ObjectAttributeList: AttributeKeyAndValueList; /** * A reference to the object being mutated. */ ObjectReference: ObjectReference; } export interface BatchAddFacetToObjectResponse { } export interface BatchAttachObject { /** * The parent object reference. */ ParentReference: ObjectReference; /** * The child object reference that is to be attached to the object. */ ChildReference: ObjectReference; /** * The name of the link. */ LinkName: LinkName; } export interface BatchAttachObjectResponse { /** * The ObjectIdentifier of the object that has been attached. */ attachedObjectIdentifier?: ObjectIdentifier; } export interface BatchAttachPolicy { /** * The reference that is associated with the policy object. */ PolicyReference: ObjectReference; /** * The reference that identifies the object to which the policy will be attached. */ ObjectReference: ObjectReference; } export interface BatchAttachPolicyResponse { } export interface BatchAttachToIndex { /** * A reference to the index that you are attaching the object to. */ IndexReference: ObjectReference; /** * A reference to the object that you are attaching to the index. */ TargetReference: ObjectReference; } export interface BatchAttachToIndexResponse { /** * The ObjectIdentifier of the object that was attached to the index. */ AttachedObjectIdentifier?: ObjectIdentifier; } export interface BatchAttachTypedLink { /** * Identifies the source object that the typed link will attach to. */ SourceObjectReference: ObjectReference; /** * Identifies the target object that the typed link will attach to. */ TargetObjectReference: ObjectReference; /** * Identifies the typed link facet that is associated with the typed link. */ TypedLinkFacet: TypedLinkSchemaAndFacetName; /** * A set of attributes that are associated with the typed link. */ Attributes: AttributeNameAndValueList; } export interface BatchAttachTypedLinkResponse { /** * Returns a typed link specifier as output. */ TypedLinkSpecifier?: TypedLinkSpecifier; } export interface BatchCreateIndex { /** * Specifies the attributes that should be indexed on. Currently only a single attribute is supported. */ OrderedIndexedAttributeList: AttributeKeyList; /** * Indicates whether the attribute that is being indexed has unique values or not. */ IsUnique: Bool; /** * A reference to the parent object that contains the index object. */ ParentReference?: ObjectReference; /** * The name of the link between the parent object and the index object. */ LinkName?: LinkName; /** * The batch reference name. See Transaction Support for more information. */ BatchReferenceName?: BatchReferenceName; } export interface BatchCreateIndexResponse { /** * The ObjectIdentifier of the index created by this operation. */ ObjectIdentifier?: ObjectIdentifier; } export interface BatchCreateObject { /** * A list of FacetArns that will be associated with the object. For more information, see arns. */ SchemaFacet: SchemaFacetList; /** * An attribute map, which contains an attribute ARN as the key and attribute value as the map value. */ ObjectAttributeList: AttributeKeyAndValueList; /** * If specified, the parent reference to which this object will be attached. */ ParentReference?: ObjectReference; /** * The name of the link. */ LinkName?: LinkName; /** * The batch reference name. See Transaction Support for more information. */ BatchReferenceName?: BatchReferenceName; } export interface BatchCreateObjectResponse { /** * The ID that is associated with the object. */ ObjectIdentifier?: ObjectIdentifier; } export interface BatchDeleteObject { /** * The reference that identifies the object. */ ObjectReference: ObjectReference; } export interface BatchDeleteObjectResponse { } export interface BatchDetachFromIndex { /** * A reference to the index object. */ IndexReference: ObjectReference; /** * A reference to the object being detached from the index. */ TargetReference: ObjectReference; } export interface BatchDetachFromIndexResponse { /** * The ObjectIdentifier of the object that was detached from the index. */ DetachedObjectIdentifier?: ObjectIdentifier; } export interface BatchDetachObject { /** * Parent reference from which the object with the specified link name is detached. */ ParentReference: ObjectReference; /** * The name of the link. */ LinkName: LinkName; /** * The batch reference name. See Transaction Support for more information. */ BatchReferenceName?: BatchReferenceName; } export interface BatchDetachObjectResponse { /** * The ObjectIdentifier of the detached object. */ detachedObjectIdentifier?: ObjectIdentifier; } export interface BatchDetachPolicy { /** * Reference that identifies the policy object. */ PolicyReference: ObjectReference; /** * Reference that identifies the object whose policy object will be detached. */ ObjectReference: ObjectReference; } export interface BatchDetachPolicyResponse { } export interface BatchDetachTypedLink { /** * Used to accept a typed link specifier as input. */ TypedLinkSpecifier: TypedLinkSpecifier; } export interface BatchDetachTypedLinkResponse { } export interface BatchGetLinkAttributes { /** * Allows a typed link specifier to be accepted as input. */ TypedLinkSpecifier: TypedLinkSpecifier; /** * A list of attribute names whose values will be retrieved. */ AttributeNames: AttributeNameList; } export interface BatchGetLinkAttributesResponse { /** * The attributes that are associated with the typed link. */ Attributes?: AttributeKeyAndValueList; } export interface BatchGetObjectAttributes { /** * Reference that identifies the object whose attributes will be retrieved. */ ObjectReference: ObjectReference; /** * Identifier for the facet whose attributes will be retrieved. See SchemaFacet for details. */ SchemaFacet: SchemaFacet; /** * List of attribute names whose values will be retrieved. */ AttributeNames: AttributeNameList; } export interface BatchGetObjectAttributesResponse { /** * The attribute values that are associated with an object. */ Attributes?: AttributeKeyAndValueList; } export interface BatchGetObjectInformation { /** * A reference to the object. */ ObjectReference: ObjectReference; } export interface BatchGetObjectInformationResponse { /** * The facets attached to the specified object. */ SchemaFacets?: SchemaFacetList; /** * The ObjectIdentifier of the specified object. */ ObjectIdentifier?: ObjectIdentifier; } export interface BatchListAttachedIndices { /** * A reference to the object that has indices attached. */ TargetReference: ObjectReference; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; } export interface BatchListAttachedIndicesResponse { /** * The indices attached to the specified object. */ IndexAttachments?: IndexAttachmentList; /** * The pagination token. */ NextToken?: NextToken; } export interface BatchListIncomingTypedLinks { /** * The reference that identifies the object whose attributes will be listed. */ ObjectReference: ObjectReference; /** * Provides range filters for multiple attributes. When providing ranges to typed link selection, any inexact ranges must be specified at the end. Any attributes that do not have a range specified are presumed to match the entire range. */ FilterAttributeRanges?: TypedLinkAttributeRangeList; /** * Filters are interpreted in the order of the attributes on the typed link facet, not the order in which they are supplied to any API calls. */ FilterTypedLink?: TypedLinkSchemaAndFacetName; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; } export interface BatchListIncomingTypedLinksResponse { /** * Returns one or more typed link specifiers as output. */ LinkSpecifiers?: TypedLinkSpecifierList; /** * The pagination token. */ NextToken?: NextToken; } export interface BatchListIndex { /** * Specifies the ranges of indexed values that you want to query. */ RangesOnIndexedValues?: ObjectAttributeRangeList; /** * The reference to the index to list. */ IndexReference: ObjectReference; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; /** * The pagination token. */ NextToken?: NextToken; } export interface BatchListIndexResponse { /** * The objects and indexed values attached to the index. */ IndexAttachments?: IndexAttachmentList; /** * The pagination token. */ NextToken?: NextToken; } export interface BatchListObjectAttributes { /** * Reference of the object whose attributes need to be listed. */ ObjectReference: ObjectReference; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of items to be retrieved in a single call. This is an approximate number. */ MaxResults?: NumberResults; /** * Used to filter the list of object attributes that are associated with a certain facet. */ FacetFilter?: SchemaFacet; } export interface BatchListObjectAttributesResponse { /** * The attributes map that is associated with the object. AttributeArn is the key; attribute value is the value. */ Attributes?: AttributeKeyAndValueList; /** * The pagination token. */ NextToken?: NextToken; } export interface BatchListObjectChildren { /** * Reference of the object for which child objects are being listed. */ ObjectReference: ObjectReference; /** * The pagination token. */ NextToken?: NextToken; /** * Maximum number of items to be retrieved in a single call. This is an approximate number. */ MaxResults?: NumberResults; } export interface BatchListObjectChildrenResponse { /** * The children structure, which is a map with the key as the LinkName and ObjectIdentifier as the value. */ Children?: LinkNameToObjectIdentifierMap; /** * The pagination token. */ NextToken?: NextToken; } export interface BatchListObjectParentPaths { /** * The reference that identifies the object whose attributes will be listed. */ ObjectReference: ObjectReference; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; } export interface BatchListObjectParentPathsResponse { /** * Returns the path to the ObjectIdentifiers that are associated with the directory. */ PathToObjectIdentifiersList?: PathToObjectIdentifiersList; /** * The pagination token. */ NextToken?: NextToken; } export interface BatchListObjectParents { ObjectReference: ObjectReference; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of items to be retrieved in a single call. This is an approximate number. */ MaxResults?: NumberResults; } export interface BatchListObjectParentsResponse { /** * Returns a list of parent reference and LinkName Tuples. */ ParentLinks?: ObjectIdentifierAndLinkNameList; /** * The pagination token. */ NextToken?: NextToken; } export interface BatchListObjectPolicies { /** * The reference that identifies the object whose attributes will be listed. */ ObjectReference: ObjectReference; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; } export interface BatchListObjectPoliciesResponse { /** * A list of policy ObjectIdentifiers, that are attached to the object. */ AttachedPolicyIds?: ObjectIdentifierList; /** * The pagination token. */ NextToken?: NextToken; } export interface BatchListOutgoingTypedLinks { /** * The reference that identifies the object whose attributes will be listed. */ ObjectReference: ObjectReference; /** * Provides range filters for multiple attributes. When providing ranges to typed link selection, any inexact ranges must be specified at the end. Any attributes that do not have a range specified are presumed to match the entire range. */ FilterAttributeRanges?: TypedLinkAttributeRangeList; /** * Filters are interpreted in the order of the attributes defined on the typed link facet, not the order they are supplied to any API calls. */ FilterTypedLink?: TypedLinkSchemaAndFacetName; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; } export interface BatchListOutgoingTypedLinksResponse { /** * Returns a typed link specifier as output. */ TypedLinkSpecifiers?: TypedLinkSpecifierList; /** * The pagination token. */ NextToken?: NextToken; } export interface BatchListPolicyAttachments { /** * The reference that identifies the policy object. */ PolicyReference: ObjectReference; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; } export interface BatchListPolicyAttachmentsResponse { /** * A list of ObjectIdentifiers to which the policy is attached. */ ObjectIdentifiers?: ObjectIdentifierList; /** * The pagination token. */ NextToken?: NextToken; } export interface BatchLookupPolicy { /** * Reference that identifies the object whose policies will be looked up. */ ObjectReference: ObjectReference; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; } export interface BatchLookupPolicyResponse { /** * Provides list of path to policies. Policies contain PolicyId, ObjectIdentifier, and PolicyType. For more information, see Policies. */ PolicyToPathList?: PolicyToPathList; /** * The pagination token. */ NextToken?: NextToken; } export interface BatchReadException { /** * A type of exception, such as InvalidArnException. */ Type?: BatchReadExceptionType; /** * An exception message that is associated with the failure. */ Message?: ExceptionMessage; } export type BatchReadExceptionType = "ValidationException"|"InvalidArnException"|"ResourceNotFoundException"|"InvalidNextTokenException"|"AccessDeniedException"|"NotNodeException"|"FacetValidationException"|"CannotListParentOfRootException"|"NotIndexException"|"NotPolicyException"|"DirectoryNotEnabledException"|"LimitExceededException"|"InternalServiceException"|string; export interface BatchReadOperation { /** * Lists all attributes that are associated with an object. */ ListObjectAttributes?: BatchListObjectAttributes; /** * Returns a paginated list of child objects that are associated with a given object. */ ListObjectChildren?: BatchListObjectChildren; /** * Lists indices attached to an object. */ ListAttachedIndices?: BatchListAttachedIndices; /** * Retrieves all available parent paths for any object type such as node, leaf node, policy node, and index node objects. For more information about objects, see Directory Structure. */ ListObjectParentPaths?: BatchListObjectParentPaths; /** * Retrieves metadata about an object. */ GetObjectInformation?: BatchGetObjectInformation; /** * Retrieves attributes within a facet that are associated with an object. */ GetObjectAttributes?: BatchGetObjectAttributes; /** * Lists parent objects that are associated with a given object in pagination fashion. */ ListObjectParents?: BatchListObjectParents; /** * Returns policies attached to an object in pagination fashion. */ ListObjectPolicies?: BatchListObjectPolicies; /** * Returns all of the ObjectIdentifiers to which a given policy is attached. */ ListPolicyAttachments?: BatchListPolicyAttachments; /** * Lists all policies from the root of the Directory to the object specified. If there are no policies present, an empty list is returned. If policies are present, and if some objects don't have the policies attached, it returns the ObjectIdentifier for such objects. If policies are present, it returns ObjectIdentifier, policyId, and policyType. Paths that don't lead to the root from the target object are ignored. For more information, see Policies. */ LookupPolicy?: BatchLookupPolicy; /** * Lists objects attached to the specified index. */ ListIndex?: BatchListIndex; /** * Returns a paginated list of all the outgoing TypedLinkSpecifier information for an object. It also supports filtering by typed link facet and identity attributes. For more information, see Typed Links. */ ListOutgoingTypedLinks?: BatchListOutgoingTypedLinks; /** * Returns a paginated list of all the incoming TypedLinkSpecifier information for an object. It also supports filtering by typed link facet and identity attributes. For more information, see Typed Links. */ ListIncomingTypedLinks?: BatchListIncomingTypedLinks; /** * Retrieves attributes that are associated with a typed link. */ GetLinkAttributes?: BatchGetLinkAttributes; } export type BatchReadOperationList = BatchReadOperation[]; export interface BatchReadOperationResponse { /** * Identifies which operation in a batch has succeeded. */ SuccessfulResponse?: BatchReadSuccessfulResponse; /** * Identifies which operation in a batch has failed. */ ExceptionResponse?: BatchReadException; } export type BatchReadOperationResponseList = BatchReadOperationResponse[]; export interface BatchReadRequest { /** * The Amazon Resource Name (ARN) that is associated with the Directory. For more information, see arns. */ DirectoryArn: Arn; /** * A list of operations that are part of the batch. */ Operations: BatchReadOperationList; /** * Represents the manner and timing in which the successful write or update of an object is reflected in a subsequent read operation of that same object. */ ConsistencyLevel?: ConsistencyLevel; } export interface BatchReadResponse { /** * A list of all the responses for each batch read. */ Responses?: BatchReadOperationResponseList; } export interface BatchReadSuccessfulResponse { /** * Lists all attributes that are associated with an object. */ ListObjectAttributes?: BatchListObjectAttributesResponse; /** * Returns a paginated list of child objects that are associated with a given object. */ ListObjectChildren?: BatchListObjectChildrenResponse; /** * Retrieves metadata about an object. */ GetObjectInformation?: BatchGetObjectInformationResponse; /** * Retrieves attributes within a facet that are associated with an object. */ GetObjectAttributes?: BatchGetObjectAttributesResponse; /** * Lists indices attached to an object. */ ListAttachedIndices?: BatchListAttachedIndicesResponse; /** * Retrieves all available parent paths for any object type such as node, leaf node, policy node, and index node objects. For more information about objects, see Directory Structure. */ ListObjectParentPaths?: BatchListObjectParentPathsResponse; /** * Returns policies attached to an object in pagination fashion. */ ListObjectPolicies?: BatchListObjectPoliciesResponse; /** * Returns all of the ObjectIdentifiers to which a given policy is attached. */ ListPolicyAttachments?: BatchListPolicyAttachmentsResponse; /** * Lists all policies from the root of the Directory to the object specified. If there are no policies present, an empty list is returned. If policies are present, and if some objects don't have the policies attached, it returns the ObjectIdentifier for such objects. If policies are present, it returns ObjectIdentifier, policyId, and policyType. Paths that don't lead to the root from the target object are ignored. For more information, see Policies. */ LookupPolicy?: BatchLookupPolicyResponse; /** * Lists objects attached to the specified index. */ ListIndex?: BatchListIndexResponse; /** * Returns a paginated list of all the outgoing TypedLinkSpecifier information for an object. It also supports filtering by typed link facet and identity attributes. For more information, see Typed Links. */ ListOutgoingTypedLinks?: BatchListOutgoingTypedLinksResponse; /** * Returns a paginated list of all the incoming TypedLinkSpecifier information for an object. It also supports filtering by typed link facet and identity attributes. For more information, see Typed Links. */ ListIncomingTypedLinks?: BatchListIncomingTypedLinksResponse; /** * The list of attributes to retrieve from the typed link. */ GetLinkAttributes?: BatchGetLinkAttributesResponse; /** * The list of parent objects to retrieve. */ ListObjectParents?: BatchListObjectParentsResponse; } export type BatchReferenceName = string; export interface BatchRemoveFacetFromObject { /** * The facet to remove from the object. */ SchemaFacet: SchemaFacet; /** * A reference to the object whose facet will be removed. */ ObjectReference: ObjectReference; } export interface BatchRemoveFacetFromObjectResponse { } export interface BatchUpdateLinkAttributes { /** * Allows a typed link specifier to be accepted as input. */ TypedLinkSpecifier: TypedLinkSpecifier; /** * The attributes update structure. */ AttributeUpdates: LinkAttributeUpdateList; } export interface BatchUpdateLinkAttributesResponse { } export interface BatchUpdateObjectAttributes { /** * Reference that identifies the object. */ ObjectReference: ObjectReference; /** * Attributes update structure. */ AttributeUpdates: ObjectAttributeUpdateList; } export interface BatchUpdateObjectAttributesResponse { /** * ID that is associated with the object. */ ObjectIdentifier?: ObjectIdentifier; } export interface BatchWriteOperation { /** * Creates an object. */ CreateObject?: BatchCreateObject; /** * Attaches an object to a Directory. */ AttachObject?: BatchAttachObject; /** * Detaches an object from a Directory. */ DetachObject?: BatchDetachObject; /** * Updates a given object's attributes. */ UpdateObjectAttributes?: BatchUpdateObjectAttributes; /** * Deletes an object in a Directory. */ DeleteObject?: BatchDeleteObject; /** * A batch operation that adds a facet to an object. */ AddFacetToObject?: BatchAddFacetToObject; /** * A batch operation that removes a facet from an object. */ RemoveFacetFromObject?: BatchRemoveFacetFromObject; /** * Attaches a policy object to a regular object. An object can have a limited number of attached policies. */ AttachPolicy?: BatchAttachPolicy; /** * Detaches a policy from a Directory. */ DetachPolicy?: BatchDetachPolicy; /** * Creates an index object. See Indexing and search for more information. */ CreateIndex?: BatchCreateIndex; /** * Attaches the specified object to the specified index. */ AttachToIndex?: BatchAttachToIndex; /** * Detaches the specified object from the specified index. */ DetachFromIndex?: BatchDetachFromIndex; /** * Attaches a typed link to a specified source and target object. For more information, see Typed Links. */ AttachTypedLink?: BatchAttachTypedLink; /** * Detaches a typed link from a specified source and target object. For more information, see Typed Links. */ DetachTypedLink?: BatchDetachTypedLink; /** * Updates a given object's attributes. */ UpdateLinkAttributes?: BatchUpdateLinkAttributes; } export type BatchWriteOperationList = BatchWriteOperation[]; export interface BatchWriteOperationResponse { /** * Creates an object in a Directory. */ CreateObject?: BatchCreateObjectResponse; /** * Attaches an object to a Directory. */ AttachObject?: BatchAttachObjectResponse; /** * Detaches an object from a Directory. */ DetachObject?: BatchDetachObjectResponse; /** * Updates a given object’s attributes. */ UpdateObjectAttributes?: BatchUpdateObjectAttributesResponse; /** * Deletes an object in a Directory. */ DeleteObject?: BatchDeleteObjectResponse; /** * The result of an add facet to object batch operation. */ AddFacetToObject?: BatchAddFacetToObjectResponse; /** * The result of a batch remove facet from object operation. */ RemoveFacetFromObject?: BatchRemoveFacetFromObjectResponse; /** * Attaches a policy object to a regular object. An object can have a limited number of attached policies. */ AttachPolicy?: BatchAttachPolicyResponse; /** * Detaches a policy from a Directory. */ DetachPolicy?: BatchDetachPolicyResponse; /** * Creates an index object. See Indexing and search for more information. */ CreateIndex?: BatchCreateIndexResponse; /** * Attaches the specified object to the specified index. */ AttachToIndex?: BatchAttachToIndexResponse; /** * Detaches the specified object from the specified index. */ DetachFromIndex?: BatchDetachFromIndexResponse; /** * Attaches a typed link to a specified source and target object. For more information, see Typed Links. */ AttachTypedLink?: BatchAttachTypedLinkResponse; /** * Detaches a typed link from a specified source and target object. For more information, see Typed Links. */ DetachTypedLink?: BatchDetachTypedLinkResponse; /** * Represents the output of a BatchWrite response operation. */ UpdateLinkAttributes?: BatchUpdateLinkAttributesResponse; } export type BatchWriteOperationResponseList = BatchWriteOperationResponse[]; export interface BatchWriteRequest { /** * The Amazon Resource Name (ARN) that is associated with the Directory. For more information, see arns. */ DirectoryArn: Arn; /** * A list of operations that are part of the batch. */ Operations: BatchWriteOperationList; } export interface BatchWriteResponse { /** * A list of all the responses for each batch write. */ Responses?: BatchWriteOperationResponseList; } export type BinaryAttributeValue = Buffer|Uint8Array|Blob|string; export type Bool = boolean; export type BooleanAttributeValue = boolean; export type ConsistencyLevel = "SERIALIZABLE"|"EVENTUAL"|string; export interface CreateDirectoryRequest { /** * The name of the Directory. Should be unique per account, per region. */ Name: DirectoryName; /** * The Amazon Resource Name (ARN) of the published schema that will be copied into the data Directory. For more information, see arns. */ SchemaArn: Arn; } export interface CreateDirectoryResponse { /** * The ARN that is associated with the Directory. For more information, see arns. */ DirectoryArn: DirectoryArn; /** * The name of the Directory. */ Name: DirectoryName; /** * The root object node of the created directory. */ ObjectIdentifier: ObjectIdentifier; /** * The ARN of the published schema in the Directory. Once a published schema is copied into the directory, it has its own ARN, which is referred to applied schema ARN. For more information, see arns. */ AppliedSchemaArn: Arn; } export interface CreateFacetRequest { /** * The schema ARN in which the new Facet will be created. For more information, see arns. */ SchemaArn: Arn; /** * The name of the Facet, which is unique for a given schema. */ Name: FacetName; /** * The attributes that are associated with the Facet. */ Attributes?: FacetAttributeList; /** * Specifies whether a given object created from this facet is of type node, leaf node, policy or index. Node: Can have multiple children but one parent. Leaf node: Cannot have children but can have multiple parents. Policy: Allows you to store a policy document and policy type. For more information, see Policies. Index: Can be created with the Index API. */ ObjectType?: ObjectType; /** * There are two different styles that you can define on any given facet, Static and Dynamic. For static facets, all attributes must be defined in the schema. For dynamic facets, attributes can be defined during data plane operations. */ FacetStyle?: FacetStyle; } export interface CreateFacetResponse { } export interface CreateIndexRequest { /** * The ARN of the directory where the index should be created. */ DirectoryArn: Arn; /** * Specifies the attributes that should be indexed on. Currently only a single attribute is supported. */ OrderedIndexedAttributeList: AttributeKeyList; /** * Indicates whether the attribute that is being indexed has unique values or not. */ IsUnique: Bool; /** * A reference to the parent object that contains the index object. */ ParentReference?: ObjectReference; /** * The name of the link between the parent object and the index object. */ LinkName?: LinkName; } export interface CreateIndexResponse { /** * The ObjectIdentifier of the index created by this operation. */ ObjectIdentifier?: ObjectIdentifier; } export interface CreateObjectRequest { /** * The Amazon Resource Name (ARN) that is associated with the Directory in which the object will be created. For more information, see arns. */ DirectoryArn: Arn; /** * A list of schema facets to be associated with the object. Do not provide minor version components. See SchemaFacet for details. */ SchemaFacets: SchemaFacetList; /** * The attribute map whose attribute ARN contains the key and attribute value as the map value. */ ObjectAttributeList?: AttributeKeyAndValueList; /** * If specified, the parent reference to which this object will be attached. */ ParentReference?: ObjectReference; /** * The name of link that is used to attach this object to a parent. */ LinkName?: LinkName; } export interface CreateObjectResponse { /** * The identifier that is associated with the object. */ ObjectIdentifier?: ObjectIdentifier; } export interface CreateSchemaRequest { /** * The name that is associated with the schema. This is unique to each account and in each region. */ Name: SchemaName; } export interface CreateSchemaResponse { /** * The Amazon Resource Name (ARN) that is associated with the schema. For more information, see arns. */ SchemaArn?: Arn; } export interface CreateTypedLinkFacetRequest { /** * The Amazon Resource Name (ARN) that is associated with the schema. For more information, see arns. */ SchemaArn: Arn; /** * Facet structure that is associated with the typed link facet. */ Facet: TypedLinkFacet; } export interface CreateTypedLinkFacetResponse { } export type _Date = Date; export type DatetimeAttributeValue = Date; export interface DeleteDirectoryRequest { /** * The ARN of the directory to delete. */ DirectoryArn: Arn; } export interface DeleteDirectoryResponse { /** * The ARN of the deleted directory. */ DirectoryArn: Arn; } export interface DeleteFacetRequest { /** * The Amazon Resource Name (ARN) that is associated with the Facet. For more information, see arns. */ SchemaArn: Arn; /** * The name of the facet to delete. */ Name: FacetName; } export interface DeleteFacetResponse { } export interface DeleteObjectRequest { /** * The Amazon Resource Name (ARN) that is associated with the Directory where the object resides. For more information, see arns. */ DirectoryArn: Arn; /** * A reference that identifies the object. */ ObjectReference: ObjectReference; } export interface DeleteObjectResponse { } export interface DeleteSchemaRequest { /** * The Amazon Resource Name (ARN) of the development schema. For more information, see arns. */ SchemaArn: Arn; } export interface DeleteSchemaResponse { /** * The input ARN that is returned as part of the response. For more information, see arns. */ SchemaArn?: Arn; } export interface DeleteTypedLinkFacetRequest { /** * The Amazon Resource Name (ARN) that is associated with the schema. For more information, see arns. */ SchemaArn: Arn; /** * The unique name of the typed link facet. */ Name: TypedLinkName; } export interface DeleteTypedLinkFacetResponse { } export interface DetachFromIndexRequest { /** * The Amazon Resource Name (ARN) of the directory the index and object exist in. */ DirectoryArn: Arn; /** * A reference to the index object. */ IndexReference: ObjectReference; /** * A reference to the object being detached from the index. */ TargetReference: ObjectReference; } export interface DetachFromIndexResponse { /** * The ObjectIdentifier of the object that was detached from the index. */ DetachedObjectIdentifier?: ObjectIdentifier; } export interface DetachObjectRequest { /** * The Amazon Resource Name (ARN) that is associated with the Directory where objects reside. For more information, see arns. */ DirectoryArn: Arn; /** * The parent reference from which the object with the specified link name is detached. */ ParentReference: ObjectReference; /** * The link name associated with the object that needs to be detached. */ LinkName: LinkName; } export interface DetachObjectResponse { /** * The ObjectIdentifier that was detached from the object. */ DetachedObjectIdentifier?: ObjectIdentifier; } export interface DetachPolicyRequest { /** * The Amazon Resource Name (ARN) that is associated with the Directory where both objects reside. For more information, see arns. */ DirectoryArn: Arn; /** * Reference that identifies the policy object. */ PolicyReference: ObjectReference; /** * Reference that identifies the object whose policy object will be detached. */ ObjectReference: ObjectReference; } export interface DetachPolicyResponse { } export interface DetachTypedLinkRequest { /** * The Amazon Resource Name (ARN) of the directory where you want to detach the typed link. */ DirectoryArn: Arn; /** * Used to accept a typed link specifier as input. */ TypedLinkSpecifier: TypedLinkSpecifier; } export interface Directory { /** * The name of the directory. */ Name?: DirectoryName; /** * The Amazon Resource Name (ARN) that is associated with the directory. For more information, see arns. */ DirectoryArn?: DirectoryArn; /** * The state of the directory. Can be either Enabled, Disabled, or Deleted. */ State?: DirectoryState; /** * The date and time when the directory was created. */ CreationDateTime?: _Date; } export type DirectoryArn = string; export type DirectoryList = Directory[]; export type DirectoryName = string; export type DirectoryState = "ENABLED"|"DISABLED"|"DELETED"|string; export interface DisableDirectoryRequest { /** * The ARN of the directory to disable. */ DirectoryArn: Arn; } export interface DisableDirectoryResponse { /** * The ARN of the directory that has been disabled. */ DirectoryArn: Arn; } export interface EnableDirectoryRequest { /** * The ARN of the directory to enable. */ DirectoryArn: Arn; } export interface EnableDirectoryResponse { /** * The ARN of the enabled directory. */ DirectoryArn: Arn; } export type ExceptionMessage = string; export interface Facet { /** * The name of the Facet. */ Name?: FacetName; /** * The object type that is associated with the facet. See CreateFacetRequest$ObjectType for more details. */ ObjectType?: ObjectType; /** * There are two different styles that you can define on any given facet, Static and Dynamic. For static facets, all attributes must be defined in the schema. For dynamic facets, attributes can be defined during data plane operations. */ FacetStyle?: FacetStyle; } export interface FacetAttribute { /** * The name of the facet attribute. */ Name: AttributeName; /** * A facet attribute consists of either a definition or a reference. This structure contains the attribute definition. See Attribute References for more information. */ AttributeDefinition?: FacetAttributeDefinition; /** * An attribute reference that is associated with the attribute. See Attribute References for more information. */ AttributeReference?: FacetAttributeReference; /** * The required behavior of the FacetAttribute. */ RequiredBehavior?: RequiredAttributeBehavior; } export interface FacetAttributeDefinition { /** * The type of the attribute. */ Type: FacetAttributeType; /** * The default value of the attribute (if configured). */ DefaultValue?: TypedAttributeValue; /** * Whether the attribute is mutable or not. */ IsImmutable?: Bool; /** * Validation rules attached to the attribute definition. */ Rules?: RuleMap; } export type FacetAttributeList = FacetAttribute[]; export interface FacetAttributeReference { /** * The target facet name that is associated with the facet reference. See Attribute References for more information. */ TargetFacetName: FacetName; /** * The target attribute name that is associated with the facet reference. See Attribute References for more information. */ TargetAttributeName: AttributeName; } export type FacetAttributeType = "STRING"|"BINARY"|"BOOLEAN"|"NUMBER"|"DATETIME"|"VARIANT"|string; export interface FacetAttributeUpdate { /** * The attribute to update. */ Attribute?: FacetAttribute; /** * The action to perform when updating the attribute. */ Action?: UpdateActionType; } export type FacetAttributeUpdateList = FacetAttributeUpdate[]; export type FacetName = string; export type FacetNameList = FacetName[]; export type FacetStyle = "STATIC"|"DYNAMIC"|string; export interface GetAppliedSchemaVersionRequest { /** * The ARN of the applied schema. */ SchemaArn: Arn; } export interface GetAppliedSchemaVersionResponse { /** * Current applied schema ARN, including the minor version in use if one was provided. */ AppliedSchemaArn?: Arn; } export interface GetDirectoryRequest { /** * The ARN of the directory. */ DirectoryArn: DirectoryArn; } export interface GetDirectoryResponse { /** * Metadata about the directory. */ Directory: Directory; } export interface GetFacetRequest { /** * The Amazon Resource Name (ARN) that is associated with the Facet. For more information, see arns. */ SchemaArn: Arn; /** * The name of the facet to retrieve. */ Name: FacetName; } export interface GetFacetResponse { /** * The Facet structure that is associated with the facet. */ Facet?: Facet; } export interface GetLinkAttributesRequest { /** * The Amazon Resource Name (ARN) that is associated with the Directory where the typed link resides. For more information, see arns or Typed Links. */ DirectoryArn: Arn; /** * Allows a typed link specifier to be accepted as input. */ TypedLinkSpecifier: TypedLinkSpecifier; /** * A list of attribute names whose values will be retrieved. */ AttributeNames: AttributeNameList; /** * The consistency level at which to retrieve the attributes on a typed link. */ ConsistencyLevel?: ConsistencyLevel; } export interface GetLinkAttributesResponse { /** * The attributes that are associated with the typed link. */ Attributes?: AttributeKeyAndValueList; } export interface GetObjectAttributesRequest { /** * The Amazon Resource Name (ARN) that is associated with the Directory where the object resides. */ DirectoryArn: Arn; /** * Reference that identifies the object whose attributes will be retrieved. */ ObjectReference: ObjectReference; /** * The consistency level at which to retrieve the attributes on an object. */ ConsistencyLevel?: ConsistencyLevel; /** * Identifier for the facet whose attributes will be retrieved. See SchemaFacet for details. */ SchemaFacet: SchemaFacet; /** * List of attribute names whose values will be retrieved. */ AttributeNames: AttributeNameList; } export interface GetObjectAttributesResponse { /** * The attributes that are associated with the object. */ Attributes?: AttributeKeyAndValueList; } export interface GetObjectInformationRequest { /** * The ARN of the directory being retrieved. */ DirectoryArn: Arn; /** * A reference to the object. */ ObjectReference: ObjectReference; /** * The consistency level at which to retrieve the object information. */ ConsistencyLevel?: ConsistencyLevel; } export interface GetObjectInformationResponse { /** * The facets attached to the specified object. Although the response does not include minor version information, the most recently applied minor version of each Facet is in effect. See GetAppliedSchemaVersion for details. */ SchemaFacets?: SchemaFacetList; /** * The ObjectIdentifier of the specified object. */ ObjectIdentifier?: ObjectIdentifier; } export interface GetSchemaAsJsonRequest { /** * The ARN of the schema to retrieve. */ SchemaArn: Arn; } export interface GetSchemaAsJsonResponse { /** * The name of the retrieved schema. */ Name?: SchemaName; /** * The JSON representation of the schema document. */ Document?: SchemaJsonDocument; } export interface GetTypedLinkFacetInformationRequest { /** * The Amazon Resource Name (ARN) that is associated with the schema. For more information, see arns. */ SchemaArn: Arn; /** * The unique name of the typed link facet. */ Name: TypedLinkName; } export interface GetTypedLinkFacetInformationResponse { /** * The order of identity attributes for the facet, from most significant to least significant. The ability to filter typed links considers the order that the attributes are defined on the typed link facet. When providing ranges to typed link selection, any inexact ranges must be specified at the end. Any attributes that do not have a range specified are presumed to match the entire range. Filters are interpreted in the order of the attributes on the typed link facet, not the order in which they are supplied to any API calls. For more information about identity attributes, see Typed Links. */ IdentityAttributeOrder?: AttributeNameList; } export interface IndexAttachment { /** * The indexed attribute values. */ IndexedAttributes?: AttributeKeyAndValueList; /** * In response to ListIndex, the ObjectIdentifier of the object attached to the index. In response to ListAttachedIndices, the ObjectIdentifier of the index attached to the object. This field will always contain the ObjectIdentifier of the object on the opposite side of the attachment specified in the query. */ ObjectIdentifier?: ObjectIdentifier; } export type IndexAttachmentList = IndexAttachment[]; export interface LinkAttributeAction { /** * A type that can be either UPDATE_OR_CREATE or DELETE. */ AttributeActionType?: UpdateActionType; /** * The value that you want to update to. */ AttributeUpdateValue?: TypedAttributeValue; } export interface LinkAttributeUpdate { /** * The key of the attribute being updated. */ AttributeKey?: AttributeKey; /** * The action to perform as part of the attribute update. */ AttributeAction?: LinkAttributeAction; } export type LinkAttributeUpdateList = LinkAttributeUpdate[]; export type LinkName = string; export type LinkNameToObjectIdentifierMap = {[key: string]: ObjectIdentifier}; export interface ListAppliedSchemaArnsRequest { /** * The ARN of the directory you are listing. */ DirectoryArn: Arn; /** * The response for ListAppliedSchemaArns when this parameter is used will list all minor version ARNs for a major version. */ SchemaArn?: Arn; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; } export interface ListAppliedSchemaArnsResponse { /** * The ARNs of schemas that are applied to the directory. */ SchemaArns?: Arns; /** * The pagination token. */ NextToken?: NextToken; } export interface ListAttachedIndicesRequest { /** * The ARN of the directory. */ DirectoryArn: Arn; /** * A reference to the object that has indices attached. */ TargetReference: ObjectReference; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; /** * The consistency level to use for this operation. */ ConsistencyLevel?: ConsistencyLevel; } export interface ListAttachedIndicesResponse { /** * The indices attached to the specified object. */ IndexAttachments?: IndexAttachmentList; /** * The pagination token. */ NextToken?: NextToken; } export interface ListDevelopmentSchemaArnsRequest { /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; } export interface ListDevelopmentSchemaArnsResponse { /** * The ARNs of retrieved development schemas. */ SchemaArns?: Arns; /** * The pagination token. */ NextToken?: NextToken; } export interface ListDirectoriesRequest { /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; /** * The state of the directories in the list. Can be either Enabled, Disabled, or Deleted. */ state?: DirectoryState; } export interface ListDirectoriesResponse { /** * Lists all directories that are associated with your account in pagination fashion. */ Directories: DirectoryList; /** * The pagination token. */ NextToken?: NextToken; } export interface ListFacetAttributesRequest { /** * The ARN of the schema where the facet resides. */ SchemaArn: Arn; /** * The name of the facet whose attributes will be retrieved. */ Name: FacetName; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; } export interface ListFacetAttributesResponse { /** * The attributes attached to the facet. */ Attributes?: FacetAttributeList; /** * The pagination token. */ NextToken?: NextToken; } export interface ListFacetNamesRequest { /** * The Amazon Resource Name (ARN) to retrieve facet names from. */ SchemaArn: Arn; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; } export interface ListFacetNamesResponse { /** * The names of facets that exist within the schema. */ FacetNames?: FacetNameList; /** * The pagination token. */ NextToken?: NextToken; } export interface ListIncomingTypedLinksRequest { /** * The Amazon Resource Name (ARN) of the directory where you want to list the typed links. */ DirectoryArn: Arn; /** * Reference that identifies the object whose attributes will be listed. */ ObjectReference: ObjectReference; /** * Provides range filters for multiple attributes. When providing ranges to typed link selection, any inexact ranges must be specified at the end. Any attributes that do not have a range specified are presumed to match the entire range. */ FilterAttributeRanges?: TypedLinkAttributeRangeList; /** * Filters are interpreted in the order of the attributes on the typed link facet, not the order in which they are supplied to any API calls. */ FilterTypedLink?: TypedLinkSchemaAndFacetName; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; /** * The consistency level to execute the request at. */ ConsistencyLevel?: ConsistencyLevel; } export interface ListIncomingTypedLinksResponse { /** * Returns one or more typed link specifiers as output. */ LinkSpecifiers?: TypedLinkSpecifierList; /** * The pagination token. */ NextToken?: NextToken; } export interface ListIndexRequest { /** * The ARN of the directory that the index exists in. */ DirectoryArn: Arn; /** * Specifies the ranges of indexed values that you want to query. */ RangesOnIndexedValues?: ObjectAttributeRangeList; /** * The reference to the index to list. */ IndexReference: ObjectReference; /** * The maximum number of objects in a single page to retrieve from the index during a request. For more information, see Amazon Cloud Directory Limits. */ MaxResults?: NumberResults; /** * The pagination token. */ NextToken?: NextToken; /** * The consistency level to execute the request at. */ ConsistencyLevel?: ConsistencyLevel; } export interface ListIndexResponse { /** * The objects and indexed values attached to the index. */ IndexAttachments?: IndexAttachmentList; /** * The pagination token. */ NextToken?: NextToken; } export interface ListManagedSchemaArnsRequest { /** * The response for ListManagedSchemaArns. When this parameter is used, all minor version ARNs for a major version are listed. */ SchemaArn?: Arn; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; } export interface ListManagedSchemaArnsResponse { /** * The ARNs for all AWS managed schemas. */ SchemaArns?: Arns; /** * The pagination token. */ NextToken?: NextToken; } export interface ListObjectAttributesRequest { /** * The Amazon Resource Name (ARN) that is associated with the Directory where the object resides. For more information, see arns. */ DirectoryArn: Arn; /** * The reference that identifies the object whose attributes will be listed. */ ObjectReference: ObjectReference; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of items to be retrieved in a single call. This is an approximate number. */ MaxResults?: NumberResults; /** * Represents the manner and timing in which the successful write or update of an object is reflected in a subsequent read operation of that same object. */ ConsistencyLevel?: ConsistencyLevel; /** * Used to filter the list of object attributes that are associated with a certain facet. */ FacetFilter?: SchemaFacet; } export interface ListObjectAttributesResponse { /** * Attributes map that is associated with the object. AttributeArn is the key, and attribute value is the value. */ Attributes?: AttributeKeyAndValueList; /** * The pagination token. */ NextToken?: NextToken; } export interface ListObjectChildrenRequest { /** * The Amazon Resource Name (ARN) that is associated with the Directory where the object resides. For more information, see arns. */ DirectoryArn: Arn; /** * The reference that identifies the object for which child objects are being listed. */ ObjectReference: ObjectReference; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of items to be retrieved in a single call. This is an approximate number. */ MaxResults?: NumberResults; /** * Represents the manner and timing in which the successful write or update of an object is reflected in a subsequent read operation of that same object. */ ConsistencyLevel?: ConsistencyLevel; } export interface ListObjectChildrenResponse { /** * Children structure, which is a map with key as the LinkName and ObjectIdentifier as the value. */ Children?: LinkNameToObjectIdentifierMap; /** * The pagination token. */ NextToken?: NextToken; } export interface ListObjectParentPathsRequest { /** * The ARN of the directory to which the parent path applies. */ DirectoryArn: Arn; /** * The reference that identifies the object whose parent paths are listed. */ ObjectReference: ObjectReference; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of items to be retrieved in a single call. This is an approximate number. */ MaxResults?: NumberResults; } export interface ListObjectParentPathsResponse { /** * Returns the path to the ObjectIdentifiers that are associated with the directory. */ PathToObjectIdentifiersList?: PathToObjectIdentifiersList; /** * The pagination token. */ NextToken?: NextToken; } export interface ListObjectParentsRequest { /** * The Amazon Resource Name (ARN) that is associated with the Directory where the object resides. For more information, see arns. */ DirectoryArn: Arn; /** * The reference that identifies the object for which parent objects are being listed. */ ObjectReference: ObjectReference; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of items to be retrieved in a single call. This is an approximate number. */ MaxResults?: NumberResults; /** * Represents the manner and timing in which the successful write or update of an object is reflected in a subsequent read operation of that same object. */ ConsistencyLevel?: ConsistencyLevel; /** * When set to True, returns all ListObjectParentsResponse$ParentLinks. There could be multiple links between a parent-child pair. */ IncludeAllLinksToEachParent?: Bool; } export interface ListObjectParentsResponse { /** * The parent structure, which is a map with key as the ObjectIdentifier and LinkName as the value. */ Parents?: ObjectIdentifierToLinkNameMap; /** * The pagination token. */ NextToken?: NextToken; /** * Returns a list of parent reference and LinkName Tuples. */ ParentLinks?: ObjectIdentifierAndLinkNameList; } export interface ListObjectPoliciesRequest { /** * The Amazon Resource Name (ARN) that is associated with the Directory where objects reside. For more information, see arns. */ DirectoryArn: Arn; /** * Reference that identifies the object for which policies will be listed. */ ObjectReference: ObjectReference; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of items to be retrieved in a single call. This is an approximate number. */ MaxResults?: NumberResults; /** * Represents the manner and timing in which the successful write or update of an object is reflected in a subsequent read operation of that same object. */ ConsistencyLevel?: ConsistencyLevel; } export interface ListObjectPoliciesResponse { /** * A list of policy ObjectIdentifiers, that are attached to the object. */ AttachedPolicyIds?: ObjectIdentifierList; /** * The pagination token. */ NextToken?: NextToken; } export interface ListOutgoingTypedLinksRequest { /** * The Amazon Resource Name (ARN) of the directory where you want to list the typed links. */ DirectoryArn: Arn; /** * A reference that identifies the object whose attributes will be listed. */ ObjectReference: ObjectReference; /** * Provides range filters for multiple attributes. When providing ranges to typed link selection, any inexact ranges must be specified at the end. Any attributes that do not have a range specified are presumed to match the entire range. */ FilterAttributeRanges?: TypedLinkAttributeRangeList; /** * Filters are interpreted in the order of the attributes defined on the typed link facet, not the order they are supplied to any API calls. */ FilterTypedLink?: TypedLinkSchemaAndFacetName; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; /** * The consistency level to execute the request at. */ ConsistencyLevel?: ConsistencyLevel; } export interface ListOutgoingTypedLinksResponse { /** * Returns a typed link specifier as output. */ TypedLinkSpecifiers?: TypedLinkSpecifierList; /** * The pagination token. */ NextToken?: NextToken; } export interface ListPolicyAttachmentsRequest { /** * The Amazon Resource Name (ARN) that is associated with the Directory where objects reside. For more information, see arns. */ DirectoryArn: Arn; /** * The reference that identifies the policy object. */ PolicyReference: ObjectReference; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of items to be retrieved in a single call. This is an approximate number. */ MaxResults?: NumberResults; /** * Represents the manner and timing in which the successful write or update of an object is reflected in a subsequent read operation of that same object. */ ConsistencyLevel?: ConsistencyLevel; } export interface ListPolicyAttachmentsResponse { /** * A list of ObjectIdentifiers to which the policy is attached. */ ObjectIdentifiers?: ObjectIdentifierList; /** * The pagination token. */ NextToken?: NextToken; } export interface ListPublishedSchemaArnsRequest { /** * The response for ListPublishedSchemaArns when this parameter is used will list all minor version ARNs for a major version. */ SchemaArn?: Arn; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; } export interface ListPublishedSchemaArnsResponse { /** * The ARNs of published schemas. */ SchemaArns?: Arns; /** * The pagination token. */ NextToken?: NextToken; } export interface ListTagsForResourceRequest { /** * The Amazon Resource Name (ARN) of the resource. Tagging is only supported for directories. */ ResourceArn: Arn; /** * The pagination token. This is for future use. Currently pagination is not supported for tagging. */ NextToken?: NextToken; /** * The MaxResults parameter sets the maximum number of results returned in a single page. This is for future use and is not supported currently. */ MaxResults?: TagsNumberResults; } export interface ListTagsForResourceResponse { /** * A list of tag key value pairs that are associated with the response. */ Tags?: TagList; /** * The token to use to retrieve the next page of results. This value is null when there are no more results to return. */ NextToken?: NextToken; } export interface ListTypedLinkFacetAttributesRequest { /** * The Amazon Resource Name (ARN) that is associated with the schema. For more information, see arns. */ SchemaArn: Arn; /** * The unique name of the typed link facet. */ Name: TypedLinkName; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; } export interface ListTypedLinkFacetAttributesResponse { /** * An ordered set of attributes associate with the typed link. */ Attributes?: TypedLinkAttributeDefinitionList; /** * The pagination token. */ NextToken?: NextToken; } export interface ListTypedLinkFacetNamesRequest { /** * The Amazon Resource Name (ARN) that is associated with the schema. For more information, see arns. */ SchemaArn: Arn; /** * The pagination token. */ NextToken?: NextToken; /** * The maximum number of results to retrieve. */ MaxResults?: NumberResults; } export interface ListTypedLinkFacetNamesResponse { /** * The names of typed link facets that exist within the schema. */ FacetNames?: TypedLinkNameList; /** * The pagination token. */ NextToken?: NextToken; } export interface LookupPolicyRequest { /** * The Amazon Resource Name (ARN) that is associated with the Directory. For more information, see arns. */ DirectoryArn: Arn; /** * Reference that identifies the object whose policies will be looked up. */ ObjectReference: ObjectReference; /** * The token to request the next page of results. */ NextToken?: NextToken; /** * The maximum number of items to be retrieved in a single call. This is an approximate number. */ MaxResults?: NumberResults; } export interface LookupPolicyResponse { /** * Provides list of path to policies. Policies contain PolicyId, ObjectIdentifier, and PolicyType. For more information, see Policies. */ PolicyToPathList?: PolicyToPathList; /** * The pagination token. */ NextToken?: NextToken; } export type NextToken = string; export type NumberAttributeValue = string; export type NumberResults = number; export interface ObjectAttributeAction { /** * A type that can be either Update or Delete. */ ObjectAttributeActionType?: UpdateActionType; /** * The value that you want to update to. */ ObjectAttributeUpdateValue?: TypedAttributeValue; } export interface ObjectAttributeRange { /** * The key of the attribute that the attribute range covers. */ AttributeKey?: AttributeKey; /** * The range of attribute values being selected. */ Range?: TypedAttributeValueRange; } export type ObjectAttributeRangeList = ObjectAttributeRange[]; export interface ObjectAttributeUpdate { /** * The key of the attribute being updated. */ ObjectAttributeKey?: AttributeKey; /** * The action to perform as part of the attribute update. */ ObjectAttributeAction?: ObjectAttributeAction; } export type ObjectAttributeUpdateList = ObjectAttributeUpdate[]; export type ObjectIdentifier = string; export type ObjectIdentifierAndLinkNameList = ObjectIdentifierAndLinkNameTuple[]; export interface ObjectIdentifierAndLinkNameTuple { /** * The ID that is associated with the object. */ ObjectIdentifier?: ObjectIdentifier; /** * The name of the link between the parent and the child object. */ LinkName?: LinkName; } export type ObjectIdentifierList = ObjectIdentifier[]; export type ObjectIdentifierToLinkNameMap = {[key: string]: LinkName}; export interface ObjectReference { /** * A path selector supports easy selection of an object by the parent/child links leading to it from the directory root. Use the link names from each parent/child link to construct the path. Path selectors start with a slash (/) and link names are separated by slashes. For more information about paths, see Access Objects. You can identify an object in one of the following ways: $ObjectIdentifier - An object identifier is an opaque string provided by Amazon Cloud Directory. When creating objects, the system will provide you with the identifier of the created object. An object’s identifier is immutable and no two objects will ever share the same object identifier. To identify an object with ObjectIdentifier, the ObjectIdentifier must be wrapped in double quotes. /some/path - Identifies the object based on path #SomeBatchReference - Identifies the object in a batch call */ Selector?: SelectorObjectReference; } export type ObjectType = "NODE"|"LEAF_NODE"|"POLICY"|"INDEX"|string; export type PathString = string; export interface PathToObjectIdentifiers { /** * The path that is used to identify the object starting from directory root. */ Path?: PathString; /** * Lists ObjectIdentifiers starting from directory root to the object in the request. */ ObjectIdentifiers?: ObjectIdentifierList; } export type PathToObjectIdentifiersList = PathToObjectIdentifiers[]; export interface PolicyAttachment { /** * The ID of PolicyAttachment. */ PolicyId?: ObjectIdentifier; /** * The ObjectIdentifier that is associated with PolicyAttachment. */ ObjectIdentifier?: ObjectIdentifier; /** * The type of policy that can be associated with PolicyAttachment. */ PolicyType?: PolicyType; } export type PolicyAttachmentList = PolicyAttachment[]; export interface PolicyToPath { /** * The path that is referenced from the root. */ Path?: PathString; /** * List of policy objects. */ Policies?: PolicyAttachmentList; } export type PolicyToPathList = PolicyToPath[]; export type PolicyType = string; export interface PublishSchemaRequest { /** * The Amazon Resource Name (ARN) that is associated with the development schema. For more information, see arns. */ DevelopmentSchemaArn: Arn; /** * The major version under which the schema will be published. Schemas have both a major and minor version associated with them. */ Version: Version; /** * The minor version under which the schema will be published. This parameter is recommended. Schemas have both a major and minor version associated with them. */ MinorVersion?: Version; /** * The new name under which the schema will be published. If this is not provided, the development schema is considered. */ Name?: SchemaName; } export interface PublishSchemaResponse { /** * The ARN that is associated with the published schema. For more information, see arns. */ PublishedSchemaArn?: Arn; } export interface PutSchemaFromJsonRequest { /** * The ARN of the schema to update. */ SchemaArn: Arn; /** * The replacement JSON schema. */ Document: SchemaJsonDocument; } export interface PutSchemaFromJsonResponse { /** * The ARN of the schema to update. */ Arn?: Arn; } export type RangeMode = "FIRST"|"LAST"|"LAST_BEFORE_MISSING_VALUES"|"INCLUSIVE"|"EXCLUSIVE"|string; export interface RemoveFacetFromObjectRequest { /** * The ARN of the directory in which the object resides. */ DirectoryArn: Arn; /** * The facet to remove. See SchemaFacet for details. */ SchemaFacet: SchemaFacet; /** * A reference to the object to remove the facet from. */ ObjectReference: ObjectReference; } export interface RemoveFacetFromObjectResponse { } export type RequiredAttributeBehavior = "REQUIRED_ALWAYS"|"NOT_REQUIRED"|string; export interface Rule { /** * The type of attribute validation rule. */ Type?: RuleType; /** * The minimum and maximum parameters that are associated with the rule. */ Parameters?: RuleParameterMap; } export type RuleKey = string; export type RuleMap = {[key: string]: Rule}; export type RuleParameterKey = string; export type RuleParameterMap = {[key: string]: RuleParameterValue}; export type RuleParameterValue = string; export type RuleType = "BINARY_LENGTH"|"NUMBER_COMPARISON"|"STRING_FROM_SET"|"STRING_LENGTH"|string; export interface SchemaFacet { /** * The ARN of the schema that contains the facet with no minor component. See arns and In-Place Schema Upgrade for a description of when to provide minor versions. If this value is set, FacetName must also be set. */ SchemaArn?: Arn; /** * The name of the facet. If this value is set, SchemaArn must also be set. */ FacetName?: FacetName; } export type SchemaFacetList = SchemaFacet[]; export type SchemaJsonDocument = string; export type SchemaName = string; export type SelectorObjectReference = string; export type StringAttributeValue = string; export interface Tag { /** * The key that is associated with the tag. */ Key?: TagKey; /** * The value that is associated with the tag. */ Value?: TagValue; } export type TagKey = string; export type TagKeyList = TagKey[]; export type TagList = Tag[]; export interface TagResourceRequest { /** * The Amazon Resource Name (ARN) of the resource. Tagging is only supported for directories. */ ResourceArn: Arn; /** * A list of tag key-value pairs. */ Tags: TagList; } export interface TagResourceResponse { } export type TagValue = string; export type TagsNumberResults = number; export interface TypedAttributeValue { /** * A string data value. */ StringValue?: StringAttributeValue; /** * A binary data value. */ BinaryValue?: BinaryAttributeValue; /** * A Boolean data value. */ BooleanValue?: BooleanAttributeValue; /** * A number data value. */ NumberValue?: NumberAttributeValue; /** * A date and time value. */ DatetimeValue?: DatetimeAttributeValue; } export interface TypedAttributeValueRange { /** * The inclusive or exclusive range start. */ StartMode: RangeMode; /** * The value to start the range at. */ StartValue?: TypedAttributeValue; /** * The inclusive or exclusive range end. */ EndMode: RangeMode; /** * The attribute value to terminate the range at. */ EndValue?: TypedAttributeValue; } export interface TypedLinkAttributeDefinition { /** * The unique name of the typed link attribute. */ Name: AttributeName; /** * The type of the attribute. */ Type: FacetAttributeType; /** * The default value of the attribute (if configured). */ DefaultValue?: TypedAttributeValue; /** * Whether the attribute is mutable or not. */ IsImmutable?: Bool; /** * Validation rules that are attached to the attribute definition. */ Rules?: RuleMap; /** * The required behavior of the TypedLinkAttributeDefinition. */ RequiredBehavior: RequiredAttributeBehavior; } export type TypedLinkAttributeDefinitionList = TypedLinkAttributeDefinition[]; export interface TypedLinkAttributeRange { /** * The unique name of the typed link attribute. */ AttributeName?: AttributeName; /** * The range of attribute values that are being selected. */ Range: TypedAttributeValueRange; } export type TypedLinkAttributeRangeList = TypedLinkAttributeRange[]; export interface TypedLinkFacet { /** * The unique name of the typed link facet. */ Name: TypedLinkName; /** * A set of key-value pairs associated with the typed link. Typed link attributes are used when you have data values that are related to the link itself, and not to one of the two objects being linked. Identity attributes also serve to distinguish the link from others of the same type between the same objects. */ Attributes: TypedLinkAttributeDefinitionList; /** * The set of attributes that distinguish links made from this facet from each other, in the order of significance. Listing typed links can filter on the values of these attributes. See ListOutgoingTypedLinks and ListIncomingTypedLinks for details. */ IdentityAttributeOrder: AttributeNameList; } export interface TypedLinkFacetAttributeUpdate { /** * The attribute to update. */ Attribute: TypedLinkAttributeDefinition; /** * The action to perform when updating the attribute. */ Action: UpdateActionType; } export type TypedLinkFacetAttributeUpdateList = TypedLinkFacetAttributeUpdate[]; export type TypedLinkName = string; export type TypedLinkNameList = TypedLinkName[]; export interface TypedLinkSchemaAndFacetName { /** * The Amazon Resource Name (ARN) that is associated with the schema. For more information, see arns. */ SchemaArn: Arn; /** * The unique name of the typed link facet. */ TypedLinkName: TypedLinkName; } export interface TypedLinkSpecifier { /** * Identifies the typed link facet that is associated with the typed link. */ TypedLinkFacet: TypedLinkSchemaAndFacetName; /** * Identifies the source object that the typed link will attach to. */ SourceObjectReference: ObjectReference; /** * Identifies the target object that the typed link will attach to. */ TargetObjectReference: ObjectReference; /** * Identifies the attribute value to update. */ IdentityAttributeValues: AttributeNameAndValueList; } export type TypedLinkSpecifierList = TypedLinkSpecifier[]; export interface UntagResourceRequest { /** * The Amazon Resource Name (ARN) of the resource. Tagging is only supported for directories. */ ResourceArn: Arn; /** * Keys of the tag that need to be removed from the resource. */ TagKeys: TagKeyList; } export interface UntagResourceResponse { } export type UpdateActionType = "CREATE_OR_UPDATE"|"DELETE"|string; export interface UpdateFacetRequest { /** * The Amazon Resource Name (ARN) that is associated with the Facet. For more information, see arns. */ SchemaArn: Arn; /** * The name of the facet. */ Name: FacetName; /** * List of attributes that need to be updated in a given schema Facet. Each attribute is followed by AttributeAction, which specifies the type of update operation to perform. */ AttributeUpdates?: FacetAttributeUpdateList; /** * The object type that is associated with the facet. See CreateFacetRequest$ObjectType for more details. */ ObjectType?: ObjectType; } export interface UpdateFacetResponse { } export interface UpdateLinkAttributesRequest { /** * The Amazon Resource Name (ARN) that is associated with the Directory where the updated typed link resides. For more information, see arns or Typed Links. */ DirectoryArn: Arn; /** * Allows a typed link specifier to be accepted as input. */ TypedLinkSpecifier: TypedLinkSpecifier; /** * The attributes update structure. */ AttributeUpdates: LinkAttributeUpdateList; } export interface UpdateLinkAttributesResponse { } export interface UpdateObjectAttributesRequest { /** * The Amazon Resource Name (ARN) that is associated with the Directory where the object resides. For more information, see arns. */ DirectoryArn: Arn; /** * The reference that identifies the object. */ ObjectReference: ObjectReference; /** * The attributes update structure. */ AttributeUpdates: ObjectAttributeUpdateList; } export interface UpdateObjectAttributesResponse { /** * The ObjectIdentifier of the updated object. */ ObjectIdentifier?: ObjectIdentifier; } export interface UpdateSchemaRequest { /** * The Amazon Resource Name (ARN) of the development schema. For more information, see arns. */ SchemaArn: Arn; /** * The name of the schema. */ Name: SchemaName; } export interface UpdateSchemaResponse { /** * The ARN that is associated with the updated schema. For more information, see arns. */ SchemaArn?: Arn; } export interface UpdateTypedLinkFacetRequest { /** * The Amazon Resource Name (ARN) that is associated with the schema. For more information, see arns. */ SchemaArn: Arn; /** * The unique name of the typed link facet. */ Name: TypedLinkName; /** * Attributes update structure. */ AttributeUpdates: TypedLinkFacetAttributeUpdateList; /** * The order of identity attributes for the facet, from most significant to least significant. The ability to filter typed links considers the order that the attributes are defined on the typed link facet. When providing ranges to a typed link selection, any inexact ranges must be specified at the end. Any attributes that do not have a range specified are presumed to match the entire range. Filters are interpreted in the order of the attributes on the typed link facet, not the order in which they are supplied to any API calls. For more information about identity attributes, see Typed Links. */ IdentityAttributeOrder: AttributeNameList; } export interface UpdateTypedLinkFacetResponse { } export interface UpgradeAppliedSchemaRequest { /** * The revision of the published schema to upgrade the directory to. */ PublishedSchemaArn: Arn; /** * The ARN for the directory to which the upgraded schema will be applied. */ DirectoryArn: Arn; /** * Used for testing whether the major version schemas are backward compatible or not. If schema compatibility fails, an exception would be thrown else the call would succeed but no changes will be saved. This parameter is optional. */ DryRun?: Bool; } export interface UpgradeAppliedSchemaResponse { /** * The ARN of the upgraded schema that is returned as part of the response. */ UpgradedSchemaArn?: Arn; /** * The ARN of the directory that is returned as part of the response. */ DirectoryArn?: Arn; } export interface UpgradePublishedSchemaRequest { /** * The ARN of the development schema with the changes used for the upgrade. */ DevelopmentSchemaArn: Arn; /** * The ARN of the published schema to be upgraded. */ PublishedSchemaArn: Arn; /** * Identifies the minor version of the published schema that will be created. This parameter is NOT optional. */ MinorVersion: Version; /** * Used for testing whether the Development schema provided is backwards compatible, or not, with the publish schema provided by the user to be upgraded. If schema compatibility fails, an exception would be thrown else the call would succeed. This parameter is optional and defaults to false. */ DryRun?: Bool; } export interface UpgradePublishedSchemaResponse { /** * The ARN of the upgraded schema that is returned as part of the response. */ UpgradedSchemaArn?: Arn; } export type Version = string; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2016-05-10"|"2016-05-10"|"2017-01-11"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the CloudDirectory client. */ export import Types = CloudDirectory; } export = CloudDirectory;
the_stack
import React, { useEffect, useState, createContext, useContext } from 'react' import firebase from "firebase" import "firebase/firestore" import "firebase/auth" import { useDocumentListen, useDataSourceListen } from '../firestore' import Provider, { ProviderDraft, Role } from 'models/commerce/Provider' import Product, { ProductDraft } from 'models/commerce/Product' import SKU from 'models/commerce/SKU' import Cart from 'models/commerce/Cart' import User from 'models/commerce/User' import Shipping from 'models/commerce/Shipping' import Order from 'models/commerce/Order' import { AuthContext } from '../auth' const _useAdmin = (): [Role | undefined, boolean, firebase.auth.Error?] => { interface Prop { data?: Role loading: boolean error?: firebase.auth.Error } const [state, setState] = useState<Prop>({ loading: true }) useEffect(() => { let enabled = true let listener = firebase.auth().onIdTokenChanged(async (auth) => { if (auth) { const result = await auth?.getIdTokenResult() if (enabled) { const adminID = result.claims.admin if (adminID) { const user: User = new User(auth.uid) const snapshot = await user.providers.collectionReference.doc(adminID).get() const role: Role = Role.fromSnapshot(snapshot) setState({ data: role, loading: false, error: undefined }) } else { setState({ data: undefined, loading: false, error: undefined }) } } } else { if (enabled) { setState({ data: undefined, loading: false, error: undefined }) } } }, (error) => { if (enabled) { setState({ data: undefined, loading: false, error: error }) } }) return () => { enabled = false listener() } }, []); return [state.data, state.loading, state.error] } export const AdminContext = createContext<[Role | undefined, boolean, firebase.auth.Error | undefined]>([undefined, true, undefined]) export const AdminProvider = ({ children }: { children: any }) => { const [auth, isLoading, error] = _useAdmin() if (error) console.error(error) return <AdminContext.Provider value={[auth, isLoading, error]}> {children} </AdminContext.Provider> } export const useAdmin = (): [Role | undefined, boolean, firebase.auth.Error | undefined] => { return useContext(AdminContext) } export const useProviderBlank = (): [Provider | undefined, boolean, firebase.auth.Error | undefined] => { const [admin, waiting, error] = useAdmin() const provider = admin !== undefined ? new Provider(admin.id) : undefined return [provider, waiting, error] } // Admin export const AdminProviderContext = createContext<[Provider | undefined, boolean, Error | undefined]>([undefined, true, undefined]) export const AdminProviderProvider = ({ children }: { children: any }) => { const [auth, waiting] = useAdmin() const [data, isLoading, error] = useDocumentListen<Provider>(Provider, auth?.id ? new Provider(auth.id).documentReference : undefined, waiting) return <AdminProviderContext.Provider value={[data, isLoading, error]}> {children} </AdminProviderContext.Provider> } export const AdminProviderDraftContext = createContext<[ProviderDraft | undefined, boolean, Error | undefined]>([undefined, true, undefined]) export const AdminProviderDraftProvider = ({ children }: { children: any }) => { const [auth, waiting] = useAdmin() const [data, isLoading, error] = useDocumentListen<ProviderDraft>(ProviderDraft, auth?.id ? new ProviderDraft(auth.id).documentReference : undefined, waiting) return <AdminProviderDraftContext.Provider value={[data, isLoading, error]}> {children} </AdminProviderDraftContext.Provider> } export const AdminProviderProductContext = createContext<[Product | undefined, boolean, Error | undefined]>([undefined, true, undefined]) export const AdminProviderProductProvider = ({ id, children }: { id: string, children: any }) => { const [provider, waiting] = useProviderBlank() const documentReference = (provider && id) ? provider?.products.collectionReference.doc(id) : undefined const [data, isLoading, error] = useDocumentListen<Product>(Product, documentReference, waiting) return <AdminProviderProductContext.Provider value={[data, isLoading, error]}> {children} </AdminProviderProductContext.Provider> } export const AdminProviderProductDraftContext = createContext<[ProductDraft | undefined, boolean, Error | undefined]>([undefined, true, undefined]) export const AdminProviderProductDraftProvider = ({ id, children }: { id: string, children: any }) => { const [provider, waiting] = useProviderBlank() const documentReference = (provider && id) ? provider?.productDrafts.collectionReference.doc(id) : undefined const [data, isLoading, error] = useDocumentListen<ProductDraft>(ProductDraft, documentReference, waiting) return <AdminProviderProductDraftContext.Provider value={[data, isLoading, error]}> {children} </AdminProviderProductDraftContext.Provider> } export const AdminProviderOrderContext = createContext<[Order | undefined, boolean, Error | undefined]>([undefined, true, undefined]) export const AdminProviderOrderProvider = ({ id, children }: { id?: string, children: any }) => { const [provider, waiting] = useProviderBlank() const documentReference = (provider && id) ? provider.orders.collectionReference.doc(id) : undefined const [data, isLoading, error] = useDocumentListen<Order>(Order, documentReference, waiting) return <AdminProviderOrderContext.Provider value={[data, isLoading, error]}> {children} </AdminProviderOrderContext.Provider> } export const useAdminProvider = (): [Provider | undefined, boolean, Error | undefined] => { return useContext(AdminProviderContext) } export const useAdminProviderDraft = (): [ProviderDraft | undefined, boolean, Error | undefined] => { return useContext(AdminProviderDraftContext) } export const useAdminProviderProducts = (): [Product[], boolean, Error?] => { const [provider, waiting] = useAdminProvider() const collectionReference = provider ? provider.products.collectionReference : undefined return useDataSourceListen<Product>(Product, { path: collectionReference?.path }, waiting) } export const useAdminProviderProduct = (): [Product | undefined, boolean, Error | undefined] => { return useContext(AdminProviderProductContext) } export const useAdminProviderProductSKUs = (id?: string): [SKU[], boolean, Error?] => { const [provider, waiting] = useAdminProvider() const collectionReference = (provider && id) ? provider.products.collectionReference.doc(id).collection('skus') : undefined return useDataSourceListen<SKU>(SKU, { path: collectionReference?.path }, waiting) } export const useAdminProviderProductDraft = (): [ProductDraft | undefined, boolean, Error | undefined] => { return useContext(AdminProviderProductDraftContext) } export const useAdminProviderProductDraftSKUs = (id?: string): [SKU[], boolean, Error?] => { const [provider, waiting] = useAdminProvider() const collectionReference = (provider && id) ? provider.productDrafts.collectionReference.doc(id).collection('skus') : undefined return useDataSourceListen<SKU>(SKU, { path: collectionReference?.path }, waiting) } export const useAdminProviderOrders = (): [Order[], boolean, Error?] => { const [provider, waiting] = useAdminProvider() const collectionReference = provider ? provider.orders.collectionReference : undefined return useDataSourceListen<Order>(Order, { path: collectionReference?.path }, waiting) } export const useAdminProviderProductSKU = (productID?: string, skuID?: string): [SKU | undefined, boolean, Error?] => { const [provider, waiting] = useAdminProvider() const documentReference = (provider && productID && skuID) ? provider.products.doc(productID, Product).skus.collectionReference.doc(skuID) : undefined return useDocumentListen<SKU>(SKU, documentReference, waiting) } export const useAdminProviderOrder = (id?: string): [Order | undefined, boolean, Error?] => { const [provider, waiting] = useAdminProvider() const documentReference = (provider && id) ? provider.orders.collectionReference.doc(id) : undefined return useDocumentListen<Order>(Order, documentReference, waiting) } // User export const UserContext = createContext<[User | undefined, boolean, Error | undefined]>([undefined, true, undefined]) export const UserProvider = ({ children }: { children: any }) => { const [auth, waiting] = useContext(AuthContext) const [user, isLoading, error] = useDocumentListen<User>(User, auth?.uid ? new User(auth.uid).documentReference : undefined, waiting) return <UserContext.Provider value={[user, isLoading, error]}> {children} </UserContext.Provider> } export const RolesContext = createContext<[Role[], boolean, Error | undefined]>([[], true, undefined]) export const RolesProvider = ({ children }: { children: any }) => { const [user, waiting] = useContext(UserContext) const [roles, isLoading, error] = useDataSourceListen<Role>(Role, user ? { path: user.providers.collectionReference.path } : undefined, waiting) return <RolesContext.Provider value={[roles, isLoading, error]}> {children} </RolesContext.Provider> } export const CartContext = createContext<[Cart | undefined, boolean, Error | undefined]>([undefined, true, undefined]) export const CartProvider = ({ children }: { children: any }) => { const [auth, waiting] = useContext(AuthContext) const [cart, isLoading, error] = useDocumentListen<Cart>(Cart, auth?.uid ? new Cart(auth.uid).documentReference : undefined, waiting) return <CartContext.Provider value={[cart, isLoading, error]}> {children} </CartContext.Provider> } export const useUserShipping = (id?: string): [Shipping | undefined, boolean, Error | undefined] => { const [auth, isAuthLoading] = useContext(AuthContext) const collectionReference = new User(auth?.uid).shippingAddresses.collectionReference const [ref] = useState(id ? collectionReference.doc(id) : collectionReference.doc()) const [shipping, isLoading, error] = useDocumentListen<Shipping>(Shipping, ref, isAuthLoading) return [shipping, isLoading, error] } export const useUserShippingAddresses = (): [Shipping[], boolean, Error | undefined] => { const [auth, isAuthLoading] = useContext(AuthContext) const collectionReference = new User(auth?.uid).shippingAddresses.collectionReference const [data, isLoading, error] = useDataSourceListen<Shipping>(Shipping, { path: collectionReference?.path }, isAuthLoading) return [data, isLoading, error] } export const useCart = (): [Cart | undefined, boolean, Error | undefined] => { return useContext(CartContext) } export const useUser = (): [User | undefined, boolean, Error | undefined] => { return useContext(UserContext) } export const useRoles = (): [Role[], boolean, Error | undefined] => { return useContext(RolesContext) } // Provider // export const ProviderContext = createContext<[Provider | undefined, boolean, Error | undefined]>([undefined, true, undefined]) // export const ProviderProvider = ({ id, children }: { id?: string, children: any }) => { // const [provider, isLoading, error] = useDocumentListen<Provider>(Provider, id ? new Provider(id).documentReference : undefined) // return <ProviderContext.Provider value={[provider, isLoading, error]}> {children} </ProviderContext.Provider> // } // export const ProviderProductContext = createContext<[Product | undefined, boolean, Error | undefined]>([undefined, true, undefined]) // export const ProviderProductProvider = ({ id, children }: { id?: string, children: any }) => { // const [provider, waiting] = useContext(ProviderContext) // const [product, isLoading, error] = useDocumentListen<Product>(Product, id ? provider?.products.collectionReference.doc(id) : undefined, waiting) // return <ProviderProductContext.Provider value={[product, isLoading, error]}> {children} </ProviderProductContext.Provider> // } // export const useProvider = (): [Provider | undefined, boolean, Error | undefined] => { // return useContext(ProviderContext) // } // export const useProviderProduct = (): [Product | undefined, boolean, Error | undefined] => { // return useContext(ProviderProductContext) // }
the_stack
* Interfaces and methods for training models using tf.Tensor objects. */ import * as tfc from '@tensorflow/tfjs-core'; import {Scalar, Tensor, Tensor1D, tensor1d, util} from '@tensorflow/tfjs-core'; import {expandDims, gather, sliceAlongFirstAxis} from '../backend/tfjs_backend'; import {BaseCallback, configureCallbacks, CustomCallbackArgs, History, ModelLoggingVerbosity, standardizeCallbacks, YieldEveryOptions} from '../base_callbacks'; import {NotImplementedError, ValueError} from '../errors'; import {disposeTensorsInLogs, UnresolvedLogs} from '../logs'; import {range} from '../utils/math_utils'; import {ClassWeight, ClassWeightMap} from './training_utils'; /** * Interface configuration model training based on data as `tf.Tensor`s. */ export interface ModelFitArgs { /** * Number of samples per gradient update. If unspecified, it * will default to 32. */ batchSize?: number; /** * Integer number of times to iterate over the training data arrays. */ epochs?: number; /** * Verbosity level. * * Expected to be 0, 1, or 2. Default: 1. * * 0 - No printed message during fit() call. * 1 - In Node.js (tfjs-node), prints the progress bar, together with * real-time updates of loss and metric values and training speed. * In the browser: no action. This is the default. * 2 - Not implemented yet. */ verbose?: ModelLoggingVerbosity; /** * List of callbacks to be called during training. * Can have one or more of the following callbacks: * - `onTrainBegin(logs)`: called when training starts. * - `onTrainEnd(logs)`: called when training ends. * - `onEpochBegin(epoch, logs)`: called at the start of every epoch. * - `onEpochEnd(epoch, logs)`: called at the end of every epoch. * - `onBatchBegin(batch, logs)`: called at the start of every batch. * - `onBatchEnd(batch, logs)`: called at the end of every batch. * - `onYield(epoch, batch, logs)`: called every `yieldEvery` milliseconds * with the current epoch, batch and logs. The logs are the same * as in `onBatchEnd()`. Note that `onYield` can skip batches or * epochs. See also docs for `yieldEvery` below. */ callbacks?: BaseCallback[]|CustomCallbackArgs|CustomCallbackArgs[]; /** * Float between 0 and 1: fraction of the training data * to be used as validation data. The model will set apart this fraction of * the training data, will not train on it, and will evaluate the loss and * any model metrics on this data at the end of each epoch. * The validation data is selected from the last samples in the `x` and `y` * data provided, before shuffling. */ validationSplit?: number; /** * Data on which to evaluate the loss and any model * metrics at the end of each epoch. The model will not be trained on this * data. This could be a tuple [xVal, yVal] or a tuple [xVal, yVal, * valSampleWeights]. The model will not be trained on this data. * `validationData` will override `validationSplit`. */ validationData?: [ Tensor|Tensor[], Tensor|Tensor[] ]|[Tensor | Tensor[], Tensor|Tensor[], Tensor|Tensor[]]; /** * Whether to shuffle the training data before each epoch. Has * no effect when `stepsPerEpoch` is not `null`. */ shuffle?: boolean; /** * Optional object mapping class indices (integers) to * a weight (float) to apply to the model's loss for the samples from this * class during training. This can be useful to tell the model to "pay more * attention" to samples from an under-represented class. * * If the model has multiple outputs, a class weight can be specified for * each of the outputs by setting this field an array of weight object * or a object that maps model output names (e.g., `model.outputNames[0]`) * to weight objects. */ classWeight?: ClassWeight|ClassWeight[]|ClassWeightMap; /** * Optional array of the same length as x, containing * weights to apply to the model's loss for each sample. In the case of * temporal data, you can pass a 2D array with shape (samples, * sequenceLength), to apply a different weight to every timestep of every * sample. In this case you should make sure to specify * sampleWeightMode="temporal" in compile(). */ sampleWeight?: Tensor; /** * Epoch at which to start training (useful for resuming a previous training * run). When this is used, `epochs` is the index of the "final epoch". * The model is not trained for a number of iterations given by `epochs`, * but merely until the epoch of index `epochs` is reached. */ initialEpoch?: number; /** * Total number of steps (batches of samples) before * declaring one epoch finished and starting the next epoch. When training * with Input Tensors such as TensorFlow data tensors, the default `null` is * equal to the number of unique samples in your dataset divided by the * batch size, or 1 if that cannot be determined. */ stepsPerEpoch?: number; /** * Only relevant if `stepsPerEpoch` is specified. Total number of steps * (batches of samples) to validate before stopping. */ validationSteps?: number; /** * Configures the frequency of yielding the main thread to other tasks. * * In the browser environment, yielding the main thread can improve the * responsiveness of the page during training. In the Node.js environment, * it can ensure tasks queued in the event loop can be handled in a timely * manner. * * The value can be one of the following: * - `'auto'`: The yielding happens at a certain frame rate (currently set * at 125ms). This is the default. * - `'batch'`: yield every batch. * - `'epoch'`: yield every epoch. * - any `number`: yield every `number` milliseconds. * - `'never'`: never yield. (yielding can still happen through `await * nextFrame()` calls in custom callbacks.) */ yieldEvery?: YieldEveryOptions; } export function checkBatchSize(batchSize: number) { tfc.util.assert( batchSize > 0 && Number.isInteger(batchSize), () => `batchSize is required to be a positive integer, but got ${ batchSize}`); } /** * Slice a Tensor or an Array of Tensors, by start and stop indices. * * Porting Note: The `_slice_arrays` function in PyKeras is covered by this * function and `sliceArraysByIndices()` together. * * @param arrays: the input. * @param start: the starting index (inclusive). * @param stop: the stopping index (exclusive). * @returns The result of the slicing. If `arrays` is an `Array` of * `tf.Tensor`s, the slicing will be applied to all elements of the `Array` * in the same way. */ export function sliceArrays( arrays: Tensor|Tensor[], start: number, stop: number): Tensor|Tensor[] { if (arrays == null) { return [null]; } else if (Array.isArray(arrays)) { return arrays.map(array => sliceAlongFirstAxis(array, start, stop - start)); } else { // Tensor. return sliceAlongFirstAxis(arrays, start, stop - start); } } /** * Slice a Tensor or an Array of Tensors, by random-order indices. * * Porting Note: The `_slice_arrays` function in PyKeras is covered by this * function and `sliceArrays()` together. * * @param arrays The input `tf.Tensor` or `Array` of `tf.Tensor`s to slice. * If an `Array` of `tf.Tensor`s, all `tf.Tensor`s will be sliced in the * same fashion. * @param indices The indices to use for slicing along the first (batch) * dimension. * @returns Result(s) of the slicing. */ export function sliceArraysByIndices( arrays: Tensor|Tensor[], indices: Tensor1D): Tensor|Tensor[] { return tfc.tidy(() => { if (arrays == null) { return null; } else if (Array.isArray(arrays)) { return arrays.map( array => (sliceArraysByIndices(array, indices) as Tensor)); } else { // TODO(cais): indices should be a pre-constructed Tensor1D to avoid // tensor1d() calls. return gather( arrays, indices.dtype === 'int32' ? indices : tfc.cast(indices, 'int32')); } }); } /** * Returns a list of batch indices (tuples of indices). * @param size: Integer, total size of the data to slice into batches. * @param batchSize: Integer, batch size. * @returns An Array of [batchStart, batchEnd] tuples. batchStart is * inclusive; batchEnd is exclusive. I.e., each batch consists of indices x * that satisfy batchStart <= x < batchEnd. */ export function makeBatches( size: number, batchSize: number): Array<[number, number]> { const output: Array<[number, number]> = []; let batchStart = 0; let batchEnd: number = null; while (batchStart < size) { batchEnd = batchStart + batchSize; if (batchEnd >= size) { batchEnd = size; } output.push([batchStart, batchEnd]); batchStart = batchEnd; } return output; } /** * Abstract fit function for `f(ins)`. * @param f A Function returning a list of tensors. For training, this * function is expected to perform the updates to the variables. * @param ins List of tensors to be fed to `f`. * @param outLabels List of strings, display names of the outputs of `f`. * @param batchSize Integer batch size or `== null` if unknown. Default : 32. * @param epochs Number of times to iterate over the data. Default : 1. * @param verbose Verbosity mode: 0, 1, or 2. Default: 1. * @param callbacks List of callbacks to be called during training. * @param valF Function to call for validation. * @param valIns List of tensors to be fed to `valF`. * @param shuffle Whether to shuffle the data at the beginning of every * epoch. Default : true. * @param callbackMetrics List of strings, the display names of the metrics * passed to the callbacks. They should be the concatenation of the * display names of the outputs of `f` and the list of display names * of the outputs of `valF`. * @param initialEpoch Epoch at which to start training (useful for * resuming a previous training run). Default : 0. * @param stepsPerEpoch Total number of steps (batches on samples) before * declaring one epoch finished and starting the next epoch. Ignored with * the default value of `undefined` or `null`. * @param validationSteps Number of steps to run validation for (only if * doing validation from data tensors). Not applicable for tfjs-layers. * @returns A `History` object. */ async function fitLoop( // Type `model` as `any` here to avoid circular dependency w/ training.ts. // tslint:disable-next-line:no-any model: any, f: (data: Tensor[]) => Scalar[], ins: Tensor[], outLabels?: string[], batchSize?: number, epochs?: number, verbose?: number, callbacks?: BaseCallback[], valF?: (data: Tensor[]) => Scalar[], valIns?: Tensor[], shuffle?: boolean|string, callbackMetrics?: string[], initialEpoch?: number, stepsPerEpoch?: number, validationSteps?: number): Promise<History> { if (batchSize == null) { batchSize = 32; } if (epochs == null) { epochs = 1; } if (shuffle == null) { shuffle = true; } if (initialEpoch == null) { initialEpoch = 0; } // TODO(cais): Change const to let below when implementing validation. let doValidation = false; if (valF != null && valIns != null) { doValidation = true; // TODO(cais): verbose message. } if (validationSteps != null) { doValidation = true; if (stepsPerEpoch == null) { throw new ValueError( 'Can only use `validationSteps` when doing step-wise training, ' + 'i.e., `stepsPerEpoch` must be set.'); } } const numTrainSamples = model.checkNumSamples(ins, batchSize, stepsPerEpoch, 'steps_per_epoch'); let indexArray: number[]; if (numTrainSamples != null) { indexArray = range(0, numTrainSamples); } if (verbose == null) { verbose = 1; } const {callbackList, history} = configureCallbacks( callbacks, verbose, epochs, initialEpoch, numTrainSamples, stepsPerEpoch, batchSize, doValidation, callbackMetrics); callbackList.setModel(model); model.history = history; await callbackList.onTrainBegin(); model.stopTraining_ = false; // TODO(cais): Take care of callbacks.validation_data as in PyKeras. // TODO(cais): Pre-convert feeds for performance as in PyKeras. for (let epoch = initialEpoch; epoch < epochs; ++epoch) { await callbackList.onEpochBegin(epoch); const epochLogs: UnresolvedLogs = {}; if (stepsPerEpoch != null) { throw new NotImplementedError( 'stepsPerEpoch mode is not implemented yet.'); } else { if (shuffle === 'batch') { throw new NotImplementedError('batch shuffling is not implemneted yet'); } else if (shuffle) { util.shuffle(indexArray); } // Convert the potentially shuffled indices to Tensor1D, to avoid the // cost of repeated creation of Array1Ds later on. const epochIndexArray1D = tensor1d(indexArray); const batches = makeBatches(numTrainSamples, batchSize); for (let batchIndex = 0; batchIndex < batches.length; ++batchIndex) { const batchLogs: UnresolvedLogs = {}; await callbackList.onBatchBegin(batchIndex, batchLogs); tfc.tidy(() => { const batchStart = batches[batchIndex][0]; const batchEnd = batches[batchIndex][1]; const batchIds = sliceAlongFirstAxis( epochIndexArray1D, batchStart, batchEnd - batchStart) as Tensor1D; batchLogs['batch'] = batchIndex; batchLogs['size'] = batchEnd - batchStart; // TODO(cais): In ins, train flag can be a number, instead of an // Tensor? Do we need to handle this in tfjs-layers? const insBatch = sliceArraysByIndices(ins, batchIds) as Tensor[]; const outs = f(insBatch); for (let i = 0; i < outLabels.length; ++i) { const label = outLabels[i]; const out = outs[i]; batchLogs[label] = out; tfc.keep(out); // TODO(cais): Use scope() to avoid ownership. } if (batchIndex === batches.length - 1) { // Last batch. if (doValidation) { const valOuts = model.testLoop(valF, valIns, batchSize); // Porting Notes: In tfjs-layers, valOuts is always an Array. for (let i = 0; i < outLabels.length; ++i) { const label = outLabels[i]; const out = valOuts[i]; tfc.keep(out); // TODO(cais): Use scope() to avoid ownership. epochLogs['val_' + label] = out; } } } }); await callbackList.onBatchEnd(batchIndex, batchLogs); disposeTensorsInLogs(batchLogs); if (model.stopTraining_) { break; } // TODO(cais): return outs as list of Tensor. } epochIndexArray1D.dispose(); } // TODO(cais): Run validation at the end of the epoch. await callbackList.onEpochEnd(epoch, epochLogs); if (model.stopTraining_) { break; } } await callbackList.onTrainEnd(); await model.history.syncData(); return model.history; } export async function fitTensors( // Type `model` as `any` here to avoid circular dependency w/ training.ts. // tslint:disable-next-line:no-any model: any, x: Tensor|Tensor[]|{[inputName: string]: Tensor}, y: Tensor|Tensor[]|{[inputName: string]: Tensor}, args: ModelFitArgs = {}): Promise<History> { if (model.isTraining) { throw new Error( 'Cannot start training because another fit() call is ongoing.'); } model.isTraining = true; let inputs: Tensor[]; let targets: Tensor[]; let inputValX: Tensor|Tensor[]; let inputValY: Tensor|Tensor[]; let valX: Tensor|Tensor[]; let valY: Tensor|Tensor[]; let sampleWeights: Tensor[]; try { const batchSize = args.batchSize == null ? 32 : args.batchSize; checkBatchSize(batchSize); // Validate user data. // TODO(cais): Support sampleWeight. const checkBatchAxis = false; const standardizedOuts = await model.standardizeUserData( x, y, args.sampleWeight, args.classWeight, checkBatchAxis, batchSize) as [Tensor[], Tensor[], Tensor[]]; inputs = standardizedOuts[0]; targets = standardizedOuts[1]; sampleWeights = standardizedOuts[2]; // Prepare validation data. let doValidation = false; let valIns: Tensor[]; if (args.validationData != null && args.validationData.length > 0) { doValidation = true; if (args.validationData.length === 2) { // config.validationData consists of valX and valY. inputValX = args.validationData[0]; inputValY = args.validationData[1]; } else if (args.validationData.length === 3) { throw new NotImplementedError( 'validationData including sample weights is not supported yet.'); } else { throw new ValueError( `When passing validation data, it must contain 2 (valX, valY) ` + `or 3 (valX, valY, valSampleWeight) items; ` + `${args.validationData} is invalid.`); } const checkBatchAxis = true; const valStandardized = await model.standardizeUserData( inputValX, inputValY, null, /** Unused sample weights. */ null, /** Unused class weights. */ checkBatchAxis, batchSize) as [Tensor[], Tensor[], Tensor[]]; valX = valStandardized[0]; valY = valStandardized[1]; valIns = valX.concat(valY); // TODO(cais): Add useLearningPhase data properly. } else if ( args.validationSplit != null && args.validationSplit > 0 && args.validationSplit < 1) { doValidation = true; // Porting Note: In tfjs-layers, inputs[0] is always a Tensor. const splitAt = Math.floor(inputs[0].shape[0] * (1 - args.validationSplit)); const originalBatchSize = inputs[0].shape[0]; valX = sliceArrays(inputs, splitAt, originalBatchSize) as Tensor[]; inputs = sliceArrays(inputs, 0, splitAt) as Tensor[]; valY = sliceArrays(targets, splitAt, originalBatchSize) as Tensor[]; targets = sliceArrays(targets, 0, splitAt) as Tensor[]; // TODO(cais): Once sampleWeights becomes available, slice it to get // valSampleWeights. valIns = valX.concat(valY); // TODO(cais): Add useLearningPhase data properly. } else if (args.validationSteps != null) { doValidation = true; // TODO(cais): Add useLearningPhase. } const ins = inputs.concat(targets).concat(sampleWeights); model.checkTrainableWeightsConsistency(); // TODO(cais): Handle use_learning_phase and learning_phase? // Porting Note: Here we see a key deviation of tfjs-layers from // Keras. // Due to the imperative nature of tfjs-layers' backend (tfjs-core), // we do not construct symbolic computation graphs to embody the // training process. Instead, we define a function that performs the // training action. In PyKeras, the data (inputs and targets) are fed // through graph placeholders. In tfjs-layers, the data are fed as // function arguments. Since the function are defined below in the // scope, we don't have equivalents of PyKeras's // `_make_train_funciton`. const trainFunction = model.makeTrainFunction(); const outLabels = model.getDedupedMetricsNames() as string[]; let valFunction: (data: Tensor[]) => Scalar[]; let callbackMetrics: string[]; if (doValidation) { model.makeTestFunction(); valFunction = model.testFunction; callbackMetrics = outLabels.slice().concat(outLabels.map(n => 'val_' + n)); } else { valFunction = null; valIns = []; callbackMetrics = outLabels.slice(); } const callbacks = standardizeCallbacks(args.callbacks, args.yieldEvery); const out = await fitLoop( model, trainFunction, ins, outLabels, batchSize, args.epochs, args.verbose, callbacks, valFunction, valIns, args.shuffle, callbackMetrics, args.initialEpoch, null, null); return out; } finally { model.isTraining = false; // Memory clean up. disposeNewTensors(inputs, x); disposeNewTensors(targets, y); disposeNewTensors(valX as Tensor[], inputValX); disposeNewTensors(valY as Tensor[], inputValY); if (sampleWeights != null) { tfc.dispose(sampleWeights); } } // TODO(cais): Add value to outLabels. } /** * Ensure tensors all have a rank of at least 2. * * If a tensor has a rank of 1, it is dimension-expanded to rank 2. * If any tensor has a rank of 0 (i.e., is a scalar), an error will be thrown. */ export function ensureTensorsRank2OrHigher(tensors: Tensor|Tensor[]): Tensor[] { const outs: Tensor[] = []; if (tensors instanceof Tensor) { tensors = [tensors]; } // Make Tensors at least 2D. for (let i = 0; i < tensors.length; ++i) { const tensor = tensors[i]; if (tensor.rank === 1) { outs.push(expandDims(tensor, 1)); } else if (tensor.rank === 0) { throw new Error( 'Expected tensor to be at least 1D, but received a 0D tensor ' + '(scalar).'); } else { outs.push(tensor); } } return outs; } /** * Compare a set of tensors with a reference (old) set, discard the ones * in the new set that are not present in the reference set. * * This method is used for memory clenaup during calls such as * LayersModel.fit(). * * @param tensors New set which may contain Tensors not present in * `refTensors`. * @param refTensors Reference Tensor set. */ // TODO(cais, kangyizhang): Deduplicate with tfjs-data. export function disposeNewTensors( tensors: Tensor|Tensor[]|{[inputName: string]: Tensor}, refTensors: Tensor|Tensor[]|{[inputName: string]: Tensor}): void { if (tensors == null) { return; } const oldTensorIds: number[] = []; if (refTensors instanceof Tensor) { oldTensorIds.push(refTensors.id); } else if (Array.isArray(refTensors)) { refTensors.forEach(t => oldTensorIds.push(t.id)); } else if (refTensors != null) { // `oldTensors` is a map from string name to Tensor. for (const name in refTensors) { const oldTensor = refTensors[name]; oldTensorIds.push(oldTensor.id); } } const tensorsToDispose: Tensor[] = []; if (tensors instanceof Tensor) { if (oldTensorIds.indexOf(tensors.id) === -1) { tensorsToDispose.push(tensors); } } else if (Array.isArray(tensors)) { tensors.forEach(t => { if (oldTensorIds.indexOf(t.id) === -1) { tensorsToDispose.push(t); } }); } else if (tensors != null) { // `oldTensors` is a map from string name to Tensor. for (const name in tensors) { const tensor = tensors[name]; if (oldTensorIds.indexOf(tensor.id) === -1) { tensorsToDispose.push(tensor); } } } tensorsToDispose.forEach(t => { if (!t.isDisposed) { t.dispose(); } }); }
the_stack
import * as d3 from "d3"; import { has, map, keys, groupBy, sortBy, filter, find, compact, first, every, identity } from "lodash"; const exitNode = "<<<Exit>>>"; // @ts-expect-error ts-migrate(2339) FIXME: Property 'scale' does not exist on type 'typeof im... Remove this comment to see the full error message const colors = d3.scale.category10(); // helper function colorMap - color gray if "end" is detected function colorMap(d: any) { return colors(d.name); } // Return array of ancestors of nodes, highest first, but excluding the root. function getAncestors(node: any) { const path = []; let current = node; while (current.parent) { path.unshift(current); current = current.parent; } return path; } function buildNodesFromHierarchyData(data: any) { const grouped = groupBy(data, "sequence"); return map(grouped, value => { const sorted = sortBy(value, "stage"); return { size: value[0].value || 0, sequence: value[0].sequence, nodes: map(sorted, i => i.node), }; }); } function buildNodesFromTableData(data: any) { const validKey = (key: any) => key !== "value"; const dataKeys = sortBy(filter(keys(data[0]), validKey), identity); return map(data, (row, sequence) => ({ size: row.value || 0, sequence, nodes: compact(map(dataKeys, key => row[key])), })); } function isDataInHierarchyFormat(data: any) { const firstRow = first(data); return every(["sequence", "stage", "node", "value"], field => has(firstRow, field)); } function buildHierarchy(data: any) { data = isDataInHierarchyFormat(data) ? buildNodesFromHierarchyData(data) : buildNodesFromTableData(data); // build tree const root = { name: "root", children: [], }; data.forEach((d: any) => { const nodes = d.nodes; const size = parseInt(d.size, 10); // build graph, nodes, and child nodes let currentNode = root; for (let j = 0; j < nodes.length; j += 1) { let children = currentNode.children; const nodeName = nodes[j]; const isLeaf = j + 1 === nodes.length; if (!children) { currentNode.children = children = []; children.push({ // @ts-expect-error ts-migrate(2322) FIXME: Type 'string' is not assignable to type 'never'. name: exitNode, // @ts-expect-error ts-migrate(2322) FIXME: Type 'any' is not assignable to type 'never'. size: currentNode.size, }); } // @ts-expect-error ts-migrate(2339) FIXME: Property 'name' does not exist on type 'never'. let childNode = find(children, child => child.name === nodeName); if (isLeaf && childNode) { // @ts-expect-error ts-migrate(2339) FIXME: Property 'children' does not exist on type 'never'... Remove this comment to see the full error message childNode.children = childNode.children || []; // @ts-expect-error ts-migrate(2339) FIXME: Property 'children' does not exist on type 'never'... Remove this comment to see the full error message childNode.children.push({ name: exitNode, size, }); } else if (isLeaf) { children.push({ // @ts-expect-error ts-migrate(2322) FIXME: Type 'any' is not assignable to type 'never'. name: nodeName, // @ts-expect-error ts-migrate(2322) FIXME: Type 'number' is not assignable to type 'never'. size, }); } else { if (!childNode) { // @ts-expect-error ts-migrate(2322) FIXME: Type '{ name: any; children: never[]; }' is not as... Remove this comment to see the full error message childNode = { name: nodeName, children: [], }; // @ts-expect-error ts-migrate(2345) FIXME: Argument of type 'undefined' is not assignable to ... Remove this comment to see the full error message children.push(childNode); } // @ts-expect-error ts-migrate(2322) FIXME: Type 'undefined' is not assignable to type '{ name... Remove this comment to see the full error message currentNode = childNode; } } }); return root; } function isDataValid(data: any) { return data && data.rows.length > 0; } export default function initSunburst(data: any) { if (!isDataValid(data)) { return (element: any) => { d3.select(element) .selectAll("*") .remove(); }; } data = buildHierarchy(data.rows); return (element: any) => { d3.select(element) .selectAll("*") .remove(); // svg dimensions const width = element.clientWidth; const height = element.offsetHeight; // Breadcrumb dimensions: width, height, spacing, width of tip/tail. const b = { w: width / 6, h: 30, s: 3, t: 10, }; const radius = Math.min(width - b.h, height - b.h) / 2 - 5; if (radius <= 0) { return; } // margins const margin = { top: radius, bottom: 50, left: radius, right: 0, }; // Drawing variables: e.g. colors, totalSize, partitions, arcs // Total size of all nodes, to be used later when data is loaded let totalSize = 0; // create d3.layout.partition // @ts-expect-error ts-migrate(2339) FIXME: Property 'layout' does not exist on type 'typeof i... Remove this comment to see the full error message const partition = d3.layout .partition() .size([2 * Math.PI, radius * radius]) .value((d: any) => d.size); // create arcs for drawing D3 paths const arc = d3.svg // @ts-expect-error ts-migrate(2339) FIXME: Property 'arc' does not exist on type '(url: strin... Remove this comment to see the full error message .arc() .startAngle((d: any) => d.x) .endAngle((d: any) => d.x + d.dx) .innerRadius((d: any) => Math.sqrt(d.y)) .outerRadius((d: any) => Math.sqrt(d.y + d.dy)); /** * Define and initialize D3 select references and div-containers * * e.g. vis, breadcrumbs, lastCrumb, summary, sunburst, legend */ const vis = d3.select(element); // create and position breadcrumbs container and svg const breadcrumbs = vis .append("div") .classed("breadcrumbs-container", true) .append("svg") .attr("width", width) .attr("height", b.h) .attr("fill", "white") .attr("font-weight", 600); // create and position SVG const container = vis.append("div"); // create and position summary container const summary = container.append("div").classed("summary-container", true); const sunburst = container .append("div") .classed("sunburst-container", true) .append("svg") .attr("width", radius * 2) .attr("height", radius * 2) .append("g") .attr("transform", `translate(${margin.left},${margin.top})`); // create last breadcrumb element const lastCrumb = breadcrumbs.append("text").classed("lastCrumb", true); // Generate a string representation for drawing a breadcrumb polygon. function breadcrumbPoints(d: any, i: any) { const points = []; points.push("0,0"); points.push(`${b.w},0`); points.push(`${b.w + b.t},${b.h / 2}`); points.push(`${b.w},${b.h}`); points.push(`0,${b.h}`); if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex. points.push(`${b.t},${b.h / 2}`); } return points.join(" "); } // Update the breadcrumb breadcrumbs to show the current sequence and percentage. function updateBreadcrumbs(ancestors: any, percentageString: any) { // Data join, where primary key = name + depth. // @ts-expect-error ts-migrate(2571) FIXME: Object is of type 'unknown'. const g = breadcrumbs.selectAll("g").data(ancestors, d => d.name + d.depth); // Add breadcrumb and label for entering nodes. const breadcrumb = g.enter().append("g"); breadcrumb .append("polygon") .classed("breadcrumbs-shape", true) .attr("points", breadcrumbPoints) .attr("fill", colorMap); breadcrumb .append("text") .classed("breadcrumbs-text", true) .attr("x", (b.w + b.t) / 2) .attr("y", b.h / 2) .attr("dy", "0.35em") .attr("font-size", "10px") .attr("text-anchor", "middle") // @ts-expect-error ts-migrate(2571) FIXME: Object is of type 'unknown'. .text(d => d.name); // Set position for entering and updating nodes. g.attr("transform", (d, i) => `translate(${i * (b.w + b.s)}, 0)`); // Remove exiting nodes. g.exit().remove(); // Update percentage at the lastCrumb. lastCrumb .attr("x", (ancestors.length + 0.5) * (b.w + b.s)) .attr("y", b.h / 2) .attr("dy", "0.35em") .attr("text-anchor", "middle") .attr("fill", "black") .attr("font-weight", 600) .text(percentageString); } // helper function mouseover to handle mouseover events/animations and calculation // of ancestor nodes etc function mouseover(d: any) { // build percentage string const percentage = ((100 * d.value) / totalSize).toPrecision(3); let percentageString = `${percentage}%`; // @ts-expect-error ts-migrate(2365) FIXME: Operator '<' cannot be applied to types 'string' a... Remove this comment to see the full error message if (percentage < 1) { percentageString = "< 1.0%"; } // update breadcrumbs (get all ancestors) const ancestors = getAncestors(d); updateBreadcrumbs(ancestors, percentageString); // update sunburst (Fade all the segments and highlight only ancestors of current segment) sunburst.selectAll("path").attr("opacity", 0.3); sunburst .selectAll("path") .filter(node => ancestors.indexOf(node) >= 0) .attr("opacity", 1); // update summary summary.html(` <span>层级:${d.depth}</span> <span class='percentage' style='font-size: 2em;'>${percentageString}</span> <span>${d.value} / ${totalSize}</span> `); // display summary and breadcrumbs if hidden summary.style("visibility", ""); breadcrumbs.style("visibility", ""); } // helper function click to handle mouseleave events/animations function click() { // Deactivate all segments then retransition each segment to full opacity. sunburst.selectAll("path").on("mouseover", null); sunburst .selectAll("path") .transition() .duration(1000) .attr("opacity", 1) // @ts-expect-error ts-migrate(2554) FIXME: Expected 1 arguments, but got 2. .each("end", function endClick() { // @ts-expect-error ts-migrate(2683) FIXME: 'this' implicitly has type 'any' because it does n... Remove this comment to see the full error message d3.select(this).on("mouseover", mouseover); }); // hide summary and breadcrumbs if visible breadcrumbs.style("visibility", "hidden"); summary.style("visibility", "hidden"); } // Build only nodes of a threshold "visible" sizes to improve efficiency // 0.005 radians = 0.29 degrees const nodes = partition.nodes(data).filter((d: any) => d.dx > 0.005 && d.name !== exitNode); // this section is required to update the colors.domain() every time the data updates const uniqueNames = (function uniqueNames(a) { const output: any = []; a.forEach((d: any) => { if (output.indexOf(d.name) === -1) output.push(d.name); }); return output; })(nodes); colors.domain(uniqueNames); // update domain colors // create path based on nodes const path = sunburst .data([data]) .selectAll("path") .data(nodes) .enter() .append("path") .classed("nodePath", true) // @ts-expect-error ts-migrate(2571) FIXME: Object is of type 'unknown'. .attr("display", d => (d.depth ? null : "none")) .attr("d", arc) .attr("fill", colorMap) .attr("opacity", 1) .attr("stroke", "white") .on("mouseover", mouseover); // // trigger mouse click over sunburst to reset visualization summary vis.on("click", click); // Update totalSize of the tree = value of root node from partition. // @ts-expect-error ts-migrate(2531) FIXME: Object is possibly 'null'. totalSize = path.node().__data__.value; }; }
the_stack
import { HOME } from '../../robot-controls' import { robotReducer as reducer, actionTypes } from '..' import type { Action } from '../../types' import type { RobotState } from '..' const EXPECTED_INITIAL_STATE = { deckPopulated: null, modulesReviewed: null, // intrument probed + basic tip-tracking flags // TODO(mc, 2018-01-22): combine these into subreducer probedByMount: {}, tipOnByMount: {}, // labware confirmed flags confirmedBySlot: {}, // TODO(mc, 2018-01-22): make this state a sub-reducer calibrationRequest: { type: '', inProgress: false, error: null }, } describe('robot reducer - calibration', () => { it('initial state', () => { const state = reducer(undefined, {} as any) expect(state.calibration).toEqual(EXPECTED_INITIAL_STATE) }) it('handles robot:REFRESH_SESSION', () => { const state = reducer( { calibration: {} } as any, { type: 'robot:REFRESH_SESSION' } as any ) expect(state.calibration).toEqual(EXPECTED_INITIAL_STATE) }) it('handles DISCONNECT_RESPONSE success', () => { const expected = reducer(undefined, {} as any).calibration const state: RobotState = { calibration: { dummy: 'state' } } as any const action: Action = { type: 'robot:DISCONNECT_RESPONSE', payload: {} } expect(reducer(state, action).calibration).toEqual(expected) }) it('handles protocol:UPLOAD', () => { const expected = reducer(undefined, {} as any).calibration const state: RobotState = { calibration: { dummy: 'state' } } as any const action: Action = { type: 'protocol:UPLOAD', payload: {} as any, meta: {} as any, } expect(reducer(state, action).calibration).toEqual(expected) }) it('handles SET_MODULES_REVIEWED action', () => { const setToTrue: Action = { type: 'robot:SET_MODULES_REVIEWED', payload: true, } const setToFalse: Action = { type: 'robot:SET_MODULES_REVIEWED', payload: false, } let state: RobotState = { calibration: { modulesReviewed: false } } as any expect(reducer(state, setToTrue).calibration).toEqual({ modulesReviewed: true, }) state = { calibration: { modulesReviewed: true } } as any expect(reducer(state, setToFalse).calibration).toEqual({ modulesReviewed: false, }) }) it('handles SET_DECK_POPULATED action', () => { const setToTrue = { type: actionTypes.SET_DECK_POPULATED, payload: true, } as any const setToFalse = { type: actionTypes.SET_DECK_POPULATED, payload: false, } as any let state: RobotState = { calibration: { deckPopulated: false } } as any expect(reducer(state, setToTrue).calibration).toEqual({ deckPopulated: true, }) state = { calibration: { deckPopulated: true } } as any expect(reducer(state, setToFalse).calibration).toEqual({ deckPopulated: false, }) }) it('handles PICKUP_AND_HOME action', () => { const state: RobotState = { calibration: { deckPopulated: false, modulesReviewed: false, calibrationRequest: { type: '', inProgress: false, error: new Error(), }, }, } as any const action: Action = { type: 'robot:PICKUP_AND_HOME', payload: { mount: 'left', slot: '5' }, meta: {} as any, } expect(reducer(state, action).calibration).toEqual({ deckPopulated: true, modulesReviewed: true, calibrationRequest: { type: 'PICKUP_AND_HOME', mount: 'left', slot: '5', inProgress: true, error: null, }, }) }) it('handles PICKUP_AND_HOME response actions', () => { const state: RobotState = { calibration: { calibrationRequest: { type: 'PICKUP_AND_HOME', mount: 'left', slot: '5', inProgress: true, error: null, }, tipOnByMount: { right: false }, }, } as any const success: Action = { type: 'robot:PICKUP_AND_HOME_SUCCESS', payload: {}, } const failure: Action = { type: 'robot:PICKUP_AND_HOME_FAILURE', error: true, payload: new Error('AH'), } expect(reducer(state, success).calibration).toEqual({ calibrationRequest: { type: 'PICKUP_AND_HOME', mount: 'left', slot: '5', inProgress: false, error: null, }, tipOnByMount: { left: true, right: false }, }) expect(reducer(state, failure).calibration).toEqual({ calibrationRequest: { type: 'PICKUP_AND_HOME', mount: 'left', slot: '5', inProgress: false, error: new Error('AH'), }, tipOnByMount: { right: false }, }) }) it('handles DROP_TIP_AND_HOME action', () => { const state: RobotState = { calibration: { calibrationRequest: { type: '', inProgress: false, error: new Error('AH'), }, }, } as any const action: Action = { type: 'robot:DROP_TIP_AND_HOME', payload: { mount: 'right', slot: '5' }, meta: {} as any, } expect(reducer(state, action).calibration).toEqual({ calibrationRequest: { type: 'DROP_TIP_AND_HOME', mount: 'right', slot: '5', inProgress: true, error: null, }, }) }) it('handles DROP_TIP_AND_HOME response actions', () => { const state: RobotState = { calibration: { calibrationRequest: { type: 'DROP_TIP_AND_HOME', mount: 'right', slot: '5', inProgress: true, error: null, }, tipOnByMount: { left: false, right: true }, }, } as any const success: Action = { type: 'robot:DROP_TIP_AND_HOME_SUCCESS', payload: {}, } const failure: Action = { type: 'robot:DROP_TIP_AND_HOME_FAILURE', error: true, payload: new Error('AH'), } expect(reducer(state, success).calibration).toEqual({ calibrationRequest: { type: 'DROP_TIP_AND_HOME', mount: 'right', slot: '5', inProgress: false, error: null, }, tipOnByMount: { left: false, right: false }, }) expect(reducer(state, failure).calibration).toEqual({ calibrationRequest: { type: 'DROP_TIP_AND_HOME', mount: 'right', slot: '5', inProgress: false, error: new Error('AH'), }, tipOnByMount: { left: false, right: true }, }) }) it('handles CONFIRM_TIPRACK action', () => { const state: RobotState = { calibration: { calibrationRequest: { type: '', mount: 'right', slot: '5', inProgress: false, error: new Error('AH'), }, }, } as any const action: Action = { type: 'robot:CONFIRM_TIPRACK', payload: { mount: 'right', slot: '5' }, meta: {} as any, } expect(reducer(state, action).calibration).toEqual({ calibrationRequest: { type: 'CONFIRM_TIPRACK', inProgress: true, error: null, mount: 'right', slot: '5', }, }) }) it('handles CONFIRM_TIPRACK response actions', () => { const state: RobotState = { calibration: { calibrationRequest: { type: 'CONFIRM_TIPRACK', inProgress: true, error: null, mount: 'right', slot: '5', }, tipOnByMount: { right: true }, confirmedBySlot: { 5: false }, }, } as any const success: Action = { type: 'robot:CONFIRM_TIPRACK_SUCCESS', payload: { tipOn: false }, } const failure: Action = { type: 'robot:CONFIRM_TIPRACK_FAILURE', error: true, payload: new Error('AH'), } expect(reducer(state, success).calibration).toEqual({ calibrationRequest: { type: 'CONFIRM_TIPRACK', inProgress: false, error: null, mount: 'right', slot: '5', }, tipOnByMount: { right: false }, confirmedBySlot: { 5: true }, }) expect(reducer(state, failure).calibration).toEqual({ calibrationRequest: { type: 'CONFIRM_TIPRACK', inProgress: false, error: new Error('AH'), mount: 'right', slot: '5', }, tipOnByMount: { right: true }, confirmedBySlot: { 5: false }, }) }) it('handles MOVE_TO_FRONT action', () => { const state: RobotState = { calibration: { deckPopulated: true, modulesReviewed: true, calibrationRequest: { type: '', mount: '', inProgress: false, error: new Error(), }, }, } as any const action = { type: actionTypes.MOVE_TO_FRONT, payload: { mount: 'left' }, } as any expect(reducer(state, action).calibration).toEqual({ deckPopulated: false, modulesReviewed: false, calibrationRequest: { type: 'MOVE_TO_FRONT', mount: 'left', inProgress: true, error: null, }, }) }) it('handles MOVE_TO_FRONT_RESPONSE action', () => { const state: RobotState = { calibration: { calibrationRequest: { type: 'MOVE_TO_FRONT', mount: 'right', inProgress: true, error: null, }, }, } as any const success = { type: actionTypes.MOVE_TO_FRONT_RESPONSE, error: false, } as any const failure = { type: actionTypes.MOVE_TO_FRONT_RESPONSE, error: true, payload: new Error('AH'), } as any expect(reducer(state, success).calibration).toEqual({ calibrationRequest: { type: 'MOVE_TO_FRONT', mount: 'right', inProgress: false, error: null, }, }) expect(reducer(state, failure).calibration).toEqual({ calibrationRequest: { type: 'MOVE_TO_FRONT', mount: 'right', inProgress: false, error: new Error('AH'), }, }) }) it('handles PROBE_TIP action', () => { const state: RobotState = { calibration: { calibrationRequest: { type: '', mount: 'left', inProgress: false, error: new Error('AH'), }, probedByMount: { left: true, right: true }, }, } as any const action = { type: actionTypes.PROBE_TIP, payload: { mount: 'left' }, } as any expect(reducer(state, action).calibration).toEqual({ calibrationRequest: { type: 'PROBE_TIP', mount: 'left', inProgress: true, error: null, }, probedByMount: { left: false, right: true }, }) }) it('handles PROBE_TIP_RESPONSE action', () => { const state: RobotState = { calibration: { calibrationRequest: { type: 'PROBE_TIP', mount: 'right', inProgress: true, error: null, }, }, } as any const success = { type: actionTypes.PROBE_TIP_RESPONSE, error: false, } as any const failure = { type: actionTypes.PROBE_TIP_RESPONSE, error: true, payload: new Error('AH'), } as any expect(reducer(state, success).calibration).toEqual({ calibrationRequest: { type: 'PROBE_TIP', mount: 'right', inProgress: false, error: null, }, confirmedBySlot: {}, }) expect(reducer(state, failure).calibration).toEqual({ calibrationRequest: { type: 'PROBE_TIP', mount: 'right', inProgress: false, error: new Error('AH'), }, confirmedBySlot: {}, }) }) it('handles CONFIRM_PROBED', () => { const state: RobotState = { calibration: { probedByMount: { left: false, right: true }, }, } as any const action: Action = { type: 'robot:CONFIRM_PROBED', payload: 'left', meta: {} as any, } expect(reducer(state, action).calibration).toEqual({ probedByMount: { left: true, right: true }, }) }) it('handles MOVE_TO action', () => { const state: RobotState = { calibration: { deckPopulated: false, modulesReviewed: false, calibrationRequest: { type: '', inProgress: false, error: new Error('AH'), }, }, } as any const action: Action = { type: 'robot:MOVE_TO', payload: { mount: 'left', slot: '3' }, meta: {} as any, } expect(reducer(state, action).calibration).toEqual({ deckPopulated: true, modulesReviewed: true, calibrationRequest: { type: 'MOVE_TO', inProgress: true, error: null, mount: 'left', slot: '3', }, }) }) it('handles MOVE_TO response actions', () => { const state: RobotState = { calibration: { calibrationRequest: { type: 'MOVE_TO', inProgress: true, error: null, mount: 'right', slot: '5', }, }, } as any const success: Action = { type: 'robot:MOVE_TO_SUCCESS', payload: {} } const failure: Action = { type: 'robot:MOVE_TO_FAILURE', error: true, payload: new Error('AH'), } expect(reducer(state, success).calibration).toEqual({ calibrationRequest: { type: 'MOVE_TO', inProgress: false, error: null, mount: 'right', slot: '5', }, }) expect(reducer(state, failure).calibration).toEqual({ calibrationRequest: { type: 'MOVE_TO', inProgress: false, error: new Error('AH'), mount: 'right', slot: '5', }, }) }) it('handles JOG action', () => { const state: RobotState = { calibration: { calibrationRequest: { type: '', inProgress: false, error: new Error(), }, }, } as any const action: Action = { type: 'robot:JOG', payload: { mount: 'right' }, meta: {} as any, } expect(reducer(state, action).calibration).toEqual({ calibrationRequest: { type: 'JOG', inProgress: true, error: null, mount: 'right', }, }) }) it('handles JOG response actions', () => { const state: RobotState = { calibration: { calibrationRequest: { type: 'JOG', inProgress: true, error: null, mount: 'right', }, }, } as any const success: Action = { type: 'robot:JOG_SUCCESS', payload: {}, } const failure: Action = { type: 'robot:JOG_FAILURE', error: true, payload: new Error('AH'), } expect(reducer(state, success).calibration).toEqual({ calibrationRequest: { type: 'JOG', inProgress: false, error: null, mount: 'right', }, }) expect(reducer(state, failure).calibration).toEqual({ calibrationRequest: { type: 'JOG', inProgress: false, error: new Error('AH'), mount: 'right', }, }) }) it('handles UPDATE_OFFSET action', () => { const state: RobotState = { calibration: { calibrationRequest: { type: '', inProgress: false, error: new Error(), }, }, } as any const action: Action = { type: 'robot:UPDATE_OFFSET', payload: { mount: 'right', slot: '5' }, meta: {} as any, } expect(reducer(state, action).calibration).toEqual({ calibrationRequest: { type: 'UPDATE_OFFSET', inProgress: true, error: null, mount: 'right', slot: '5', }, }) }) it('handles UPDATE_OFFSET response actions', () => { const state: RobotState = { calibration: { calibrationRequest: { type: 'UPDATE_OFFSET', inProgress: true, error: null, mount: 'right', slot: '5', }, confirmedBySlot: {}, }, } as any const success: Action = { type: 'robot:UPDATE_OFFSET_SUCCESS', payload: {}, } const failure: Action = { type: 'robot:UPDATE_OFFSET_FAILURE', error: true, payload: new Error('AH'), } expect(reducer(state, success).calibration).toEqual({ calibrationRequest: { type: 'UPDATE_OFFSET', inProgress: false, error: null, mount: 'right', slot: '5', }, confirmedBySlot: { 5: true }, }) expect(reducer(state, failure).calibration).toEqual({ calibrationRequest: { type: 'UPDATE_OFFSET', inProgress: false, error: new Error('AH'), mount: 'right', slot: '5', }, confirmedBySlot: {}, }) }) it('handles CONFIRM_LABWARE action', () => { const state: RobotState = { calibration: { confirmedBySlot: {}, }, } as any const action = { type: actionTypes.CONFIRM_LABWARE, payload: { labware: '5' }, } as any expect(reducer(state, action).calibration).toEqual({ confirmedBySlot: { 5: true }, }) }) it('handles CLEAR_CALIBRATION_REQUEST and robot home actions', () => { const state: RobotState = { calibration: { calibrationRequest: { type: 'JOG', inProgress: true, error: null, mount: 'right', }, }, } as any const clearAction: Action = { type: 'robot:CLEAR_CALIBRATION_REQUEST' } expect(reducer(state, clearAction).calibration).toEqual({ calibrationRequest: { type: '', inProgress: false, error: null }, }) const homeAction = { type: HOME } as any expect(reducer(state, homeAction).calibration).toEqual({ calibrationRequest: { type: '', inProgress: false, error: null }, }) }) it('handles RETURN_TIP action', () => { const state: RobotState = { calibration: { calibrationRequest: { type: '', inProgress: false, error: new Error(), }, }, } as any const action = { type: actionTypes.RETURN_TIP, payload: { mount: 'left' }, } as any expect(reducer(state, action).calibration).toEqual({ calibrationRequest: { type: 'RETURN_TIP', inProgress: true, error: null, mount: 'left', }, }) }) it('handles RETURN_TIP_RESPONSE success', () => { const state: RobotState = { calibration: { calibrationRequest: { type: 'RETURN_TIP', inProgress: true, error: null, mount: 'left', }, tipOnByMount: { left: true, }, }, } as any const action = { type: actionTypes.RETURN_TIP_RESPONSE, } as any expect(reducer(state, action).calibration).toEqual({ calibrationRequest: { type: 'RETURN_TIP', inProgress: false, error: null, mount: 'left', }, tipOnByMount: { left: false, }, }) }) it('handles RETURN_TIP_RESPONSE failure', () => { const state: RobotState = { calibration: { calibrationRequest: { type: 'RETURN_TIP', inProgress: true, error: null, mount: 'left', }, tipOnByMount: { left: true, }, }, } as any const action = { type: actionTypes.RETURN_TIP_RESPONSE, error: true, payload: { message: 'AH' }, } as any expect(reducer(state, action).calibration).toEqual({ calibrationRequest: { type: 'RETURN_TIP', inProgress: false, error: { message: 'AH' }, mount: 'left', }, tipOnByMount: { left: false, }, }) }) })
the_stack
// Type definitions for Ionic // Project: http://ionicframework.com // Definitions by: Spencer Williams <https://github.com/spencerwi/> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference path="../angularjs/angular.d.ts" /> interface IonicStatic { /** * What Ionic package version is. */ version: string; Platform: { /** * Trigger a callback once the device is ready, or immediately * if the device is already ready. This method can be run from * anywhere and does not need to be wrapped by any additonal methods. * When the app is within a WebView (Cordova), it’ll fire * the callback once the device is ready. If the app is within * a web browser, it’ll fire the callback after window.load. * Please remember that Cordova features (Camera, FileSystem, etc) still * will not work in a web browser. */ ready(callback: ()=>any): void; /** * Set the grade of the device: ‘a’, ‘b’, or ‘c’. ‘a’ is the best * (most css features enabled), ‘c’ is the worst. By default, sets the grade * depending on the current device. */ setGrade(grade: string): void; /** * Return the current device (given by cordova). */ device(): any; /** * Check if the platform name provided is detected. */ is(platformName: string): boolean; /** * Check if we are running within a WebView (such as Cordova). */ isWebView(): boolean; /** * Whether we are running on iPad. */ isIPad(): boolean; /** * Whether we are running on iOS. */ isIOS(): boolean; /** * Whether we are running on Android. */ isAndroid(): boolean; /** * Whether we are running on Windows Phone. */ isWindowsPhone(): boolean; /** * The name of the current platform. */ platform(): string; /** * The version of the current device platform. */ version(): number; /** * Exit the app. */ exitApp(): void; /** * Shows or hides the device status bar (in Cordova). Requires cordova plugin add org.apache.cordova.statusbar */ showStatusBar(shouldShow: boolean): void; /** * Sets whether the app is fullscreen or not (in Cordova). */ fullScreen(showFullScreen?: boolean, showStatusBar?: boolean): void; /** * Whether the device is ready. */ isReady: boolean; /** * Whether the device is fullscreen. */ isFullScreen: boolean; /** * An array of all platforms found. */ platforms: Array<string>; /** * What grade the current platform is. */ grade: string; }; } declare var ionic: IonicStatic; declare module 'ionic' { export = ionic; } declare namespace ionic { namespace actionSheet { interface IonicActionSheetService { show(options: IonicActionSheetOptions): ()=>void; } interface IonicActionSheetButton { text: string; } interface IonicActionSheetOptions { buttons?: Array<IonicActionSheetButton>; titleText?: string; cancelText?: string; destructiveText?: string; cancel?: ()=>any; buttonClicked?: (index: number)=>boolean; destructiveButtonClicked?: ()=>boolean; cancelOnStateChange?: boolean; cssClass?: string; } } namespace backdrop { interface IonicBackdropService { retain(): void; release(): void; } } namespace gestures { interface IonicGestureService { on(eventType: string, callback: (e: any)=>any, $element: angular.IAugmentedJQuery, options: any): IonicGesture; off(gesture: IonicGesture, eventType: string, callback: (e: any)=>any): void; } interface IonicGesture { element: Element; enabled: boolean; options: {stop_browser_behavior: string }; on(gesture: string, handler: Function): IonicGesture; off(gesture: string, handler: Function): IonicGesture; trigger(gesture: string, eventData: any): IonicGesture; enable(state: boolean): IonicGesture; } } namespace list { interface IonicListDelegate { showReorder(showReorder?: boolean): boolean; showDelete(showDelete?: boolean): boolean; canSwipeItems(canSwipeItems?: boolean): boolean; closeOptionButtons(): void; $getByHandle(handle: string): IonicListDelegate; } } namespace loading { interface IonicLoadingService { show(opts?: IonicLoadingOptions): void; hide(): void; } interface IonicLoadingOptions { template?: string; templateUrl?: string; scope?: any; noBackdrop?: boolean; hideOnStateChange?: boolean; delay?: number; duration?: number; } } namespace modal { interface IonicModalService { fromTemplate(templateString: string, options?: IonicModalOptions): IonicModalController; fromTemplateUrl(templateUrl: string, options?: IonicModalOptions): angular.IPromise<IonicModalController>; } interface IonicModalController { initialize(options: IonicModalOptions): void; show(): angular.IPromise<void>; hide(): angular.IPromise<void>; remove(): angular.IPromise<void>; isShown(): boolean; scope: ng.IScope; } interface IonicModalOptions { scope?: any; animation?: string; focusFirstInput?: boolean; backdropClickToClose?: boolean; hardwareBackButtonClose?: boolean; } } namespace navigation { interface IonicNavBarDelegate { align(direction?: string): void; showBackButton(show?: boolean): boolean; showBar(show?: boolean): boolean; title(title: string): void; } interface IonicHistoryService { viewHistory(): any; currentView(view?: any): any; currentHistoryId(): string; currentTitle(val?: string): string; backView(view?: any): any; backTitle(): string; forwardView(view?: any): any; currentStateName(): string; goBack(backCount?: number): void; removeBackView(): void; clearHistory(): void; clearCache(): angular.IPromise<any>; nextViewOptions(options: IonicHistoryNextViewOptions): void; } interface IonicHistoryNextViewOptions { disableAnimate?: boolean; disableBack?: boolean; historyRoot?: boolean; } } namespace platform { interface IonicPlatformService { onHardwareBackButton(callback: Function): void; offHardwareBackButton(callback: Function): void; registerBackButtonAction(callback: Function, priority: number, actionId?: any): Function; on(type: string, callback: Function): Function; ready(callback?: Function): angular.IPromise<any>; } } namespace popover { interface IonicPopoverService { fromTemplate(templateString: string, options: IonicPopoverOptions): IonicPopoverController; fromTemplateUrl(templateUrl: string, options: IonicPopoverOptions): angular.IPromise<IonicPopoverController>; } interface IonicPopoverController { initialize(options: IonicPopoverOptions): void; show($event?: any): angular.IPromise<any>; hide(): angular.IPromise<any>; isShown(): boolean; remove(): angular.IPromise<any>; scope: ng.IScope; } interface IonicPopoverOptions { scope?: any; focusFirstInput?: boolean; backdropClickToClose?: boolean; hardwareBackButtonClose?: boolean; } } namespace popup { interface IonicPopupService { show(options: IonicPopupFullOptions): IonicPopupPromise; alert(options: IonicPopupAlertOptions): IonicPopupPromise; confirm(options: IonicPopupConfirmOptions): IonicPopupConfirmPromise; prompt(options: IonicPopupPromptOptions): IonicPopupPromise; } interface IonicPopupConfirmPromise extends angular.IPromise<boolean> { close(value?: boolean): void; } interface IonicPopupPromise extends angular.IPromise<any> { close(value?: any): any; } interface IonicPopupBaseOptions { title?: string; cssClass?: string; subTitle?: string; template?: string; templateUrl?: string; } interface IonicPopupFullOptions extends IonicPopupBaseOptions { scope?: any; buttons?: Array<IonicPopupButton>; } interface IonicPopupButton { text: string; type?: string; onTap?(event?: any): void; } interface IonicPopupAlertOptions extends IonicPopupBaseOptions { okText?: string; okType?: string; } interface IonicPopupConfirmOptions extends IonicPopupBaseOptions { cancelText?: string; cancelType?: string; okText?: string; okType?: string; } interface IonicPopupPromptOptions extends IonicPopupBaseOptions { inputType?: string; inputPlaceholder?: string; cancelText?: string; cancelType?: string; okText?: string; okType?: string; } } namespace scroll { interface IonicScrollDelegate { resize(): void; scrollTop(shouldAnimate?: boolean): void; scrollBottom(shouldAnimate?: boolean): void; scrollTo(left: number, top: number, shouldAnimate?: boolean): void; scrollBy(left: number, top: number, shouldAnimate?: boolean): void; zoomTo(level: number, animate?: boolean, originLeft?: number, originTop?: number): void; zoomBy(factor: number, animate?: boolean, originLeft?: number, originTop?: number): void; getScrollPosition(): {left: number; top: number}; anchorScroll(shouldAnimate?: boolean): void; freezeScroll(shouldFreeze?: boolean): boolean; freezeAllScrolls(shouldFreeze?: boolean): boolean; getScrollView(): any; $getByHandle(handle: string): IonicScrollDelegate; } } namespace sideMenu { interface IonicSideMenuDelegate { toggleLeft(isOpen?: boolean): void; toggleRight(isOpen?: boolean): void; getOpenRatio(): number; isOpen(): boolean; isOpenLeft(): boolean; isOpenRight(): boolean; canDragContent(canDrag?: boolean): boolean; edgeDragThreshold(value?: boolean|number): boolean; $getByHandle(handle: string): IonicSideMenuDelegate; } } namespace slideBox { interface IonicSlideBoxDelegate { update(): void; slide(to: number, speed?: number): void; enableSlide(shouldEnable?: boolean): boolean; previous(speed?: number): void; next(speed?: number): void; stop(): void; start(): void; currentIndex(): number; slidesCount(): number; $getByHandle(handle: string): IonicSlideBoxDelegate; } } namespace tabs { interface IonicTabsDelegate { select(index: number): void; selectedIndex(): number; $getByHandle(handle: string): IonicTabsDelegate; showBar(show?: boolean): boolean; } } namespace utility { interface IonicConfigProvider { views: { transition(transition?: string): string; maxCache(maxNumber?: number): number; forwardCache(value?: boolean): boolean; swipeBackEnabled(value?: boolean): boolean; }; scrolling: { jsScrolling(value?: boolean): boolean; }; backButton: { icon(value?: string): string; text(value?: string): string; previousTitleText(value?: boolean): boolean; }; form: { checkbox(value?: string): string; toggle(value?: string): string; }; spinner: { icon(value?: string): string; }; tabs: { style(value?: string): string; position(value?: string): string; }; templates: { maxPrefetch(value?: number): number; }; navBar: { alignTitle(value?: string): string; positionPrimaryButtons(value?: string): string; positionSecondaryButtons(value?: string): string; }; } interface IonicPositionService { position(element: any): {top: number; left: number; width: number; height: number}; offset(element: any): {top: number; left: number; width: number; height: number}; } } }
the_stack
import * as moment from 'moment'; import * as namespaces from './clientapi/WebApiCoreFetchClientAuto'; //import * as namespaces from './clientapi/WebApiFetchClientAuto'; const DemoWebApi_Controllers_Client = namespaces.DemoWebApi_Controllers_Client; describe('Basic', ()=>{ it('simple 1', done=>{ expect(true).toBeTruthy(); done(); }); it('simple 2', done=>{ expect(true).toBeTruthy(); done(); }); }); const forDotNetCore=true; const baseUri = forDotNetCore ? 'http://localhost:5000/' : 'http://localhost:10965/'; describe('Values', ()=>{ const api = new DemoWebApi_Controllers_Client.Values(baseUri); it('getById', (done)=>{ api.getById(3).then( d=> { expect(d).toBe('3'); done(); } ); }); it('get', (done) => { api.get().then( data => { console.debug(data.length); expect(data[1]).toBe('value2'); done(); }, error => { // fail(errorResponseToString(error)); done(); } ); } ); it('Post', (done) => { api.post('Abc').then( data => { console.debug(data.length); expect(data).toBe('ABC'); done(); }, error => { // fail(errorResponseToString(error)); done(); } ); } ); }); describe('Heroes API', () => { const service= new namespaces.DemoWebApi_Controllers_Client.Heroes(baseUri); it('getAll', (done) => { service.getHeros().then( data => { console.debug(data.length); expect(data.length).toBeGreaterThan(0); done(); }, error => { done(); } ); } ); it('Add', (done) => { service.post('somebody').then( data => { console.info('Add hero: '+JSON.stringify(data)); expect(data.name).toBe('somebody'); done(); }, error => { done(); } ); } ); it('PostWithQuery', (done) => { service.postWithQuery('somebodyqqq').then( data => { expect(data.name).toBe('somebodyqqq'); done(); }, error => { done(); } ); } ); it('search', (done) => { service.search('Torna').then( data => { console.debug(data.length); expect(data.length).toBe(1); expect(data[0].name).toBe('Tornado'); done(); }, error => { done(); } ); } ); }); describe('entities API', () => { const client = new namespaces.DemoWebApi_Controllers_Client.Entities(baseUri); //it('getPersonNotFound', (done) => { // client.getPersonNotFound(123) // .then( // data => { // fail('That is bad. Should be 404.'); // done(); // }, // error => { // expect(errorResponseToString(error)).toContain('404'); // done(); // } // ); //} //); it('add', (done) => { let id: number; const newPerson: namespaces.DemoWebApi_DemoData_Client.Person = { name: 'John Smith' + Date.now().toString(), givenName: 'John', surname: 'Smith', dob: new Date('1977-12-28') }; client.createPerson(newPerson) .then( data => { id = data; expect(data).toBeTruthy(); done(); }, error => { done(); } ); } ); it('addWthHeadersHandling', (done) => { let id: number; const newPerson: namespaces.DemoWebApi_DemoData_Client.Person = { name: 'John Smith' + Date.now().toString(), givenName: 'John', surname: 'Smith', dob: new Date('1977-12-28') }; client.createPerson3(newPerson, ()=>{return {middle: 'Hey'};}) .then( data => { expect(data.givenName).toBe('Hey'); done(); }, error => { done(); } ); } ); }); describe('Tuple API', () => { const service= new namespaces.DemoWebApi_Controllers_Client.Tuple(baseUri); it('getTuple2', (done) => { service.getTuple2().then( data => { expect(data.item1).toBe('Two'); expect(data.item2).toBe(2); done(); }, error => { done(); } ); } ); it('postTuple2', (done) => { service.postTuple2({ item1: "One", item2: 2 }).then( data => { expect(data).toBe('One'); done(); }, error => { done(); } ); } ); it('getTuple7', (done) => { service.getTuple7().then( data => { expect(data.item1).toBe('Seven'); expect(data.item7).toBe(7); done(); }, error => { done(); } ); } ); it('getTuple2', (done) => { service.getTuple2().then( data => { expect(data.item1).toBe('Two'); expect(data.item2).toBe(2); done(); }, error => { done(); } ); } ); it('postTuple7', (done) => { service.postTuple7({ item1: 'One', item2: '', item3: '', item4: '', item5: '', item6: 33333, item7: 9 }).then( data => { expect(data).toBe('One'); done(); }, error => { done(); } ); } ); it('getTuple8', (done) => { service.getTuple8().then( data => { expect(data.item1).toBe('Nested'); expect(data.rest.item1).toBe('nine'); done(); }, error => { done(); } ); } ); it('postTuple8', (done) => { service.postTuple8({ item1: 'One', item2: '', item3: '', item4: '', item5: '', item6: '', item7: '', rest: { item1: 'a', item2: 'b', item3: 'c' } }).then( data => { expect(data).toBe('a'); done(); }, error => { done(); } ); } ); it('linkPersonCompany1', (done) => { service.linkPersonCompany1({ item1: { name: 'someone', surname: 'my', givenName: 'something', }, item2: { name: 'Super', addresses: [{ city: 'New York', street1: 'Somewhere st' }] } }).then( data => { expect(data.name).toBe('someone'); done(); }, error => { done(); } ); } ); }); describe('SuperDemo API', () => { const service=new namespaces.DemoWebApi_Controllers_Client.SuperDemo(baseUri); it('getBool', (done) => { service.getBool().then( data => { expect(data).toBeTruthy(); done(); }, error => { done(); } ); } ); it('GetNextHour', (done) => { const dt = new Date(Date.now()); const h = dt.getHours(); service.getNextHour(dt).then( data => { console.debug(JSON.stringify(data)); const m = moment(data); const dd = m.toDate(); expect(dd.getHours()).toBe(h + 1); done(); }, error => { done(); } ); } ); it('GetNextYear', (done) => { const dt = new Date(Date.now()); const h = dt.getFullYear(); service.getNextYear(dt).then( data => { const m = moment(data); const dd = m.toDate(); expect(dd.getFullYear()).toBe(h + 1); done(); }, error => { done(); } ); } ); it('PostNextYear', (done) => { const dt = new Date(Date.now()); const h = dt.getFullYear(); service.postNextYear(dt).then( data => { const m = moment(data); const dd = m.toDate(); expect(dd.getFullYear()).toBe(h + 1); done(); }, error => { done(); } ); } ); it('getFloatZero', (done) => { service.getFloatZero().then( data => { expect(data).toBeLessThan(0.000001); done(); }, error => { done(); } ); } ); it('getDoubleZero', (done) => { service.getDoubleZero().then( data => { expect(data).not.toBe(0); done(); }, error => { done(); } ); } ); it('getDecimalZero', (done) => { service.getDecimalZero().then( data => { expect(data).toBe(0); done(); }, error => { done(); } ); } ); it('getIntSquare', (done) => { service.getIntSquare(100).then( data => { expect(data).toBe(10000); done(); }, error => { done(); } ); } ); it('getDecimalSquare', (done) => { service.getDecimalSquare(100).then( data => { expect(data).toBe(10000); done(); }, error => { done(); } ); } ); it('getDateTime', (done) => { service.getDateTime(true).then( data => { expect(data).toBeDefined(); done(); }, error => { done(); } ); } ); it('getDateTimeNull', (done) => { service.getDateTime(false).then( data => { expect(data).toBeNull();// Aurelia httpclient throws error upon 204. done(); }, error => { expect(true).toBeTruthy(); done(); } ); } ); it('getNullableDecimal', (done) => { service.getNullableDecimal(true).then( data => { expect(data).toBeGreaterThan(10); done(); }, error => { done(); } ); } ); it('getNullableDecimalNull', (done) => { service.getNullableDecimal(false).then( data => { expect(data).toBeNull(); //aurelia httpclient throws empty error while the service is returning 204 done(); }, error => { console.debug('getNullableDecimalNull: '+ JSON.stringify(error)); expect(true).toBeTruthy(); done(); } ); } ); it('getNullString', (done) => { service.getNullString().then( data => { forDotNetCore? expect(data).toBe(''):expect(data).toBeNull(); done(); }, error => { done(); } ); } ); it('getNullPerson', (done) => { service.getNullPerson().then( data => { expect(data).toBeNull(); //Aurelia httpclient throws error upon service statuscode 204 //expect(data).toBe(''); // .net core return 204 nocontent empty body done(); }, error => { expect(true).toBeTruthy(); done(); } ); } ); it('getByteArray', (done) => { service.getByteArray().then( data => { expect(data.length).toBeGreaterThan(0); done(); }, error => { done(); } ); } ); it('getTextStream', (done) => { service.getTextStream().then( data => { console.debug('getTextStream'); console.debug(data); // abcdefg expect(data.size).toBe(7); const reader = new FileReader();//axios actually give string rather than a blob structure reader.onload = () => { expect(reader.result).toBe('abcdefg'); }; reader.readAsText(data); done(); }, error => { done(); } ); } ); it('getActionResult', (done) => { service.getActionResult().then( data => { expect(data).toBe('abcdefg'); done(); }, error => { done(); } ); } ); it('getbyte', (done) => { service.getbyte().then( data => { expect(data).toEqual(255); done(); }, error => { done(); } ); } ); it('getActionStringResult', (done) => { service.getActionStringResult().then( data => { expect(data).toContain('abcdefg'); done(); }, error => { done(); } ); } ); it('getChar', (done) => { service.getChar().then( data => { expect(data).toBe('A'); done(); }, error => { done(); } ); } ); it('getDecimal', (done) => { service.getDecimal().then( data => { expect(data).toBe(79228162514264337593543950335); done(); }, error => { done(); } ); } ); it('getdouble', (done) => { service.getdouble().then( data => { expect(data).toBe(-1.7976931348623e308); done(); }, error => { done(); } ); } ); it('getUint', (done) => { service.getUint().then( data => { expect(data).toBe(4294967295); done(); }, error => { done(); } ); } ); it('getulong', (done) => { service.getulong().then( data => { expect(data).toBe(18446744073709551615); done(); }, error => { done(); } ); } ); it('getInt2D', (done) => { service.getInt2D().then( data => { expect(data[0][0]).toBe(1); expect(data[0][3]).toBe(4); expect(data[1][0]).toBe(5); expect(data[1][3]).toBe(8); done(); }, error => { done(); } ); } ); it('getInt2DJagged', (done) => { service.getInt2DJagged().then( data => { expect(data[0][0]).toBe(1); expect(data[0][3]).toBe(4); expect(data[1][0]).toBe(5); expect(data[1][3]).toBe(8); done(); }, error => { done(); } ); } ); it('postInt2D', (done) => { service.postInt2D([[1, 2, 3, 4], [5, 6, 7, 8]]).then( data => { expect(data).toBeTruthy(); done(); }, error => { done(); } ); } ); it('postIntArray', (done) => { service.postIntArray([1, 2, 3, 4, 5, 6, 7, 8]).then( data => { expect(data).toBeTruthy(); done(); }, error => { done(); } ); } ); it('getIntArrayQ', (done) => { service.getIntArrayQ([6, 7, 8]).then( data => { expect(data.length).toBe(3); expect(data[2]).toBe(8); done(); }, error => { done(); } ); } ); it('postDay', (done) => { service.postDay(namespaces.DemoWebApi_DemoData_Client.Days.Fri, namespaces.DemoWebApi_DemoData_Client.Days.Mon).then( data => { expect(data.length).toBe(2); expect(data[1]).toBe(namespaces.DemoWebApi_DemoData_Client.Days.Mon); done(); }, error => { done(); } ); } ); it('postWithQueryButEmptyBody', (done) => { service.postWithQueryButEmptyBody('abc', 123).then( data => { expect(data.item1).toBe('abc'); expect(data.item2).toBe(123); done(); }, error => { done(); } ); } ); it('getDictionaryOfPeople', (done) => { service.getDictionaryOfPeople().then( data => { let p = data['spider Man']; //ASP.NET Web API with NewtonSoftJson made it camcel; if (!p) { p = data['Spider Man']; //.NET Core is OK } expect(p.name).toBe('Peter Parker'); expect(p.addresses[0].city).toBe('New York'); done(); }, error => { done(); } ); } ); it('PostDictionaryOfPeople', (done) => { service.postDictionary({ 'Iron Man': { 'surname': 'Stark', 'givenName': 'Tony', 'dob': null, 'id': '00000000-0000-0000-0000-000000000000', 'name': 'Tony Stark', 'addresses': [] }, 'Spider Man': { 'name': 'Peter Parker', 'addresses': [ { 'id': '00000000-0000-0000-0000-000000000000', 'city': 'New York', state: 'Somewhere', 'postalCode': null, 'country': null, 'type': 0, location: { x: 100, y: 200 } } ] } }).then( data => { expect(data).toBe(2); done(); }, error => { done(); } ); } ); it('getKeyhValuePair', (done) => { service.getKeyhValuePair().then( data => { expect(data.key).toBe('Spider Man'); expect(data.value.addresses[0].city).toBe('New York'); done(); }, error => { done(); } ); } ); it('getBool', (done) => { service.getBool().then( data => { expect(data).toBeTruthy(); done(); }, error => { done(); } ); } ); it('getNextYearNullable', (done) => { let now = new Date(Date.now()); service.getNextYearNullable(2, now).then( data => { const m = moment(data); let dt = m.toDate(); expect(dt.getFullYear()).toEqual(now.getFullYear() + 2); done(); }, error => { done(); } ); } ); it('getNextHourNullable', (done) => { let now = new Date(Date.now()); service.getNextHourNullable(2, now).then( data => { const m = moment(data); let dt = m.toDate(); expect(dt.getHours() % 24).toEqual((now.getHours() + 2) % 24) done(); }, error => { done(); } ); } ); it('getNextYearNullable2', (done) => { let now = new Date(Date.now()); service.getNextYearNullable(2, undefined).then( data => { const m = moment(data); let dt = m.toDate(); expect(dt.getFullYear()).toEqual(now.getFullYear() + 2); done(); }, error => { done(); } ); } ); it('getNextHourNullable2', (done) => { let now = new Date(Date.now()); service.getNextHourNullable(2, null).then( data => { const m = moment(data); let dt = m.toDate(); expect(dt.getHours()%24).toEqual((now.getHours() + 2)%24) done(); }, error => { done(); } ); } ); it('searchDateRange', (done) => { let startDt = new Date(Date.now()); let endDt = new Date(Date.now() + 100000); service.searchDateRange(startDt, endDt).then( data => { const m1 = moment(data.item1); const m2 = moment(data.item2); expect(m1.toDate()).toEqual(startDt); expect(m2.toDate()).toEqual(endDt); done(); }, error => { done(); } ); } ); it('searchDateRangeEndUndefined', (done) => { let startDt = new Date(Date.now()); let endDt = new Date(Date.now() + 100000); service.searchDateRange(startDt, undefined).then( data => { const m1 = moment(data.item1); expect(m1.toDate()).toEqual(startDt); expect(data.item2).toBeNull(); //OK with null rather than undefined done(); }, error => { done(); } ); } ); it('searchDateRangeStartUndefined', (done) => { let startDt = new Date(Date.now()); let endDt = new Date(Date.now() + 100000); service.searchDateRange(undefined, endDt).then( data => { //fail('The API should return http 400 error.'); in .net core 2.0, the service return status 400. Apparently this was a bug which was fixed in 2.1 forDotNetCore?expect(data.item1).toBeNull():expect(data.item1).toBeUndefined(); const m = moment(data.item2); expect(m.toDate().getHours()).toEqual(endDt.getHours()); done(); }, error => { // let errorText = errorResponseToString(error); // if (errorText.indexOf('400') < 0) { // fail(errorText); // } expect(true).toBeTruthy(); done(); } ); } ); it('searchDateRangeBotNull', (done) => { let startDt = new Date(Date.now()); let endDt = new Date(Date.now() + 100000); service.searchDateRange(null, undefined).then( data => { expect(data.item1).toBeNull(); expect(data.item1).toBeNull(); done(); }, error => { done(); } ); } ); });
the_stack
import type {Directive, DirectiveResult, PartInfo} from './directive.js'; const DEV_MODE = true; const ENABLE_EXTRA_SECURITY_HOOKS = true; const ENABLE_SHADYDOM_NOPATCH = true; /** * `true` if we're building for google3 with temporary back-compat helpers. * This export is not present in prod builds. * @internal */ export const INTERNAL = true; let issueWarning: (code: string, warning: string) => void; if (DEV_MODE) { globalThis.litIssuedWarnings ??= new Set(); // Issue a warning, if we haven't already. issueWarning = (code: string, warning: string) => { warning += code ? ` See https://lit.dev/msg/${code} for more information.` : ''; if (!globalThis.litIssuedWarnings!.has(warning)) { console.warn(warning); globalThis.litIssuedWarnings!.add(warning); } }; issueWarning( 'dev-mode', `Lit is in dev mode. Not recommended for production!` ); } const wrap = ENABLE_SHADYDOM_NOPATCH && window.ShadyDOM?.inUse && window.ShadyDOM?.noPatch === true ? window.ShadyDOM!.wrap : (node: Node) => node; const trustedTypes = (globalThis as unknown as Partial<Window>).trustedTypes; /** * Our TrustedTypePolicy for HTML which is declared using the html template * tag function. * * That HTML is a developer-authored constant, and is parsed with innerHTML * before any untrusted expressions have been mixed in. Therefor it is * considered safe by construction. */ const policy = trustedTypes ? trustedTypes.createPolicy('lit-html', { createHTML: (s) => s, }) : undefined; /** * Used to sanitize any value before it is written into the DOM. This can be * used to implement a security policy of allowed and disallowed values in * order to prevent XSS attacks. * * One way of using this callback would be to check attributes and properties * against a list of high risk fields, and require that values written to such * fields be instances of a class which is safe by construction. Closure's Safe * HTML Types is one implementation of this technique ( * https://github.com/google/safe-html-types/blob/master/doc/safehtml-types.md). * The TrustedTypes polyfill in API-only mode could also be used as a basis * for this technique (https://github.com/WICG/trusted-types). * * @param node The HTML node (usually either a #text node or an Element) that * is being written to. Note that this is just an exemplar node, the write * may take place against another instance of the same class of node. * @param name The name of an attribute or property (for example, 'href'). * @param type Indicates whether the write that's about to be performed will * be to a property or a node. * @return A function that will sanitize this class of writes. */ export type SanitizerFactory = ( node: Node, name: string, type: 'property' | 'attribute' ) => ValueSanitizer; /** * A function which can sanitize values that will be written to a specific kind * of DOM sink. * * See SanitizerFactory. * * @param value The value to sanitize. Will be the actual value passed into * the lit-html template literal, so this could be of any type. * @return The value to write to the DOM. Usually the same as the input value, * unless sanitization is needed. */ export type ValueSanitizer = (value: unknown) => unknown; const identityFunction: ValueSanitizer = (value: unknown) => value; const noopSanitizer: SanitizerFactory = ( _node: Node, _name: string, _type: 'property' | 'attribute' ) => identityFunction; /** Sets the global sanitizer factory. */ const setSanitizer = (newSanitizer: SanitizerFactory) => { if (!ENABLE_EXTRA_SECURITY_HOOKS) { return; } if (sanitizerFactoryInternal !== noopSanitizer) { throw new Error( `Attempted to overwrite existing lit-html security policy.` + ` setSanitizeDOMValueFactory should be called at most once.` ); } sanitizerFactoryInternal = newSanitizer; }; /** * Only used in internal tests, not a part of the public API. */ const _testOnlyClearSanitizerFactoryDoNotCallOrElse = () => { sanitizerFactoryInternal = noopSanitizer; }; const createSanitizer: SanitizerFactory = (node, name, type) => { return sanitizerFactoryInternal(node, name, type); }; // Added to an attribute name to mark the attribute as bound so we can find // it easily. const boundAttributeSuffix = '$lit$'; // This marker is used in many syntactic positions in HTML, so it must be // a valid element name and attribute name. We don't support dynamic names (yet) // but this at least ensures that the parse tree is closer to the template // intention. const marker = `lit$${String(Math.random()).slice(9)}$`; // String used to tell if a comment is a marker comment const markerMatch = '?' + marker; // Text used to insert a comment marker node. We use processing instruction // syntax because it's slightly smaller, but parses as a comment node. const nodeMarker = `<${markerMatch}>`; const d = document; // Creates a dynamic marker. We never have to search for these in the DOM. const createMarker = (v = '') => d.createComment(v); // https://tc39.github.io/ecma262/#sec-typeof-operator type Primitive = null | undefined | boolean | number | string | symbol | bigint; const isPrimitive = (value: unknown): value is Primitive => value === null || (typeof value != 'object' && typeof value != 'function'); const isArray = Array.isArray; const isIterable = (value: unknown): value is Iterable<unknown> => isArray(value) || // eslint-disable-next-line @typescript-eslint/no-explicit-any typeof (value as any)?.[Symbol.iterator] === 'function'; const SPACE_CHAR = `[ \t\n\f\r]`; const ATTR_VALUE_CHAR = `[^ \t\n\f\r"'\`<>=]`; const NAME_CHAR = `[^\\s"'>=/]`; // These regexes represent the five parsing states that we care about in the // Template's HTML scanner. They match the *end* of the state they're named // after. // Depending on the match, we transition to a new state. If there's no match, // we stay in the same state. // Note that the regexes are stateful. We utilize lastIndex and sync it // across the multiple regexes used. In addition to the five regexes below // we also dynamically create a regex to find the matching end tags for raw // text elements. /** * End of text is: `<` followed by: * (comment start) or (tag) or (dynamic tag binding) */ const textEndRegex = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g; const COMMENT_START = 1; const TAG_NAME = 2; const DYNAMIC_TAG_NAME = 3; const commentEndRegex = /-->/g; /** * Comments not started with <!--, like </{, can be ended by a single `>` */ const comment2EndRegex = />/g; /** * The tagEnd regex matches the end of the "inside an opening" tag syntax * position. It either matches a `>`, an attribute-like sequence, or the end * of the string after a space (attribute-name position ending). * * See attributes in the HTML spec: * https://www.w3.org/TR/html5/syntax.html#elements-attributes * * " \t\n\f\r" are HTML space characters: * https://infra.spec.whatwg.org/#ascii-whitespace * * So an attribute is: * * The name: any character except a whitespace character, ("), ('), ">", * "=", or "/". Note: this is different from the HTML spec which also excludes control characters. * * Followed by zero or more space characters * * Followed by "=" * * Followed by zero or more space characters * * Followed by: * * Any character except space, ('), ("), "<", ">", "=", (`), or * * (") then any non-("), or * * (') then any non-(') */ const tagEndRegex = new RegExp( `>|${SPACE_CHAR}(?:(${NAME_CHAR}+)(${SPACE_CHAR}*=${SPACE_CHAR}*(?:${ATTR_VALUE_CHAR}|("|')|))|$)`, 'g' ); const ENTIRE_MATCH = 0; const ATTRIBUTE_NAME = 1; const SPACES_AND_EQUALS = 2; const QUOTE_CHAR = 3; const singleQuoteAttrEndRegex = /'/g; const doubleQuoteAttrEndRegex = /"/g; /** * Matches the raw text elements. * * Comments are not parsed within raw text elements, so we need to search their * text content for marker strings. */ const rawTextElement = /^(?:script|style|textarea)$/i; /** TemplateResult types */ const HTML_RESULT = 1; const SVG_RESULT = 2; type ResultType = typeof HTML_RESULT | typeof SVG_RESULT; // TemplatePart types // IMPORTANT: these must match the values in PartType const ATTRIBUTE_PART = 1; const CHILD_PART = 2; const PROPERTY_PART = 3; const BOOLEAN_ATTRIBUTE_PART = 4; const EVENT_PART = 5; const ELEMENT_PART = 6; const COMMENT_PART = 7; /** * The return type of the template tag functions. */ export type TemplateResult<T extends ResultType = ResultType> = { // This property needs to remain unminified. ['_$litType$']: T; strings: TemplateStringsArray; values: unknown[]; }; export type HTMLTemplateResult = TemplateResult<typeof HTML_RESULT>; export type SVGTemplateResult = TemplateResult<typeof SVG_RESULT>; export interface CompiledTemplateResult { // This is a factory in order to make template initialization lazy // and allow ShadyRenderOptions scope to be passed in. // This property needs to remain unminified. ['_$litType$']: CompiledTemplate; values: unknown[]; } export interface CompiledTemplate extends Omit<Template, 'el'> { // el is overridden to be optional. We initialize it on first render el?: HTMLTemplateElement; // The prepared HTML string to create a template element from. h: TrustedHTML; } /** * Generates a template literal tag function that returns a TemplateResult with * the given result type. */ const tag = <T extends ResultType>(type: T) => (strings: TemplateStringsArray, ...values: unknown[]): TemplateResult<T> => { // Warn against templates octal escape sequences // We do this here rather than in render so that the warning is closer to the // template definition. if (DEV_MODE && strings.some((s) => s === undefined)) { console.warn( 'Some template strings are undefined.\n' + 'This is probably caused by illegal octal escape sequences.' ); } return { // This property needs to remain unminified. ['_$litType$']: type, strings, values, }; }; /** * Interprets a template literal as an HTML template that can efficiently * render to and update a container. * * ```ts * const header = (title: string) => html`<h1>${title}</h1>`; * ``` * * The `html` tag returns a description of the DOM to render as a value. It is * lazy, meaning no work is done until the template is rendered. When rendering, * if a template comes from the same expression as a previously rendered result, * it's efficiently updated instead of replaced. */ export const html = tag(HTML_RESULT); /** * Interprets a template literal as an SVG template that can efficiently * render to and update a container. */ export const svg = tag(SVG_RESULT); /** * A sentinel value that signals that a value was handled by a directive and * should not be written to the DOM. */ export const noChange = Symbol.for('lit-noChange'); /** * A sentinel value that signals a ChildPart to fully clear its content. * * ```ts * const button = html`${ * user.isAdmin * ? html`<button>DELETE</button>` * : nothing * }`; * ``` * * Prefer using `nothing` over other falsy values as it provides a consistent * behavior between various expression binding contexts. * * In child expressions, `undefined`, `null`, `''`, and `nothing` all behave the * same and render no nodes. In attribute expressions, `nothing` _removes_ the * attribute, while `undefined` and `null` will render an empty string. In * property expressions `nothing` becomes `undefined`. */ export const nothing = Symbol.for('lit-nothing'); /** * The cache of prepared templates, keyed by the tagged TemplateStringsArray * and _not_ accounting for the specific template tag used. This means that * template tags cannot be dynamic - the must statically be one of html, svg, * or attr. This restriction simplifies the cache lookup, which is on the hot * path for rendering. */ const templateCache = new WeakMap<TemplateStringsArray, Template>(); /** * Object specifying options for controlling lit-html rendering. Note that * while `render` may be called multiple times on the same `container` (and * `renderBefore` reference node) to efficiently update the rendered content, * only the options passed in during the first render are respected during * the lifetime of renders to that unique `container` + `renderBefore` * combination. */ export interface RenderOptions { /** * An object to use as the `this` value for event listeners. It's often * useful to set this to the host component rendering a template. */ host?: object; /** * A DOM node before which to render content in the container. */ renderBefore?: ChildNode | null; /** * Node used for cloning the template (`importNode` will be called on this * node). This controls the `ownerDocument` of the rendered DOM, along with * any inherited context. Defaults to the global `document`. */ creationScope?: {importNode(node: Node, deep?: boolean): Node}; /** * The initial connected state for the top-level part being rendered. If no * `isConnected` option is set, `AsyncDirective`s will be connected by * default. Set to `false` if the initial render occurs in a disconnected tree * and `AsyncDirective`s should see `isConnected === false` for their initial * render. The `part.setConnected()` method must be used subsequent to initial * render to change the connected state of the part. */ isConnected?: boolean; } /** * Internally we can export this interface and change the type of * render()'s options. */ interface InternalRenderOptions extends RenderOptions { /** * An internal-only migration flag * @internal */ clearContainerForLit2MigrationOnly?: boolean; } /** * Renders a value, usually a lit-html TemplateResult, to the container. * @param value * @param container * @param options */ export const render = ( value: unknown, container: HTMLElement | DocumentFragment, options?: RenderOptions ): RootPart => { const partOwnerNode = options?.renderBefore ?? container; // This property needs to remain unminified. // eslint-disable-next-line @typescript-eslint/no-explicit-any let part: ChildPart = (partOwnerNode as any)['_$litPart$']; if (part === undefined) { const endNode = options?.renderBefore ?? null; // Internal modification: don't clear container to match lit-html 2.0 if ( INTERNAL && (options as InternalRenderOptions)?.clearContainerForLit2MigrationOnly === true ) { let n = container.firstChild; // Clear only up to the `endNode` aka `renderBefore` node. while (n && n !== endNode) { const next = n.nextSibling; n.remove(); n = next; } } // This property needs to remain unminified. // eslint-disable-next-line @typescript-eslint/no-explicit-any (partOwnerNode as any)['_$litPart$'] = part = new ChildPart( container.insertBefore(createMarker(), endNode), endNode, undefined, options ?? {} ); } part._$setValue(value); return part as RootPart; }; if (ENABLE_EXTRA_SECURITY_HOOKS) { render.setSanitizer = setSanitizer; render.createSanitizer = createSanitizer; if (DEV_MODE) { render._testOnlyClearSanitizerFactoryDoNotCallOrElse = _testOnlyClearSanitizerFactoryDoNotCallOrElse; } } const walker = d.createTreeWalker( d, 129 /* NodeFilter.SHOW_{ELEMENT|COMMENT} */, null, false ); let sanitizerFactoryInternal: SanitizerFactory = noopSanitizer; // // Classes only below here, const variable declarations only above here... // // Keeping variable declarations and classes together improves minification. // Interfaces and type aliases can be interleaved freely. // // Type for classes that have a `_directive` or `_directives[]` field, used by // `resolveDirective` export interface DirectiveParent { _$parent?: DirectiveParent; _$isConnected: boolean; __directive?: Directive; __directives?: Array<Directive | undefined>; } /** * Returns an HTML string for the given TemplateStringsArray and result type * (HTML or SVG), along with the case-sensitive bound attribute names in * template order. The HTML contains comment comment markers denoting the * `ChildPart`s and suffixes on bound attributes denoting the `AttributeParts`. * * @param strings template strings array * @param type HTML or SVG * @return Array containing `[html, attrNames]` (array returned for terseness, * to avoid object fields since this code is shared with non-minified SSR * code) */ const getTemplateHtml = ( strings: TemplateStringsArray, type: ResultType ): [TrustedHTML, Array<string | undefined>] => { // Insert makers into the template HTML to represent the position of // bindings. The following code scans the template strings to determine the // syntactic position of the bindings. They can be in text position, where // we insert an HTML comment, attribute value position, where we insert a // sentinel string and re-write the attribute name, or inside a tag where // we insert the sentinel string. const l = strings.length - 1; // Stores the case-sensitive bound attribute names in the order of their // parts. ElementParts are also reflected in this array as undefined // rather than a string, to disambiguate from attribute bindings. const attrNames: Array<string | undefined> = []; let html = type === SVG_RESULT ? '<svg>' : ''; // When we're inside a raw text tag (not it's text content), the regex // will still be tagRegex so we can find attributes, but will switch to // this regex when the tag ends. let rawTextEndRegex: RegExp | undefined; // The current parsing state, represented as a reference to one of the // regexes let regex = textEndRegex; for (let i = 0; i < l; i++) { const s = strings[i]; // The index of the end of the last attribute name. When this is // positive at end of a string, it means we're in an attribute value // position and need to rewrite the attribute name. // We also use a special value of -2 to indicate that we encountered // the end of a string in attribute name position. let attrNameEndIndex = -1; let attrName: string | undefined; let lastIndex = 0; let match!: RegExpExecArray | null; // The conditions in this loop handle the current parse state, and the // assignments to the `regex` variable are the state transitions. while (lastIndex < s.length) { // Make sure we start searching from where we previously left off regex.lastIndex = lastIndex; match = regex.exec(s); if (match === null) { break; } lastIndex = regex.lastIndex; if (regex === textEndRegex) { if (match[COMMENT_START] === '!--') { regex = commentEndRegex; } else if (match[COMMENT_START] !== undefined) { // We started a weird comment, like </{ regex = comment2EndRegex; } else if (match[TAG_NAME] !== undefined) { if (rawTextElement.test(match[TAG_NAME])) { // Record if we encounter a raw-text element. We'll switch to // this regex at the end of the tag. rawTextEndRegex = new RegExp(`</${match[TAG_NAME]}`, 'g'); } regex = tagEndRegex; } else if (match[DYNAMIC_TAG_NAME] !== undefined) { if (DEV_MODE) { throw new Error( 'Bindings in tag names are not supported. Please use static templates instead. ' + 'See https://lit.dev/docs/templates/expressions/#static-expressions' ); } regex = tagEndRegex; } } else if (regex === tagEndRegex) { if (match[ENTIRE_MATCH] === '>') { // End of a tag. If we had started a raw-text element, use that // regex regex = rawTextEndRegex ?? textEndRegex; // We may be ending an unquoted attribute value, so make sure we // clear any pending attrNameEndIndex attrNameEndIndex = -1; } else if (match[ATTRIBUTE_NAME] === undefined) { // Attribute name position attrNameEndIndex = -2; } else { attrNameEndIndex = regex.lastIndex - match[SPACES_AND_EQUALS].length; attrName = match[ATTRIBUTE_NAME]; regex = match[QUOTE_CHAR] === undefined ? tagEndRegex : match[QUOTE_CHAR] === '"' ? doubleQuoteAttrEndRegex : singleQuoteAttrEndRegex; } } else if ( regex === doubleQuoteAttrEndRegex || regex === singleQuoteAttrEndRegex ) { regex = tagEndRegex; } else if (regex === commentEndRegex || regex === comment2EndRegex) { regex = textEndRegex; } else { // Not one of the five state regexes, so it must be the dynamically // created raw text regex and we're at the close of that element. regex = tagEndRegex; rawTextEndRegex = undefined; } } if (DEV_MODE) { // If we have a attrNameEndIndex, which indicates that we should // rewrite the attribute name, assert that we're in a valid attribute // position - either in a tag, or a quoted attribute value. console.assert( attrNameEndIndex === -1 || regex === tagEndRegex || regex === singleQuoteAttrEndRegex || regex === doubleQuoteAttrEndRegex, 'unexpected parse state B' ); } // We have four cases: // 1. We're in text position, and not in a raw text element // (regex === textEndRegex): insert a comment marker. // 2. We have a non-negative attrNameEndIndex which means we need to // rewrite the attribute name to add a bound attribute suffix. // 3. We're at the non-first binding in a multi-binding attribute, use a // plain marker. // 4. We're somewhere else inside the tag. If we're in attribute name // position (attrNameEndIndex === -2), add a sequential suffix to // generate a unique attribute name. // Detect a binding next to self-closing tag end and insert a space to // separate the marker from the tag end: const end = regex === tagEndRegex && strings[i + 1].startsWith('/>') ? ' ' : ''; html += regex === textEndRegex ? s + nodeMarker : attrNameEndIndex >= 0 ? (attrNames.push(attrName!), s.slice(0, attrNameEndIndex) + boundAttributeSuffix + s.slice(attrNameEndIndex)) + marker + end : s + marker + (attrNameEndIndex === -2 ? (attrNames.push(undefined), i) : end); } const htmlResult: string | TrustedHTML = html + (strings[l] || '<?>') + (type === SVG_RESULT ? '</svg>' : ''); // Returned as an array for terseness return [ policy !== undefined ? policy.createHTML(htmlResult) : (htmlResult as unknown as TrustedHTML), attrNames, ]; }; /** @internal */ export type {Template}; class Template { /** @internal */ el!: HTMLTemplateElement; /** @internal */ parts: Array<TemplatePart> = []; constructor( // This property needs to remain unminified. {strings, ['_$litType$']: type}: TemplateResult, options?: RenderOptions ) { let node: Node | null; let nodeIndex = 0; let attrNameIndex = 0; const partCount = strings.length - 1; const parts = this.parts; // Create template element const [html, attrNames] = getTemplateHtml(strings, type); this.el = Template.createElement(html, options); walker.currentNode = this.el.content; // Reparent SVG nodes into template root if (type === SVG_RESULT) { const content = this.el.content; const svgElement = content.firstChild!; svgElement.remove(); content.append(...svgElement.childNodes); } // Walk the template to find binding markers and create TemplateParts while ((node = walker.nextNode()) !== null && parts.length < partCount) { if (node.nodeType === 1) { if (DEV_MODE) { const tag = (node as Element).localName; // Warn if `textarea` includes an expression and throw if `template` // does since these are not supported. We do this by checking // innerHTML for anything that looks like a marker. This catches // cases like bindings in textarea there markers turn into text nodes. if ( /^(?:textarea|template)$/i!.test(tag) && (node as Element).innerHTML.includes(marker) ) { const m = `Expressions are not supported inside \`${tag}\` ` + `elements. See https://lit.dev/msg/expression-in-${tag} for more ` + `information.`; if (tag === 'template') { throw new Error(m); } else issueWarning('', m); } } // TODO (justinfagnani): for attempted dynamic tag names, we don't // increment the bindingIndex, and it'll be off by 1 in the element // and off by two after it. if ((node as Element).hasAttributes()) { // We defer removing bound attributes because on IE we might not be // iterating attributes in their template order, and would sometimes // remove an attribute that we still need to create a part for. const attrsToRemove = []; for (const name of (node as Element).getAttributeNames()) { // `name` is the name of the attribute we're iterating over, but not // _neccessarily_ the name of the attribute we will create a part // for. They can be different in browsers that don't iterate on // attributes in source order. In that case the attrNames array // contains the attribute name we'll process next. We only need the // attribute name here to know if we should process a bound attribute // on this element. if ( name.endsWith(boundAttributeSuffix) || name.startsWith(marker) ) { const realName = attrNames[attrNameIndex++]; attrsToRemove.push(name); if (realName !== undefined) { // Lowercase for case-sensitive SVG attributes like viewBox const value = (node as Element).getAttribute( realName.toLowerCase() + boundAttributeSuffix )!; const statics = value.split(marker); const m = /([.?@])?(.*)/.exec(realName)!; parts.push({ type: ATTRIBUTE_PART, index: nodeIndex, name: m[2], strings: statics, ctor: m[1] === '.' ? PropertyPart : m[1] === '?' ? BooleanAttributePart : m[1] === '@' ? EventPart : AttributePart, }); } else { parts.push({ type: ELEMENT_PART, index: nodeIndex, }); } } } for (const name of attrsToRemove) { (node as Element).removeAttribute(name); } } // TODO (justinfagnani): benchmark the regex against testing for each // of the 3 raw text element names. if (rawTextElement.test((node as Element).tagName)) { // For raw text elements we need to split the text content on // markers, create a Text node for each segment, and create // a TemplatePart for each marker. const strings = (node as Element).textContent!.split(marker); const lastIndex = strings.length - 1; if (lastIndex > 0) { (node as Element).textContent = trustedTypes ? (trustedTypes.emptyScript as unknown as '') : ''; // Generate a new text node for each literal section // These nodes are also used as the markers for node parts // We can't use empty text nodes as markers because they're // normalized when cloning in IE (could simplify when // IE is no longer supported) for (let i = 0; i < lastIndex; i++) { (node as Element).append(strings[i], createMarker()); // Walk past the marker node we just added walker.nextNode(); parts.push({type: CHILD_PART, index: ++nodeIndex}); } // Note because this marker is added after the walker's current // node, it will be walked to in the outer loop (and ignored), so // we don't need to adjust nodeIndex here (node as Element).append(strings[lastIndex], createMarker()); } } } else if (node.nodeType === 8) { const data = (node as Comment).data; if (data === markerMatch) { parts.push({type: CHILD_PART, index: nodeIndex}); } else { let i = -1; while ((i = (node as Comment).data.indexOf(marker, i + 1)) !== -1) { // Comment node has a binding marker inside, make an inactive part // The binding won't work, but subsequent bindings will parts.push({type: COMMENT_PART, index: nodeIndex}); // Move to the end of the match i += marker.length - 1; } } } nodeIndex++; } } // Overridden via `litHtmlPolyfillSupport` to provide platform support. /** @nocollapse */ static createElement(html: TrustedHTML, _options?: RenderOptions) { const el = d.createElement('template'); el.innerHTML = html as unknown as string; return el; } } export interface Disconnectable { _$parent?: Disconnectable; _$disconnectableChildren?: Set<Disconnectable>; // Rather than hold connection state on instances, Disconnectables recursively // fetch the connection state from the RootPart they are connected in via // getters up the Disconnectable tree via _$parent references. This pushes the // cost of tracking the isConnected state to `AsyncDirectives`, and avoids // needing to pass all Disconnectables (parts, template instances, and // directives) their connection state each time it changes, which would be // costly for trees that have no AsyncDirectives. _$isConnected: boolean; } function resolveDirective( part: ChildPart | AttributePart | ElementPart, value: unknown, parent: DirectiveParent = part, attributeIndex?: number ): unknown { // Bail early if the value is explicitly noChange. Note, this means any // nested directive is still attached and is not run. if (value === noChange) { return value; } let currentDirective = attributeIndex !== undefined ? (parent as AttributePart).__directives?.[attributeIndex] : (parent as ChildPart | ElementPart | Directive).__directive; const nextDirectiveConstructor = isPrimitive(value) ? undefined : // This property needs to remain unminified. (value as DirectiveResult)['_$litDirective$']; if (currentDirective?.constructor !== nextDirectiveConstructor) { // This property needs to remain unminified. currentDirective?.['_$notifyDirectiveConnectionChanged']?.(false); if (nextDirectiveConstructor === undefined) { currentDirective = undefined; } else { currentDirective = new nextDirectiveConstructor(part as PartInfo); currentDirective._$initialize(part, parent, attributeIndex); } if (attributeIndex !== undefined) { ((parent as AttributePart).__directives ??= [])[attributeIndex] = currentDirective; } else { (parent as ChildPart | Directive).__directive = currentDirective; } } if (currentDirective !== undefined) { value = resolveDirective( part, currentDirective._$resolve(part, (value as DirectiveResult).values), currentDirective, attributeIndex ); } return value; } /** * An updateable instance of a Template. Holds references to the Parts used to * update the template instance. */ class TemplateInstance implements Disconnectable { /** @internal */ _$template: Template; /** @internal */ _parts: Array<Part | undefined> = []; /** @internal */ _$parent: ChildPart; /** @internal */ _$disconnectableChildren?: Set<Disconnectable> = undefined; constructor(template: Template, parent: ChildPart) { this._$template = template; this._$parent = parent; } // Called by ChildPart parentNode getter get parentNode() { return this._$parent.parentNode; } // See comment in Disconnectable interface for why this is a getter get _$isConnected() { return this._$parent._$isConnected; } // This method is separate from the constructor because we need to return a // DocumentFragment and we don't want to hold onto it with an instance field. _clone(options: RenderOptions | undefined) { const { el: {content}, parts: parts, } = this._$template; const fragment = (options?.creationScope ?? d).importNode(content, true); walker.currentNode = fragment; let node = walker.nextNode()!; let nodeIndex = 0; let partIndex = 0; let templatePart = parts[0]; while (templatePart !== undefined) { if (nodeIndex === templatePart.index) { let part: Part | undefined; if (templatePart.type === CHILD_PART) { part = new ChildPart( node as HTMLElement, node.nextSibling, this, options ); } else if (templatePart.type === ATTRIBUTE_PART) { part = new templatePart.ctor( node as HTMLElement, templatePart.name, templatePart.strings, this, options ); } else if (templatePart.type === ELEMENT_PART) { part = new ElementPart(node as HTMLElement, this, options); } this._parts.push(part); templatePart = parts[++partIndex]; } if (nodeIndex !== templatePart?.index) { node = walker.nextNode()!; nodeIndex++; } } return fragment; } _update(values: Array<unknown>) { let i = 0; for (const part of this._parts) { if (part !== undefined) { if ((part as AttributePart).strings !== undefined) { (part as AttributePart)._$setValue(values, part as AttributePart, i); // The number of values the part consumes is part.strings.length - 1 // since values are in between template spans. We increment i by 1 // later in the loop, so increment it by part.strings.length - 2 here i += (part as AttributePart).strings!.length - 2; } else { part._$setValue(values[i]); } } i++; } } } /* * Parts */ type AttributeTemplatePart = { readonly type: typeof ATTRIBUTE_PART; readonly index: number; readonly name: string; /** @internal */ readonly ctor: typeof AttributePart; /** @internal */ readonly strings: ReadonlyArray<string>; }; type NodeTemplatePart = { readonly type: typeof CHILD_PART; readonly index: number; }; type ElementTemplatePart = { readonly type: typeof ELEMENT_PART; readonly index: number; }; type CommentTemplatePart = { readonly type: typeof COMMENT_PART; readonly index: number; }; /** * A TemplatePart represents a dynamic part in a template, before the template * is instantiated. When a template is instantiated Parts are created from * TemplateParts. */ type TemplatePart = | NodeTemplatePart | AttributeTemplatePart | ElementTemplatePart | CommentTemplatePart; export type Part = | ChildPart | AttributePart | PropertyPart | BooleanAttributePart | ElementPart | EventPart; export type {ChildPart}; class ChildPart implements Disconnectable { readonly type = CHILD_PART; readonly options: RenderOptions | undefined; _$committedValue: unknown = nothing; /** @internal */ __directive?: Directive; /** @internal */ _$startNode: ChildNode; /** @internal */ _$endNode: ChildNode | null; private _textSanitizer: ValueSanitizer | undefined; /** @internal */ _$parent: Disconnectable | undefined; /** * Connection state for RootParts only (i.e. ChildPart without _$parent * returned from top-level `render`). This field is unsed otherwise. The * intention would clearer if we made `RootPart` a subclass of `ChildPart` * with this field (and a different _$isConnected getter), but the subclass * caused a perf regression, possibly due to making call sites polymorphic. * @internal */ __isConnected: boolean; // See comment in Disconnectable interface for why this is a getter get _$isConnected() { // ChildParts that are not at the root should always be created with a // parent; only RootChildNode's won't, so they return the local isConnected // state return this._$parent?._$isConnected ?? this.__isConnected; } // The following fields will be patched onto ChildParts when required by // AsyncDirective /** @internal */ _$disconnectableChildren?: Set<Disconnectable> = undefined; /** @internal */ _$notifyConnectionChanged?( isConnected: boolean, removeFromParent?: boolean, from?: number ): void; /** @internal */ _$reparentDisconnectables?(parent: Disconnectable): void; constructor( startNode: ChildNode, endNode: ChildNode | null, parent: TemplateInstance | ChildPart | undefined, options: RenderOptions | undefined ) { this._$startNode = startNode; this._$endNode = endNode; this._$parent = parent; this.options = options; // Note __isConnected is only ever accessed on RootParts (i.e. when there is // no _$parent); the value on a non-root-part is "don't care", but checking // for parent would be more code this.__isConnected = options?.isConnected ?? true; if (ENABLE_EXTRA_SECURITY_HOOKS) { // Explicitly initialize for consistent class shape. this._textSanitizer = undefined; } } /** * The parent node into which the part renders its content. * * A ChildPart's content consists of a range of adjacent child nodes of * `.parentNode`, possibly bordered by 'marker nodes' (`.startNode` and * `.endNode`). * * - If both `.startNode` and `.endNode` are non-null, then the part's content * consists of all siblings between `.startNode` and `.endNode`, exclusively. * * - If `.startNode` is non-null but `.endNode` is null, then the part's * content consists of all siblings following `.startNode`, up to and * including the last child of `.parentNode`. If `.endNode` is non-null, then * `.startNode` will always be non-null. * * - If both `.endNode` and `.startNode` are null, then the part's content * consists of all child nodes of `.parentNode`. */ get parentNode(): Node { let parentNode: Node = wrap(this._$startNode).parentNode!; const parent = this._$parent; if ( parent !== undefined && parentNode.nodeType === 11 /* Node.DOCUMENT_FRAGMENT */ ) { // If the parentNode is a DocumentFragment, it may be because the DOM is // still in the cloned fragment during initial render; if so, get the real // parentNode the part will be committed into by asking the parent. parentNode = (parent as ChildPart | TemplateInstance).parentNode; } return parentNode; } /** * The part's leading marker node, if any. See `.parentNode` for more * information. */ get startNode(): Node | null { return this._$startNode; } /** * The part's trailing marker node, if any. See `.parentNode` for more * information. */ get endNode(): Node | null { return this._$endNode; } _$setValue(value: unknown, directiveParent: DirectiveParent = this): void { if (DEV_MODE && this.parentNode === null) { throw new Error( `This \`ChildPart\` has no \`parentNode\` and therefore cannot accept a value. This likely means the element containing the part was manipulated in an unsupported way outside of Lit's control such that the part's marker nodes were ejected from DOM. For example, setting the element's \`innerHTML\` or \`textContent\` can do this.` ); } value = resolveDirective(this, value, directiveParent); if (isPrimitive(value)) { // Non-rendering child values. It's important that these do not render // empty text nodes to avoid issues with preventing default <slot> // fallback content. if (value === nothing || value == null || value === '') { if (this._$committedValue !== nothing) { this._$clear(); } this._$committedValue = nothing; } else if (value !== this._$committedValue && value !== noChange) { this._commitText(value); } // This property needs to remain unminified. } else if ((value as TemplateResult)['_$litType$'] !== undefined) { this._commitTemplateResult(value as TemplateResult); } else if ((value as Node).nodeType !== undefined) { this._commitNode(value as Node); } else if (isIterable(value)) { this._commitIterable(value); } else { // Fallback, will render the string representation this._commitText(value); } } private _insert<T extends Node>(node: T, ref = this._$endNode) { return wrap(wrap(this._$startNode).parentNode!).insertBefore(node, ref); } private _commitNode(value: Node): void { if (this._$committedValue !== value) { this._$clear(); if ( ENABLE_EXTRA_SECURITY_HOOKS && sanitizerFactoryInternal !== noopSanitizer ) { const parentNodeName = this._$startNode.parentNode?.nodeName; if (parentNodeName === 'STYLE' || parentNodeName === 'SCRIPT') { let message = 'Forbidden'; if (DEV_MODE) { if (parentNodeName === 'STYLE') { message = `Lit does not support binding inside style nodes. ` + `This is a security risk, as style injection attacks can ` + `exfiltrate data and spoof UIs. ` + `Consider instead using css\`...\` literals ` + `to compose styles, and make do dynamic styling with ` + `css custom properties, ::parts, <slot>s, ` + `and by mutating the DOM rather than stylesheets.`; } else { message = `Lit does not support binding inside script nodes. ` + `This is a security risk, as it could allow arbitrary ` + `code execution.`; } } throw new Error(message); } } this._$committedValue = this._insert(value); } } private _commitText(value: unknown): void { // If the committed value is a primitive it means we called _commitText on // the previous render, and we know that this._$startNode.nextSibling is a // Text node. We can now just replace the text content (.data) of the node. if ( this._$committedValue !== nothing && isPrimitive(this._$committedValue) ) { const node = wrap(this._$startNode).nextSibling as Text; if (ENABLE_EXTRA_SECURITY_HOOKS) { if (this._textSanitizer === undefined) { this._textSanitizer = createSanitizer(node, 'data', 'property'); } value = this._textSanitizer(value); } (node as Text).data = value as string; } else { if (ENABLE_EXTRA_SECURITY_HOOKS) { const textNode = document.createTextNode(''); this._commitNode(textNode); // When setting text content, for security purposes it matters a lot // what the parent is. For example, <style> and <script> need to be // handled with care, while <span> does not. So first we need to put a // text node into the document, then we can sanitize its contentx. if (this._textSanitizer === undefined) { this._textSanitizer = createSanitizer(textNode, 'data', 'property'); } value = this._textSanitizer(value); textNode.data = value as string; } else { this._commitNode(d.createTextNode(value as string)); } } this._$committedValue = value; } private _commitTemplateResult( result: TemplateResult | CompiledTemplateResult ): void { // This property needs to remain unminified. const {values, ['_$litType$']: type} = result; // If $litType$ is a number, result is a plain TemplateResult and we get // the template from the template cache. If not, result is a // CompiledTemplateResult and _$litType$ is a CompiledTemplate and we need // to create the <template> element the first time we see it. const template: Template | CompiledTemplate = typeof type === 'number' ? this._$getTemplate(result as TemplateResult) : (type.el === undefined && (type.el = Template.createElement(type.h, this.options)), type); if ((this._$committedValue as TemplateInstance)?._$template === template) { (this._$committedValue as TemplateInstance)._update(values); } else { const instance = new TemplateInstance(template as Template, this); const fragment = instance._clone(this.options); instance._update(values); this._commitNode(fragment); this._$committedValue = instance; } } // Overridden via `litHtmlPolyfillSupport` to provide platform support. /** @internal */ _$getTemplate(result: TemplateResult) { let template = templateCache.get(result.strings); if (template === undefined) { templateCache.set(result.strings, (template = new Template(result))); } return template; } private _commitIterable(value: Iterable<unknown>): void { // For an Iterable, we create a new InstancePart per item, then set its // value to the item. This is a little bit of overhead for every item in // an Iterable, but it lets us recurse easily and efficiently update Arrays // of TemplateResults that will be commonly returned from expressions like: // array.map((i) => html`${i}`), by reusing existing TemplateInstances. // If value is an array, then the previous render was of an // iterable and value will contain the ChildParts from the previous // render. If value is not an array, clear this part and make a new // array for ChildParts. if (!isArray(this._$committedValue)) { this._$committedValue = []; this._$clear(); } // Lets us keep track of how many items we stamped so we can clear leftover // items from a previous render const itemParts = this._$committedValue as ChildPart[]; let partIndex = 0; let itemPart: ChildPart | undefined; for (const item of value) { if (partIndex === itemParts.length) { // If no existing part, create a new one // TODO (justinfagnani): test perf impact of always creating two parts // instead of sharing parts between nodes // https://github.com/lit/lit/issues/1266 itemParts.push( (itemPart = new ChildPart( this._insert(createMarker()), this._insert(createMarker()), this, this.options )) ); } else { // Reuse an existing part itemPart = itemParts[partIndex]; } itemPart._$setValue(item); partIndex++; } if (partIndex < itemParts.length) { // itemParts always have end nodes this._$clear( itemPart && wrap(itemPart._$endNode!).nextSibling, partIndex ); // Truncate the parts array so _value reflects the current state itemParts.length = partIndex; } } /** * Removes the nodes contained within this Part from the DOM. * * @param start Start node to clear from, for clearing a subset of the part's * DOM (used when truncating iterables) * @param from When `start` is specified, the index within the iterable from * which ChildParts are being removed, used for disconnecting directives in * those Parts. * * @internal */ _$clear( start: ChildNode | null = wrap(this._$startNode).nextSibling, from?: number ) { this._$notifyConnectionChanged?.(false, true, from); while (start && start !== this._$endNode) { const n = wrap(start!).nextSibling; (wrap(start!) as Element).remove(); start = n; } } /** * Implementation of RootPart's `isConnected`. Note that this metod * should only be called on `RootPart`s (the `ChildPart` returned from a * top-level `render()` call). It has no effect on non-root ChildParts. * @param isConnected Whether to set * @internal */ setConnected(isConnected: boolean) { if (this._$parent === undefined) { this.__isConnected = isConnected; this._$notifyConnectionChanged?.(isConnected); } else if (DEV_MODE) { throw new Error( 'part.setConnected() may only be called on a ' + 'RootPart returned from render().' ); } } } /** * A top-level `ChildPart` returned from `render` that manages the connected * state of `AsyncDirective`s created throughout the tree below it. */ export interface RootPart extends ChildPart { /** * Sets the connection state for `AsyncDirective`s contained within this root * ChildPart. * * lit-html does not automatically monitor the connectedness of DOM rendered; * as such, it is the responsibility of the caller to `render` to ensure that * `part.setConnected(false)` is called before the part object is potentially * discarded, to ensure that `AsyncDirective`s have a chance to dispose of * any resources being held. If a `RootPart` that was prevously * disconnected is subsequently re-connected (and its `AsyncDirective`s should * re-connect), `setConnected(true)` should be called. * * @param isConnected Whether directives within this tree should be connected * or not */ setConnected(isConnected: boolean): void; } export type {AttributePart}; class AttributePart implements Disconnectable { readonly type = ATTRIBUTE_PART as | typeof ATTRIBUTE_PART | typeof PROPERTY_PART | typeof BOOLEAN_ATTRIBUTE_PART | typeof EVENT_PART; readonly element: HTMLElement; readonly name: string; readonly options: RenderOptions | undefined; /** * If this attribute part represents an interpolation, this contains the * static strings of the interpolation. For single-value, complete bindings, * this is undefined. */ readonly strings?: ReadonlyArray<string>; /** @internal */ _$committedValue: unknown | Array<unknown> = nothing; /** @internal */ __directives?: Array<Directive | undefined>; /** @internal */ _$parent: Disconnectable; /** @internal */ _$disconnectableChildren?: Set<Disconnectable> = undefined; protected _sanitizer: ValueSanitizer | undefined; get tagName() { return this.element.tagName; } // See comment in Disconnectable interface for why this is a getter get _$isConnected() { return this._$parent._$isConnected; } constructor( element: HTMLElement, name: string, strings: ReadonlyArray<string>, parent: Disconnectable, options: RenderOptions | undefined ) { this.element = element; this.name = name; this._$parent = parent; this.options = options; if (strings.length > 2 || strings[0] !== '' || strings[1] !== '') { this._$committedValue = new Array(strings.length - 1).fill(new String()); this.strings = strings; } else { this._$committedValue = nothing; } if (ENABLE_EXTRA_SECURITY_HOOKS) { this._sanitizer = undefined; } } /** * Sets the value of this part by resolving the value from possibly multiple * values and static strings and committing it to the DOM. * If this part is single-valued, `this._strings` will be undefined, and the * method will be called with a single value argument. If this part is * multi-value, `this._strings` will be defined, and the method is called * with the value array of the part's owning TemplateInstance, and an offset * into the value array from which the values should be read. * This method is overloaded this way to eliminate short-lived array slices * of the template instance values, and allow a fast-path for single-valued * parts. * * @param value The part value, or an array of values for multi-valued parts * @param valueIndex the index to start reading values from. `undefined` for * single-valued parts * @param noCommit causes the part to not commit its value to the DOM. Used * in hydration to prime attribute parts with their first-rendered value, * but not set the attribute, and in SSR to no-op the DOM operation and * capture the value for serialization. * * @internal */ _$setValue( value: unknown | Array<unknown>, directiveParent: DirectiveParent = this, valueIndex?: number, noCommit?: boolean ) { const strings = this.strings; // Whether any of the values has changed, for dirty-checking let change = false; if (strings === undefined) { // Single-value binding case value = resolveDirective(this, value, directiveParent, 0); change = !isPrimitive(value) || (value !== this._$committedValue && value !== noChange); if (change) { this._$committedValue = value; } } else { // Interpolation case const values = value as Array<unknown>; value = strings[0]; let i, v; for (i = 0; i < strings.length - 1; i++) { v = resolveDirective(this, values[valueIndex! + i], directiveParent, i); if (v === noChange) { // If the user-provided value is `noChange`, use the previous value v = (this._$committedValue as Array<unknown>)[i]; } change ||= !isPrimitive(v) || v !== (this._$committedValue as Array<unknown>)[i]; if (v === nothing) { value = nothing; } else if (value !== nothing) { value += (v ?? '') + strings[i + 1]; } // We always record each value, even if one is `nothing`, for future // change detection. (this._$committedValue as Array<unknown>)[i] = v; } } if (change && !noCommit) { this._commitValue(value); } } /** @internal */ _commitValue(value: unknown) { if (value === nothing) { (wrap(this.element) as Element).removeAttribute(this.name); } else { if (ENABLE_EXTRA_SECURITY_HOOKS) { if (this._sanitizer === undefined) { this._sanitizer = sanitizerFactoryInternal( this.element, this.name, 'attribute' ); } value = this._sanitizer(value ?? ''); } (wrap(this.element) as Element).setAttribute( this.name, (value ?? '') as string ); } } } export type {PropertyPart}; class PropertyPart extends AttributePart { override readonly type = PROPERTY_PART; /** @internal */ override _commitValue(value: unknown) { if (ENABLE_EXTRA_SECURITY_HOOKS) { if (this._sanitizer === undefined) { this._sanitizer = sanitizerFactoryInternal( this.element, this.name, 'property' ); } value = this._sanitizer(value); } // eslint-disable-next-line @typescript-eslint/no-explicit-any (this.element as any)[this.name] = value === nothing ? undefined : value; } } export type {BooleanAttributePart}; class BooleanAttributePart extends AttributePart { override readonly type = BOOLEAN_ATTRIBUTE_PART; /** @internal */ override _commitValue(value: unknown) { if (value && value !== nothing) { (wrap(this.element) as Element).setAttribute(this.name, ''); } else { (wrap(this.element) as Element).removeAttribute(this.name); } } } type EventListenerWithOptions = EventListenerOrEventListenerObject & Partial<AddEventListenerOptions>; /** * An AttributePart that manages an event listener via add/removeEventListener. * * This part works by adding itself as the event listener on an element, then * delegating to the value passed to it. This reduces the number of calls to * add/removeEventListener if the listener changes frequently, such as when an * inline function is used as a listener. * * Because event options are passed when adding listeners, we must take case * to add and remove the part as a listener when the event options change. */ export type {EventPart}; class EventPart extends AttributePart { override readonly type = EVENT_PART; constructor( element: HTMLElement, name: string, strings: ReadonlyArray<string>, parent: Disconnectable, options: RenderOptions | undefined ) { super(element, name, strings, parent, options); if (DEV_MODE && this.strings !== undefined) { throw new Error( `A \`<${element.localName}>\` has a \`@${name}=...\` listener with ` + 'invalid content. Event listeners in templates must have exactly ' + 'one expression and no surrounding text.' ); } } // EventPart does not use the base _$setValue/_resolveValue implementation // since the dirty checking is more complex /** @internal */ override _$setValue( newListener: unknown, directiveParent: DirectiveParent = this ) { newListener = resolveDirective(this, newListener, directiveParent, 0) ?? nothing; if (newListener === noChange) { return; } const oldListener = this._$committedValue; // If the new value is nothing or any options change we have to remove the // part as a listener. const shouldRemoveListener = (newListener === nothing && oldListener !== nothing) || (newListener as EventListenerWithOptions).capture !== (oldListener as EventListenerWithOptions).capture || (newListener as EventListenerWithOptions).once !== (oldListener as EventListenerWithOptions).once || (newListener as EventListenerWithOptions).passive !== (oldListener as EventListenerWithOptions).passive; // If the new value is not nothing and we removed the listener, we have // to add the part as a listener. const shouldAddListener = newListener !== nothing && (oldListener === nothing || shouldRemoveListener); if (shouldRemoveListener) { this.element.removeEventListener( this.name, this, oldListener as EventListenerWithOptions ); } if (shouldAddListener) { // Beware: IE11 and Chrome 41 don't like using the listener as the // options object. Figure out how to deal w/ this in IE11 - maybe // patch addEventListener? this.element.addEventListener( this.name, this, newListener as EventListenerWithOptions ); } this._$committedValue = newListener; } handleEvent(event: Event) { if (typeof this._$committedValue === 'function') { this._$committedValue.call(this.options?.host ?? this.element, event); } else { (this._$committedValue as EventListenerObject).handleEvent(event); } } } export type {ElementPart}; class ElementPart implements Disconnectable { readonly type = ELEMENT_PART; /** @internal */ __directive?: Directive; // This is to ensure that every Part has a _$committedValue _$committedValue: undefined; /** @internal */ _$parent!: Disconnectable; /** @internal */ _$disconnectableChildren?: Set<Disconnectable> = undefined; options: RenderOptions | undefined; constructor( public element: Element, parent: Disconnectable, options: RenderOptions | undefined ) { this._$parent = parent; this.options = options; } // See comment in Disconnectable interface for why this is a getter get _$isConnected() { return this._$parent._$isConnected; } _$setValue(value: unknown): void { resolveDirective(this, value); } } /** * END USERS SHOULD NOT RELY ON THIS OBJECT. * * Private exports for use by other Lit packages, not intended for use by * external users. * * We currently do not make a mangled rollup build of the lit-ssr code. In order * to keep a number of (otherwise private) top-level exports mangled in the * client side code, we export a _$LH object containing those members (or * helper methods for accessing private fields of those members), and then * re-export them for use in lit-ssr. This keeps lit-ssr agnostic to whether the * client-side code is being used in `dev` mode or `prod` mode. * * This has a unique name, to disambiguate it from private exports in * lit-element, which re-exports all of lit-html. * * @private */ export const _$LH = { // Used in lit-ssr _boundAttributeSuffix: boundAttributeSuffix, _marker: marker, _markerMatch: markerMatch, _HTML_RESULT: HTML_RESULT, _getTemplateHtml: getTemplateHtml, // Used in hydrate _TemplateInstance: TemplateInstance, _isIterable: isIterable, _resolveDirective: resolveDirective, // Used in tests and private-ssr-support _ChildPart: ChildPart, _AttributePart: AttributePart, _BooleanAttributePart: BooleanAttributePart, _EventPart: EventPart, _PropertyPart: PropertyPart, _ElementPart: ElementPart, }; // Apply polyfills if available const polyfillSupport = DEV_MODE ? window.litHtmlPolyfillSupportDevMode : window.litHtmlPolyfillSupport; polyfillSupport?.(Template, ChildPart); // IMPORTANT: do not change the property name or the assignment expression. // This line will be used in regexes to search for lit-html usage. (globalThis.litHtmlVersions ??= []).push('2.0.1'); if (DEV_MODE && globalThis.litHtmlVersions.length > 1) { issueWarning!( 'multiple-versions', `Multiple versions of Lit loaded. ` + `Loading multiple versions is not recommended.` ); }
the_stack
import BootstrapNotify from "../../libs/bootstrap-notify/BootstrapNotify"; import Loader from "../../libs/loader/Loader"; import DomAttributes from "../../core/utils/DomAttributes"; import ShuffleWrapper from "../shuffle/ShuffleWrapper"; import Ajax from "../../core/ajax/Ajax"; import Navigation from "../../core/Navigation"; import DomElements from "../../core/utils/DomElements"; import StringUtils from "../../core/utils/StringUtils"; import DataTransferDialogs from "../../core/ui/Dialogs/DataTransferDialogs"; import TagManagementDialogs from "../../core/ui/Dialogs/TagManagementDialogs"; import BootboxWrapper from "../bootbox/BootboxWrapper"; import AjaxResponseDto from "../../DTO/AjaxResponseDto"; import AjaxEvents from "../../core/ajax/AjaxEvents"; import AbstractAjax from "../../core/ajax/AbstractAjax"; var bootbox = require('bootbox'); import * as $ from 'jquery'; import 'lightgallery'; import 'lightgallery/modules/lg-thumbnail' import 'lightgallery/modules/lg-zoom' import 'lightgallery/dist/css/lightgallery.min.css' import 'lightgallery/dist/css/lg-transitions.min.css' export default class LightGallery { /** * @type Object */ private selectors = { ids: { trashButton : '#lightgallery_trash_button', pencilButton : '#lightgallery_pencil_button', saveButton : '#lightgallery_save_button', transferButton : '#lightgallery_transfer_button', downloadButton : '#lg-download', fileTransferButton : '#lightgallery_transfer_button', tagsManageButton : '#lightgallery_manage_tags_button' }, classes: { upperToolbar : '.lg-toolbar', thumbnails : '.lg-thumb', nextButton : '.lg-next ', downloadButton : '.lg-download', currentViewedImage : '.lg-current', imagePreviewWrapper : '.lg-inner', currentViewedFilename : '.lg-sub-html', galleryMainWrapper : '.lg', textHolderCaption : '.caption-text-holder', massActionRemoveButton : '.mass-action-lightgallery-remove-images', massActionTransferButton : '.mass-action-lightgallery-transfer-images', massActionButtons : '.mass-action-lightgallery-button', lightboxGallery : '.lightbox-gallery', }, other: { checkboxForImage : '.checkbox-circle input', checkboxForImageWrapper :'.checkbox-circle' } }; /** * @type Object */ private messages = { imageRemovalConfirmation : "Do You want to remove this image/s?", imageNameEditConfirmation : "Do You want to rename this image?", }; /** * @type Object */ private keys = { KEY_FILE_FULL_PATH : "file_full_path" }; /** * @type Object */ private vars = { currentFileName : '', moduleRoute : 'modules_my_images' }; /** * @type BootstrapNotify */ private bootstrapNotify = new BootstrapNotify(); /** * @type ShuffleWrapper */ private shuffler = new ShuffleWrapper(); /** * @type Ajax */ private ajax = new Ajax(); /** * @type AjaxEvents */ private ajaxEvents = new AjaxEvents(); /** * @type DataTransferDialogs */ private dataTransferDialogs = new DataTransferDialogs(); /** * @type TagManagementDialogs */ private tagManagementDialogs = new TagManagementDialogs(); public init() { this.shuffler.init(); this.initGallery(); this.addPlugins(); this.preventCheckboxEventTriggering(); this.handleGalleryEvents(); this.handleCheckboxForImageInGalleryView(); this.preventSettingMasonryGalleryAsAbsolute(); }; private initGallery(){ let $lightboxGallery = $(this.selectors.classes.lightboxGallery); if( DomElements.doElementsExists($lightboxGallery) ){ //@ts-ignore $lightboxGallery.lightGallery({ thumbnail: true }); } }; public reinitGallery(){ let $lightboxGallery = $(this.selectors.classes.lightboxGallery); if( DomElements.doElementsExists($lightboxGallery) ){ $lightboxGallery.data('lightGallery').destroy(true); this.initGallery(); } }; private addPlugins(){ this.addPluginRemoveFile(); this.addPluginRenameFile(); this.addPluginTransferFile(); this.addPluginManageFileTags(); }; private addPluginRemoveFile(){ let lightboxGallery = $(this.selectors.classes.lightboxGallery); let _this = this; // Handling removing images lightboxGallery.on('onAfterOpen.lg', function () { let trashIcon = '<a class=\"lg-icon\" id="lightgallery_trash_button"><i class="fa fa-trash" remove-record aria-hidden="true"></i></a>'; $(_this.selectors.classes.upperToolbar).append(trashIcon); let trashButton = $(_this.selectors.ids.trashButton); // Button click $(trashButton).click(() => { let downloadButton = $(_this.selectors.ids.downloadButton); let filePath = $(downloadButton).attr('href'); let callback = function(){ // Rebuilding thumbnails etc _this.removeImageWithMiniature(filePath); _this.handleClosingGalleryIfThereAreNoMoreImages(); }; BootboxWrapper.confirm({ message: _this.messages.imageRemovalConfirmation, backdrop: true, callback: function (result) { if (result) { // File removal ajax _this.ajaxEvents.callAjaxFileRemovalForFilePath([filePath], callback); } } }); }) }); }; private addPluginRenameFile(){ let lightboxGallery = $(this.selectors.classes.lightboxGallery); let _this = this; // Handling editing name lightboxGallery.on('onAfterOpen.lg', function (event) { let pencilIcon = '<a class=\"lg-icon\" id="lightgallery_pencil_button"><i class="fas fa-pencil-alt"></i></a>'; let saveIcon = '<a class=\"lg-icon d-none\" id="lightgallery_save_button"><i class="far fa-save"></i></a>'; $(_this.selectors.classes.upperToolbar).append(saveIcon); $(_this.selectors.classes.upperToolbar).append(pencilIcon); let pencilButton = $(_this.selectors.ids.pencilButton); let saveButton = $(_this.selectors.ids.saveButton); let downloadButton = $(_this.selectors.ids.downloadButton); $(saveButton).click( () => { // Confirmation box BootboxWrapper.confirm({ message: _this.messages.imageNameEditConfirmation, backdrop: true, callback: function (result) { if (result) { let filePath = $(downloadButton).attr('href'); let newFileName = $(_this.selectors.classes.currentViewedFilename).text(); let data = { file_new_name : newFileName, file_full_path : filePath.replace("/", "") }; Loader.toggleMainLoader(); $.ajax({ method: Ajax.REQUEST_TYPE_POST, url: AbstractAjax.API_URLS.fileRename, data: data, success: (data) => { // Info: filePath must also be updated if( !StringUtils.areTheSame(_this.vars.currentFileName, newFileName) ){ let newFilePath = filePath.replace(_this.vars.currentFileName, newFileName); let links = $("[href^='" + filePath + "']"); let images = $("[data-src-real^='" + filePath + "']"); let dataSrcDivs = $('[data-src^="' + filePath + '"]'); $(images).attr('data-src-real', newFilePath); $(images).attr('alt', newFileName); $(links).attr('href', newFilePath); $(dataSrcDivs).attr('data-src', newFilePath); _this.handleGalleryCaptionOnFileRename(_this.vars.currentFileName, newFileName); _this.vars.currentFileName = $(_this.selectors.classes.currentViewedFilename).text(); } _this.bootstrapNotify.showGreenNotification(data); }, }).fail((data) => { _this.bootstrapNotify.showRedNotification(data.responseText); }).always(() => { Loader.toggleMainLoader(); }); } } }); }); // Handles toggling blocking everything in gallery besides filename area $(pencilButton).click(() => { _this.vars.currentFileName = $(_this.selectors.classes.currentViewedFilename).text(); let galleryMainWrapper = $('.lg'); let allGalleryElements = $('.lg *'); let textHolder = $(_this.selectors.classes.currentViewedFilename); let isNameEdited = false; let enabledElements = [ textHolder, pencilButton, saveButton, _this.selectors.classes.upperToolbar ]; let elementsToToggleBlurr = [ _this.selectors.classes.imagePreviewWrapper, _this.selectors.classes.thumbnails ]; // Toggle disabling all gui elements while editing - do not allow user to leave while editing is on $.each(allGalleryElements, (index, element) => { $(element).toggleClass('disabled'); }); // Toggle blurring images while editing - additional change to blocking user from leaving $(galleryMainWrapper).toggleClass('blurred'); $.each(enabledElements, (index, element) => { //@ts-ignore DomAttributes.unsetDisabledClass($(element)); }); if( $(galleryMainWrapper).hasClass('blurred') ){ $.each(elementsToToggleBlurr, (index, element) => { $(element).css({filter: "blur(3px)"}); }); $(saveButton).removeClass('d-none'); isNameEdited = true; }else{ $.each(elementsToToggleBlurr, (index, element) => { $(element).css({filter: "blur(0px)"}); }); $(saveButton).addClass('d-none'); isNameEdited = false; } //Toggle content editable if(isNameEdited){ $(textHolder).attr('contenteditable','true'); }else{ $(textHolder).removeAttr('contenteditable'); } }) }); }; private addPluginTransferFile() { let lightboxGallery = $(this.selectors.classes.lightboxGallery); let _this = this; // Handling editing name lightboxGallery.on('onAfterOpen.lg', function (event) { let transferIcon = '<a class=\"lg-icon\" id="lightgallery_transfer_button"><i class="fas fa-random file-transfer"></i></a>'; $(_this.selectors.classes.upperToolbar).append(transferIcon); _this.attachCallDialogForDataTransfer(); }); }; private addPluginManageFileTags() { let lightboxGallery = $(this.selectors.classes.lightboxGallery); let _this = this; // Handling managing tags lightboxGallery.on('onAfterOpen.lg', function (event) { let tagsManageIcon = '<a class=\"lg-icon\" id="lightgallery_manage_tags_button"><i class="fas fa-tags manage-file-tags"></i></a>'; $(_this.selectors.classes.upperToolbar).append(tagsManageIcon); _this.attachCallDialogForTagsManagement() }); }; private attachCallDialogForDataTransfer() { let button = $(this.selectors.ids.fileTransferButton); let _this = this; if( DomElements.doElementsExists(button) ){ $(button).on('click', (event) => { let clickedButton = $(event.target); let buttonsToolbar = $(clickedButton).closest(_this.selectors.classes.upperToolbar); let fileCurrentPath = $(buttonsToolbar).find(_this.selectors.classes.downloadButton).attr('href'); let callback = function (){ _this.removeImageWithMiniature(fileCurrentPath); _this.handleClosingGalleryIfThereAreNoMoreImages(); BootboxWrapper.hideAll(); }; let escapedFileCurrentPath = ( fileCurrentPath.indexOf('/') === 0 ? fileCurrentPath.replace("/", "") : fileCurrentPath ) ; _this.dataTransferDialogs.buildDataTransferDialog([escapedFileCurrentPath], 'My Images', callback); }); } }; private attachCallDialogForTagsManagement() { let button = $(this.selectors.ids.tagsManageButton); let _this = this; if( DomElements.doElementsExists(button) ){ $(button).on('click', (event) => { let clickedButton = $(event.target); let buttonsToolbar = $(clickedButton).closest(_this.selectors.classes.upperToolbar); let fileCurrentPath = $(buttonsToolbar).find(_this.selectors.classes.downloadButton).attr('href'); let addTagsToImageOnViewAndRebuildShuffleGroups = (tags) => { let gallery = $(_this.selectors.classes.lightboxGallery); let currImage = $(gallery).find('[data-src^="' + fileCurrentPath + '"]'); let tagsArr = tags.split(','); let tagsJson = JSON.stringify(tagsArr); if( DomElements.doElementsExists(currImage) ){ $(currImage).attr('data-groups', tagsJson); } let tagsArray = _this.shuffler.buildTagsArrayFromTagsForImages(); _this.shuffler.removeTagsFromFilter(); _this.shuffler.appendTagsToFilter(tagsArray); _this.shuffler.addTagsButtonsEvents(); }; /** * SpecialActions::UpdateTags - should be theoretically used here but due to special handling of * miniatures etc in background - this must remain like this */ _this.tagManagementDialogs.buildTagManagementDialog(fileCurrentPath, 'My Images', addTagsToImageOnViewAndRebuildShuffleGroups); }); } }; public removeImageWithMiniature(filePath){ let thumbnails = $(this.selectors.classes.thumbnails); let removedImageMiniature = $(thumbnails).find("[data-src-real^='" + filePath + "']"); let nextButton = $(this.selectors.classes.nextButton); let currentViewedImage = $(this.selectors.classes.currentViewedImage); let htmlGallery = $(this.selectors.classes.lightboxGallery); $(removedImageMiniature).parent('div').remove(); $(currentViewedImage).remove(); $(nextButton).click(); this.initGallery(); // now the image that is removed in slider is fine but it must be removed also from shuffler instance to update tags etc let currentImageInGalleryView = $(htmlGallery).find('[data-src^="' + filePath + '"]'); let currentImageUniqueId = $(currentImageInGalleryView).attr('data-unique-id'); // ShuffleJS tags need to be rebuilt this.shuffler.removeImageByDataUniqueId(currentImageUniqueId); // first remove image from instance let tagsArray = this.shuffler.buildTagsArrayFromTagsForImages(); // prepare updated set of tags this.shuffler.removeTagsFromFilter(); // clean current tags and add new set this.shuffler.appendTagsToFilter(tagsArray); this.shuffler.addTagsButtonsEvents(); this.shuffler.switchToGroupAllIfGroupIsRemoved(); }; private handleGalleryCaptionOnFileRename(currFilename, newFilename){ let textHolder = $(this.selectors.classes.textHolderCaption + "[data-filename^='" + currFilename + "']"); textHolder.text(newFilename); textHolder.attr('data-alt', newFilename); }; private handleGalleryEvents(){ let _this = this; let lightboxGallery = $(this.selectors.classes.lightboxGallery); lightboxGallery.on('onAfterSlide.lg', function () { _this.handleMovingBetweenImagesAfterImageRemoval(lightboxGallery); }); lightboxGallery.on('onCloseAfter.lg',function() { _this.handleRebuildingEntireGalleryWhenClosingIt(lightboxGallery); }); lightboxGallery.on('onAfterOpen.lg',function() { _this.modifyThumbnailsWhenOpeningGallery(lightboxGallery); }); }; private handleMovingBetweenImagesAfterImageRemoval(lightboxGallery){ // Handling skipping removed images - because of above - this is dirty solution but works let downloadButton = $(this.selectors.ids.downloadButton); var filePath = $(downloadButton).attr('href'); let isImagePresent = ( lightboxGallery.find("[data-src-real^='" + filePath + "']").length > 0 ); let _this = this; if( !isImagePresent ){ $('.lg-next').click(); } // Handling proper slideback when image was removed - dirty like above let prevButton = $('button.lg-prev'); $(prevButton).on('click', () => { let downloadButton = $(_this.selectors.ids.downloadButton); var filePathOnClick = $(downloadButton).attr('href'); if (filePathOnClick === filePath){ lightboxGallery.data('lightGallery').goToPrevSlide(); } }); }; private handleRebuildingEntireGalleryWhenClosingIt(lightboxGallery){ // Handling rebuilding entire gallery when closing - needed because plugin somehows stores data in it's object not in storage this.reinitGallery(); }; private handleClosingGalleryIfThereAreNoMoreImages() { let lightboxGallery = $(this.selectors.classes.lightboxGallery); let foundImages = $(lightboxGallery).find('img'); let closeButton = $('.lg-close'); if( !DomElements.doElementsExists(foundImages) ){ $(closeButton).click(); } }; /** * @description will modify the thumbnails * - add data-src-real attribute (used with backend generated miniatures) */ private modifyThumbnailsWhenOpeningGallery($lightboxGallery: JQuery<HTMLElement>): void { let $thumbnailsImages = $('.lg-thumb img'); $.each($thumbnailsImages, (index, thumbnailImage) => { let $thumbnailImage = $(thumbnailImage); let thumbnailSrc = $thumbnailImage.attr('src'); let $correspondingGalleryImage = $lightboxGallery.find('[src^="' + thumbnailSrc + '"]'); let dataSrcReal = $correspondingGalleryImage.attr('data-src-real'); $thumbnailImage.attr('data-src-real', dataSrcReal); }) } /** * This function will prevent triggering events such as showing gallery for image in wrapper (click) */ private preventCheckboxEventTriggering(){ let lightboxGallery = $(this.selectors.classes.lightboxGallery); let checkboxesForImagesWrappers = $( lightboxGallery.find(this.selectors.other.checkboxForImageWrapper) ); let checkboxesForImages = $( lightboxGallery.find(this.selectors.other.checkboxForImage) ); $(checkboxesForImagesWrappers).on('click', (event) => { event.stopImmediatePropagation(); let clickedElement = event.currentTarget; let isCheckbox = DomAttributes.isCheckbox(clickedElement, false); if( !isCheckbox ){ let checkbox = $(clickedElement).find('input'); let isChecked = DomAttributes.isChecked(checkbox); if(isChecked){ DomAttributes.unsetChecked(checkbox); $(checkbox).trigger('click'); return false; } DomAttributes.setChecked(checkbox); $(checkbox).trigger('click'); } }); checkboxesForImages.on('click', (event) => { event.stopImmediatePropagation(); }) }; /** * This function will handle toggling disability for mass action buttons, at least one image must be checked * to remove the disabled class. */ private handleCheckboxForImageInGalleryView(){ let _this = this; let lightboxGallery = $(this.selectors.classes.lightboxGallery); let checkboxesForImages = ( lightboxGallery.find(this.selectors.other.checkboxForImage) ); $(checkboxesForImages).on('change', () => { let checkedCheckboxes = ( lightboxGallery.find(this.selectors.other.checkboxForImage + ':checked') ); let massActionButtons = $(_this.selectors.classes.massActionButtons); if( DomElements.doElementsExists(checkedCheckboxes) ){ DomAttributes.unsetDisabledClass(massActionButtons); return false; } DomAttributes.setDisabledClass(massActionButtons); }) }; /** * This Bugfix is needed because masonry js gallery keeps overwriting styles for gallery * so with high number of images inside div - it won't scale anymore, It cannot be changed in twig * because JS overwrites it and besides i don't want to interfere with original code of that lib. */ private preventSettingMasonryGalleryAsAbsolute(){ let _this = this; document.addEventListener("DOMContentLoaded", function() { let $myGallery = $('.lightgallery .my-gallery'); let $thumbnails = $(_this.selectors.classes.lightboxGallery); if( DomElements.doElementsExists($myGallery) && DomElements.doElementsExists($thumbnails)){ $myGallery.attr("style", ""); $thumbnails.attr("style", ""); } }); } }
the_stack
import * as assert from 'assert' import { getMonoid } from '../src/Array' import { left, right } from '../src/Either' import * as Eq from '../src/Eq' import { pipe } from '../src/function' import { none, some as optionSome } from '../src/Option' import * as _ from '../src/ReadonlySet' import * as S from '../src/string' import * as N from '../src/number' import * as U from './util' import { separated } from '../src/Separated' const gte2 = (n: number) => n >= 2 interface Foo { readonly x: string } const foo = (x: string): Foo => ({ x }) const fooEq: Eq.Eq<Foo> = { equals: (a: Foo, b: Foo) => a.x === b.x } describe('ReadonlySet', () => { it('toReadonlyArray', () => { U.deepStrictEqual(_.toReadonlyArray(N.Ord)(new Set()), []) U.deepStrictEqual(_.toReadonlyArray(N.Ord)(new Set([1, 2, 3])), [1, 2, 3]) U.deepStrictEqual(_.toReadonlyArray(N.Ord)(new Set([3, 2, 1])), [1, 2, 3]) }) it('getEq', () => { const E = _.getEq(N.Eq) U.deepStrictEqual(E.equals(new Set([1, 2, 3]), new Set([1, 2, 3])), true) U.deepStrictEqual(E.equals(new Set([1, 2, 3]), new Set([1, 2])), false) U.deepStrictEqual(E.equals(new Set([1, 2]), new Set([1, 2, 3])), false) }) it('some', () => { U.deepStrictEqual(_.some((s: string) => s.trim() === '')(new Set<string>()), false) U.deepStrictEqual(_.some(gte2)(new Set([1, 2, 3])), true) U.deepStrictEqual(_.some(gte2)(new Set([1])), false) }) it('map', () => { U.deepStrictEqual(_.map(N.Eq)((n: number) => n % 2)(new Set([])), new Set([])) U.deepStrictEqual(_.map(N.Eq)((n: number) => n % 2)(new Set([1, 2, 3, 4])), new Set([0, 1])) U.deepStrictEqual(_.map(S.Eq)((n: number) => `${n % 2}`)(new Set([1, 2, 3, 4])), new Set(['0', '1'])) }) it('every', () => { U.deepStrictEqual(_.every(gte2)(new Set([1, 2, 3])), false) U.deepStrictEqual(_.every(gte2)(new Set([2, 3])), true) }) it('chain', () => { U.deepStrictEqual(_.chain(S.Eq)((n: number) => new Set([n.toString()]))(new Set([])), new Set([])) U.deepStrictEqual(_.chain(S.Eq)(() => new Set([]))(new Set([1, 2])), new Set([])) U.deepStrictEqual( _.chain(S.Eq)((n: number) => new Set([`${n}`, `${n + 1}`]))(new Set([1, 2])), new Set(['1', '2', '3']) ) }) it('isSubset', () => { U.deepStrictEqual(_.isSubset(N.Eq)(new Set([1, 2]), new Set([1, 2, 3])), true) U.deepStrictEqual(_.isSubset(N.Eq)(new Set([1, 2, 4]), new Set([1, 2, 3])), false) U.deepStrictEqual(pipe(new Set([1, 2]), _.isSubset(N.Eq)(new Set([1, 2, 3]))), true) U.deepStrictEqual(pipe(new Set([1, 2, 4]), _.isSubset(N.Eq)(new Set([1, 2, 3]))), false) }) it('filter', () => { U.deepStrictEqual(_.filter(gte2)(new Set([1, 2, 3])), new Set([2, 3])) // refinements const isNumber = (u: string | number): u is number => typeof u === 'number' const actual = _.filter(isNumber)(new Set([1, 'a', 2])) U.deepStrictEqual(actual, new Set([1, 2])) }) it('partition', () => { U.deepStrictEqual(_.partition(() => true)(new Set([])), separated(new Set([]), new Set([]))) U.deepStrictEqual(_.partition(() => true)(new Set([1])), separated(new Set([]), new Set([1]))) U.deepStrictEqual(_.partition(() => false)(new Set([1])), separated(new Set([1]), new Set([]))) U.deepStrictEqual( _.partition((n: number) => n % 2 === 0)(new Set([1, 2, 3, 4])), separated(new Set([1, 3]), new Set([2, 4])) ) // refinements const isNumber = (u: string | number): u is number => typeof u === 'number' const actual = _.partition(isNumber)(new Set([1, 'a', 2])) U.deepStrictEqual(actual, separated(new Set(['a']), new Set([1, 2]))) }) it('union', () => { U.deepStrictEqual(_.union(N.Eq)(new Set([1, 2]), new Set([1, 3])), new Set([1, 2, 3])) U.deepStrictEqual(pipe(new Set([1, 2]), _.union(N.Eq)(new Set([1, 3]))), new Set([1, 2, 3])) }) it('intersection', () => { U.deepStrictEqual(_.intersection(N.Eq)(new Set([1, 2]), new Set([1, 3])), new Set([1])) U.deepStrictEqual(pipe(new Set([1, 2]), _.intersection(N.Eq)(new Set([1, 3]))), new Set([1])) }) it('partitionMap', () => { U.deepStrictEqual( _.partitionMap(N.Eq, S.Eq)((n: number) => left(n))(new Set([])), separated(new Set([]), new Set([])) ) U.deepStrictEqual( _.partitionMap(N.Eq, S.Eq)((n: number) => (n % 2 === 0 ? left(n) : right(`${n}`)))(new Set([1, 2, 3])), separated(new Set([2]), new Set(['1', '3'])) ) const SL = Eq.struct({ value: N.Eq }) const SR = Eq.struct({ value: S.Eq }) U.deepStrictEqual( _.partitionMap( SL, SR )((x: { readonly value: number }) => (x.value % 2 === 0 ? left({ value: 2 }) : right({ value: 'odd' })))( new Set([{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }]) ), separated(new Set([{ value: 2 }]), new Set([{ value: 'odd' }])) ) }) it('getUnionMonoid', () => { const M = _.getUnionMonoid(N.Eq) U.deepStrictEqual(M.concat(new Set([1, 2]), new Set([1, 3])), new Set([1, 2, 3])) U.deepStrictEqual(M.concat(new Set([1, 2]), M.empty), new Set([1, 2])) U.deepStrictEqual(M.concat(M.empty, new Set([1, 3])), new Set([1, 3])) }) it('getIntersectionSemigroup', () => { const IS = _.getIntersectionSemigroup(N.Eq) U.deepStrictEqual(IS.concat(new Set([1, 2]), new Set([1, 3])), new Set([1])) U.deepStrictEqual(IS.concat(new Set([1, 2]), _.empty), _.empty) U.deepStrictEqual(IS.concat(_.empty, new Set([1, 3])), _.empty) }) it('getDifferenceMagma', () => { const M = _.getDifferenceMagma(N.Eq) U.deepStrictEqual(M.concat(new Set([1, 2]), new Set([1, 3])), new Set([2])) }) it('difference', () => { U.deepStrictEqual(_.difference(N.Eq)(new Set([1, 2]), new Set([1, 3])), new Set([2])) U.deepStrictEqual(pipe(new Set([1, 2]), _.difference(N.Eq)(new Set([1, 3]))), new Set([2])) }) it('reduce', () => { U.deepStrictEqual(_.reduce(N.Ord)('', (b, a) => b + a)(new Set([1, 2, 3])), '123') U.deepStrictEqual(_.reduce(N.Ord)('', (b, a) => b + a)(new Set([3, 2, 1])), '123') }) it('foldMap', () => { U.deepStrictEqual(_.foldMap(N.Ord, getMonoid<number>())((a) => [a])(new Set([1, 2, 3])), [1, 2, 3]) U.deepStrictEqual(_.foldMap(N.Ord, getMonoid<number>())((a) => [a])(new Set([3, 2, 1])), [1, 2, 3]) }) it('reduceRight', () => { const f = _.reduceRight(N.Ord)('', (a, b) => b + a) U.deepStrictEqual(f(new Set([1, 2, 3])), '321') U.deepStrictEqual(f(new Set([3, 2, 1])), '321') }) it('singleton', () => { U.deepStrictEqual(_.singleton(1), new Set([1])) }) it('insert', () => { const x = new Set([1, 2]) U.deepStrictEqual(_.insert(N.Eq)(3)(x), new Set([1, 2, 3])) // should return the same ference if the element is already a member U.deepStrictEqual(_.insert(N.Eq)(2)(x), x) }) it('remove', () => { U.deepStrictEqual(_.remove(N.Eq)(3)(new Set([1, 2])), new Set([1, 2])) U.deepStrictEqual(_.remove(N.Eq)(1)(new Set([1, 2])), new Set([2])) }) it('fromArray', () => { // tslint:disable-next-line: deprecation U.deepStrictEqual(_.fromArray(N.Eq)([]), new Set([])) // tslint:disable-next-line: deprecation U.deepStrictEqual(_.fromArray(N.Eq)([1]), new Set([1])) // tslint:disable-next-line: deprecation U.deepStrictEqual(_.fromArray(N.Eq)([1, 1]), new Set([1])) // tslint:disable-next-line: deprecation U.deepStrictEqual(_.fromArray(N.Eq)([1, 2]), new Set([1, 2])) // tslint:disable-next-line: deprecation U.deepStrictEqual(_.fromArray(fooEq)(['a', 'a', 'b'].map(foo)), new Set(['a', 'b'].map(foo))) }) it('compact', () => { U.deepStrictEqual(_.compact(N.Eq)(new Set([optionSome(1), none, optionSome(2)])), new Set([1, 2])) type R = { readonly id: string } const E: Eq.Eq<R> = pipe( S.Eq, Eq.contramap((x) => x.id) ) U.deepStrictEqual( _.compact(E)(new Set([optionSome({ id: 'a' }), none, optionSome({ id: 'a' })])), new Set([{ id: 'a' }]) ) }) it('separate', () => { U.deepStrictEqual( _.separate(S.Eq, N.Eq)(new Set([right(1), left('a'), right(2)])), separated(new Set(['a']), new Set([1, 2])) ) type L = { readonly error: string } type R = { readonly id: string } const SL: Eq.Eq<L> = pipe( S.Eq, Eq.contramap((x) => x.error) ) const SR: Eq.Eq<R> = pipe( S.Eq, Eq.contramap((x) => x.id) ) U.deepStrictEqual( _.separate( SL, SR )(new Set([right({ id: 'a' }), left({ error: 'error' }), right({ id: 'a' }), left({ error: 'error' })])), separated(new Set([{ error: 'error' }]), new Set([{ id: 'a' }])) ) }) it('filterMap', () => { U.deepStrictEqual( _.filterMap(N.Eq)((s: string) => (s.length > 1 ? optionSome(s.length) : none))(new Set(['a', 'bb', 'ccc'])), new Set([2, 3]) ) type R = { readonly id: string } const E: Eq.Eq<R> = pipe( S.Eq, Eq.contramap((x) => x.id) ) U.deepStrictEqual( _.filterMap(E)((x: { readonly id: string }) => optionSome(x))(new Set([{ id: 'a' }, { id: 'a' }])), new Set([{ id: 'a' }]) ) }) it('getShow', () => { const Sh = _.getShow(S.Show) const s1 = new Set<string>([]) U.deepStrictEqual(Sh.show(s1), `new Set([])`) const s2 = new Set<string>(['a']) U.deepStrictEqual(Sh.show(s2), `new Set(["a"])`) const s3 = new Set<string>(['b', 'a']) U.deepStrictEqual(Sh.show(s3), `new Set(["a", "b"])`) }) it('fromSet', () => { const as = new Set(['a']) const bs = _.fromSet(as) U.deepStrictEqual(bs, as) assert.notStrictEqual(bs, as) }) it('toSet', () => { const as: ReadonlySet<string> = new Set(['a']) const bs = _.toSet(as) U.deepStrictEqual(bs, as) assert.notStrictEqual(bs, as) }) it('isEmpty', () => { U.deepStrictEqual(_.isEmpty(_.empty), true) U.deepStrictEqual(_.isEmpty(new Set()), true) U.deepStrictEqual(_.isEmpty(new Set(['a'])), false) }) it('size', () => { U.deepStrictEqual(_.size(_.empty), 0) U.deepStrictEqual(_.size(new Set()), 0) U.deepStrictEqual(_.size(new Set(['a'])), 1) }) it('toggle', () => { U.deepStrictEqual(_.toggle(N.Eq)(1)(new Set([2])), new Set([1, 2])) U.deepStrictEqual(_.toggle(N.Eq)(1)(new Set([1, 2])), new Set([2])) }) })
the_stack
import * as Block from './block' import * as NodeApi from './node-api' import * as BlockStore from './block-store' import * as BlockStoreInMemory from './block-store-inmemory' import * as MiniObservable from './mini-observable' const IS_DEBUG = false interface EventListenerInfo<T extends 'head' | 'block'> { listener: NodeApi.NodeEventListener<T> options: NodeApi.NodeEventListenerOptionsMap[T] } export class NodeImpl implements NodeApi.NodeApi { private headListeners: EventListenerInfo<'head'>[] = [] private blockListeners: EventListenerInfo<'block'>[] = [] private headEvents = new MiniObservable.SimpleEventEmitter<void>() private lastHeadEvents = new Set<string>() private blocksToNotify: string[] = [] constructor(private blockStore: BlockStore.BlockStore = new BlockStoreInMemory.InMemoryBlockStore()) { this.headEvents.subscribe(_ => this.notifyAllEvents()) } private async notifyAllEvents() { let blocksToNotify = this.blocksToNotify this.blocksToNotify = [] if (this.blockListeners.length) { for (let blockId of blocksToNotify) { this.notifyEvent({ type: 'block', blockId }) } } let lastHeadEvents = this.lastHeadEvents this.lastHeadEvents = new Set() for (let branch of lastHeadEvents) { let headBlockId = await this.blockStore.getBranchHead(branch) console.log(`branch ${branch} : ${headBlockId.substr(0, 7)}`) this.notifyEvent({ type: 'head', branch, headBlockId }) } } async blocks(callback: (blockId: string, block: Block.Block) => any) { await this.blockStore.blocks(callback) } async branches(): Promise<string[]> { return this.blockStore.getBranches() } async blockChainHead(branch: string) { return this.blockStore.getBranchHead(branch) } async blockChainBlockIds(startBlockId: string, depth: number): Promise<string[]> { return (await this.browseBlockchainByFirstParent(startBlockId, depth, false)).map(item => item.metadata.blockId) } async blockChainBlockMetadata(startBlockId: string, depth: number): Promise<Block.BlockMetadata[]> { return (await this.browseBlockchainByFirstParent(startBlockId, depth, false)).map(item => item.metadata) } async blockChainBlockData(startBlockId: string, depth: number): Promise<Block.Block[]> { return (await this.browseBlockchainByFirstParent(startBlockId, depth, true)).map(item => item.block) } // registers a new block in the collection // process block's metadata // update head if required (new block is valid and has the longest chain) async registerBlock(blockId: string, block: Block.Block): Promise<Block.BlockMetadata> { //console.log(`receive block ${blockId}`) if (!blockId || !block || !block.branch) { console.error(`invalid block ! Aborting registration`) return null } if (await this.blockStore.hasBlockData(blockId)) { //console.log(`already registered block ${blockId && blockId.substring(0, 5)}`) return await this.blockStore.getBlockMetadata(blockId) } let fixedId = await Block.idOfBlock(block) if (fixedId != blockId) { console.warn(`skipping a block with wrong advertized id ${blockId} ${fixedId}\n${JSON.stringify(block, null, 4)}`) return null } await this.blockStore.setBlockData(blockId, block) return this.processBlockMetadata(blockId, block) } private async processBlockMetadata(blockId: string, block: Block.Block) { if (!blockId || !block) throw `processBlockMetadata received null args` if (await this.blockStore.hasBlockMetadata(blockId)) { return } // check we have all the parents, if not add missing parents to wait list if (block.previousBlockIds) { let isWaitingForParents = false for (let parentBlockId of block.previousBlockIds) { if (!await this.blockStore.hasBlockMetadata(parentBlockId)) { //console.log(`${blockId} waits for parent ${parentBlockId}`) await this.blockStore.registerWaitingBlock(blockId, parentBlockId) isWaitingForParents = true } } if (isWaitingForParents) return } let metadata = this.realProcessBlock(blockId, block) return metadata } private async maybeWakeupBlocks(blockId: string) { if (!await this.blockStore.hasBlockMetadata(blockId)) { console.error(`waking up without metadata`) return } if (!await this.blockStore.hasBlockData(blockId)) { console.error(`waking up without data`) return } let waitingBlocks = [] await this.blockStore.browseWaitingBlocksAndForget(blockId, waitingBlockId => { waitingBlocks.push(waitingBlockId) }) for (let waitingBlockId of waitingBlocks) { let waitingBlock = await this.blockStore.getBlockData(waitingBlockId) if (!waitingBlockId || !waitingBlock) { console.error(`error cannot find block ${waitingBlockId} data triggered by ${blockId}`) return } await this.realProcessBlock(waitingBlockId, waitingBlock) } } private async realProcessBlock(blockId: string, block: Block.Block) { let metadata = await this.processMetaData(blockId, block) if (!metadata) { console.error("cannot build metadata for block") return null } if (blockId != metadata.blockId) { console.error(`is someone hacking us ?`) return } IS_DEBUG && console.log(`store metadata for ${metadata.blockId}`); await this.blockStore.setBlockMetadata(metadata.blockId, metadata) this.blocksToNotify.push(blockId) await this.maybeUpdateHead(block, metadata) this.headEvents.emit(null) //this.notifyAllEvents() await this.maybeWakeupBlocks(metadata.blockId) return metadata } private async maybeUpdateHead(block: Block.Block, metadata: Block.BlockMetadata) { let oldHead = await this.blockStore.getBranchHead(block.branch) if (metadata.isValid && await this.compareBlockchains(metadata.blockId, oldHead) > 0) { if (!metadata.blockId || !block.branch) return this.blockStore.setBranchHead(block.branch, metadata.blockId) IS_DEBUG && console.log(`new head on branch ${block.branch} : ${metadata.blockId.substring(0, 5)}`) this.lastHeadEvents.add(block.branch) } } async addEventListener<K extends keyof NodeApi.BlockchainEventMap>(type: K, options: NodeApi.NodeEventListenerOptionsMap[K], listener: (event: NodeApi.BlockchainEventMap[K]) => any): Promise<void> { let info = { listener, options } switch (type) { case 'head': this.headListeners.push(info) for (let branch of await this.blockStore.getBranches()) this.notifyHeadEventToListener({ type: 'head', branch, headBlockId: await this.blockStore.getBranchHead(branch) }, info) break case 'block': this.blockListeners.push(info) // TODO fix that await this.blockStore.blocks(blockId => listener({ type: 'block', blockId })) break } } removeEventListener<K extends keyof NodeApi.BlockchainEventMap>(eventListener: NodeApi.NodeEventListener<K>): void { this.blockListeners = this.blockListeners.filter(el => el.listener !== eventListener) this.headListeners = this.headListeners.filter(el => el.listener !== eventListener) } async knowsBlock(id: string): Promise<boolean> { return this.blockStore.hasBlockData(id) } async knowsBlockAsValidated(id: string): Promise<boolean> { return this.blockStore.hasBlockMetadata(id) } // TODO : with generic validation, compare the global validation value (pow, pos, other...) private async compareBlockchains(block1Id: string, block2Id: string): Promise<number> { if (block1Id == block2Id) return 0 if (!block1Id) return -1 if (!block2Id) return 1 let meta1 = await this.blockStore.getBlockMetadata(block1Id) let meta2 = await this.blockStore.getBlockMetadata(block2Id) if (!meta1 || !meta2) throw "error, not enough block history" // valid is biggest if (!meta1.isValid) return -1 if (!meta2.isValid) return 1 // TODO : use parametrized algorithm for validation and trusting // greatest confidence if (meta1.confidence > meta2.confidence) return 1 if (meta1.confidence < meta2.confidence) return -1 // greatest number of blocks (maximum diversity) if (meta1.blockCount > meta2.blockCount) return 1 if (meta1.blockCount < meta2.blockCount) return -1 // biggest id return meta1.blockId.localeCompare(meta2.blockId) } private notifyEvent(event: NodeApi.NodeEvent) { IS_DEBUG && console.log(`notify ${event.type} ${JSON.stringify(event)}`) if (event.type == 'block') { this.blockListeners.forEach(listener => listener.listener(event)) } else if (event.type == 'head') { this.headListeners.forEach(listener => this.notifyHeadEventToListener(event, listener)) } } private notifyHeadEventToListener(event: NodeApi.BlockchainEventMap['head'], listener: EventListenerInfo<'head'>) { if (!listener.options || !listener.options.branch || listener.options.branch == (event as NodeApi.BlockchainEventMap['head']).branch) { listener.listener(event as NodeApi.BlockchainEventMap['head']) } } /** * @param blockId Be careful the blockId must be valid ! * @param block */ private async processMetaData(blockId: string, block: Block.Block): Promise<Block.BlockMetadata> { if (!blockId || !block) { console.log(`error cannot find block`) return null } let blockCount = 1 let confidence = Block.blockConfidence(block) if (block.previousBlockIds) { for (let previousBlockId of block.previousBlockIds) { let previousBlockMetadata = await this.blockStore.getBlockMetadata(previousBlockId) if (!previousBlockMetadata) { console.log("cannot find the parent block in database, so cannot processMetadata") return null } blockCount += 1 * previousBlockMetadata.blockCount confidence += 1 * previousBlockMetadata.confidence } } // TODO find the process through which difficulty is raised let metadata: Block.BlockMetadata = { blockId, previousBlockIds: block.previousBlockIds, isValid: await Block.isBlockValid(block), blockCount, confidence } return metadata } private async browseBlockchainByFirstParent(startBlockId: string, depth: number, fetchBlocks: boolean) { let result: { metadata: Block.BlockMetadata; block: Block.Block; }[] = [] while (startBlockId && depth-- > 0) { let metadata = await this.blockStore.getBlockMetadata(startBlockId) let block = fetchBlocks ? await this.blockStore.getBlockData(startBlockId) : null result.push({ metadata, block }) // TODO this only browse first parent, it should browser the entire tree ! startBlockId = metadata && metadata.previousBlockIds && metadata.previousBlockIds.length && metadata.previousBlockIds[0] } return result } }
the_stack
import { css } from "../src/css" import { toCSSVar } from "../src/create-theme-vars" const theme = toCSSVar({ breakpoints: { sm: "40em", md: "52em", lg: "64em", xl: "80em", }, colors: { red: { 500: "#ff0000", }, primary: "tomato", secondary: "cyan", }, fontSizes: [12, 14, 16, 24, 36], space: [0, 4, 8, 16, 32, 64, 128, 256, 512], fonts: { monospace: "Menlo, monospace", }, lineHeights: { body: 1.5, }, fontWeights: { bold: 600, }, sizes: { small: 4, medium: 8, large: 16, sidebar: 320, }, buttons: { primary: { p: 3, fontWeight: "bold", color: "white", bg: "primary", borderRadius: 2, }, }, text: { caps: { fontSize: [1, 2], letterSpacing: "0.1em", textTransform: "uppercase", }, title: { fontSize: [3, 4], letterSpacing: ["-0.01em", "-0.02em"], }, }, borderWidths: { thin: 1, }, borderStyles: { thick: "solid", }, radii: { small: 5, }, textTransform: { header: "uppercase", }, transition: { duration: { slow: "1s", }, easing: { smooth: "ease-in-out", }, property: { common: "opacity, transform, background-color, color", }, }, }) test("returns system props styles", () => { const result = css({ color: "primary", fontSize: [2, 3, 4], })(theme) expect(result).toMatchInlineSnapshot(` Object { "@media screen and (min-width: 40em)": Object { "fontSize": "var(--fontSizes-3)", }, "@media screen and (min-width: 52em)": Object { "fontSize": "var(--fontSizes-4)", }, "color": "var(--colors-primary)", "fontSize": "var(--fontSizes-2)", } `) }) test("returns nested system props styles", () => { const result = css({ color: "primary", "&:hover": { color: "secondary", }, })(theme) expect(result).toMatchInlineSnapshot(` Object { "&:hover": Object { "color": "var(--colors-secondary)", }, "color": "var(--colors-primary)", } `) }) test("returns nested responsive styles", () => { const result = css({ color: "primary", h1: { py: [3, 4], }, })(theme) expect(result).toMatchInlineSnapshot(` Object { "color": "var(--colors-primary)", "h1": Object { "@media screen and (min-width: 40em)": Object { "paddingBottom": "var(--space-4)", "paddingTop": "var(--space-4)", }, "paddingBottom": "var(--space-3)", "paddingTop": "var(--space-3)", }, } `) }) test("handles all core styled system props", () => { const result = css({ m: 0, mb: 2, mx: "auto", p: 3, py: 4, fontSize: 3, fontWeight: "bold", color: "primary", bg: "secondary", fontFamily: "monospace", lineHeight: "body", textTransform: "uppercase", })(theme) expect(result).toMatchInlineSnapshot(` Object { "background": "var(--colors-secondary)", "color": "var(--colors-primary)", "fontFamily": "var(--fonts-monospace)", "fontSize": "var(--fontSizes-3)", "fontWeight": "var(--fontWeights-bold)", "lineHeight": "var(--lineHeights-body)", "margin": "var(--space-0)", "marginBottom": "var(--space-2)", "marginInlineEnd": "auto", "marginInlineStart": "auto", "padding": "var(--space-3)", "paddingBottom": "var(--space-4)", "paddingTop": "var(--space-4)", "textTransform": "uppercase", } `) }) test("works with the css prop", () => { const result = css({ color: "primary", m: 0, fontSize: 2, })(theme) expect(result).toMatchInlineSnapshot(` Object { "color": "var(--colors-primary)", "fontSize": "var(--fontSizes-2)", "margin": "var(--space-0)", } `) }) test("works with functional arguments", () => { const result = css((t: any) => ({ color: t.colors.primary, }))(theme) expect(result).toEqual({ color: "tomato", }) }) test("supports functional values", () => { const result = css({ color: (t: any) => t.colors.primary, })(theme) expect(result).toEqual({ color: "tomato", }) }) test("returns variants from theme", () => { const result = css({ apply: "buttons.primary", })(theme) expect(result).toMatchInlineSnapshot(` Object { "background": "var(--colors-primary)", "borderRadius": "2px", "color": "white", "fontWeight": "var(--fontWeights-bold)", "padding": "var(--space-3)", } `) }) test("handles variants with responsive values", () => { const result = css({ apply: "text.caps", })(theme) expect(result).toMatchInlineSnapshot(` Object { "@media screen and (min-width: 40em)": Object { "fontSize": "var(--fontSizes-2)", }, "fontSize": "var(--fontSizes-1)", "letterSpacing": "0.1em", "textTransform": "uppercase", } `) }) test("handles responsive variants", () => { const result = css({ apply: "text.title", })(theme) expect(result).toMatchInlineSnapshot(` Object { "@media screen and (min-width: 40em)": Object { "fontSize": "var(--fontSizes-4)", "letterSpacing": "-0.02em", }, "fontSize": "var(--fontSizes-3)", "letterSpacing": "-0.01em", } `) }) test("handles negative margins from scale", () => { const result = css({ mt: -3, mx: -4, })(theme) expect(result).toMatchInlineSnapshot(` Object { "marginInlineEnd": "calc(var(--space-4) * -1)", "marginInlineStart": "calc(var(--space-4) * -1)", "marginTop": "calc(var(--space-3) * -1)", } `) }) test("handles negative values from custom css var scale", () => { const customTheme = toCSSVar({ ...theme, space: ["var(--size-0)", "var(--size-1)", "var(--size-2)", "var(--size-3)"], }) const result = css({ mt: -1, mx: -2, top: -3, right: -3, bottom: -3, left: -3, })(customTheme) // Custom CSS variables are mapped to CSS vars controlled by chakra expect(result).toMatchInlineSnapshot(` Object { "bottom": "calc(var(--space-3) * -1)", "left": "calc(var(--space-3) * -1)", "marginInlineEnd": "calc(var(--space-2) * -1)", "marginInlineStart": "calc(var(--space-2) * -1)", "marginTop": "calc(var(--space-1) * -1)", "right": "calc(var(--space-3) * -1)", "top": "calc(var(--space-3) * -1)", } `) }) test("handles negative top, left, bottom, and right from scale", () => { const result = css({ top: -1, right: -4, bottom: -3, left: -2, })(theme) expect(result).toMatchInlineSnapshot(` Object { "bottom": "calc(var(--space-3) * -1)", "left": "calc(var(--space-2) * -1)", "right": "calc(var(--space-4) * -1)", "top": "calc(var(--space-1) * -1)", } `) }) test("skip breakpoints", () => { const result = css({ width: ["100%", null, "50%"], })(theme) expect(result).toEqual({ width: "100%", "@media screen and (min-width: 40em)": {}, "@media screen and (min-width: 52em)": { width: "50%", }, }) }) test("padding shorthand does not collide with nested p selector", () => { const result = css({ p: { fontSize: 32, color: "tomato", p: 2, }, padding: 32, })(theme) expect(result).toMatchInlineSnapshot(` Object { "p": Object { "color": "tomato", "fontSize": "32px", "padding": "var(--space-2)", }, "padding": "32px", } `) }) // test.skip("ignores array values longer than breakpoints", () => { // // intentionally not using createBreakpoints here // // because you cant just slice off it // const customBreakpoints: any = ["0em", "32em", "40em"] // customBreakpoints.base = customBreakpoints[0] // customBreakpoints.sm = customBreakpoints[1] // customBreakpoints.lg = customBreakpoints[2] // const result = css({ // width: [32, 64, 128, 256, 512], // })({ // breakpoints: customBreakpoints, // }) // expect(result).toEqual({ // width: 32, // "@media screen and (min-width: 32em)": { // width: 64, // }, // "@media screen and (min-width: 40em)": { // width: 128, // }, // }) // }) test("functional values can return responsive arrays", () => { const result = css({ color: (t: any) => [t.colors.primary, t.colors.secondary], })(theme) expect(result).toMatchInlineSnapshot(` Object { "@media screen and (min-width: 40em)": Object { "color": "cyan", }, "color": "tomato", } `) }) test("resolves color correctly", () => { const result = css({ color: "red", })(theme) expect(result).toEqual({ color: "red", }) }) test("returns individual border styles", () => { const result = css({ borderTopWidth: "thin", borderTopColor: "primary", borderTopStyle: "thick", borderTopLeftRadius: "small", borderTopRightRadius: "small", borderBottomWidth: "thin", borderBottomColor: "primary", borderBottomStyle: "thick", borderBottomLeftRadius: "small", borderBottomRightRadius: "small", borderRightWidth: "thin", borderRightColor: "primary", borderRightStyle: "thick", borderLeftWidth: "thin", borderLeftColor: "primary", borderLeftStyle: "thick", })(toCSSVar(theme)) expect(result).toMatchInlineSnapshot(` Object { "borderBottomColor": "var(--colors-primary)", "borderBottomLeftRadius": "var(--radii-small)", "borderBottomRightRadius": "var(--radii-small)", "borderBottomStyle": "var(--borderStyles-thick)", "borderBottomWidth": "var(--borderWidths-thin)", "borderLeftColor": "var(--colors-primary)", "borderLeftStyle": "var(--borderStyles-thick)", "borderLeftWidth": "var(--borderWidths-thin)", "borderRightColor": "var(--colors-primary)", "borderRightStyle": "var(--borderStyles-thick)", "borderRightWidth": "var(--borderWidths-thin)", "borderTopColor": "var(--colors-primary)", "borderTopLeftRadius": "var(--radii-small)", "borderTopRightRadius": "var(--radii-small)", "borderTopStyle": "var(--borderStyles-thick)", "borderTopWidth": "var(--borderWidths-thin)", } `) }) test("flexBasis uses theme.sizes", () => { const style = css({ flexBasis: "sidebar", })(toCSSVar(theme)) expect(style).toMatchInlineSnapshot(` Object { "flexBasis": "var(--sizes-sidebar)", } `) }) test("fill and stroke use theme.colors", () => { const style = css({ fill: "primary", stroke: "secondary", })(theme) expect(style).toMatchInlineSnapshot(` Object { "fill": "var(--colors-primary)", "stroke": "var(--colors-secondary)", } `) }) test("multiples are transformed", () => { const style = css({ marginX: 2, marginY: 2, paddingX: 2, paddingY: 2, width: "large", })(theme) expect(style).toMatchInlineSnapshot(` Object { "marginBottom": "var(--space-2)", "marginInlineEnd": "var(--space-2)", "marginInlineStart": "var(--space-2)", "marginTop": "var(--space-2)", "paddingBottom": "var(--space-2)", "paddingInlineEnd": "var(--space-2)", "paddingInlineStart": "var(--space-2)", "paddingTop": "var(--space-2)", "width": "var(--sizes-large)", } `) }) test("returns outline color from theme", () => { const result = css({ outlineColor: "primary", })(theme) expect(result).toMatchInlineSnapshot(` Object { "outlineColor": "var(--colors-primary)", } `) }) test("returns correct media query order", () => { const result = css({ width: ["100%", null, "50%"], color: ["red", "green", "blue"], })(theme) expect(result).toMatchInlineSnapshot(` Object { "@media screen and (min-width: 40em)": Object { "color": "green", }, "@media screen and (min-width: 52em)": Object { "color": "blue", "width": "50%", }, "color": "red", "width": "100%", } `) }) test("returns correct media query 2nd order", () => { const result = css({ flexDirection: "column", justifyContent: [null, "flex-start", "flex-end"], color: "background", height: "100%", px: [2, 3, 4], py: 4, })(theme) const keys = Object.keys(result) expect(keys).toMatchInlineSnapshot(` Array [ "flexDirection", "justifyContent", "@media screen and (min-width: 40em)", "@media screen and (min-width: 52em)", "color", "height", "paddingInlineStart", "paddingInlineEnd", "paddingTop", "paddingBottom", ] `) }) test("pseudo selectors are transformed", () => { const result = css({ _before: { paddingBottom: 2, paddingLeft: [2, 3, 4], paddingRight: { base: 1, sm: 2 }, }, })(theme) expect(result).toMatchInlineSnapshot(` Object { "&::before": Object { "@media screen and (min-width: 40em)": Object { "paddingLeft": "var(--space-3)", "paddingRight": "var(--space-2)", }, "@media screen and (min-width: 52em)": Object { "paddingLeft": "var(--space-4)", }, "paddingBottom": "var(--space-2)", "paddingLeft": "var(--space-2)", "paddingRight": "var(--space-1)", }, } `) }) test("should expand textStyle and layerStyle", () => { const theme = toCSSVar({ colors: { red: { 300: "#red" } }, breakpoints: { sm: "400px", md: "768px", lg: "1200px", xl: "1800px", }, layerStyles: { v1: { color: "red.300", bg: "tomato", }, }, textStyles: { caps: { textTransform: "uppercase", letterSpacing: "wide", fontSize: "lg", }, lower: { textTransform: "lowercase", letterSpacing: "0.2px", fontSize: "sm", }, }, }) expect(css({ layerStyle: "v1" })(theme)).toMatchInlineSnapshot(` Object { "background": "tomato", "color": "var(--colors-red-300)", } `) expect(css({ textStyle: "caps" })(theme)).toMatchInlineSnapshot(` Object { "fontSize": "lg", "letterSpacing": "wide", "textTransform": "uppercase", } `) expect(css({ textStyle: ["caps", "lower"] })(theme)).toMatchInlineSnapshot(` Object { "@media screen and (min-width: 400px)": Object { "fontSize": "sm", "letterSpacing": "0.2px", "textTransform": "lowercase", }, "fontSize": "lg", "letterSpacing": "wide", "textTransform": "uppercase", } `) }) test("transition tokens are replaced correctly", () => { expect( css({ transitionProperty: "common", transitionDuration: "slow", transitionTimingFunction: "smooth", })(theme), ).toMatchInlineSnapshot(` Object { "transitionDuration": "var(--transition-duration-slow)", "transitionProperty": "var(--transition-property-common)", "transitionTimingFunction": "var(--transition-easing-smooth)", } `) })
the_stack
import React from 'react'; import PropTypes from 'prop-types'; import { format as dateFnsFormat } from 'date-fns'; import { noop } from 'lodash'; import BaseComponent, { BaseProps } from '../_base/baseComponent'; import { strings } from '@douyinfe/semi-foundation/timePicker/constants'; import ScrollList from '../scrollList/index'; import ScrollItem from '../scrollList/scrollItem'; import ComboboxFoundation, { formatOption } from '@douyinfe/semi-foundation/timePicker/ComboxFoundation'; import LocaleConsumer from '../locale/localeConsumer'; import { TimePickerProps } from './TimePicker'; import { Locale } from '../locale/interface'; export type ComboboxProps = Pick<TimePickerProps, 'format' | 'prefixCls' | 'disabledHours' | 'disabledMinutes' | 'disabledSeconds' | 'hideDisabledOptions' | 'use12Hours' | 'scrollItemProps' | 'panelFooter' | 'panelHeader'> & BaseProps & { defaultOpenValue?: TimePickerProps['value']; showHour?: boolean; showMinute?: boolean; showSecond?: boolean; onChange?: (value: { isAM: boolean; value: string; timeStampValue: number }) => void; onCurrentSelectPanelChange?: (range: string) => void; isAM?: boolean; timeStampValue?: any; }; export interface ComboboxState { showHour: boolean; showMinute: boolean; showSecond: boolean; hourOptions: number[]; minuteOptions: number[]; secondOptions: number[]; } export type FormatOptionReturn = ReturnType<typeof formatOption>; export interface AMPMOptionItem { value: string; text: string; } class Combobox extends BaseComponent<ComboboxProps, ComboboxState> { static propTypes = { format: PropTypes.string, defaultOpenValue: PropTypes.object, prefixCls: PropTypes.string, onChange: PropTypes.func, showHour: PropTypes.bool, showMinute: PropTypes.bool, showSecond: PropTypes.bool, disabledHours: PropTypes.func, disabledMinutes: PropTypes.func, disabledSeconds: PropTypes.func, hideDisabledOptions: PropTypes.bool, onCurrentSelectPanelChange: PropTypes.func, use12Hours: PropTypes.bool, isAM: PropTypes.bool, timeStampValue: PropTypes.any, scrollItemProps: PropTypes.object, }; static defaultProps = { disabledHours: noop, disabledMinutes: noop, disabledSeconds: noop, format: strings.DEFAULT_FORMAT, }; foundation: ComboboxFoundation; constructor(props: ComboboxProps) { super(props); this.foundation = new ComboboxFoundation(this.adapter); this.state = { ...this.foundation.initData(), }; } componentDidUpdate(prevProps: ComboboxProps, prevState: ComboboxState) { if (prevProps.timeStampValue !== this.props.timeStampValue || prevProps.format !== this.props.format) { this.setState({ ...this.foundation.initData(), }); } } componentWillUnmount() { // this.foundation.destroy(); } componentDidMount() { // this.foundation.init(); } cacheRefCurrent = (key: string, current: ScrollItem<FormatOptionReturn> | ScrollItem<AMPMOptionItem>) => { if (key && typeof key === 'string') { this.adapter.setCache(key, current); } }; reselect = () => { const currentKeys = ['ampm', 'hour', 'minute', 'second']; currentKeys.forEach(key => { const current = this.adapter.getCache(key); if (current && current.scrollToIndex) { current.scrollToIndex(); } }); }; onItemChange = ({ type, value, disabled }: { type?: string; value: string; disabled?: boolean; }) => { // eslint-disable-next-line prefer-const let { onChange, use12Hours, isAM, format, timeStampValue } = this.props; const transformValue = this.foundation.getDisplayDateFromTimeStamp(timeStampValue); // TODO: foundation if (type === 'hour') { if (use12Hours) { if (isAM) { transformValue.setHours(Number(value) % 12); } else { transformValue.setHours((Number(value) % 12) + 12); } } else { transformValue.setHours(Number(value)); } } else if (type === 'minute') { transformValue.setMinutes(Number(value)); } else if (type === 'ampm') { const ampm = value.toUpperCase(); if (use12Hours) { if (ampm === 'PM') { isAM = false; transformValue.getHours() < 12 && transformValue.setHours((transformValue.getHours() % 12) + 12); } if (ampm === 'AM') { isAM = true; transformValue.getHours() >= 12 && transformValue.setHours(transformValue.getHours() - 12); } } } else { transformValue.setSeconds(Number(value)); } onChange && onChange({ isAM, value: dateFnsFormat(transformValue, format && format.replace(/(\s+)A/g, '$1a')), // dateFns only supports "h: mm: ss a" timeStampValue: Number(transformValue), }); }; onEnterSelectPanel = (range: string) => { const { onCurrentSelectPanelChange } = this.props; onCurrentSelectPanelChange(range); }; renderHourSelect(hour: number, locale: Locale['TimePicker']) { const { prefixCls, disabledHours, use12Hours, scrollItemProps } = this.props; const { showHour, hourOptions } = this.state; if (!showHour) { return null; } const disabledOptions = disabledHours(); let hourOptionsAdj, hourAdj; if (use12Hours) { hourOptionsAdj = [12].concat(hourOptions.filter(h => h < 12 && h > 0)); hourAdj = hour % 12 || 12; } else { hourOptionsAdj = hourOptions; hourAdj = hour; } const transformHour = (value: string) => value + locale.hour; const className = `${prefixCls}-list-hour`; return ( <ScrollItem<FormatOptionReturn> ref={current => this.cacheRefCurrent('hour', current)} mode={'wheel'} transform={transformHour} cycled={true} className={className} list={hourOptionsAdj.map(option => formatOption(option, disabledOptions))} selectedIndex={hourOptionsAdj.indexOf(hourAdj)} type="hour" onSelect={this.onItemChange} {...scrollItemProps} /> ); } renderMinuteSelect(minute: number, locale: Locale['TimePicker']) { const { prefixCls, disabledMinutes, timeStampValue, scrollItemProps } = this.props; const { showMinute, minuteOptions } = this.state; if (!showMinute) { return null; } const value = new Date(timeStampValue); const disabledOptions = disabledMinutes && disabledMinutes(value.getHours()); const className = `${prefixCls}-list-minute`; const transformMinute = (min: string) => min + locale.minute; return ( <ScrollItem<FormatOptionReturn> ref={current => this.cacheRefCurrent('minute', current)} mode={'wheel'} transform={transformMinute} cycled={true} list={minuteOptions.map(option => formatOption(option, disabledOptions))} selectedIndex={minuteOptions.indexOf(minute)} type="minute" onSelect={this.onItemChange} className={className} {...scrollItemProps} /> ); } renderSecondSelect(second: number, locale: Locale['TimePicker']) { const { prefixCls, disabledSeconds, timeStampValue, scrollItemProps } = this.props; const { showSecond, secondOptions } = this.state; if (!showSecond) { return null; } const value = new Date(timeStampValue); const disabledOptions = disabledSeconds && disabledSeconds(value.getHours(), value.getMinutes()); const className = `${prefixCls}-list-second`; const transformSecond = (sec: number) => String(sec) + locale.second; return ( <ScrollItem<FormatOptionReturn> ref={current => this.cacheRefCurrent('second', current)} mode={'wheel'} transform={transformSecond} cycled={true} list={secondOptions.map(option => formatOption(option, disabledOptions))} selectedIndex={secondOptions.indexOf(second)} className={className} type="second" onSelect={this.onItemChange} {...scrollItemProps} /> ); } renderAMPMSelect(locale: Locale['TimePicker'], localeCode: string) { const { prefixCls, use12Hours, isAM, scrollItemProps } = this.props; if (!use12Hours) { return null; } const AMPMOptions: AMPMOptionItem[] = [ { value: 'AM', text: locale.AM || '上午', }, { value: 'PM', text: locale.PM || '下午', }, ]; const selected = isAM ? 0 : 1; const className = `${prefixCls}-list-ampm`; return ( <ScrollItem<AMPMOptionItem> ref={current => this.cacheRefCurrent('ampm', current)} mode={'wheel'} className={className} cycled={false} list={AMPMOptions} selectedIndex={selected} type="ampm" onSelect={this.onItemChange} {...scrollItemProps} /> ); } getDisplayDateFromTimeStamp = (timeStampValue: Date | string) => this.foundation.getDisplayDateFromTimeStamp(timeStampValue); render() { const { timeStampValue, panelHeader, panelFooter } = this.props; const value = this.getDisplayDateFromTimeStamp(timeStampValue); return ( <LocaleConsumer componentName="TimePicker"> {(locale: Locale['TimePicker'], localeCode: Locale['code']) => ( <ScrollList header={panelHeader} footer={panelFooter}> {this.renderAMPMSelect(locale, localeCode)} {this.renderHourSelect(value.getHours(), locale)} {this.renderMinuteSelect(value.getMinutes(), locale)} {this.renderSecondSelect(value.getSeconds(), locale)} </ScrollList> )} </LocaleConsumer> ); } } export default Combobox;
the_stack
import * as React from "react" import { ScrollDiv } from "../ScrollDiv.js" import { SizingDiv } from "../SizingDiv.js" import { StickyDiv } from "../StickyDiv.js" import type { GridProps } from "../types.js" import { useDataDimension } from "../useDataDimension.js" import { useIndicesForDimensions } from "../useDimensionIndices.js" import { useScrollAdjustWindowDims } from "../useScrollAdjustedDim.js" import { useScrollItems } from "../useScrollItems.js" import { useSmartSticky } from "../useSmartSticky.js" import { useWindowApi } from "../useWindowApi.js" import { useWindowDimensions } from "../useWindowDimensions.js" import { useWindowScroll } from "../useWindowScroll.js" export function Grid<T>({ data, children, defaultRowHeight, rowHeights, defaultColumnWidth, columnWidths, tabIndex, overscan: userOverscan, apiRef, disableSticky: userDisableSticky, "data-testid": testId, getKey, className, style, width: sizingWidth, height: sizingHeight, onScroll: userOnScroll, pinnedTopCount = 0, pinnedBottomCount = 0, pinnedLeftCount = 0, pinnedRightCount = 0, }: GridProps<T>) { const windowRef = React.useRef<HTMLDivElement>(null) useWindowApi(windowRef, apiRef) const [width, height, browserWidth] = useWindowDimensions(windowRef) const [overscan, disableSticky] = useSmartSticky(browserWidth, userOverscan, userDisableSticky) const [topOffset, leftOffset, onScroll] = useWindowScroll({ userOnScroll, }) const [topLeft, topMid, topRight, midLeft, midMid, midRight, botLeft, botMid, botRight] = React.useMemo(() => { const topSection = data.slice(0, pinnedTopCount) const botSection = data.slice(pinnedTopCount, pinnedTopCount + pinnedBottomCount) const midSection = data.slice(pinnedTopCount + pinnedBottomCount) const topLeft = topSection.map((row) => row.slice(0, pinnedLeftCount)) const topMid = topSection.map((row) => row.slice(pinnedLeftCount)) const topRight = topSection.map((row) => row.slice(pinnedLeftCount, pinnedLeftCount + pinnedRightCount), ) const midLeft = midSection.map((row) => row.slice(0, pinnedLeftCount)) const midMid = midSection.map((row) => row.slice(pinnedLeftCount)) const midRight = midSection.map((row) => row.slice(pinnedLeftCount, pinnedLeftCount + pinnedRightCount), ) const botLeft = botSection.map((row) => row.slice(0, pinnedLeftCount)) const botMid = botSection.map((row) => row.slice(pinnedLeftCount)) const botRight = botSection.map((row) => row.slice(pinnedLeftCount, pinnedLeftCount + pinnedRightCount), ) return [topLeft, topMid, topRight, midLeft, midMid, midRight, botLeft, botMid, botRight] }, [data, pinnedBottomCount, pinnedLeftCount, pinnedRightCount, pinnedTopCount]) const [adjustedWidth, adjustedHeight] = useScrollAdjustWindowDims({ height, width, rowHeight: defaultRowHeight, columnWidth: defaultColumnWidth, columnWidths, rowHeights, rowCount: data.length, columnCount: data[0]?.length ?? 0, }) const [dataHeights, innerHeight] = useDataDimension({ count: midMid.length, defaultDimension: defaultRowHeight, windowDim: adjustedHeight, dimensions: rowHeights, }) const [dataWidths, innerWidth] = useDataDimension({ count: midMid[0]?.length ?? 0, defaultDimension: defaultColumnWidth, windowDim: adjustedWidth, dimensions: columnWidths, }) const [topHeights, totalTopHeight] = useDataDimension({ count: topMid.length, defaultDimension: defaultRowHeight, windowDim: adjustedHeight, dimensions: rowHeights, }) const [botHeights, totalBotHeight] = useDataDimension({ count: botMid.length, defaultDimension: defaultRowHeight, windowDim: adjustedHeight, dimensions: rowHeights, }) const totalLeftWidth = React.useMemo( () => (pinnedLeftCount ? dataWidths.slice(0, pinnedLeftCount).reduce((a, b) => a + b) : 0), [dataWidths, pinnedLeftCount], ) const totalRightWidth = React.useMemo( () => pinnedRightCount ? dataWidths .slice(pinnedLeftCount, pinnedLeftCount + pinnedRightCount) .reduce((a, b) => a + b) : 0, [dataWidths, pinnedLeftCount, pinnedRightCount], ) const [vertStart, vertEnd, runningHeight] = useIndicesForDimensions({ itemDimensions: dataHeights, offset: topOffset, windowDimension: height, overscan: overscan ?? 1, }) const [horiStart, horiEnd, runningWidth] = useIndicesForDimensions({ windowDimension: width, offset: leftOffset, itemDimensions: dataWidths, overscan: overscan ?? 1, }) const scrollableItems = useScrollItems({ children, data: midMid, dataHeights, dataWidths, getKey, horiEnd, horiStart, runningHeight, runningWidth, vertEnd, vertStart, }) const midLeftItems = useScrollItems({ children, data: midLeft, dataHeights, dataWidths, getKey, horiStart: 0, horiEnd: pinnedLeftCount, runningHeight, runningWidth: 0, vertStart, vertEnd, pinnedColumn: "left", }) const midRightItems = useScrollItems({ children, data: midRight, dataHeights, dataWidths, getKey, horiStart: 0, horiEnd: pinnedRightCount, runningHeight, runningWidth: 0, vertStart, vertEnd, pinnedColumn: "right", }) const topLeftItems = useScrollItems({ children, data: topLeft, dataHeights: topHeights, dataWidths, getKey, horiStart: 0, horiEnd: pinnedLeftCount, runningHeight: 0, runningWidth: 0, vertStart: 0, vertEnd: pinnedTopCount, pinnedColumn: "left", pinnedRow: "top", }) const topMidItems = useScrollItems({ children, data: topMid, dataHeights: topHeights, dataWidths, getKey, horiStart, horiEnd, runningHeight: 0, runningWidth, vertStart: 0, vertEnd: pinnedTopCount, pinnedRow: "top", }) const topRightItems = useScrollItems({ children, data: topRight, dataHeights: topHeights, dataWidths, getKey, horiStart: 0, horiEnd: pinnedRightCount, runningHeight: 0, runningWidth: 0, vertStart: 0, vertEnd: pinnedTopCount, pinnedColumn: "right", pinnedRow: "top", }) const botMidItems = useScrollItems({ children, data: botMid, dataHeights: botHeights, dataWidths, getKey, horiStart, horiEnd, runningHeight: 0, runningWidth, vertStart: 0, vertEnd: pinnedBottomCount, pinnedRow: "bottom", }) const botLeftItems = useScrollItems({ children, data: botLeft, dataHeights: botHeights, dataWidths, getKey, horiStart: 0, horiEnd: pinnedLeftCount, runningHeight: 0, runningWidth: 0, vertStart: 0, vertEnd: pinnedBottomCount, pinnedColumn: "left", pinnedRow: "bottom", }) const botRightItems = useScrollItems({ children, data: botRight, dataHeights: botHeights, dataWidths, getKey, horiStart: 0, horiEnd: pinnedRightCount, runningHeight: 0, runningWidth: 0, vertStart: 0, vertEnd: pinnedBottomCount, pinnedColumn: "right", pinnedRow: "top", }) return ( <SizingDiv width={sizingWidth} height={sizingHeight} testId={testId} className={className} userStyle={style} > <div ref={windowRef} tabIndex={tabIndex} onScroll={onScroll} style={{ contain: "strict", height, width, position: "relative", overflow: "auto", }} > <div style={{ width: innerWidth + totalLeftWidth + totalRightWidth, height: innerHeight + totalTopHeight + totalBotHeight, }} > <StickyDiv disabled={disableSticky ?? false} height={adjustedHeight} width={adjustedWidth} > {/* Scrollable Window */} <ScrollDiv disableSticky={disableSticky} topOffset={topOffset} leftOffset={leftOffset} top={totalTopHeight} left={totalLeftWidth} > {scrollableItems} </ScrollDiv> {/* Mid Left */} {!!pinnedLeftCount && ( <div style={{ position: "sticky", left: 0, width: adjustedWidth }}> <ScrollDiv disableSticky={disableSticky} topOffset={topOffset} leftOffset={0} top={totalTopHeight} left={0} > {midLeftItems} </ScrollDiv> </div> )} {/* Mid Right */} {!!pinnedRightCount && ( <div style={{ position: "sticky", left: 0, width: adjustedWidth }}> <ScrollDiv disableSticky={disableSticky} topOffset={topOffset} leftOffset={0} top={totalTopHeight} left={adjustedWidth - totalRightWidth} > {midRightItems} </ScrollDiv> </div> )} {/* Top Mid */} {!!pinnedTopCount && ( <div style={{ position: "sticky", top: 0, left: 0, }} > <ScrollDiv disableSticky={disableSticky} topOffset={0} leftOffset={leftOffset} top={0} left={totalLeftWidth} > {topMidItems} </ScrollDiv> </div> )} {/* Top Left */} {!!pinnedTopCount && !!pinnedLeftCount && ( <div style={{ position: "sticky", top: 0, left: 0, width: adjustedWidth }}> <ScrollDiv disableSticky={false} top={0} left={0} topOffset={0} leftOffset={0}> {topLeftItems} </ScrollDiv> </div> )} {/* Top Right */} {!!pinnedTopCount && !!pinnedRightCount && ( <div style={{ position: "sticky", top: 0, left: 0, width: adjustedWidth }}> <ScrollDiv disableSticky={false} top={0} left={adjustedWidth - totalRightWidth} topOffset={0} leftOffset={0} > {topRightItems} </ScrollDiv> </div> )} {/* Bot Mid */} {!!pinnedBottomCount && ( <div style={{ position: "sticky", top: adjustedHeight - totalBotHeight, left: 0 }}> <ScrollDiv disableSticky={disableSticky} leftOffset={leftOffset} topOffset={0} top={0} left={totalLeftWidth} > {botMidItems} </ScrollDiv> </div> )} {/* Bot Left */} {!!pinnedBottomCount && !!pinnedLeftCount && ( <div style={{ position: "sticky", top: adjustedHeight - totalBotHeight, left: 0, width: adjustedWidth, }} > <ScrollDiv disableSticky={disableSticky} leftOffset={0} topOffset={0} top={0} left={0} > {botLeftItems} </ScrollDiv> </div> )} {/* Bot Right */} {!!pinnedBottomCount && !!pinnedRightCount && ( <div style={{ position: "sticky", top: adjustedHeight - totalBotHeight, left: 0, width: adjustedWidth, }} > <ScrollDiv disableSticky={disableSticky} leftOffset={0} topOffset={0} top={0} left={adjustedWidth - totalRightWidth} > {botRightItems} </ScrollDiv> </div> )} </StickyDiv> </div> </div> </SizingDiv> ) }
the_stack
import { OrderByDirection, QueryType } from './constant' import { Db } from './index' import { Validate } from './validate' import { Util } from './util' // import { Command } from './command'; // import * as isRegExp from 'is-regex' import { QuerySerializer } from './serializer/query' import { UpdateSerializer } from './serializer/update' // import { WSClient } from "./websocket/wsclient" import { IWatchOptions, DBRealtimeListener } from './typings/index' import { RealtimeWebSocketClient } from './realtime/websocket-client' import { ErrorCode } from './constant' import { getReqOpts, stringifyByEJSON, processReturn } from './utils/utils' import { ERRORS } from './const/code' import { EJSON } from 'bson' interface GetRes { data: any[] requestId: string total: number limit: number offset: number } interface BaseOption { timeout?: number // 接口调用超时设置 } export interface QueryOption extends BaseOption { // 查询数量 limit?: number // 偏移量 offset?: number // 指定显示或者不显示哪些字段 projection?: Object // 结果排序 order?: Record<string, any>[] } export interface UpdateOption extends BaseOption { // 是否只影响单条doc multiple?: boolean // // 是否插入 // upsert?: boolean // // 是否replace // merge?: boolean } /** * 查询模块 * * @author haroldhu */ export class Query { /** * Db 的引用 * * @internal */ protected _db: Db /** * Collection name * * @internal */ protected _coll: string /** * * @protected * @type {string} * @memberof Query */ protected _transactionId: string /** * 过滤条件 * * @internal */ private _fieldFilters: string // /** // * 排序条件 // * // * @internal // */ // private _fieldOrders: QueryOrder[] // /** // * 查询条件 // * // * @internal // */ // private _queryOptions: QueryOption /** * 统一条件项 * * @private * @type {(QueryOption | UpdateOption)} * @memberof Query */ public _apiOptions: QueryOption | UpdateOption /** * 请求实例 * * @internal */ public _request: any /** * websocket 参数 pingTimeout */ // private _pingTimeout: number /** * websocket 参数 pongTimeout */ // private _pongTimeout: number /** * websocket 参数 reconnectTimeout */ // private _reconnectTimeout: number /** * websocket 参数 wsURL */ // private _wsURL: string /** * 初始化 * * @internal * * @param db - 数据库的引用 * @param coll - 集合名称 * @param fieldFilters - 过滤条件 * @param fieldOrders - 排序条件 * @param queryOptions - 查询条件 */ public constructor( db: Db, coll: string, fieldFilters?: string, apiOptions?: QueryOption | UpdateOption, transactionId?: string ) { this._db = db this._coll = coll this._fieldFilters = fieldFilters this._apiOptions = apiOptions || {} /* eslint-disable new-cap */ this._request = new Db.reqClass(this._db.config) this._transactionId = transactionId } /** * 发起请求获取文档列表 * * - 默认获取集合下全部文档数据 * - 可以把通过 `orderBy`、`where`、`skip`、`limit`设置的数据添加请求参数上 */ public async get(): Promise<GetRes> { /* eslint-disable no-param-reassign */ const order = (this._apiOptions as QueryOption).order interface Param { collectionName: string transactionId?: string query?: Object queryType: QueryType order?: string[] offset?: number limit?: number projection?: Object } let param: Param = { collectionName: this._coll, queryType: QueryType.WHERE, transactionId: this._transactionId } if (this._fieldFilters) { param.query = this._fieldFilters } if (order) { param.order = stringifyByEJSON(order) } // if (this._queryOptions.offset) { // param.offset = this._queryOptions.offset // } const offset = (this._apiOptions as QueryOption).offset if (offset) { param.offset = offset } const limit = (this._apiOptions as QueryOption).limit // if (this._queryOptions.limit) { // param.limit = this._queryOptions.limit < 1000 ? this._queryOptions.limit : 1000 // } else { // param.limit = 100 // } if (limit) { param.limit = limit < 1000 ? limit : 1000 } else { param.limit = 100 } const projection = (this._apiOptions as QueryOption).projection // if (this._queryOptions.projection) { // param.projection = this._queryOptions.projection // } if (projection) { param.projection = stringifyByEJSON(projection) } const res = await this._request.send( 'database.getDocument', param, getReqOpts(this._apiOptions) ) if (res.code) { return res } // if (res.code) { // throw E({ ...res }) // } else { const list = res.data.list.map(item => EJSON.parse(item)) const documents = Util.formatResDocumentData(list) const result: any = { data: documents, requestId: res.requestId } if (res.limit) result.limit = res.limit if (res.offset) result.offset = res.offset return result } // } /** * 获取总数 */ public async count() { interface Param { collectionName: string query?: Object queryType: QueryType } let param: Param = { collectionName: this._coll, queryType: QueryType.WHERE } if (this._fieldFilters) { param.query = this._fieldFilters } const res = await this._request.send( 'database.calculateDocument', param, getReqOpts(this._apiOptions) ) if (res.code) { return res } // if (res.code) { // throw E({ ...res }) // } else { return { requestId: res.requestId, total: res.data.total } // } } /** * 查询条件 * * @param query */ public where(query: object) { // query校验 1. 必填对象类型 2. value 不可均为undefiend if (Object.prototype.toString.call(query).slice(8, -1) !== 'Object') { throw Error(ErrorCode.QueryParamTypeError) } const keys = Object.keys(query) const checkFlag = keys.some(item => { return query[item] !== undefined }) if (keys.length && !checkFlag) { throw Error(ErrorCode.QueryParamValueError) } return new Query( this._db, this._coll, QuerySerializer.encodeEJSON(query), this._apiOptions, this._transactionId // this._fieldOrders, // this._queryOptions ) } /** * 设置请求操作项 * * @param {(QueryOption | UpdateOption)} apiOptions * @memberof Query */ public options(apiOptions: QueryOption | UpdateOption) { // 校验字段是否合规 Validate.isValidOptions(apiOptions) return new Query(this._db, this._coll, this._fieldFilters, apiOptions, this._transactionId) } /** * 设置排序方式 * * @param fieldPath - 字段路径 * @param directionStr - 排序方式 */ public orderBy(fieldPath: string, directionStr: OrderByDirection): Query { Validate.isFieldPath(fieldPath) Validate.isFieldOrder(directionStr) const newOrder: Record<string, any> = { // key: fieldPath, // direction: directionStr === 'desc' ? -1 : 1 [fieldPath]: directionStr === 'desc' ? -1 : 1 } // const combinedOrders = this._fieldOrders.concat(newOrder) const order = (this._apiOptions as QueryOption).order || {} const newApiOption = Object.assign({}, this._apiOptions, { // order: order.concat(newOrder) order: Object.assign({}, order, newOrder) }) return new Query(this._db, this._coll, this._fieldFilters, newApiOption, this._transactionId) } /** * 设置查询条数 * * @param limit - 限制条数 */ public limit(limit: number): Query { Validate.isInteger('limit', limit) let newApiOption: QueryOption = { ...this._apiOptions } newApiOption.limit = limit return new Query(this._db, this._coll, this._fieldFilters, newApiOption, this._transactionId) } /** * 设置偏移量 * * @param offset - 偏移量 */ public skip(offset: number): Query { Validate.isInteger('offset', offset) // let option = { ...this._queryOptions } let newApiOption: QueryOption = { ...this._apiOptions } newApiOption.offset = offset return new Query(this._db, this._coll, this._fieldFilters, newApiOption, this._transactionId) } /** * 发起请求批量更新文档 * * @param data 数据 */ public async update(data: Object): Promise<any> { if (!data || typeof data !== 'object') { return processReturn(this._db.config.throwOnCode, { ...ERRORS.INVALID_PARAM, message: '参数必需是非空对象' }) } if (data.hasOwnProperty('_id')) { return processReturn(this._db.config.throwOnCode, { ...ERRORS.INVALID_PARAM, message: '不能更新_id的值' }) } let { multiple } = this._apiOptions as UpdateOption const multi = multiple === undefined ? true : multiple // where update 不传multi默认为true let param: any = { collectionName: this._coll, // query: this._fieldFilters, queryType: QueryType.WHERE, // query: QuerySerializer.encode(this._fieldFilters), multi, merge: true, upsert: false, data: UpdateSerializer.encodeEJSON(data) } if (this._fieldFilters) { param.query = this._fieldFilters } const res = await this._request.send( 'database.modifyDocument', param, getReqOpts(this._apiOptions) ) if (res.code) { return res } // if (res.code) { // throw E({ ...res }) // } else { return { requestId: res.requestId, updated: res.data.updated, upsertId: res.data.upsert_id } // } } /** * 指定要返回的字段 * project 示例 * 存在doc {a:1, b:2, c: [1,2,3,4], d: [{item: 1}, [item: 2]]} * 1. 指定返回doc中字段a,b, projection设置为{a: true, b:true} * 2. 指定返回doc中数组字段c的 前1个元素 projection设置为{c: db.command.project.slice(1)} * 3. 指定返回doc中数组字段c的 第2,3个元素 projection设置为{c: db.command.project.slice([1,2])} * 4. 指定返回doc中数组字段d中的 满足属性值item大于1的第一个元素 projections设置为{c: db.command.project.elemMatch({item: db.command.gt(1)})} * * @param projection */ public field(projection: any): Query { let transformProjection = {} for (let k in projection) { // 区分bool类型,number类型 和 Object类型 if (typeof projection[k] === 'boolean') { transformProjection[k] = projection[k] === true ? 1 : 0 } if (typeof projection[k] === 'number') { transformProjection[k] = projection[k] > 0 ? 1 : 0 } if (typeof projection[k] === 'object') { transformProjection[k] = projection[k] } } let newApiOption: QueryOption = { ...this._apiOptions } newApiOption.projection = transformProjection return new Query(this._db, this._coll, this._fieldFilters, newApiOption, this._transactionId) } /** * 条件删除文档 */ public async remove() { // if (Object.keys(this._queryOptions).length > 0) { // console.warn('`offset`, `limit` and `projection` are not supported in remove() operation') // } // if (this._fieldOrders.length > 0) { // console.warn('`orderBy` is not supported in remove() operation') // } const { offset, limit, projection, order } = this._apiOptions as QueryOption if ( offset !== undefined || limit !== undefined || projection !== undefined || order !== undefined ) { console.warn( '`offset`, `limit`, `projection`, `orderBy` are not supported in remove() operation' ) } let { multiple } = this._apiOptions as UpdateOption const multi = multiple === undefined ? true : multiple // where remove 不传multi默认为true const param = { collectionName: this._coll, query: this._fieldFilters, queryType: QueryType.WHERE, multi } const res = await this._request.send( 'database.removeDocument', param, getReqOpts(this._apiOptions) ) if (res.code) { return res } // if (res.code) { // throw E({ ...res }) // } else { return { requestId: res.requestId, deleted: res.data.deleted } // } } public async updateAndReturn(data: Object): Promise<any> { if (!data || typeof data !== 'object') { return processReturn(this._db.config.throwOnCode, { ...ERRORS.INVALID_PARAM, message: '参数必需是非空对象' }) } if (data.hasOwnProperty('_id')) { return processReturn(this._db.config.throwOnCode, { ...ERRORS.INVALID_PARAM, message: '不能更新_id的值' }) } let param: any = { collectionName: this._coll, queryType: QueryType.WHERE, data: UpdateSerializer.encodeEJSON(data) } if (this._transactionId) { param.transactionId = this._transactionId } if (this._fieldFilters) { param.query = this._fieldFilters } const res = await this._request.send( 'database.modifyAndReturnDoc', param, getReqOpts(this._apiOptions) ) if (res.code) { return res } return { requestId: res.requestId, updated: res.data.updated, doc: res.data.doc && EJSON.parse(res.data.doc) } } /** * 监听query对应的doc变化 */ watch = (options: IWatchOptions): DBRealtimeListener => { if (!Db.ws) { Db.ws = new RealtimeWebSocketClient({ context: { appConfig: { docSizeLimit: 1000, realtimePingInterval: 10000, realtimePongWaitTimeout: 5000, request: this._request } } }) } const { limit, order } = this._apiOptions as QueryOption return (Db.ws as RealtimeWebSocketClient).watch({ ...options, envId: this._db.config.env, collectionName: this._coll, query: JSON.stringify(this._fieldFilters), // 实时推送这里需要换成ejson协议,todo limit, orderBy: order ? order.reduce<Record<string, string>>((acc, cur) => { acc[cur.field] = cur.direction return acc }, {}) : undefined }) } }
the_stack
import { AcadWeekInfo } from 'nusmoderator'; import { castArray, difference, each, first, flatMapDeep, get, groupBy, invert, isEmpty, isEqual, last, map, mapValues, omitBy, partition, pick, range, sample, values, } from 'lodash'; import { addDays, min as minDate, parseISO } from 'date-fns'; import qs from 'query-string'; import { ClassNo, consumeWeeks, LessonType, Module, ModuleCode, NumericWeeks, RawLesson, Semester, } from 'types/modules'; import { ColoredLesson, HoverLesson, Lesson, ModuleLessonConfig, SemTimetableConfig, SemTimetableConfigWithLessons, TimetableArrangement, TimetableDayArrangement, TimetableDayFormat, } from 'types/timetables'; import { ModuleCodeMap, ModulesMap } from 'types/reducers'; import { ExamClashes } from 'types/views'; import { getTimeAsDate } from './timify'; import { getModuleSemesterData, getModuleTimetable } from './modules'; import { deltas } from './array'; type lessonTypeAbbrev = { [lessonType: string]: string }; export const LESSON_TYPE_ABBREV: lessonTypeAbbrev = { 'Design Lecture': 'DLEC', Laboratory: 'LAB', Lecture: 'LEC', 'Packaged Lecture': 'PLEC', 'Packaged Tutorial': 'PTUT', Recitation: 'REC', 'Sectional Teaching': 'SEC', 'Seminar-Style Module Class': 'SEM', Tutorial: 'TUT', 'Tutorial Type 2': 'TUT2', 'Tutorial Type 3': 'TUT3', Workshop: 'WS', }; // Reverse lookup map of LESSON_TYPE_ABBREV export const LESSON_ABBREV_TYPE: { [key: string]: LessonType } = invert(LESSON_TYPE_ABBREV); // Used for module config serialization - these must be query string safe // See: https://stackoverflow.com/a/31300627 export const LESSON_TYPE_SEP = ':'; export const LESSON_SEP = ','; const EMPTY_OBJECT = {}; export function isValidSemester(semester: Semester): boolean { return semester >= 1 && semester <= 4; } // Returns a random configuration of a module's timetable lessons. // Used when a module is first added. // TODO: Suggest a configuration that does not clash with itself. // { // [lessonType: string]: ClassNo, // } export function randomModuleLessonConfig(lessons: readonly RawLesson[]): ModuleLessonConfig { const lessonByGroups: { [lessonType: string]: readonly RawLesson[] } = groupBy( lessons, (lesson) => lesson.lessonType, ); const lessonByGroupsByClassNo: { [lessonType: string]: { [classNo: string]: readonly RawLesson[] }; } = mapValues(lessonByGroups, (lessonsOfSamelessonType: readonly RawLesson[]) => groupBy(lessonsOfSamelessonType, (lesson) => lesson.classNo), ); return mapValues( lessonByGroupsByClassNo, (group: { [classNo: string]: readonly RawLesson[] }) => (first(sample(group)) as RawLesson).classNo, ); } // Replaces ClassNo in SemTimetableConfig with Array<Lesson> export function hydrateSemTimetableWithLessons( semTimetableConfig: SemTimetableConfig, modules: ModulesMap, semester: Semester, ): SemTimetableConfigWithLessons { return mapValues( semTimetableConfig, (moduleLessonConfig: ModuleLessonConfig, moduleCode: ModuleCode) => { const module: Module = modules[moduleCode]; if (!module) return EMPTY_OBJECT; // TODO: Split this part into a smaller function: hydrateModuleConfigWithLessons. return mapValues(moduleLessonConfig, (classNo: ClassNo, lessonType: LessonType) => { const lessons = getModuleTimetable(module, semester); const newLessons = lessons.filter( (lesson: RawLesson): boolean => lesson.lessonType === lessonType && lesson.classNo === classNo, ); const timetableLessons: Lesson[] = newLessons.map( (lesson: RawLesson): Lesson => ({ ...lesson, moduleCode, title: module.title, }), ); return timetableLessons; }); }, ); } // Filters a flat array of lessons and returns the lessons corresponding to lessonType. export function lessonsForLessonType<T extends RawLesson>( lessons: readonly T[], lessonType: LessonType, ): readonly T[] { return lessons.filter((lesson) => lesson.lessonType === lessonType); } // Converts from timetable config format to flat array of lessons. // { // [moduleCode: string]: { // [lessonType: string]: [Lesson, Lesson, ...], // [lessonType: string]: [Lesson, ...], // } // } export function timetableLessonsArray(timetable: SemTimetableConfigWithLessons): Lesson[] { return flatMapDeep(timetable, values); } // Groups flat array of lessons by day. // { // Monday: [Lesson, Lesson, ...], // Tuesday: [Lesson, ...], // } export function groupLessonsByDay(lessons: ColoredLesson[]): TimetableDayFormat { return groupBy(lessons, (lesson) => lesson.day); } // Determines if two lessons overlap: export function doLessonsOverlap(lesson1: Lesson, lesson2: Lesson): boolean { return ( lesson1.day === lesson2.day && lesson1.startTime < lesson2.endTime && lesson2.startTime < lesson1.endTime ); } // Converts a flat array of lessons *for ONE day* into rows of lessons within that day row. // Result invariants: // - Each lesson will not overlap with each other. // [ // [Lesson, Lesson, ...], // [Lesson, ...], // ] export function arrangeLessonsWithinDay(lessons: ColoredLesson[]): TimetableDayArrangement { const rows: TimetableDayArrangement = [[]]; if (isEmpty(lessons)) { return rows; } const sortedLessons = lessons.sort((a, b) => { const timeDiff = a.startTime.localeCompare(b.startTime); return timeDiff !== 0 ? timeDiff : a.classNo.localeCompare(b.classNo); }); sortedLessons.forEach((lesson: ColoredLesson) => { for (let i = 0; i < rows.length; i++) { const rowLessons: ColoredLesson[] = rows[i]; const previousLesson = last(rowLessons); if (!previousLesson || !doLessonsOverlap(previousLesson, lesson)) { // Lesson does not overlap with any Lesson in the row. Add it to row. rowLessons.push(lesson); return; } } // No existing rows are available to fit this lesson in. Append a new row. rows.push([lesson]); }); return rows; } // Accepts a flat array of lessons and groups them by day and rows with each day // for rendering on the timetable. // Clashes in Array<Lesson> will go onto the next row within that day. // { // Monday: [ // [Lesson, Lesson, ...], // ], // Tuesday: [ // [Lesson, Lesson, Lesson, ...], // [Lesson, Lesson, ...], // [Lesson, ...], // ], // ... // } export function arrangeLessonsForWeek(lessons: ColoredLesson[]): TimetableArrangement { const dayLessons = groupLessonsByDay(lessons); return mapValues(dayLessons, (dayLesson: ColoredLesson[]) => arrangeLessonsWithinDay(dayLesson)); } // Determines if a Lesson on the timetable can be modifiable / dragged around. // Condition: There are multiple ClassNo for all the Array<Lesson> in a lessonType. export function areOtherClassesAvailable( lessons: readonly RawLesson[], lessonType: LessonType, ): boolean { const lessonTypeGroups = groupBy<RawLesson>(lessons, (lesson) => lesson.lessonType); if (!lessonTypeGroups[lessonType]) { // No such lessonType. return false; } return Object.keys(groupBy(lessonTypeGroups[lessonType], (lesson) => lesson.classNo)).length > 1; } // Find all exam clashes between modules in semester // Returns object associating exam dates with the modules clashing on those dates export function findExamClashes(modules: Module[], semester: Semester): ExamClashes { const groupedModules = groupBy(modules, (module) => get(getModuleSemesterData(module, semester), 'examDate'), ); delete groupedModules.undefined; // Remove modules without exams return omitBy(groupedModules, (mods) => mods.length === 1); // Remove non-clashing mods } export function isLessonAvailable( lesson: Lesson, date: Date, weekInfo: Readonly<AcadWeekInfo>, ): boolean { return consumeWeeks( lesson.weeks, (weeks) => weeks.includes(weekInfo.num as number), (weekRange) => { const end = minDate([parseISO(weekRange.end), date]); for (let current = parseISO(weekRange.start); current <= end; current = addDays(current, 7)) { if (isEqual(current, date)) return true; } return false; }, ); } export function isLessonOngoing(lesson: Lesson, currentTime: number): boolean { return ( parseInt(lesson.startTime, 10) <= currentTime && currentTime < parseInt(lesson.endTime, 10) ); } export function getStartTimeAsDate(lesson: Lesson, date: Date = new Date()): Date { return getTimeAsDate(lesson.startTime, date); } export function getEndTimeAsDate(lesson: Lesson, date: Date = new Date()): Date { return getTimeAsDate(lesson.endTime, date); } /** * Validates the modules in a timetable. It removes all modules which do not exist in * the provided module code map from the timetable and returns that as the first item * in the tuple, and the module code of all removed modules as the second item. * * @param timetable * @param moduleCodes * @returns {[SemTimetableConfig, ModuleCode[]]} */ export function validateTimetableModules( timetable: SemTimetableConfig, moduleCodes: ModuleCodeMap, ): [SemTimetableConfig, ModuleCode[]] { const [valid, invalid] = partition( Object.keys(timetable), (moduleCode: ModuleCode) => moduleCodes[moduleCode], ); return [pick(timetable, valid), invalid]; } /** * Validates the lesson config for a specific module. It replaces all lessons * which invalid class number with the first available class numbers, and * removes lessons that are no longer valid * @param semester * @param lessonConfig * @param module */ export function validateModuleLessons( semester: Semester, lessonConfig: ModuleLessonConfig, module: Module, ): [ModuleLessonConfig, LessonType[]] { const validatedLessonConfig: ModuleLessonConfig = {}; const updatedLessonTypes: string[] = []; const validLessons = getModuleTimetable(module, semester); const lessonsByType = groupBy(validLessons, (lesson) => lesson.lessonType); each(lessonsByType, (lessons: RawLesson[], lessonType: LessonType) => { const classNo = lessonConfig[lessonType]; // Check that the lesson exists and is valid. If it is not, insert a random // valid lesson. This covers both // // - lesson type is not in the original timetable (ie. a new lesson type was introduced) // in which case classNo is undefined and thus would not match // - classNo is not valid anymore (ie. the class was removed) // // If a lesson type is removed, then it simply won't be copied over if (!lessons.some((lesson) => lesson.classNo === classNo)) { validatedLessonConfig[lessonType] = lessons[0].classNo; updatedLessonTypes.push(lessonType); } else { validatedLessonConfig[lessonType] = classNo; } }); // Add all of the removed lesson types to the array of updated lesson types updatedLessonTypes.push(...difference(Object.keys(lessonConfig), Object.keys(lessonsByType))); return [validatedLessonConfig, updatedLessonTypes]; } // Get information for all modules present in a semester timetable config export function getSemesterModules( timetable: { [moduleCode: string]: unknown }, modules: ModulesMap, ): Module[] { return values(pick(modules, Object.keys(timetable))); } function serializeModuleConfig(config: ModuleLessonConfig): string { // eg. { Lecture: 1, Laboratory: 2 } => LEC=1,LAB=2 return map(config, (classNo, lessonType) => [LESSON_TYPE_ABBREV[lessonType], encodeURIComponent(classNo)].join(LESSON_TYPE_SEP), ).join(LESSON_SEP); } function parseModuleConfig(serialized: string | string[] | null): ModuleLessonConfig { const config: ModuleLessonConfig = {}; if (!serialized) return config; castArray(serialized).forEach((serializedModule) => { serializedModule.split(LESSON_SEP).forEach((lesson) => { const [lessonTypeAbbr, classNo] = lesson.split(LESSON_TYPE_SEP); const lessonType = LESSON_ABBREV_TYPE[lessonTypeAbbr]; // Ignore unparsable/invalid keys if (!lessonType) return; config[lessonType] = classNo; }); }); return config; } /** * Formats numeric week number array into something human readable * * - 1 => Week 1 * - 1,2 => Weeks 1,2 * - 1,2,3 => Weeks 1-3 * - 1,2,3,5,6,7 => Weeks 1-3, 5-7 */ export function formatNumericWeeks(weeks: NumericWeeks): string | null { if (weeks.length === 13) return null; if (weeks.length === 1) return `Week ${weeks[0]}`; // Check for odd / even weeks. There are more odd weeks then even weeks, so we have to split // the length check. if (deltas(weeks).every((d) => d === 2)) { if (weeks[0] % 2 === 0 && weeks.length >= 6) return 'Even Weeks'; if (weeks[0] % 2 === 1 && weeks.length >= 7) return 'Odd Weeks'; } // Merge consecutive const processed: (number | string)[] = []; let start = weeks[0]; let end = start; const mergeConsecutive = () => { if (end - start > 2) { processed.push(`${start}-${end}`); } else { processed.push(...range(start, end + 1)); } }; weeks.slice(1).forEach((next) => { if (next - end === 1) { // Consecutive week number - keep going end = next; } else { // Break = push the current chunk into processed mergeConsecutive(); start = next; end = start; } }); mergeConsecutive(); return `Weeks ${processed.join(', ')}`; } // Converts a timetable config to query string // eg: // { // CS2104: { Lecture: '1', Tutorial: '2' }, // CS2107: { Lecture: '1', Tutorial: '8' }, // } // => CS2104=LEC:1,Tut:2&CS2107=LEC:1,Tut:8 export function serializeTimetable(timetable: SemTimetableConfig): string { // We are using query string safe characters, so this encoding is unnecessary return qs.stringify(mapValues(timetable, serializeModuleConfig), { encode: false }); } export function deserializeTimetable(serialized: string): SemTimetableConfig { const params = qs.parse(serialized); return mapValues(params, parseModuleConfig); } export function isSameTimetableConfig(t1: SemTimetableConfig, t2: SemTimetableConfig): boolean { return isEqual(t1, t2); } export function isSameLesson(l1: Lesson, l2: Lesson) { return ( l1.lessonType === l2.lessonType && l1.classNo === l2.classNo && l1.moduleCode === l2.moduleCode && l1.startTime === l2.startTime && l1.endTime === l2.endTime && l1.day === l2.day && isEqual(l1.weeks, l2.weeks) ); } export function getHoverLesson(lesson: Lesson): HoverLesson { return { classNo: lesson.classNo, moduleCode: lesson.moduleCode, lessonType: lesson.lessonType, }; } /** * Obtain a semi-unique key for a lesson */ export function getLessonIdentifier(lesson: Lesson): string { return `${lesson.moduleCode}-${LESSON_TYPE_ABBREV[lesson.lessonType]}-${lesson.classNo}`; }
the_stack
import type { CSpellUserSettings } from '@cspell/cspell-types'; import * as path from 'path'; import { createCSpellSettingsInternal as csi } from '../Models/CSpellSettingsInternalDef'; import { clearCachedSettingsFiles, extractImportErrors, getCachedFileSize, getGlobalSettings, loadConfig, readSettings, readSettingsFiles, __testing__ as __configLoader_testing__, } from './configLoader'; import { calcOverrideSettings, checkFilenameMatchesGlob, getSources, mergeSettings } from './CSpellSettingsServer'; import { getDefaultBundledSettings, _defaultSettings } from './DefaultSettings'; const rootCspellLib = path.resolve(path.join(__dirname, '../..')); const samplesDir = path.resolve(rootCspellLib, 'samples'); const oc = expect.objectContaining; describe('Validate CSpellSettingsServer', () => { test('tests mergeSettings with conflicting "name"', () => { const left = csi({ name: 'Left' }); const right = csi({ name: 'Right' }); expect(mergeSettings(left, right)).toEqual( csi({ name: 'Left|Right', id: '|', enabledLanguageIds: [], source: { name: 'Left|Right', sources: [left, right] }, }) ); }); test('tests mergeSettings with conflicting "id"', () => { const left = { id: 'left' }; const enabled = { id: 'enabledId', name: 'enabledName', enabled: true }; expect(mergeSettings(left, enabled)).toEqual( csi({ enabled: true, name: '|enabledName', id: 'left|enabledId', enabledLanguageIds: [], source: { name: 'left|enabledName', sources: [csi(left), csi(enabled)] }, }) ); }); test('tests mergeSettings with conflicting "enabled"', () => { const right = csi({ id: 'right', enabled: false }); const left = csi({ id: 'left', enabled: true }); expect(mergeSettings({}, right)).toEqual(right); expect(mergeSettings(left, {})).toEqual(left); expect(mergeSettings(left, right)).toEqual( csi({ enabled: right.enabled, name: '|', id: [left.id, right.id].join('|'), enabledLanguageIds: [], source: { name: 'left|right', sources: [left, right] }, }) ); }); test('tests mergeSettings with inline object', () => { const a = { enabled: true }; const b = { enabled: false }; expect(mergeSettings(a, b)).toEqual( csi({ enabled: false, name: '|', id: '|', enabledLanguageIds: [], source: { name: 'left|right', sources: [csi(a), csi(b)] }, }) ); }); test('tests mergeSettings with ignorePaths, files, and overrides', () => { const left = csi({ id: 'left', files: ['left/**/*.*'], ignorePaths: ['node_modules'], overrides: [ { filename: '*.ts', dictionaries: ['ts-extra'], }, ], }); const right = csi({ id: 'right', enabled: true, files: ['right/**/*.*'], overrides: [{ filename: '*.jsxx', languageId: 'javascript' }], // cspell:ignore jsxx }); expect(mergeSettings({}, right)).toEqual(right); expect(mergeSettings(left, {})).toEqual(left); expect(mergeSettings(left, right)).toEqual( csi({ enabled: right.enabled, name: '|', id: [left.id, right.id].join('|'), enabledLanguageIds: [], files: left.files?.concat(right.files || []), ignorePaths: left.ignorePaths?.concat(right.ignorePaths || []), overrides: left.overrides?.concat(right.overrides || []), source: { name: 'left|right', sources: [left, right] }, }) ); }); test('tests mergeSettings with ignorePaths, files, and overrides compatibility', () => { const left = csi({ id: 'left', files: ['left/**/*.*'], ignorePaths: ['node_modules'], overrides: [ { filename: '*.ts', dictionaries: ['ts-extra'], }, ], }); const right = csi({ id: 'right', version: '0.1', enabled: true, files: ['right/**/*.*'], ignorePaths: ['node_modules'], overrides: [{ filename: '*.jsxx', languageId: 'javascript' }], // cspell:ignore jsxx }); expect(mergeSettings({}, right)).toEqual(right); expect(mergeSettings(left, {})).toEqual(left); expect(mergeSettings(left, right)).toEqual( csi({ enabled: right.enabled, name: '|', id: [left.id, right.id].join('|'), version: right.version, enabledLanguageIds: [], files: left.files?.concat(right.files || []), ignorePaths: right.ignorePaths, overrides: right.overrides, source: { name: 'left|right', sources: [left, right] }, }) ); }); test('tests mergeSettings when left/right are the same', () => { expect(mergeSettings(_defaultSettings, _defaultSettings)).toBe(_defaultSettings); }); test('tests mergeSettings when lefts are the same', () => { const base = mergeSettings(_defaultSettings, {}); const setting1 = mergeSettings(base, {}); const setting2 = mergeSettings(base, setting1); expect(setting2).toBe(setting1); const setting3 = mergeSettings(_defaultSettings, setting1); expect(setting3).toBe(setting1); }); test('tests mergeSettings when rights are the same', () => { const base = mergeSettings(_defaultSettings, { id: 'right' }); const setting1 = mergeSettings({ id: 'setting1' }, base); const setting2 = mergeSettings(setting1, base); expect(setting2).toBe(setting1); const setting3 = mergeSettings(_defaultSettings, setting1); expect(setting3).not.toBe(setting1); const setting4 = mergeSettings(setting3, base); expect(setting4).toBe(setting3); }); test.each` left | right | expected ${{}} | ${{}} | ${csi({})} ${{ dictionaries: ['a'] }} | ${{ dictionaries: ['b'] }} | ${oc(csi({ dictionaries: ['a', 'b'] }))} ${{ features: {} }} | ${{}} | ${oc(csi({ features: {} }))} ${{ features: { 'weighted-suggestions': true } }} | ${{}} | ${oc(csi({ features: { 'weighted-suggestions': true } }))} ${{ features: { 'weighted-suggestions': true } }} | ${{ features: { 'weighted-suggestions': false } }} | ${oc(csi({ features: { 'weighted-suggestions': false } }))} ${{ features: { 'weighted-suggestions': true } }} | ${{ features: { 'new-feature': true } }} | ${oc({ features: { 'weighted-suggestions': true, 'new-feature': true } })} `('mergeSettings $left with $right', ({ left, right, expected }) => { expect(mergeSettings(left, right)).toEqual(expected); }); test.each` filename | relativeTo | refFilename ${r('../../cspell.config.json')} | ${undefined} | ${r('../../cspell.config.json')} ${r('../../cspell.config.json')} | ${__dirname} | ${r('../../cspell.config.json')} ${'@cspell/cspell-bundled-dicts/cspell-default.json'} | ${__dirname} | ${require.resolve('@cspell/cspell-bundled-dicts/cspell-default.json')} ${'@cspell/cspell-bundled-dicts/cspell-default.json'} | ${undefined} | ${require.resolve('@cspell/cspell-bundled-dicts/cspell-default.json')} `('tests readSettings $filename $relativeTo', ({ filename, relativeTo, refFilename }) => { const settings = readSettings(filename, relativeTo); expect(settings.__importRef?.filename).toBe(refFilename); expect(settings.__importRef?.error).toBeUndefined(); expect(settings.import).toBeUndefined(); }); test('tests loading project cspell.json file', () => { const filename = path.join(__dirname, '..', '..', 'samples', 'linked', 'cspell-missing.json'); const settings = readSettings(filename); expect(Object.keys(settings)).not.toHaveLength(0); expect(settings.words).toBeUndefined(); }); test('tests loading a cSpell.json file', () => { const filename = path.join(__dirname, '..', '..', 'samples', 'linked', 'cspell-import.json'); const settings = readSettings(filename); expect(Object.keys(settings)).not.toHaveLength(0); expect(settings.words).toEqual(expect.arrayContaining(['import'])); }); test('readSettingsFiles cSpell.json', () => { const filename = path.join(__dirname, '..', '..', 'samples', 'linked', 'cspell-import.json'); const settings = readSettingsFiles([filename]); expect(Object.keys(settings)).not.toHaveLength(0); expect(settings.words).toEqual(expect.arrayContaining(['import'])); }); test('tests loading a cSpell.json with multiple imports file', () => { const filename = path.join(__dirname, '..', '..', 'samples', 'linked', 'cspell-imports.json'); const settings = readSettings(filename); expect(Object.keys(settings)).not.toHaveLength(0); expect(settings.words).toEqual(expect.arrayContaining(['import'])); expect(settings.words).toEqual(expect.arrayContaining(['imports'])); // cspell:word leuk expect(settings.words).toEqual(expect.arrayContaining(['leuk'])); }); test('tests loading a cSpell.json with a missing import file', () => { const filename = path.join(__dirname, '..', '..', 'samples', 'linked', 'cspell-import-missing.json'); const settings = readSettings(filename); expect(settings.__importRef?.filename).toBe(path.resolve(filename)); expect(settings.__imports?.size).toBe(2); const errors = extractImportErrors(settings); expect(errors).toHaveLength(1); expect(errors.map((ref) => ref.error.toString())).toContainEqual( expect.stringMatching('intentionally-missing-file.json') ); expect(errors.map((ref) => ref.error.toString())).toContainEqual(expect.stringMatching('Failed to read')); }); test('makes sure global settings is an object', () => { const settings = getGlobalSettings(); expect(Object.keys(settings)).not.toHaveLength(0); const merged = mergeSettings(getDefaultBundledSettings(), getGlobalSettings()); expect(Object.keys(merged)).not.toHaveLength(0); }); test('verify clearing the file cache works', () => { mergeSettings(getDefaultBundledSettings(), getGlobalSettings()); expect(getCachedFileSize()).toBeGreaterThan(0); clearCachedSettingsFiles(); expect(getCachedFileSize()).toBe(0); }); test('the loaded defaults contain expected settings', () => { const settings = getDefaultBundledSettings(); const sources = getSources(settings); const sourceNames = sources.map((s) => s.name || '?'); expect(sourceNames).toEqual(expect.arrayContaining([_defaultSettings.name])); }); test('loading circular imports (readSettings)', async () => { const configFile = path.join(samplesDir, 'linked/cspell.circularA.json'); const config = readSettings(configFile); expect(config?.ignorePaths).toEqual( expect.arrayContaining([ { glob: 'node_modules', root: path.dirname(configFile), source: configFile, }, ]) ); const errors = extractImportErrors(config); expect(errors).toEqual([]); const sources = getSources(config); expect(sources.length).toBe(2); }); test('loading circular imports (loadConfig)', async () => { const configFile = path.join(samplesDir, 'linked/cspell.circularA.json'); const config = await loadConfig(configFile); expect(config?.ignorePaths).toEqual( expect.arrayContaining([ { glob: 'node_modules', root: path.dirname(configFile), source: configFile, }, ]) ); const errors = extractImportErrors(config); expect(errors).toEqual([]); const sources = getSources(config); expect(sources.length).toBe(2); }); }); describe('Validate Overrides', () => { test.each` file | glob | expected ${'nested/dir/spell.test.ts'} | ${'nested/**'} | ${false /* nested/** tests against the current dir not __dirname */} ${'nested/dir/spell.test.ts'} | ${{ glob: 'nested/**', root: __dirname }} | ${true /* setting the root to __dirname will allow this to be true. */} ${'nested/dir/spell.test.ts'} | ${'nested'} | ${true} ${'nested/dir/spell.test.ts'} | ${'*.ts'} | ${true} ${'nested/dir/spell.test.ts'} | ${'**/*.ts'} | ${true} ${'nested/dir/spell.test.ts'} | ${['**/*.ts']} | ${true} ${'nested/dir/spell.test.ts'} | ${['**/dir/**/*.ts']} | ${true} ${'nested/dir/spell.test.js'} | ${['**/*.ts']} | ${false} ${'nested/dir/spell.test.js'} | ${['*.ts', '*.test.js']} | ${true} ${'/cspell-dicts/nl_NL/Dutch.txt'} | ${'**/nl_NL/**'} | ${false /* the file is a root filename */} ${'cspell-dicts/nl_NL/Dutch.txt'} | ${'**/nl_NL/**'} | ${true} `('checkFilenameMatchesGlob "$file" against "$glob" expect: $expected', ({ file, glob, expected }) => { file = path.resolve(__dirname, file); expect(checkFilenameMatchesGlob(file, glob)).toBe(expected); }); test.each` file | expected ${'nested/dir/spell.test.ts'} | ${{ languageId: 'typescript' }} ${'nested/docs/NL/myDoc.lex'} | ${{ languageId: 'lex', language: 'en' }} ${'nested/docs/NL/myDoc.txt'} | ${{ languageId: 'plaintext', language: 'en,nl' }} `('calcOverrideSettings $file expected $expected', ({ file, expected }) => { file = path.resolve(__dirname, file); const r = calcOverrideSettings(sampleSettings, file); expect(r).toEqual(expect.objectContaining(expected)); }); }); function p(...parts: string[]): string { return path.join(...parts); } function r(...parts: string[]): string { return path.resolve(__dirname, p(...parts)); } const rawSampleSettings: CSpellUserSettings = { language: 'en', languageId: 'plaintext', ignorePaths: ['node_modules'], overrides: [ { filename: '**/*.ts', languageId: 'typescript', }, { filename: '**/*.lex', languageId: 'lex', }, { filename: '**/NL/*.txt', language: 'en,nl', }, ], }; const sampleSettingsFilename = __filename; const sampleSettings = __configLoader_testing__.normalizeSettings(rawSampleSettings, sampleSettingsFilename, {});
the_stack
import { Octokit } from '@octokit/rest'; import * as fs from 'fs-extra'; import inquirer from 'inquirer'; import * as path from 'path'; import { v4 as uuid } from 'uuid'; import { provider as cloudformationProviderName } from '../../../provider-utils/awscloudformation/aws-constants'; import { getContainers } from '../../../provider-utils/awscloudformation/docker-compose'; import Container from '../docker-compose/ecs-objects/container'; import { EcsStack } from '../ecs-apigw-stack'; import { API_TYPE, ResourceDependency } from '../../../provider-utils/awscloudformation/service-walkthroughs/containers-walkthrough'; import { getGitHubOwnerRepoFromPath } from '../../../provider-utils/awscloudformation/utils/github'; import { $TSAny, $TSContext, JSONUtilities, pathManager, readCFNTemplate } from 'amplify-cli-core'; import { DEPLOYMENT_MECHANISM } from '../base-api-stack'; import { setExistingSecretArns } from './containers/set-existing-secret-arns'; import { category } from '../../../category-constants'; export const cfnFileName = (resourceName: string) => `${resourceName}-cloudformation-template.json`; export type ApiResource = { category: string; resourceName: string; gitHubInfo?: { path: string; tokenSecretArn: string; }; deploymentMechanism: DEPLOYMENT_MECHANISM; authName: string; restrictAccess: boolean; dependsOn: ResourceDependency[]; environmentMap: Record<string, string>; categoryPolicies: $TSAny[]; mutableParametersState: $TSAny; output?: Record<string, $TSAny>; apiType?: API_TYPE; exposedContainer?: { name: string; port: number }; }; type ExposedContainer = { name: string; port: number; }; type ContainerArtifactsMetadata = { exposedContainer: ExposedContainer; pipelineInfo: { consoleUrl: string }; }; export async function generateContainersArtifacts( context: $TSContext, resource: ApiResource, askForExposedContainer: boolean = false, ): Promise<ContainerArtifactsMetadata> { const { providers: { [cloudformationProviderName]: provider }, } = context.amplify.getProjectMeta(); const { StackName: envName } = provider; const { category: categoryName, resourceName, gitHubInfo, deploymentMechanism, categoryPolicies = [], dependsOn, environmentMap, restrictAccess, apiType, } = resource; const backendDir = context.amplify.pathManager.getBackendDirPath(); const resourceDir = path.normalize(path.join(backendDir, categoryName, resourceName)); const srcPath = path.join(resourceDir, 'src'); const { containersPorts, containers, isInitialDeploy, desiredCount, exposedContainer, secretsArns } = await processDockerConfig( context, resource, srcPath, askForExposedContainer, ); const repositories = await context.amplify.executeProviderUtils(context, 'awscloudformation', 'describeEcrRepositories'); const existingEcrRepositories: Set<string> = new Set( repositories .map(({ repositoryName }) => repositoryName) .filter(repositoryName => repositoryName.startsWith(`${envName}-${categoryName}-${resourceName}-`)), ); const stack = new EcsStack(undefined, 'ContainersStack', { categoryName, apiName: resourceName, taskPorts: containersPorts, dependsOn, policies: categoryPolicies, taskEnvironmentVariables: environmentMap, gitHubSourceActionInfo: gitHubInfo, deploymentMechanism, containers, isInitialDeploy, desiredCount, restrictAccess, currentStackName: envName, apiType, exposedContainer, secretsArns, existingEcrRepositories, }); const cfn = stack.toCloudFormation(); JSONUtilities.writeJson(path.normalize(path.join(resourceDir, cfnFileName(resourceName))), cfn); return { exposedContainer, pipelineInfo: { consoleUrl: stack.getPipelineConsoleUrl(provider.Region) }, }; } export async function processDockerConfig( context: $TSContext, resource: ApiResource, srcPath: string, askForExposedContainer: boolean = false, ) { const { providers: { [cloudformationProviderName]: provider }, } = context.amplify.getProjectMeta(); const { StackName: envName } = provider; const { resourceName, gitHubInfo, deploymentMechanism, output, exposedContainer: exposedContainerFromMeta } = resource; const dockerComposeFileNameYaml = 'docker-compose.yaml'; const dockerComposeFileNameYml = 'docker-compose.yml'; const dockerfileFileName = 'Dockerfile'; const containerDefinitionFileNames = [dockerComposeFileNameYaml, dockerComposeFileNameYml, dockerfileFileName]; const containerDefinitionFiles: Record<string, string> = {}; for await (const fileName of containerDefinitionFileNames) { switch (deploymentMechanism) { case DEPLOYMENT_MECHANISM.FULLY_MANAGED: case DEPLOYMENT_MECHANISM.SELF_MANAGED: const filePath = path.normalize(path.join(srcPath, fileName)); if (fs.existsSync(filePath)) { containerDefinitionFiles[fileName] = fs.readFileSync(filePath).toString(); } break; case DEPLOYMENT_MECHANISM.INDENPENDENTLY_MANAGED: const { path: repoUri, tokenSecretArn } = gitHubInfo; const { SecretString: gitHubToken } = await context.amplify.executeProviderUtils(context, 'awscloudformation', 'retrieveSecret', { secretArn: tokenSecretArn, }); const octokit = new Octokit({ auth: gitHubToken }); const { owner, repo, branch, path: pathInRepo } = getGitHubOwnerRepoFromPath(repoUri); try { const { data: { content, encoding }, } = (await octokit.repos.getContent({ owner, repo, ...(branch ? { ref: branch } : undefined), // only include branch if not undefined path: path.join(pathInRepo, fileName), })) as { data: { content?: string; encoding?: string } }; containerDefinitionFiles[fileName] = Buffer.from(content, <BufferEncoding>encoding).toString('utf8'); } catch (error) { const { status } = error; // It is ok if the file doesn't exist, we skip it if (status !== 404) { throw error; } } break; default: { const exhaustiveCheck: never = deploymentMechanism; throw new Error(`Unhandled type [${exhaustiveCheck}]`); } } } if (Object.keys(containerDefinitionFiles).length === 0) { throw new Error('No definition available (docker-compose.yaml / docker-compose.yml / Dockerfile)'); } if (containerDefinitionFiles[dockerComposeFileNameYaml] && containerDefinitionFiles[dockerComposeFileNameYml]) { throw new Error('There should be only one docker-compose.yaml / docker-compose.yml)'); } const composeContents = containerDefinitionFiles[dockerComposeFileNameYaml] || containerDefinitionFiles[dockerComposeFileNameYml]; const { [dockerfileFileName]: dockerfileContents } = containerDefinitionFiles; const { buildspec, containers, service, secrets } = getContainers(composeContents, dockerfileContents); const containersPorts = containers.reduce( (acc, container) => acc.concat(container.portMappings.map(({ containerPort }) => containerPort)), <number[]>[], ); const newContainersName = Array.from(new Set(containers.map(({ name }) => name))); let isInitialDeploy = Object.keys(output ?? {}).length === 0; const currentContainersSet = new Set(output?.ContainerNames?.split(',')); // Service require all containers to exists isInitialDeploy = isInitialDeploy || newContainersName.some(newContainer => !currentContainersSet.has(newContainer)); let exposedContainer: { name: string; port: number }; const containersExposed = containers.filter(container => container.portMappings.length > 0); if (containersPorts.length === 0) { throw new Error('Service requires at least one exposed port'); } else if (containersPorts.length > 1) { exposedContainer = await checkContainerExposed(containersExposed, exposedContainerFromMeta, askForExposedContainer); } else { exposedContainer = { name: containersExposed[0].name, port: containersExposed[0].portMappings[0].containerPort, }; } fs.ensureDirSync(srcPath); fs.writeFileSync(path.join(srcPath, 'buildspec.yml'), buildspec); const secretsArns: Map<string, string> = new Map<string, string>(); if ((await shouldUpdateSecrets(context, secrets)) || isInitialDeploy) { // Normalizes paths // Validate secrets file paths, existence and prefixes const errors = Object.entries(secrets).reduce((acc, [secretName, secretFilePath]) => { const baseDir = path.isAbsolute(secretFilePath) ? '' : srcPath; const normalizedFilePath = path.normalize(path.join(baseDir, secretFilePath)); secrets[secretName] = normalizedFilePath; let canRead = true; try { const fd = fs.openSync(normalizedFilePath, 'r'); fs.closeSync(fd); } catch (err) { canRead = false; } if (!canRead) { acc.push(`Secret file "${secretFilePath}" can't be read.`); return acc; } const basename = path.basename(normalizedFilePath); const hasCorrectPrefix = basename.startsWith('.secret-'); if (!hasCorrectPrefix) { acc.push(`Secret file "${secretFilePath}" doesn't start with the ".secret-" prefix.`); return acc; } const isInsideSrc = normalizedFilePath.startsWith(path.join(srcPath, path.sep)); if (isInsideSrc) { acc.push(`Secret file "${secretFilePath}" should not be inside the "src" folder. The "src" folder will be uploaded to S3.`); return acc; } return acc; }, <string[]>[]); if (errors.length > 0) { throw new Error(['Error(s) in secret file(s):'].concat(errors).join('\n')); } for await (const entries of Object.entries(secrets)) { const [secretName, secretFilePath] = entries; const contents = fs.readFileSync(secretFilePath).toString(); const ssmSecretName = `${envName}-${resourceName}-${secretName}`; const { ARN: secretArn } = await context.amplify.executeProviderUtils(context, 'awscloudformation', 'upsertSecretValue', { secret: contents, description: `Secret for ${resourceName}`, name: ssmSecretName, version: uuid(), }); secretsArns.set(secretName, secretArn); } } else { const { cfnTemplate } = readCFNTemplate(path.join(pathManager.getBackendDirPath(), category, resourceName, cfnFileName(resourceName))); setExistingSecretArns(secretsArns, cfnTemplate); } const desiredCount = service?.replicas ?? 1; // TODO: 1 should be from meta (HA setting) return { containersPorts, containers, isInitialDeploy, desiredCount, exposedContainer, secretsArns, }; } async function shouldUpdateSecrets(context: $TSContext, secrets: Record<string, string>): Promise<boolean> { const hasSecrets = Object.keys(secrets).length > 0; if (!hasSecrets || context.exeInfo.inputParams.yes) { return false; } const { update_secrets } = await inquirer.prompt({ name: 'update_secrets', type: 'confirm', message: 'Secret configuration detected. Do you wish to store new values in the cloud?', default: false, }); return update_secrets; } async function checkContainerExposed( containersExposed: Container[], exposedContainerFromMeta: { name: string; port: number } = { name: '', port: 0 }, askForExposedContainer: boolean = false, ): Promise<{ name: string; port: number }> { const containerExposed = containersExposed.find(container => container.name === exposedContainerFromMeta.name); if (!askForExposedContainer && containerExposed?.portMappings.find(port => port.containerPort === exposedContainerFromMeta.port)) { return { ...exposedContainerFromMeta }; } else { const choices: { name: string; value: Container }[] = containersExposed.map(container => ({ name: container.name, value: container })); const { containerToExpose } = await inquirer.prompt({ message: 'Select which container is the entrypoint', name: 'containerToExpose', type: 'list', choices, }); return { name: containerToExpose.name, port: containerToExpose.portMappings[0].containerPort, }; } }
the_stack
import type Ajv from ".." import _Ajv from "./ajv" import chai from "./chai" chai.should() const coercionRules = { string: { number: [ {from: 1, to: "1"}, {from: 1.5, to: "1.5"}, {from: 2e100, to: "2e+100"}, ], boolean: [ {from: false, to: "false"}, {from: true, to: "true"}, ], null: [{from: null, to: ""}], object: [{from: {}, to: undefined}], array: [ {from: [], to: undefined}, {from: [1], to: undefined}, ], }, number: { string: [ {from: "1", to: 1}, {from: "1.5", to: 1.5}, {from: "2e10", to: 2e10}, {from: "1a", to: undefined}, {from: "abc", to: undefined}, {from: "", to: undefined}, ], boolean: [ {from: false, to: 0}, {from: true, to: 1}, ], null: [{from: null, to: 0}], object: [{from: {}, to: undefined}], array: [ {from: [], to: undefined}, {from: [true], to: undefined}, ], }, integer: { string: [ {from: "1", to: 1}, {from: "1.5", to: undefined}, {from: "2e10", to: 2e10}, {from: "1a", to: undefined}, {from: "abc", to: undefined}, {from: "", to: undefined}, ], boolean: [ {from: false, to: 0}, {from: true, to: 1}, ], null: [{from: null, to: 0}], object: [{from: {}, to: undefined}], array: [ {from: [], to: undefined}, {from: ["1"], to: undefined}, ], }, boolean: { string: [ {from: "false", to: false}, {from: "true", to: true}, {from: "", to: undefined}, {from: "abc", to: undefined}, ], number: [ {from: 0, to: false}, {from: 1, to: true}, {from: 2, to: undefined}, {from: 2.5, to: undefined}, ], null: [{from: null, to: false}], object: [{from: {}, to: undefined}], array: [ {from: [], to: undefined}, {from: [0], to: undefined}, ], }, null: { string: [ {from: "", to: null}, {from: "abc", to: undefined}, {from: "null", to: undefined}, ], number: [ {from: 0, to: null}, {from: 1, to: undefined}, ], boolean: [ {from: false, to: null}, {from: true, to: undefined}, ], object: [{from: {}, to: undefined}], array: [ {from: [], to: undefined}, {from: [null], to: undefined}, ], }, array: { all: [ {type: "string", from: "abc", to: undefined}, {type: "number", from: 1, to: undefined}, {type: "boolean", from: true, to: undefined}, {type: "null", from: null, to: undefined}, {type: "object", from: {}, to: undefined}, ], }, object: { all: [ {type: "string", from: "abc", to: undefined}, {type: "number", from: 1, to: undefined}, {type: "boolean", from: true, to: undefined}, {type: "null", from: null, to: undefined}, {type: "array", from: [], to: undefined}, ], }, } const coercionArrayRules = JSON.parse(JSON.stringify(coercionRules)) coercionArrayRules.string.array = [ {from: ["abc"], to: "abc"}, {from: [123], to: "123"}, {from: [true], to: "true"}, {from: [null], to: ""}, {from: [{}], to: undefined}, {from: ["abc", "def"], to: undefined}, {from: [], to: undefined}, ] coercionArrayRules.number.array = [ {from: [1.5], to: 1.5}, {from: ["1.5"], to: 1.5}, {from: [true], to: 1}, {from: [null], to: 0}, {from: ["abc"], to: undefined}, {from: [{}], to: undefined}, ] coercionArrayRules.integer.array = [ {from: [1], to: 1}, {from: ["1"], to: 1}, {from: [true], to: 1}, {from: [null], to: 0}, {from: [1.5], to: undefined}, {from: ["abc"], to: undefined}, {from: [{}], to: undefined}, ] coercionArrayRules.boolean.array = [ {from: [true], to: true}, {from: ["true"], to: true}, {from: [1], to: true}, {from: [null], to: false}, {from: ["abc"], to: undefined}, {from: [2], to: undefined}, {from: [{}], to: undefined}, ] coercionArrayRules.null.array = [ {from: [null], to: null}, {from: [""], to: null}, {from: [0], to: null}, {from: [false], to: null}, {from: ["abc"], to: undefined}, {from: [1], to: undefined}, {from: [true], to: undefined}, {from: [{}], to: undefined}, ] coercionArrayRules.object.array = [{from: [{}], to: undefined}] coercionArrayRules.array = { string: [{from: "abc", to: ["abc"]}], number: [{from: 1, to: [1]}], boolean: [{from: true, to: [true]}], null: [{from: null, to: [null]}], object: [{from: {}, to: undefined}], } describe("Type coercion", () => { let ajv: Ajv, fullAjv: Ajv, instances: Ajv[] beforeEach(() => { ajv = new _Ajv({coerceTypes: true, verbose: true, allowUnionTypes: true}) fullAjv = new _Ajv({coerceTypes: true, verbose: true, allErrors: true, allowUnionTypes: true}) instances = [ajv, fullAjv] }) it("should coerce scalar values", () => { testRules(coercionRules, (test, schema, canCoerce /*, toType, fromType*/) => { instances.forEach((_ajv) => { const valid = _ajv.validate(schema, test.from) //if (valid !== canCoerce) console.log('true', toType, fromType, test, ajv.errors); valid.should.equal(canCoerce) }) }) }) it("should coerce scalar values (coerceTypes = array)", () => { ajv = new _Ajv({coerceTypes: "array", verbose: true}) fullAjv = new _Ajv({coerceTypes: "array", verbose: true, allErrors: true}) instances = [ajv, fullAjv] testRules(coercionArrayRules, (test, schema, canCoerce, toType, fromType) => { instances.forEach((_ajv) => { const valid = _ajv.validate(schema, test.from) if (valid !== canCoerce) console.log(toType, ".", fromType, test, schema, ajv.errors) valid.should.equal(canCoerce) }) }) }) it("should coerce values in objects/arrays and update properties/items", () => { testRules(coercionRules, (test, schema, canCoerce /*, toType, fromType*/) => { const schemaObject = { type: "object", properties: { foo: schema, }, } const schemaArray = { type: "array", items: schema, } const schemaArrObj = { type: "array", items: schemaObject, } instances.forEach((_ajv) => { testCoercion(_ajv, schemaArray, [test.from], [test.to]) testCoercion(_ajv, schemaObject, {foo: test.from}, {foo: test.to}) testCoercion(_ajv, schemaArrObj, [{foo: test.from}], [{foo: test.to}]) }) function testCoercion(_ajv, _schema, fromData, toData) { const valid = _ajv.validate(_schema, fromData) //if (valid !== canCoerce) console.log(schema, fromData, toData); valid.should.equal(canCoerce) if (valid) fromData.should.eql(toData) } }) }) it("should coerce to multiple types in order with number type", () => { const schema = { type: "object", properties: { foo: { type: ["number", "boolean", "null"], }, }, } instances.forEach((_ajv) => { let data _ajv.validate(schema, (data = {foo: "1"})).should.equal(true) data.should.eql({foo: 1}) _ajv.validate(schema, (data = {foo: "1.5"})).should.equal(true) data.should.eql({foo: 1.5}) _ajv.validate(schema, (data = {foo: "false"})).should.equal(true) data.should.eql({foo: false}) _ajv.validate(schema, (data = {foo: 1})).should.equal(true) data.should.eql({foo: 1}) // no coercion _ajv.validate(schema, (data = {foo: true})).should.equal(true) data.should.eql({foo: true}) // no coercion _ajv.validate(schema, (data = {foo: null})).should.equal(true) data.should.eql({foo: null}) // no coercion _ajv.validate(schema, (data = {foo: "abc"})).should.equal(false) data.should.eql({foo: "abc"}) // can't coerce _ajv.validate(schema, (data = {foo: {}})).should.equal(false) data.should.eql({foo: {}}) // can't coerce _ajv.validate(schema, (data = {foo: []})).should.equal(false) data.should.eql({foo: []}) // can't coerce }) }) it("should coerce to multiple types in order with integer type", () => { const schema = { type: "object", properties: { foo: { type: ["integer", "boolean", "null"], }, }, } instances.forEach((_ajv) => { let data _ajv.validate(schema, (data = {foo: "1"})).should.equal(true) data.should.eql({foo: 1}) _ajv.validate(schema, (data = {foo: "false"})).should.equal(true) data.should.eql({foo: false}) _ajv.validate(schema, (data = {foo: 1})).should.equal(true) data.should.eql({foo: 1}) // no coercion _ajv.validate(schema, (data = {foo: true})).should.equal(true) data.should.eql({foo: true}) // no coercion _ajv.validate(schema, (data = {foo: null})).should.equal(true) data.should.eql({foo: null}) // no coercion _ajv.validate(schema, (data = {foo: "abc"})).should.equal(false) data.should.eql({foo: "abc"}) // can't coerce _ajv.validate(schema, (data = {foo: {}})).should.equal(false) data.should.eql({foo: {}}) // can't coerce _ajv.validate(schema, (data = {foo: []})).should.equal(false) data.should.eql({foo: []}) // can't coerce }) }) it("should fail to coerce non-number if multiple properties/items are coerced (issue #152)", () => { const schema = { type: "object", properties: { foo: {type: "number"}, bar: {type: "number"}, }, } const schema2 = { type: "array", items: {type: "number"}, } instances.forEach((_ajv) => { const data: any = {foo: "123", bar: "bar"} _ajv.validate(schema, data).should.equal(false) data.should.eql({foo: 123, bar: "bar"}) const data2: any = ["123", "bar"] _ajv.validate(schema2, data2).should.equal(false) data2.should.eql([123, "bar"]) }) }) it("should update data if the schema is in ref that is not inlined", () => { instances.push(new _Ajv({coerceTypes: true, inlineRefs: false, allowUnionTypes: true})) const schema = { type: "object", definitions: { foo: {type: "number"}, }, properties: { foo: {$ref: "#/definitions/foo"}, }, } const schema2 = { type: "object", definitions: { foo: { // allOf is needed to make sure that "foo" is compiled to a separate function // and not simply passed through (as it would be if it were only $ref) allOf: [{$ref: "#/definitions/bar"}], }, bar: {type: "number"}, }, properties: { foo: {$ref: "#/definitions/foo"}, }, } const schemaRecursive = { type: ["object", "number"], properties: { foo: {$ref: "#"}, }, } const schemaRecursive2 = { $id: "http://e.com/schema.json#", definitions: { foo: { $id: "http://e.com/foo.json#", type: ["object", "number"], properties: { foo: {$ref: "#"}, }, }, }, type: "object", properties: { foo: {$ref: "http://e.com/foo.json#"}, }, } instances.forEach((_ajv) => { testCoercion(schema, {foo: "1"}, {foo: 1}) testCoercion(schema2, {foo: "1"}, {foo: 1}) testCoercion(schemaRecursive, {foo: {foo: "1"}}, {foo: {foo: 1}}) testCoercion(schemaRecursive2, {foo: {foo: {foo: "1"}}}, {foo: {foo: {foo: 1}}}) function testCoercion(_schema, fromData, toData) { const valid = _ajv.validate(_schema, fromData) // if (!valid) console.log(schema, fromData, toData); valid.should.equal(true) fromData.should.eql(toData) } }) }) it("should generate one error for type with coerceTypes option (issue #469)", () => { const schema = { type: "number", minimum: 10, } instances.forEach((_ajv) => { const validate = _ajv.compile(schema) validate(9).should.equal(false) validate.errors?.length.should.equal(1) validate(11).should.equal(true) validate("foo").should.equal(false) validate.errors?.length.should.equal(1) }) }) it('should check "uniqueItems" after coercion', () => { const schema = { type: "array", items: {type: "number"}, uniqueItems: true, } instances.forEach((_ajv) => { const validate = _ajv.compile(schema) validate([1, "2", 3]).should.equal(true) validate([1, "2", 2]).should.equal(false) validate.errors?.length.should.equal(1) validate.errors?.[0].keyword.should.equal("uniqueItems") }) }) it('should check "contains" after coercion', () => { const schema = { type: "array", items: {type: "number"}, contains: {const: 2}, } instances.forEach((_ajv) => { const validate = _ajv.compile(schema) validate([1, "2", 3]).should.equal(true) validate([1, "3", 4]).should.equal(false) validate.errors?.pop()?.keyword.should.equal("contains") }) }) function testRules(rules, cb) { for (const toType in rules) { for (const fromType in rules[toType]) { const tests = rules[toType][fromType] tests.forEach((test) => { const canCoerce = test.to !== undefined const schema = canCoerce ? Array.isArray(test.to) ? {type: toType, items: {type: fromType, enum: [test.to[0]]}} : {type: toType, enum: [test.to]} : {type: toType} cb(test, schema, canCoerce, toType, fromType) }) } } } })
the_stack
import File, {FileInterface} from "../../models/file"; import User, {UserInterface} from "../../models/user"; import s3 from "../../db/s3"; import env from "../../enviroment/env"; import {Response, Request} from "express"; import ChunkInterface from "./utils/ChunkInterface"; import NotAuthorizedError from "../../utils/NotAuthorizedError"; import NotFoundError from "../../utils/NotFoundError"; import crypto from "crypto"; import getBusboyData from "./utils/getBusboyData"; import videoChecker from "../../utils/videoChecker"; import uuid from "uuid"; import awaitUploadStreamS3 from "./utils/awaitUploadStreamS3"; import awaitStream from "./utils/awaitStream"; import createThumbnailAny from "./utils/createThumbailAny"; import imageChecker from "../../utils/imageChecker"; import Thumbnail, {ThumbnailInterface} from "../../models/thumbnail"; import streamToBuffer from "../../utils/streamToBuffer"; import removeChunksS3 from "./utils/removeChunksS3"; import fixStartChunkLength from "./utils/fixStartChunkLength"; import fixEndChunkLength from "./utils/fixEndChunkLength"; import getPrevIVS3 from "./utils/getPrevIVS3"; import awaitStreamVideo from "./utils/awaitStreamVideo"; import Folder, {FolderInterface} from "../../models/folder"; import DbUtilFile from "../../db/utils/fileUtils/index"; import s3Auth from "../../db/S3Personal"; import addToStoageSize from "./utils/addToStorageSize"; import subtractFromStorageSize from "./utils/subtractFromStorageSize"; import ForbiddenError from "../../utils/ForbiddenError"; import {ObjectID} from "mongodb"; const dbUtilsFile = new DbUtilFile(); class S3Service implements ChunkInterface { constructor() { } uploadFile = async (user: UserInterface, busboy: any, req: Request) => { const password = user.getEncryptionKey(); if (!password) throw new ForbiddenError("Invalid Encryption Key") const initVect = crypto.randomBytes(16); const CIPHER_KEY = crypto.createHash('sha256').update(password).digest() const cipher = crypto.createCipheriv('aes256', CIPHER_KEY, initVect); const {file, filename, formData} = await getBusboyData(busboy); const parent = formData.get("parent") || "/" const parentList = formData.get("parentList") || "/"; const size = formData.get("size") || "" const personalFile = formData.get("personal-file") ? true : false; let hasThumbnail = false; let thumbnailID = "" const isVideo = videoChecker(filename) const randomS3ID = uuid.v4(); const s3Data: any = personalFile ? await user.decryptS3Data() : {}; const bucketName = personalFile ? s3Data.bucket : env.s3Bucket; let metadata: any = { owner: user._id, parent, parentList, hasThumbnail, thumbnailID, isVideo, size, IV: initVect, s3ID: randomS3ID, } if (personalFile) metadata = {...metadata, personalFile: true} const params = { Bucket: bucketName, Body: file.pipe(cipher), Key: randomS3ID }; console.log(11, params); await awaitUploadStreamS3(params, personalFile, s3Data); console.log(22, params); const date = new Date(); const encryptedFileSize = size; const currentFile = new File({ filename, uploadDate: date.toISOString(), length: encryptedFileSize, metadata }); await currentFile.save(); await addToStoageSize(user, size, personalFile); const imageCheck = imageChecker(currentFile.filename); if (currentFile.length < 15728640 && imageCheck) { const updatedFile = await createThumbnailAny(currentFile, filename, user); return updatedFile; } else { return currentFile; } } getFileWriteStream = async (user: UserInterface, file: FileInterface, parentFolder: FolderInterface, readStream: any) => { const password = user.getEncryptionKey(); if (!password) throw new ForbiddenError("Invalid Encryption Key") const initVect = crypto.randomBytes(16); const CIPHER_KEY = crypto.createHash('sha256').update(password).digest() const cipher = crypto.createCipheriv('aes256', CIPHER_KEY, initVect); const filename = file.filename const parent = parentFolder._id const parentList = [...parentFolder.parentList, parentFolder._id] const size = file.metadata.size const personalFile = file.metadata.personalFile ? true : false let hasThumbnail = file.metadata.hasThumbnail; let thumbnailID = file.metadata.thumbnailID const isVideo = file.metadata.isVideo const metadata = { owner: user._id, parent, parentList, hasThumbnail, thumbnailID, isVideo, size, IV: file.metadata.IV, s3ID: file.metadata.s3ID, personalFile } const s3Data: any = personalFile ? await user.decryptS3Data() : {}; const bucketName = personalFile ? s3Data.bucket : env.s3Bucket; const params = { Bucket: bucketName, Body: readStream, Key: file.metadata.s3ID }; } getS3AuthThumbnail = async (thumbnail: ThumbnailInterface, user: UserInterface) => { if (thumbnail.personalFile) { const s3Data = await user.decryptS3Data(); //console.log("s3 data", s3Data) return {s3Storage: s3Auth(s3Data.id, s3Data.key), bucket: s3Data.bucket}; } else { return {s3Storage: s3, bucket: env.s3Bucket}; } } getS3Auth = async (file: FileInterface, user: UserInterface) => { if (file.metadata.personalFile) { const s3Data = await user.decryptS3Data(); //console.log("s3 data", s3Data) return {s3Storage: s3Auth(s3Data.id, s3Data.key), bucket: s3Data.bucket}; } else { return {s3Storage: s3, bucket: env.s3Bucket}; } } downloadFile = async (user: UserInterface, fileID: string, res: Response) => { const currentFile: FileInterface = await dbUtilsFile.getFileInfo(fileID, user._id); if (!currentFile) throw new NotFoundError("Download File Not Found"); const password = user.getEncryptionKey(); if (!password) throw new ForbiddenError("Invalid Encryption Key"); const {s3Storage, bucket} = await this.getS3Auth(currentFile, user); const IV = currentFile.metadata.IV.buffer as Buffer; const CIPHER_KEY = crypto.createHash('sha256').update(password).digest() const decipher = crypto.createDecipheriv('aes256', CIPHER_KEY, IV); res.set('Content-Type', 'binary/octet-stream'); res.set('Content-Disposition', 'attachment; filename="' + currentFile.filename + '"'); res.set('Content-Length', currentFile.metadata.size.toString()); const params: any = {Bucket: bucket, Key: currentFile.metadata.s3ID!}; const s3ReadStream = s3Storage.getObject(params).createReadStream(); const allStreamsToErrorCatch = [s3ReadStream, decipher]; await awaitStream(s3ReadStream.pipe(decipher), res, allStreamsToErrorCatch); } getFileReadStream = async (user: UserInterface, fileID: string) => { const currentFile: FileInterface = await dbUtilsFile.getFileInfo(fileID, user._id); if (!currentFile) throw new NotFoundError("Download File Not Found"); const password = user.getEncryptionKey(); if (!password) throw new ForbiddenError("Invalid Encryption Key"); const {s3Storage, bucket} = await this.getS3Auth(currentFile, user); const IV = currentFile.metadata.IV.buffer as Buffer; const CIPHER_KEY = crypto.createHash('sha256').update(password).digest() const decipher = crypto.createDecipheriv('aes256', CIPHER_KEY, IV); const params: any = {Bucket: bucket, Key: currentFile.metadata.s3ID!}; const s3ReadStream = s3Storage.getObject(params).createReadStream(); return s3ReadStream } streamVideo = async (user: UserInterface, fileID: string, headers: any, res: Response, req: Request) => { // To get this all working correctly with encryption and across // All browsers took many days, tears, and some of my sanity. // Shoutout to Tyzoid for helping me with the decryption // And and helping me understand how the IVs work. // P.S I hate safari >:( // Why do yall have to be weird with video streaming // 90% of the issues with this are only in Safari // Is safari going to be the next internet explorer? const userID = user._id; const currentFile: FileInterface = await dbUtilsFile.getFileInfo(fileID, userID); if (!currentFile) throw new NotFoundError("Video File Not Found"); const password = user.getEncryptionKey(); if (!password) throw new ForbiddenError("Invalid Encryption Key") const fileSize = currentFile.metadata.size; const isPersonal = currentFile.metadata.personalFile!; const range = headers.range const parts = range.replace(/bytes=/, "").split("-") let start = parseInt(parts[0], 10) let end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1 const chunksize = (end - start) + 1 const IV = currentFile.metadata.IV.buffer as Buffer; let head = { 'Content-Range': 'bytes ' + start + '-' + end + '/' + fileSize, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize, 'Content-Type': 'video/mp4' } let currentIV = IV; let fixedStart = 0; let fixedEnd = currentFile.length; if (start === 0 && end === 1) { // This is for Safari/iOS, Safari will request the first // Byte before actually playing the video. Needs to be // 16 bytes. fixedStart = 0; fixedEnd = 15; } else { // If you're a normal browser, or this isn't Safari's first request // We need to make it so start is divisible by 16, since AES256 // Has a block size of 16 bytes. fixedStart = start % 16 === 0 ? start : fixStartChunkLength(start); // I goofed up and forgot to add the encrypted file size to S3 data, // It just used the normal file size :( // So you'll notice only on the S3 route do i need to fix the end length // To, this is because the other 2 routes use the encrypted file size // Which is always a multiple of 16. I cannot change this now // Since previous versions will still have the issue, but // This is a simple fix luckily. fixedEnd = fixedEnd % 16 === 0 ? fixedEnd : fixEndChunkLength(fixedEnd) } if (+start === 0) { // This math will not work if the start is 0 // So if it is we just change fixed start back // To 0. fixedStart = 0; } // We also need to calculate the difference between the start and the // Fixed start position. Since there will be an offset if the original // Request is not divisible by 16, it will not return the right part // Of the file, you will see how we do this in the awaitStreamVideo // code. const differenceStart = start - fixedStart; if (fixedStart !== 0 && start !== 0) { // If this isn't the first request, the way AES256 works is when you try to // Decrypt a certain part of the file that isn't the start, the IV will // Actually be the 16 bytes ahead of where you are trying to // Start the decryption. currentIV = await getPrevIVS3(fixedStart - 16, currentFile.metadata.s3ID!, isPersonal, user) as Buffer; } const {s3Storage, bucket} = await this.getS3Auth(currentFile, user); const params: any = {Bucket: bucket, Key: currentFile.metadata.s3ID!, Range: `bytes=${fixedStart}-${fixedEnd}`}; const s3ReadStream = s3Storage.getObject(params).createReadStream(); const CIPHER_KEY = crypto.createHash('sha256').update(password).digest() const decipher = crypto.createDecipheriv('aes256', CIPHER_KEY, currentIV); decipher.setAutoPadding(false); res.writeHead(206, head); const allStreamsToErrorCatch = [s3ReadStream, decipher]; s3ReadStream.pipe(decipher); await awaitStreamVideo(start, end, differenceStart, decipher, res, req, allStreamsToErrorCatch, s3ReadStream); s3ReadStream.destroy(); } getThumbnail = async (user: UserInterface, id: string) => { const password = user.getEncryptionKey(); if (!password) throw new ForbiddenError("Invalid Encryption Key") const thumbnail = await Thumbnail.findById(new ObjectID(id)) as ThumbnailInterface; if (thumbnail.owner !== user._id.toString()) { throw new ForbiddenError('Thumbnail Unauthorized Error'); } const iv = thumbnail.IV!; const {s3Storage, bucket} = await this.getS3AuthThumbnail(thumbnail, user); const CIPHER_KEY = crypto.createHash('sha256').update(password).digest() const decipher = crypto.createDecipheriv("aes256", CIPHER_KEY, iv); const params: any = {Bucket: bucket, Key: thumbnail.s3ID!}; const readStream = s3Storage.getObject(params).createReadStream(); const allStreamsToErrorCatch = [readStream, decipher]; const bufferData = await streamToBuffer(readStream.pipe(decipher), allStreamsToErrorCatch); return bufferData; } getFullThumbnail = async (user: UserInterface, fileID: string, res: Response) => { const userID = user._id; const file: FileInterface = await dbUtilsFile.getFileInfo(fileID, userID); if (!file) throw new NotFoundError("File Thumbnail Not Found"); const password = user.getEncryptionKey(); const IV = file.metadata.IV.buffer as Buffer; if (!password) throw new ForbiddenError("Invalid Encryption Key") const {s3Storage, bucket} = await this.getS3Auth(file, user); const params: any = {Bucket: bucket, Key: file.metadata.s3ID!}; const readStream = s3Storage.getObject(params).createReadStream(); const CIPHER_KEY = crypto.createHash('sha256').update(password).digest() const decipher = crypto.createDecipheriv('aes256', CIPHER_KEY, IV); res.set('Content-Type', 'binary/octet-stream'); res.set('Content-Disposition', 'attachment; filename="' + file.filename + '"'); res.set('Content-Length', file.metadata.size.toString()); const allStreamsToErrorCatch = [readStream, decipher]; await awaitStream(readStream.pipe(decipher), res, allStreamsToErrorCatch); } getPublicDownload = async (fileID: string, tempToken: any, res: Response) => { const file: FileInterface = await dbUtilsFile.getPublicFile(fileID); if (!file || !file.metadata.link || file.metadata.link !== tempToken) { throw new NotAuthorizedError("File Not Public"); } const user = await User.findById(file.metadata.owner) as UserInterface; const password = user.getEncryptionKey(); if (!password) throw new ForbiddenError("Invalid Encryption Key"); const IV = file.metadata.IV.buffer as Buffer; const {s3Storage, bucket} = await this.getS3Auth(file, user); const params: any = {Bucket: bucket, Key: file.metadata.s3ID!}; const readStream = s3Storage.getObject(params).createReadStream(); const CIPHER_KEY = crypto.createHash('sha256').update(password).digest() const decipher = crypto.createDecipheriv('aes256', CIPHER_KEY, IV); res.set('Content-Type', 'binary/octet-stream'); res.set('Content-Disposition', 'attachment; filename="' + file.filename + '"'); res.set('Content-Length', file.metadata.size.toString()); const allStreamsToErrorCatch = [readStream, decipher]; await awaitStream(readStream.pipe(decipher), res, allStreamsToErrorCatch); if (file.metadata.linkType === "one") { await dbUtilsFile.removeOneTimePublicLink(fileID); } } deleteFile = async (userID: string, fileID: string) => { const file: FileInterface = await dbUtilsFile.getFileInfo(fileID, userID); if (!file) throw new NotFoundError("Delete File Not Found Error"); const user = await User.findById(userID) as UserInterface; const {s3Storage, bucket} = await this.getS3Auth(file, user); if (file.metadata.thumbnailID) { const thumbnail = await Thumbnail.findById(file.metadata.thumbnailID) as ThumbnailInterface; const paramsThumbnail: any = {Bucket: bucket, Key: thumbnail.s3ID!}; await removeChunksS3(s3Storage, paramsThumbnail); await Thumbnail.deleteOne({_id: file.metadata.thumbnailID}); } const params: any = {Bucket: bucket, Key: file.metadata.s3ID!}; await removeChunksS3(s3Storage, params); await File.deleteOne({_id: file._id}); await subtractFromStorageSize(userID, file.length, file.metadata.personalFile!); } deleteFolder = async (userID: string, folderID: string, parentList: string[]) => { const parentListString = parentList.toString() await Folder.deleteMany({"owner": userID, "parentList": {$all: parentList}}) await Folder.deleteMany({"owner": userID, "_id": folderID}); const fileList = await dbUtilsFile.getFileListByParent(userID, parentListString); if (!fileList) throw new NotFoundError("Delete File List Not Found"); const user = await User.findById(userID) as UserInterface; for (let i = 0; i < fileList.length; i++) { const currentFile = fileList[i]; const {s3Storage, bucket} = await this.getS3Auth(currentFile, user); try { if (currentFile.metadata.thumbnailID) { const thumbnail = await Thumbnail.findById(currentFile.metadata.thumbnailID) as ThumbnailInterface; const paramsThumbnail: any = {Bucket: bucket, Key: thumbnail.s3ID!}; await removeChunksS3(s3Storage, paramsThumbnail); await Thumbnail.deleteOne({_id: currentFile.metadata.thumbnailID}); } const params: any = {Bucket: bucket, Key: currentFile.metadata.s3ID!}; await removeChunksS3(s3Storage, params); await File.deleteOne({_id: currentFile._id}); } catch (e) { console.log("Could not delete file", currentFile.filename, currentFile._id); } } } deleteAll = async (userID: string) => { await Folder.deleteMany({"owner": userID}); const fileList = await dbUtilsFile.getFileListByOwner(userID); if (!fileList) throw new NotFoundError("Delete All File List Not Found Error"); const user = await User.findById(userID) as UserInterface; for (let i = 0; i < fileList.length; i++) { const currentFile = fileList[i]; const {s3Storage, bucket} = await this.getS3Auth(currentFile, user); try { if (currentFile.metadata.thumbnailID) { const thumbnail = await Thumbnail.findById(currentFile.metadata.thumbnailID) as ThumbnailInterface; const paramsThumbnail: any = {Bucket: bucket, Key: thumbnail.s3ID!}; await removeChunksS3(s3Storage, paramsThumbnail); await Thumbnail.deleteOne({_id: currentFile.metadata.thumbnailID}); } const params: any = {Bucket: bucket, Key: currentFile.metadata.s3ID!}; await removeChunksS3(s3Storage, params); await File.deleteOne({_id: currentFile._id}); } catch (e) { console.log("Could Not Remove File", currentFile.filename, currentFile._id); } } } } export default S3Service;
the_stack
import { TokenReader, ITokenizationSettings, IRenderSettings, makeRenderSettings, defaultRenderSettings, IRenderable, IRenderOptions, IPosition, IParseSettings, defaultParseSettings } from "../helpers"; import { Module } from "../javascript/components/module"; import { Stylesheet } from "../css/stylesheet"; import { readFile, writeFile, IFile } from "../filesystem"; export abstract class Node implements IRenderable { abstract parent: HTMLElement | HTMLDocument | null; abstract render(settings: IRenderSettings): string; /** Returns next adjacent sibling */ get next() { if (!this.parent) throw Error("next() requires parent element"); const myIndex = this.parent.children.indexOf(this) return this.parent.children[myIndex + 1]; } /** Returns previous adjacent sibling */ get previous() { if (!this.parent) throw Error("previous() requires parent element"); const myIndex = this.parent.children.indexOf(this) return this.parent.children[myIndex - 1]; } /** * Returns the HTMLDocument the node exists under */ get document(): HTMLDocument { let parent = this.parent; while (parent && !(parent instanceof HTMLDocument)) { parent = parent.parent; } if (!parent) throw Error("Element not descendant of a HTMLDocument"); return parent as HTMLDocument; } /** * Returns the depth of the component from the document */ get depth(): number { let depth = 1; let parent = this.parent; while (parent && !(parent instanceof HTMLDocument)) { parent = parent.parent; depth++; } return depth; } } export class TextNode extends Node implements IRenderable { constructor( public text = '', public parent: HTMLElement | null = null, public position: IPosition | null = null ) { super(); } render(settings: IRenderSettings = defaultRenderSettings) { if (this.text.length > 80 && !settings.minify) { return `\n${this.text}`; } else { return this.text.replace(/\n/g, "<br>"); } } } export class HTMLElement extends Node implements IRenderable { // Tags that don't require </...> static selfClosingTags = new Set(["area", "base", "br", "embed", "hr", "iframe", "img", "input", "link", "meta", "param", "source", "track", "!DOCTYPE"]); // Attributes which are always true if there is a value static booleanAttributes = new Set(["hidden", "readonly", "checked", "disabled", "loop", "controls"]); // Tags which don't parse children as tags static contentTags = ["script", "styles"]; tagName: string; attributes: Map<string, string | null> | null; children: Array<Node> = []; module?: Module; // Only present if tagName === "script" stylesheet?: Stylesheet; // Only present if tagName === "style" constructor( tagName: string, attributes: Map<string, string | null> | null = null, children: Array<Node> = [], public parent: HTMLElement | HTMLDocument | null = null, public position: IPosition | null = null, public closesSelf: boolean = false, // if /> ) { super(); this.tagName = tagName; this.attributes = attributes; for (const child of children) { child.parent = this; } this.children = children; } static fromTokens( reader: TokenReader<HTMLToken>, settings: IParseSettings = defaultParseSettings, parent: HTMLElement | HTMLDocument | null = null ): HTMLElement { reader.expectNext(HTMLToken.TagStart); const position: IPosition = { column: reader.current.column, line: reader.current.line }; const tagName: string = reader.current.value!; reader.expectNext(HTMLToken.TagName); let attributes: Map<string, string | null> | null = null; // Parse attributes while (reader.current.type === HTMLToken.AttributeKey) { if (!attributes) attributes = new Map(); let key = reader.current.value!; reader.move(); if (reader.current.type as HTMLToken === HTMLToken.AttributeValue) { attributes.set(key, reader.current.value!); reader.move(); } else { attributes.set(key, null); } } if (reader.current.type === HTMLToken.TagEndClose) { reader.move(); return new HTMLElement(tagName, attributes, [], parent, position, true); } else { reader.expectNext(HTMLToken.TagEnd) } if (HTMLElement.selfClosingTags.has(tagName)) { return new HTMLElement(tagName, attributes, [], parent, position); } else if (tagName === "script" && reader.current.type !== HTMLToken.TagCloseStart) { const elem = new HTMLElement(tagName, attributes, [], parent, position); elem.module = Module.fromString(reader.current.value!, reader.filename ?? "anonymous", reader.current.column, reader.current.line); reader.move(); reader.expectNext(HTMLToken.TagCloseStart); reader.expectNext(HTMLToken.TagName); reader.expectNext(HTMLToken.TagEnd); return elem; } else if (tagName === "style" && reader.current.type !== HTMLToken.TagCloseStart) { const elem = new HTMLElement(tagName, attributes, [], parent, position); elem.stylesheet = Stylesheet.fromString(reader.current.value!, reader.filename ?? "anonymous", reader.current.column, reader.current.line); reader.move(); reader.expectNext(HTMLToken.TagCloseStart); reader.expectNext(HTMLToken.TagName); reader.expectNext(HTMLToken.TagEnd); return elem; } const children: Array<Node> = []; const element = new HTMLElement(tagName, attributes, children, parent, position); while (reader.current.type !== HTMLToken.TagCloseStart) { if (reader.current.type === HTMLToken.TagStart) { children.push(HTMLElement.fromTokens(reader, settings, element)); } else if (reader.current.type === HTMLToken.Content) { if (reader.current.value && reader.current.value.trimRight().length > 0) { const position: IPosition = { column: reader.current.column, line: reader.current.line }; // Parent here can be null as it will be set in the HTMLConstructor children.push(new TextNode(reader.current.value, element, position)); } reader.move(); } else if (reader.current.type === HTMLToken.Comment) { if (settings.comments) { children.push(new HTMLComment(element, reader.current.value)); } reader.move(); } else { reader.throwExpect(`Expected tag name, comment or content under tag "${element.render(defaultRenderSettings, { inline: true })}"`); } } reader.move(); if (reader.current.value !== tagName) reader.throwError(`Expected </${tagName}>`); reader.expectNext(HTMLToken.TagName); reader.expectNext(HTMLToken.TagEnd); return element; } static fromString(string: string, settings: IParseSettings = defaultParseSettings): HTMLElement { const reader = stringToTokens(string); const element = HTMLElement.fromTokens(reader, settings); reader.expect(HTMLToken.EOF); return element; } /** * Renders the given the HTMLElement * @param settings * @param renderChildren if false only renders tagname & attributes (default: true) (used for debugging) */ render(settings: IRenderSettings = defaultRenderSettings, renderOptions?: IRenderOptions): string { let acc = "<"; acc += this.tagName; if (this.attributes) { for (const [attr, value] of this.attributes) { acc += " " + attr; if (value !== null) { acc += `="${value}"`; } } } if (this.closesSelf) acc += "/"; acc += ">"; if (renderOptions?.inline || HTMLElement.selfClosingTags.has(this.tagName) || this.closesSelf) return acc; // If module or stylesheet render that using Javascript or CSS rendering if (this.module) { const serializedChild = this.module.render(settings); if (settings.minify) { acc += serializedChild; } else { acc += ("\n" + serializedChild).replace(/\n/g, "\n" + " ".repeat(settings.indent)); acc += "\n"; } } else if (this.stylesheet) { const serializedChild = this.stylesheet.render(settings); if (settings.minify) { acc += serializedChild; } else { acc += ("\n" + serializedChild).replace(/\n/g, "\n" + " ".repeat(settings.indent)); acc += "\n"; } } else { for (const child of this.children) { const serializedChild = child.render(settings); if (settings.minify) { acc += serializedChild; } else { acc += ("\n" + serializedChild).replace(/\n/g, "\n" + " ".repeat(settings.indent)); } } if (!settings.minify && this.children.length > 0) acc += "\n"; } acc += `</${this.tagName}>`; return acc; } } export class HTMLComment extends Node implements IRenderable { constructor( public parent: HTMLElement | HTMLDocument, public comment: string = "", ) { super(); } render(settings: IRenderSettings = defaultRenderSettings): string { if (settings.minify) return ""; return `<!--${this.comment}-->` } } export class HTMLDocument implements IFile { children: Array<Node> = []; constructor(public filename: string, elements: Array<Node> = []) { elements.forEach(element => element.parent = this); this.children = elements; } static fromTokens(reader: TokenReader<HTMLToken>, settings: IParseSettings = defaultParseSettings, filename: string) { const html = new HTMLDocument(filename); while (reader.current.type !== HTMLToken.EOF) { if (reader.current.type === HTMLToken.Content) { reader.move(); continue; } if (reader.current.type === HTMLToken.Comment) { if (settings.comments) { html.children.push(new HTMLComment(html, reader.current.value)); } reader.move(); continue; } html.children.push(HTMLElement.fromTokens(reader, settings, html)); } return html; } static fromString(text: string, filename: string = "anom.html", settings: IParseSettings = defaultParseSettings): HTMLDocument { const reader = stringToTokens(text, { file: filename }); const document = HTMLDocument.fromTokens(reader, settings, filename); if (filename) document.filename = filename; reader.expect(HTMLToken.EOF); return document; } static fromFile(filename: string, settings: IParseSettings = defaultParseSettings): HTMLDocument { const string = readFile(filename); return HTMLDocument.fromString(string, filename, settings); } render(settings: Partial<IRenderSettings> = {}) { const completeSettings = makeRenderSettings(settings); let acc = ""; for (let i = 0; i < this.children.length; i++) { acc += this.children[i].render(completeSettings); if (!completeSettings.minify && i + 1 < this.children.length) acc += "\n"; } return acc; } writeToFile(settings: Partial<IRenderSettings> = {}, filename?: string) { const contents = this.render(settings); writeFile(filename ?? this.filename!, contents); } } enum HTMLToken { TagStart, // < TagName, // <...> TagEnd, // > TagEndClose, // /> TagCloseStart, // </ AttributeKey, AttributeValue, Content, Comment, EOF } const reverse = new Map() for (const key in HTMLToken) { // @ts-ignore key can be string if (!isNaN(key)) { reverse.set(parseInt(key), HTMLToken[key]) } } export function stringToTokens(html: string, settings: ITokenizationSettings = {}): TokenReader<HTMLToken> { const reader = new TokenReader<HTMLToken>({ reverse, file: settings.file || null }); let index = 0; let line = 1; let column = 0; let escapedGreaterThan: string | null = null; let attributeQuote: `"` | `'` | null = null; // If in attribute the string quote or (null) used to start reader.add({ type: HTMLToken.Content, value: "", line, column }); while (index < html.length) { // Updates line and character token position: if (html[index] === "\n") { line++; column = 0; } else { column++; } switch (reader.top.type) { case HTMLToken.Content: if (html[index] === "<" && !escapedGreaterThan) { reader.top.value = reader.top.value!.includes("\n") ? reader.top.value!.trim() : reader.top.value!; if (reader.top.value.length === 0) reader.pop(); if (html.startsWith("!--", index + 1)) { index += 3; column += 3; reader.add({ type: HTMLToken.Comment, value: "", line, column }); } else if (html[index + 1] === "/") { index++; column++; reader.add({ type: HTMLToken.TagCloseStart, line, column }); reader.add({ type: HTMLToken.TagName, value: "", line, column: column + 1 }); } else { reader.add({ type: HTMLToken.TagStart, line, column }); reader.add({ type: HTMLToken.TagName, value: "", line, column: column + 1 }); } } // This deals with not breaking on "<..." during script and style tags else if (escapedGreaterThan && html.startsWith(`</${escapedGreaterThan}`, index)) { index++; column++; escapedGreaterThan = null; reader.add({ type: HTMLToken.TagCloseStart, line, column }); reader.add({ type: HTMLToken.TagName, value: "", line, column: column + 1 }); } else { reader.top.value += html[index]; } break; case HTMLToken.TagName: if (html[index] === " " || html[index] === "\n" || html[index] === "\r" || html[index] === "\t") { reader.add({ type: HTMLToken.AttributeKey, value: "", column: column + 1, line }); } else if (html[index] === ">") { reader.add({ type: HTMLToken.TagEnd, column, line }); reader.add({ type: HTMLToken.Content, value: "", column: column + 1, line }); } else if (html.startsWith("/>", index)) { index++; column++; reader.add({ type: HTMLToken.TagEndClose, column, line }); reader.add({ type: HTMLToken.Content, value: "", column: column + 1, line }); } else { reader.top.value += html[index]; if (reader.peekFromTop(1)?.type !== HTMLToken.TagCloseStart && ["script", "style"].includes(reader.top.value!)) { escapedGreaterThan = reader.top.value!; } } break; case HTMLToken.AttributeKey: if (html[index] === "=") { reader.add({ type: HTMLToken.AttributeValue, value: "", column, line }); } else if (html[index] === ">") { if (reader.top.value?.length === 0) reader.pop(); reader.add({ type: HTMLToken.TagEnd, column, line }); reader.add({ type: HTMLToken.Content, value: "", column: column + 1, line }); } else if (html.startsWith("/>", index)) { if (reader.top.value?.length === 0) reader.pop(); index++; column++; reader.add({ type: HTMLToken.TagEndClose, column, line }); reader.add({ type: HTMLToken.Content, value: "", column: column + 1, line }); } else if (html[index] === " " && reader.top.value?.length !== 0) { reader.add({ type: HTMLToken.AttributeKey, value: "", column, line }) } else if (html[index] !== " " && html[index] !== "\n" && html[index] !== "\r" && html[index] !== "\t") { reader.top.value += html[index]; } break; case HTMLToken.AttributeValue: if (reader.top.value?.length === 0 && "'\"".includes(html[index]) && attributeQuote === null) { attributeQuote = html[index] as `"` | `'`; } else if (html[index] === attributeQuote) { attributeQuote = null; reader.add({ type: HTMLToken.AttributeKey, value: "", column, line }); } else if (attributeQuote === null && html[index] === " ") { reader.add({ type: HTMLToken.AttributeKey, value: "", column, line }); } else if (attributeQuote === null && html[index] === ">") { reader.add({ type: HTMLToken.TagEnd, column, line }); reader.add({ type: HTMLToken.Content, value: "", column: column + 1, line }); } else { reader.top.value += html[index]; } break; case HTMLToken.Comment: if (html.startsWith("-->", index)) { index += 3; column += 3; reader.add({ type: HTMLToken.Content, value: "", line, column }) } else { reader.top.value += html[index]; } break; } index++; } if (reader.top.value?.length === 0) reader.pop(); reader.add({ type: HTMLToken.EOF, line, column: column + 1 }); return reader; } /** * Returns a flat list of a HTMLElement children * @param html */ export function flatElements(html: HTMLDocument | HTMLElement): HTMLElement[] { const children: Array<HTMLElement> = [] for (const child of html.children) { if (child instanceof HTMLElement) { children.push(child); children.push(...flatElements(child)); } } return children; }
the_stack
(function () { class ClosedCaption { element: { [name: string]: any } = {}; // 节点集合 data: { [name: string]: any } = {}; // 字幕缓存 resizeRate = 100; // 字幕大小倍率 ON = `<svg width="22" height="28" viewbox="0 0 22 30" xmlns="http://www.w3.org/2000/svg"><path id="svg_1" fill-rule="evenodd" fill="#99a2aa" d="m4.07787,6.88102l14,0a2,2 0 0 1 2,2l0,10a2,2 0 0 1 -2,2l-14,0a2,2 0 0 1 -2,-2l0,-10a2,2 0 0 1 2,-2zm5,5.5a1,1 0 1 0 0,-2l-3,0a2,2 0 0 0 -2,2l0,3a2,2 0 0 0 2,2l3,0a1,1 0 0 0 0,-2l-2,0a1,1 0 0 1 -1,-1l0,-1a1,1 0 0 1 1,-1l2,0zm8,0a1,1 0 0 0 0,-2l-3,0a2,2 0 0 0 -2,2l0,3a2,2 0 0 0 2,2l3,0a1,1 0 0 0 0,-2l-2,0a1,1 0 0 1 -1,-1l0,-1a1,1 0 0 1 1,-1l2,0z"/></svg>`; OFF = `<svg width="22" height="28" viewBox="0 0 22 32" xmlns="http://www.w3.org/2000/svg"><path id="svg_1" fill-rule="evenodd" fill="#99a2aa" d="m15.172,21.87103l-11.172,0a2,2 0 0 1 -2,-2l0,-10c0,-0.34 0.084,-0.658 0.233,-0.938l-0.425,-0.426a1,1 0 1 1 1.414,-1.414l15.556,15.556a1,1 0 0 1 -1.414,1.414l-2.192,-2.192zm-10.21,-10.21c-0.577,0.351 -0.962,0.986 -0.962,1.71l0,3a2,2 0 0 0 2,2l3,0a1,1 0 0 0 0,-2l-2,0a1,1 0 0 1 -1,-1l0,-1a1,1 0 0 1 0.713,-0.958l-1.751,-1.752zm1.866,-3.79l11.172,0a2,2 0 0 1 2,2l0,10c0,0.34 -0.084,0.658 -0.233,0.938l-2.48,-2.48a1,1 0 0 0 -0.287,-1.958l-1.672,0l-1.328,-1.328l0,-0.672a1,1 0 0 1 1,-1l2,0a1,1 0 0 0 0,-2l-3,0a2,2 0 0 0 -1.977,1.695l-5.195,-5.195z"/></svg>`; color = [ { value: '16777215', content: '<span style="color:#FFF;text-shadow: #000 0px 0px 1px">白色</span>' }, { value: '16007990', content: '<b style="color:#F44336;text-shadow: #000 0px 0px 1px">红色</b>' }, { value: '10233776', content: '<b style="color:#9C27B0;text-shadow: #000 0px 0px 1px">紫色</b>' }, { value: '6765239', content: '<b style="color:#673AB7;text-shadow: #000 0px 0px 1px">深紫色</b>' }, { value: '4149685', content: '<b style="color:#3F51B5;text-shadow: #000 0px 0px 1px">靛青色</b>' }, { value: '2201331', content: '<b style="color:#2196F3;text-shadow: #000 0px 0px 1px">蓝色</b>' }, { value: '240116', content: '<b style="color:#03A9F4;text-shadow: #000 0px 0px 1px">亮蓝色</b>' } ]; position = [ { value: 'bl', content: '左下角' }, { value: 'bc', content: '底部居中' }, { value: 'br', content: '右下角' }, { value: 'tl', content: '左上角' }, { value: 'tc', content: '顶部居中' }, { value: 'tr', content: '右上角' } ]; shadow = [ { value: '0', content: '无描边', style: '' }, { value: '1', content: '重墨', style: `text-shadow: #000 1px 0px 1px, #000 0px 1px 1px, #000 0px -1px 1px,#000 -1px 0px 1px;` }, { value: '2', content: '描边', style: `text-shadow: #000 0px 0px 1px, #000 0px 0px 1px, #000 0px 0px 1px;` }, { value: '3', content: '45°投影', style: `text-shadow: #000 1px 1px 2px, #000 0px 0px 1px;` } ]; setting: { backgroundopacity: number, color: number, fontsize: number, isclosed: boolean, scale: boolean, shadow: string, position: string }; subtitlePrefer: string; // 首选语言 isON: boolean = false; // 是否启用 caption: any; // 当前字幕 contain: any; captions: any; // 字幕集 text: any; constructor() { this.setting = GM.getValue("subtitle", { backgroundopacity: 0.5, color: 16777215, fontsize: 1, isclosed: false, scale: true, shadow: "0", position: 'bc' }); this.subtitlePrefer = GM.getValue("subtitlePrefer"); // 默认语言 } /** * 绘制字幕面板 */ initUI() { this.element.node = document.createElement("div"); this.element.node.setAttribute("class", "bilibili-player-video-btn"); this.element.node.setAttribute("id", "bilibili-player-subtitle-btn"); this.element.node.setAttribute("style", "display: block;"); this.element.span = API.addElement("span", {}, this.element.node); this.element.span.innerHTML = this.ON; this.isON = true; this.element.span.onclick = () => { if (this.isON) this.iconSwitch(); else this.iconSwitch(this.caption); } this.element.table = API.addElement("div", { id: "subtitle-setting-panel", style: "position: absolute; bottom: 28px; right: 30px; background: white; border-radius: 4px; text-align: left; padding: 13px; display: none; cursor: default;" }, this.element.node); this.language(); this.fontsize(); this.fontcolor(); this.fontshadow(); this.fontposition(); this.fontopacrity(); API.addCss(API.getModule("closedCaption.css"), "caption"); this.changeResize(); this.changePosition(); } /** * 切换字幕样式 */ changeStyle() { document.querySelector("#caption-style")?.remove(); API.addCss(`span.subtitle-item-background{opacity: ${this.setting.backgroundopacity};} span.subtitle-item-text {color:#${("000000" + this.setting.color.toString(16)).slice(-6)};} span.subtitle-item {font-size: ${this.setting.fontsize * this.resizeRate}%;line-height: 110%;} span.subtitle-item {${(<any>this.shadow)[this.setting.shadow].style}}`, "caption-style"); GM.setValue("subtitle", this.setting); } /** * 切换字幕大小 */ changeResize() { this.resizeRate = this.setting.scale ? (<any>window).player.getWidth() / 1280 * 100 : 100; this.changeStyle(); } /** * 切换字幕位置 */ changePosition() { this.contain = document.querySelector(".bilibili-player-video-subtitle>div"); this.contain.className = 'subtitle-position subtitle-position-' + (this.setting.position || 'bc'); this.contain.style = ''; GM.setValue("subtitle", this.setting); } /** * 字幕图标切换 * @param caption */ iconSwitch(caption?: any) { if (caption) { this.isON = true; this.element.span.innerHTML = this.ON; this.setCaption(caption); this.text.innerHTML = caption.lan_doc; this.element.language.children[2].disabled = false; } else { this.isON = false; this.element.span.innerHTML = this.OFF; this.setCaption(); this.text.innerHTML = "关闭"; this.element.language.children[2].disabled = true; } } /** * 字幕选择 */ language() { this.element.language = API.addElement("div", {}, this.element.table); this.element.language.innerHTML = `<div>字幕</div> <div class="bilibili-player-block-string-type bpui-component bpui-selectmenu selectmenu-mode-absolute" style="width: 100px;"> <div class="bpui-selectmenu-txt">关闭</div> <div class="bpui-selectmenu-arrow bpui-icon bpui-icon-arrow-down"></div> <ul class="bpui-selectmenu-list bpui-selectmenu-list-left" style="max-height: 180px; overflow: hidden auto; white-space: nowrap;"> <li class="bpui-selectmenu-list-row" data-value="close">关闭</li> </ul></div> <button class="bpui-button" style="padding: 0px 8px;">下载</button> <a class="bpui-button" href="https://member.bilibili.com/v2#/zimu/my-zimu/zimu-editor?cid=${API.cid}&aid=${API.aid}" target="_blank" title="" style="margin-right: 0px; height: 24px; padding: 0px 6px;">添加字幕</a>`; let list = this.element.language.children[1].children[2]; this.text = this.element.language.children[1].children[0]; // this.element.language.children[2].onclick = () => { // API.importModule("download"); // API.config.reset.dlother = 1; // 开启其他下载 // API.download(); // 拉起下载面板 // } list.children[0].onclick = () => { this.text.innerHTML = "关闭"; this.setCaption(); } this.text.innerHTML = this.caption.lan_doc; this.captions = this.captions.reverse(); this.captions.forEach((d: any) => { let temp = API.addElement("div", { class: "bpui-selectmenu-list-row", "data-value": d.lan }, list, d.lan_doc, true); temp.onclick = () => { this.text.innerHTML = d.lan_doc; this.iconSwitch(d); GM.setValue("subtitlePrefer", this.subtitlePrefer = d.lan); } }) } /** * 字幕大小 */ fontsize() { this.element.fontsize = API.addElement("div", {}, this.element.table); this.element.fontsize.innerHTML = `<div>字体大小</div> <input type="range" step="25" style="width: 70%;"> <input id="subtitle-auto-resize" type="checkbox"> <label for="subtitle-auto-resize" style="cursor: pointer;">自动缩放</label>`; this.element.fontsize.children[1].value = this.setting.fontsize == 0.6 ? 0 : this.setting.fontsize == 0.8 ? 25 : this.setting.fontsize == 1.3 ? 75 : this.setting.fontsize == 1.6 ? 100 : 50; this.element.fontsize.children[1].oninput = (e: any) => { const v = e.target.value / 25; this.setting.fontsize = v > 2 ? (v - 2) * 0.3 + 1 : v * 0.2 + 0.6; this.changeStyle(); } this.element.fontsize.children[2].checked = this.setting.scale; this.element.fontsize.children[2].onchange = (e: any) => (<any>this.changeResize)(this.setting.scale = e.target.checked); } /** * 字幕颜色 */ fontcolor() { this.element.fontcolor = API.addElement("div", {}, this.element.table); this.element.fontcolor.innerHTML = `<span>字幕颜色</span> <div class="bilibili-player-block-string-type bpui-component bpui-selectmenu selectmenu-mode-absolute" style="width: 74%;"> <div class="bpui-selectmenu-txt"><span style="color:#FFF;text-shadow: #000 0px 0px 1px">白色</span></div> <div class="bpui-selectmenu-arrow bpui-icon bpui-icon-arrow-down"></div> <ul class="bpui-selectmenu-list bpui-selectmenu-list-left" style="max-height: 120px; overflow: hidden auto; white-space: nowrap;"></ul> </div>`; this.color.forEach(d => { if (d.value == <any>this.setting.color) this.element.fontcolor.children[1].children[0].innerHTML = d.content; let temp = API.addElement("li", { class: "bpui-selectmenu-list-row", "data-value": d.value }, this.element.fontcolor.children[1].children[2]); temp.innerHTML = d.content; temp.onclick = () => { this.element.fontcolor.children[1].children[0].innerHTML = d.content; (<any>this.changeStyle)(this.setting.color = parseInt(d.value)); } }); } /** * 字幕阴影 */ fontshadow() { this.element.fontshadow = API.addElement("div", {}, this.element.table); this.element.fontshadow.innerHTML = `<span>字幕描边</span> <div class="bilibili-player-block-string-type bpui-component bpui-selectmenu selectmenu-mode-absolute" style="width: 74%;"> <div class="bpui-selectmenu-txt">无描边</div> <div class="bpui-selectmenu-arrow bpui-icon bpui-icon-arrow-down"></div> <ul class="bpui-selectmenu-list bpui-selectmenu-list-left" style="max-height: 120px; overflow: hidden auto; white-space: nowrap;"></ul> </div>`; this.shadow.forEach(d => { if (d.value == this.setting.shadow) this.element.fontshadow.children[1].children[0].innerHTML = d.content; let temp = API.addElement("li", { class: "bpui-selectmenu-list-row", "data-value": d.value }, this.element.fontshadow.children[1].children[2]); temp.innerHTML = d.content; temp.onclick = () => { this.element.fontshadow.children[1].children[0].innerHTML = d.content; (<any>this.changeStyle)(this.setting.shadow = d.value); } }) } /** * 字幕位置 */ fontposition() { this.element.fontposition = API.addElement("div", {}, this.element.table); this.element.fontposition.innerHTML = `<span>字幕位置</span> <div class="bilibili-player-block-string-type bpui-component bpui-selectmenu selectmenu-mode-absolute" style="width: 74%;"> <div class="bpui-selectmenu-txt">底部居中</div> <div class="bpui-selectmenu-arrow bpui-icon bpui-icon-arrow-down"></div> <ul class="bpui-selectmenu-list bpui-selectmenu-list-left" style="max-height: 100px; overflow: hidden auto; white-space: nowrap;"></ul> </div>`; this.position.forEach(d => { if (d.value == this.setting.position) this.element.fontposition.children[1].children[0].innerHTML = d.content; let temp = API.addElement("li", { class: "bpui-selectmenu-list-row", "data-value": d.value }, this.element.fontposition.children[1].children[2]); temp.innerHTML = d.content; temp.onclick = () => { this.element.fontposition.children[1].children[0].innerHTML = d.content; (<any>this.changePosition)(this.setting.position = d.value); } }) } /** * 字幕透明度 */ fontopacrity() { this.element.fontopacrity = API.addElement("div", {}, this.element.table); this.element.fontopacrity.innerHTML = `<div>背景不透明度</div><input type="range" style="width: 100%;">`; this.element.fontopacrity.children[1].value = this.setting.backgroundopacity * 100; this.element.fontopacrity.children[1].oninput = (e: any) => { (<any>this.changeStyle)(this.setting.backgroundopacity = e.target.value / 100); } } /** * 获取CC字幕信息 */ async getCaption(data: any) { try { API.subtitle = this.captions = data.data.subtitle.subtitles || []; let i = 0; // 指示字幕语言记录 this.captions.forEach((d: any, j: any) => { if (d.lan == this.subtitlePrefer) i = j; }) if (this.captions[i]) await this.setCaption(this.captions[i]); if (this.caption) { // 只在有字幕时添加面板 (<any>window).player.addEventListener('video_resize', (event: any) => { (<any>this.changeResize)(event); }); let anchor = <HTMLDivElement>document.querySelector(".bilibili-player-video-btn-quality"); this.initUI(); if (!document.querySelector("#bilibili-player-subtitle-btn")) anchor.insertAdjacentElement("afterend", this.element.node); } } catch (e) { debug.error("closedCaption.js", e) } } /** * 设置CC字幕 * @param caption CC字幕对象 */ async setCaption(caption?: any) { let data = { body: [] }; // 空字幕 if (caption && caption.subtitle_url) { this.data[caption.subtitle_url] = this.data[caption.subtitle_url] || await xhr({ url: caption.subtitle_url, responseType: "json", credentials: false }); data = this.data[caption.subtitle_url] || data; } (<any>window).player.updateSubtitle(data); // 投喂字幕数据给播放器 setTimeout(() => { if ((<any>window).player.getState() == "PLAYING") { // 刷新一次播放状态 (<any>window).player.pause(); (<any>window).player.play(); } }, 1000); if (caption && caption.subtitle_url) { this.caption = caption; // 记忆当前字幕 API.bofqiMessage(["载入字幕", this.captions[0].lan_doc]) } else API.bofqiMessage("关闭字幕"); } } API.closedCaption = (data: any) => { try { new ClosedCaption().getCaption(data); } catch (e) { toast.error("closedCaption.js", e) } }; })(); declare namespace API { /** * CC字幕组 */ let subtitle: any[]; /** * CC字幕 * @param data 视频信息,来自https://api.bilibili.com/x/player/v2 */ function closedCaption(data: any): void; }
the_stack