text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import * as React from 'react'; import { shallow } from 'enzyme'; import { StyleSheet } from 'react-native'; import * as TestRenderer from 'react-test-renderer'; import { formatHTML, key } from '../../react-form-with-constraints/src/formatHTML'; import { input_username_valid, input_username_valueMissing } from '../../react-form-with-constraints/src/InputElementMock'; import { FieldFeedback, FieldFeedbacks, FieldFeedbackWhenValid, FormWithConstraints, TextInput } from '.'; import { SignUp } from './SignUp'; // FIXME // Cannot write "expect(fields).toEqual([{... element: signUp.username ...}])" after calling form.validateFields() or form.validateFields('username') // deepForEach() inside normalizeInputs() does not return the real TextInput // and Node.js crashes: "FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory" // However it works fine with form.validateFields(signUp.username) because we don't call deepForEach() const expectTextInput = expect.anything(); // Taken and adapted from FormWithConstraints.test.tsx describe('FormWithConstraints', () => { describe('validate', () => { describe('validateFields()', () => { test('inputs', async () => { const wrapper = TestRenderer.create(<SignUp />); const signUp = (wrapper.getInstance() as any) as SignUp; const emitValidateFieldEventSpy = jest.spyOn(signUp.form!, 'emitValidateFieldEvent'); signUp.setState({ username: 'john' }); signUp.setState({ password: '123456' }); signUp.setState({ passwordConfirm: '12345' }); const fields = await signUp.form!.validateFields(signUp.username!, signUp.passwordConfirm!); expect(fields).toEqual([ { name: 'username', element: signUp.username, validations: [ { key: '0.0', type: 'error', show: false }, { key: '0.1', type: 'error', show: false }, { key: '0.3', type: 'error', show: true }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: signUp.passwordConfirm, validations: [ { key: '2.0', type: 'error', show: true }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(2); expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [{ name: 'username', value: 'john' }], [{ name: 'passwordConfirm', value: '12345' }] ]); wrapper.unmount(); }); test('field names', async () => { const wrapper = TestRenderer.create(<SignUp />); const signUp = (wrapper.getInstance() as any) as SignUp; const emitValidateFieldEventSpy = jest.spyOn(signUp.form!, 'emitValidateFieldEvent'); signUp.setState({ username: 'john' }); signUp.setState({ password: '123456' }); signUp.setState({ passwordConfirm: '12345' }); const fields = await signUp.form!.validateFields('username', 'passwordConfirm'); expect(fields).toEqual([ { name: 'username', element: expectTextInput, validations: [ { key: '0.0', type: 'error', show: false }, { key: '0.1', type: 'error', show: false }, { key: '0.3', type: 'error', show: true }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: expectTextInput, validations: [ { key: '2.0', type: 'error', show: true }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(2); expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [{ name: 'username', value: 'john' }], [{ name: 'passwordConfirm', value: '12345' }] ]); wrapper.unmount(); }); test('inputs + field names', async () => { const wrapper = TestRenderer.create(<SignUp />); const signUp = (wrapper.getInstance() as any) as SignUp; const emitValidateFieldEventSpy = jest.spyOn(signUp.form!, 'emitValidateFieldEvent'); signUp.setState({ username: 'john' }); signUp.setState({ password: '123456' }); signUp.setState({ passwordConfirm: '12345' }); const fields = await signUp.form!.validateFields(signUp.username!, 'passwordConfirm'); expect(fields).toEqual([ { name: 'username', element: signUp.username, validations: [ { key: '0.0', type: 'error', show: false }, { key: '0.1', type: 'error', show: false }, { key: '0.3', type: 'error', show: true }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: expectTextInput, validations: [ { key: '2.0', type: 'error', show: true }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(2); expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [{ name: 'username', value: 'john' }], [{ name: 'passwordConfirm', value: '12345' }] ]); wrapper.unmount(); }); test('without arguments', async () => { const wrapper = TestRenderer.create(<SignUp />); const signUp = (wrapper.getInstance() as any) as SignUp; const emitValidateFieldEventSpy = jest.spyOn(signUp.form!, 'emitValidateFieldEvent'); signUp.setState({ username: 'john' }); signUp.setState({ password: '123456' }); signUp.setState({ passwordConfirm: '12345' }); const fields = await signUp.form!.validateFields(); expect(fields).toEqual([ { name: 'username', element: expectTextInput, validations: [ { key: '0.0', type: 'error', show: false }, { key: '0.1', type: 'error', show: false }, { key: '0.3', type: 'error', show: true }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'password', element: expectTextInput, validations: [ { key: '1.0', type: 'error', show: false }, { key: '1.1', type: 'error', show: false }, { key: '1.2', type: 'warning', show: false }, { key: '1.3', type: 'warning', show: true }, { key: '1.4', type: 'warning', show: true }, { key: '1.5', type: 'warning', show: true }, { key: '1.6', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: expectTextInput, validations: [ { key: '2.0', type: 'error', show: true }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(3); expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [{ name: 'username', value: 'john' }], [{ name: 'password', value: '123456' }], [{ name: 'passwordConfirm', value: '12345' }] ]); wrapper.unmount(); }); test('change inputs', async () => { const wrapper = TestRenderer.create(<SignUp />); const signUp = (wrapper.getInstance() as any) as SignUp; const emitValidateFieldEventSpy = jest.spyOn(signUp.form!, 'emitValidateFieldEvent'); signUp.setState({ username: '' }); signUp.setState({ password: '' }); signUp.setState({ passwordConfirm: '' }); let fields = await signUp.form!.validateFields(); expect(fields).toEqual([ { name: 'username', element: expectTextInput, validations: [ { key: '0.0', type: 'error', show: true }, { key: '0.1', type: 'error', show: undefined }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'password', element: expectTextInput, validations: [ { key: '1.0', type: 'error', show: true }, { key: '1.1', type: 'error', show: undefined }, { key: '1.2', type: 'warning', show: undefined }, { key: '1.3', type: 'warning', show: undefined }, { key: '1.4', type: 'warning', show: undefined }, { key: '1.5', type: 'warning', show: undefined }, { key: '1.6', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: expectTextInput, validations: [ { key: '2.0', type: 'error', show: false }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(3); expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [{ name: 'username', value: '' }], [{ name: 'password', value: '' }], [{ name: 'passwordConfirm', value: '' }] ]); emitValidateFieldEventSpy.mockClear(); signUp.setState({ username: 'john' }); signUp.setState({ password: '123456' }); signUp.setState({ passwordConfirm: '12345' }); fields = await signUp.form!.validateFields(); expect(fields).toEqual([ { name: 'username', element: expectTextInput, validations: [ { key: '0.0', type: 'error', show: false }, { key: '0.1', type: 'error', show: false }, { key: '0.3', type: 'error', show: true }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'password', element: expectTextInput, validations: [ { key: '1.0', type: 'error', show: false }, { key: '1.1', type: 'error', show: false }, { key: '1.2', type: 'warning', show: false }, { key: '1.3', type: 'warning', show: true }, { key: '1.4', type: 'warning', show: true }, { key: '1.5', type: 'warning', show: true }, { key: '1.6', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: expectTextInput, validations: [ { key: '2.0', type: 'error', show: true }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(3); expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [{ name: 'username', value: 'john' }], [{ name: 'password', value: '123456' }], [{ name: 'passwordConfirm', value: '12345' }] ]); wrapper.unmount(); }); }); describe('validateFieldsWithoutFeedback()', () => { test('without arguments', async () => { const wrapper = TestRenderer.create(<SignUp />); const signUp = (wrapper.getInstance() as any) as SignUp; const emitValidateFieldEventSpy = jest.spyOn(signUp.form!, 'emitValidateFieldEvent'); signUp.setState({ username: 'john' }); signUp.setState({ password: '123456' }); signUp.setState({ passwordConfirm: '12345' }); const fields1 = await signUp.form!.validateFieldsWithoutFeedback(); expect(fields1).toEqual([ { name: 'username', element: expectTextInput, validations: [ { key: '0.0', type: 'error', show: false }, { key: '0.1', type: 'error', show: false }, { key: '0.3', type: 'error', show: true }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'password', element: expectTextInput, validations: [ { key: '1.0', type: 'error', show: false }, { key: '1.1', type: 'error', show: false }, { key: '1.2', type: 'warning', show: false }, { key: '1.3', type: 'warning', show: true }, { key: '1.4', type: 'warning', show: true }, { key: '1.5', type: 'warning', show: true }, { key: '1.6', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: expectTextInput, validations: [ { key: '2.0', type: 'error', show: true }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(3); expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [{ name: 'username', value: 'john' }], [{ name: 'password', value: '123456' }], [{ name: 'passwordConfirm', value: '12345' }] ]); // Fields are already dirty so calling validateFieldsWithoutFeedback() again won't do anything emitValidateFieldEventSpy.mockClear(); signUp.setState({ username: 'jimmy' }); signUp.setState({ password: '12345' }); signUp.setState({ passwordConfirm: '12345' }); const fields2 = await signUp.form!.validateFieldsWithoutFeedback(); expect(fields2).toEqual(fields1); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(0); expect(emitValidateFieldEventSpy.mock.calls).toEqual([]); wrapper.unmount(); }); }); test('validateForm()', async () => { const wrapper = TestRenderer.create(<SignUp />); const signUp = (wrapper.getInstance() as any) as SignUp; const validateFieldsWithoutFeedbackSpy = jest.spyOn( signUp.form!, 'validateFieldsWithoutFeedback' ); await signUp.form!.validateForm(); expect(validateFieldsWithoutFeedbackSpy).toHaveBeenCalledTimes(1); expect(validateFieldsWithoutFeedbackSpy.mock.calls).toEqual([[]]); wrapper.unmount(); }); describe('normalizeInputs', () => { test('Multiple elements matching', async () => { const wrapper = TestRenderer.create( <FormWithConstraints> <TextInput name="username" /> <FieldFeedbacks for="username" /> <TextInput secureTextEntry name="password" /> <TextInput secureTextEntry name="password" /> <TextInput secureTextEntry name="password" /> <FieldFeedbacks for="password" /> </FormWithConstraints> ); const form = (wrapper.getInstance() as any) as FormWithConstraints; // [async/await toThrow is not working](https://github.com/facebook/jest/issues/1700) expect(await form.validateFields('username')).toEqual([ { name: 'username', element: expectTextInput, validations: [] } ]); await expect(form.validateFields()).rejects.toThrow( `Multiple elements matching '[name="password"]' inside the form` ); await expect(form.validateFields('password')).rejects.toThrow( `Multiple elements matching '[name="password"]' inside the form` ); wrapper.unmount(); }); test('Could not find field', async () => { const wrapper = TestRenderer.create( <FormWithConstraints> <TextInput name="username" /> </FormWithConstraints> ); const form = (wrapper.getInstance() as any) as FormWithConstraints; expect(await form.validateFields()).toEqual([]); // Ignore input without FieldFeedbacks expect(await form.validateFields('username')).toEqual([]); // Ignore input without FieldFeedbacks await expect(form.validateFields('unknown')).rejects.toThrow( `Could not find field '[name="unknown"]' inside the form` ); wrapper.unmount(); }); test('Could not find field - child with props undefined', async () => { const wrapper = TestRenderer.create( <FormWithConstraints>ChildWithPropsUndefined</FormWithConstraints> ); const form = (wrapper.getInstance() as any) as FormWithConstraints; expect(await form.validateFields()).toEqual([]); await expect(form.validateFields('unknown')).rejects.toThrow( `Could not find field '[name="unknown"]' inside the form` ); wrapper.unmount(); }); }); }); describe('Async', () => { test('then', async () => { const wrapper = TestRenderer.create(<SignUp />); const signUp = (wrapper.getInstance() as any) as SignUp; const emitValidateFieldEventSpy = jest.spyOn(signUp.form!, 'emitValidateFieldEvent'); signUp.setState({ username: 'jimmy' }); signUp.setState({ password: '12345' }); signUp.setState({ passwordConfirm: '12345' }); const fields = await signUp.form!.validateFields(); expect(fields).toEqual([ { name: 'username', element: expectTextInput, validations: [ { key: '0.0', type: 'error', show: false }, { key: '0.1', type: 'error', show: false }, { key: '0.3', type: 'info', show: true }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'password', element: expectTextInput, validations: [ { key: '1.0', type: 'error', show: false }, { key: '1.1', type: 'error', show: false }, { key: '1.2', type: 'warning', show: false }, { key: '1.3', type: 'warning', show: true }, { key: '1.4', type: 'warning', show: true }, { key: '1.5', type: 'warning', show: true }, { key: '1.6', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: expectTextInput, validations: [ { key: '2.0', type: 'error', show: false }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(3); expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [{ name: 'username', value: 'jimmy' }], [{ name: 'password', value: '12345' }], [{ name: 'passwordConfirm', value: '12345' }] ]); wrapper.unmount(); }); test('catch', async () => { const wrapper = TestRenderer.create(<SignUp />); const signUp = (wrapper.getInstance() as any) as SignUp; const emitValidateFieldEventSpy = jest.spyOn(signUp.form!, 'emitValidateFieldEvent'); signUp.setState({ username: 'error' }); signUp.setState({ password: '123456' }); signUp.setState({ passwordConfirm: '12345' }); const fields = await signUp.form!.validateFields(); expect(fields).toEqual([ { name: 'username', element: expectTextInput, validations: [ { key: '0.0', type: 'error', show: false }, { key: '0.1', type: 'error', show: false }, { key: '0.3', type: 'error', show: true }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'password', element: expectTextInput, validations: [ { key: '1.0', type: 'error', show: false }, { key: '1.1', type: 'error', show: false }, { key: '1.2', type: 'warning', show: false }, { key: '1.3', type: 'warning', show: true }, { key: '1.4', type: 'warning', show: true }, { key: '1.5', type: 'warning', show: true }, { key: '1.6', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: expectTextInput, validations: [ { key: '2.0', type: 'error', show: true }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); expect(emitValidateFieldEventSpy).toHaveBeenCalledTimes(3); expect(emitValidateFieldEventSpy.mock.calls).toEqual([ [{ name: 'username', value: 'error' }], [{ name: 'password', value: '123456' }], [{ name: 'passwordConfirm', value: '12345' }] ]); wrapper.unmount(); }); }); describe('resetFields()', () => { test('inputs', async () => { const wrapper = TestRenderer.create(<SignUp />); const signUp = (wrapper.getInstance() as any) as SignUp; signUp.setState({ username: 'john' }); signUp.setState({ password: '123456' }); signUp.setState({ passwordConfirm: '12345' }); let fields = await signUp.form!.validateFields(signUp.username!, signUp.passwordConfirm!); expect(fields).toEqual([ { name: 'username', element: signUp.username, validations: [ { key: '0.0', type: 'error', show: false }, { key: '0.1', type: 'error', show: false }, { key: '0.3', type: 'error', show: true }, { key: '0.2', type: 'whenValid', show: undefined } ] }, { name: 'passwordConfirm', element: signUp.passwordConfirm, validations: [ { key: '2.0', type: 'error', show: true }, { key: '2.1', type: 'whenValid', show: undefined } ] } ]); fields = signUp.form!.resetFields(signUp.username!, signUp.passwordConfirm!); expect(fields).toEqual([ { name: 'username', element: signUp.username, validations: [] }, { name: 'passwordConfirm', element: signUp.passwordConfirm, validations: [] } ]); wrapper.unmount(); }); }); }); describe('FieldFeedbacks', () => { let form_username: FormWithConstraints; beforeEach(() => { form_username = new FormWithConstraints({}); }); test('render()', () => { const wrapper = shallow( <FieldFeedbacks for="username"> <FieldFeedback when={value => value.length === 0}>Cannot be empty</FieldFeedback> </FieldFeedbacks>, { context: { form: form_username } } ); expect(formatHTML(wrapper.debug(), ' ')).toEqual(`\ <FieldFeedback when={[Function: when]}> Cannot be empty </FieldFeedback>`); }); }); // Taken and adapted from FieldFeedback.test.tsx describe('FieldFeedback', () => { let form_username: FormWithConstraints; let fieldFeedbacks_username: FieldFeedbacks; beforeEach(() => { form_username = new FormWithConstraints({}); fieldFeedbacks_username = new FieldFeedbacks( { for: 'username', stop: 'no' }, { form: form_username as any } ); fieldFeedbacks_username.componentDidMount(); // Needed because of fieldsStore.addField() inside componentDidMount() }); describe('render()', () => { test('error', async () => { const wrapper = shallow( <FieldFeedback when={value => value.length === 0} error> Cannot be empty </FieldFeedback>, { context: { form: form_username, fieldFeedbacks: fieldFeedbacks_username } } ); const validations = await fieldFeedbacks_username.emitValidateFieldEvent( input_username_valueMissing ); expect(validations).toEqual([{ key: '0.0', type: 'error', show: true }]); wrapper.update(); expect(formatHTML(wrapper.debug(), ' ')).toEqual(`\ <Text ${key}="0.0" style={[undefined]}> Cannot be empty </Text>`); }); // eslint-disable-next-line jest/expect-expect test('warning', async () => { // }); // eslint-disable-next-line jest/expect-expect test('info', async () => { // }); test('no error', async () => { const wrapper = shallow( <FieldFeedback when={value => value.length === 0}>Cannot be empty</FieldFeedback>, { context: { form: form_username, fieldFeedbacks: fieldFeedbacks_username } } ); const validations = await fieldFeedbacks_username.emitValidateFieldEvent( input_username_valid ); expect(validations).toEqual([{ key: '0.0', type: 'error', show: false }]); wrapper.update(); expect(wrapper.debug()).toEqual(''); }); test('without children', async () => { const wrapper = shallow(<FieldFeedback when={value => value.length === 0} />, { context: { form: form_username, fieldFeedbacks: fieldFeedbacks_username } }); const validations = await fieldFeedbacks_username.emitValidateFieldEvent( input_username_valueMissing ); expect(validations).toEqual([{ key: '0.0', type: 'error', show: true }]); wrapper.update(); expect(wrapper.debug()).toEqual(`<Text ${key}="0.0" style={[undefined]} />`); }); // eslint-disable-next-line jest/expect-expect test('with already existing class', async () => { // }); test('with div props', async () => { const wrapper = shallow( <FieldFeedback when={value => value.length === 0} style={{ color: 'yellow' }}> Cannot be empty </FieldFeedback>, { context: { form: form_username, fieldFeedbacks: fieldFeedbacks_username } } ); const validations = await fieldFeedbacks_username.emitValidateFieldEvent( input_username_valueMissing ); expect(validations).toEqual([{ key: '0.0', type: 'error', show: true }]); wrapper.update(); expect(formatHTML(wrapper.debug(), ' ')).toEqual(`\ <Text ${key}="0.0" style={{...}}> Cannot be empty </Text>`); expect(wrapper.props().style).toEqual({ color: 'yellow' }); }); test('with theme', async () => { const fieldFeedbackTheme = StyleSheet.create({ error: { color: 'red' }, warning: { color: 'orange' }, info: { color: 'blue' }, whenValid: { color: 'green' } }); const form = new FormWithConstraints({}); const fieldFeedbacks = new FieldFeedbacks( { for: 'username', stop: 'no' }, { form: form as any } ); fieldFeedbacks.componentDidMount(); // Needed because of fieldsStore.addField() inside componentDidMount() const wrapper = shallow( <FieldFeedback when={value => value.length === 0} theme={fieldFeedbackTheme}> Cannot be empty </FieldFeedback>, { context: { form, fieldFeedbacks } } ); const validations = await fieldFeedbacks.emitValidateFieldEvent(input_username_valueMissing); expect(validations).toEqual([{ key: '0.0', type: 'error', show: true }]); wrapper.update(); expect(formatHTML(wrapper.debug(), ' ')).toEqual(`\ <Text ${key}="0.0" style={{...}}> Cannot be empty </Text>`); expect(wrapper.props().style).toEqual({ color: 'red' }); }); // eslint-disable-next-line jest/expect-expect test('when="valid"', async () => { // Cannot be implemented properly }); }); }); describe('FieldFeedbackWhenValid', () => { let form_username: FormWithConstraints; let fieldFeedbacks_username: FieldFeedbacks; beforeEach(() => { form_username = new FormWithConstraints({}); fieldFeedbacks_username = new FieldFeedbacks( { for: 'username', stop: 'no' }, { form: form_username as any } ); //fieldFeedbacks_username.componentWillMount(); // Needed because of fieldsStore.addField() inside componentWillMount() }); test('render()', () => { let wrapper = shallow(<FieldFeedbackWhenValid>Looks good!</FieldFeedbackWhenValid>, { context: { form: form_username, fieldFeedbacks: fieldFeedbacks_username } }); expect(wrapper.html()).toEqual(null); wrapper.setState({ fieldIsValid: undefined }); expect(wrapper.html()).toEqual(null); wrapper.setState({ fieldIsValid: true }); expect(formatHTML(wrapper.debug(), ' ')).toEqual(`\ <Text> Looks good! </Text>`); wrapper.setState({ fieldIsValid: false }); expect(wrapper.html()).toEqual(null); // With div props wrapper = shallow( <FieldFeedbackWhenValid style={{ color: 'green' }}>Looks good!</FieldFeedbackWhenValid>, { context: { form: form_username, fieldFeedbacks: fieldFeedbacks_username } } ); wrapper.setState({ fieldIsValid: true }); expect(formatHTML(wrapper.debug(), ' ')).toEqual(`\ <Text style={{...}}> Looks good! </Text>`); }); });
the_stack
import { SplineTrailRenderer } from './SplineTrailRenderer'; //@ts-ignore let gfx = cc.gfx; let vfmtSplineTrail = new gfx.VertexFormat([ { name: 'a_position', type: gfx.ATTR_TYPE_FLOAT32, num: 2 }, { name: 'a_width', type: gfx.ATTR_TYPE_FLOAT32, num: 1 }, // 旁侧相对于中心线的距离,范围(0, segmentWidth) { name: 'a_dist', type: gfx.ATTR_TYPE_FLOAT32, num: 1 }, // 距离线段起始点的距离(累积线段长度) { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_UINT8, num: 4, normalize: true }, // 4个uint8 ]); export class SplineTrailRendererAssembler extends cc.Assembler { public useWorldPos: boolean = true; // 表示从component里获取的坐标是世界坐标 protected _worldDatas: any = {}; protected _renderNode: cc.Node = null; protected _floatsPerVert: number = 2; // update by vfmt protected _renderData: cc.RenderData = null; protected _splineTrailComp: SplineTrailRenderer = null; protected _flexBuffer: cc.FlexBuffer = null; init(comp: SplineTrailRenderer) { super.init(comp); this._splineTrailComp = comp; this._worldDatas = {}; this._renderNode = null; this._floatsPerVert = this.getVfmt()._bytes >> 2; let data = this._renderData = new cc.RenderData(); data.init(this); this.initData(); // Note: 如果不是用quad渲染,对应的vdata, idata大小不一样 // this._flexBuffer = data.createFlexData(0, initVertexCount * 4, initVertexCount * 6, this.getVfmt()); // todo: 初始化idata,quad模式下idata分布规则是固定的 } initData() { // 先创建初始化一个固定大小的buffer let initQuadCount = 50; let data = this._renderData; data.createFlexData(0, initQuadCount * 4, initQuadCount * 6, this.getVfmt()); this._flexBuffer = data._flexBuffer; } updateRenderData(comp: SplineTrailRenderer) { if (comp._vertsDirty) { // this.updateVerts(comp); // todo: fetch vertex data let vertices = comp._vertices; let vertexCount = vertices.length; let indicesCount = vertexCount / 4 * 6; let flexBuffer = this._flexBuffer; flexBuffer.reserve(vertexCount, indicesCount); flexBuffer.used(vertexCount, indicesCount); this.updateVerts(comp); // todo: optimize idata update, do no update old part this.initQuadIndices(flexBuffer.iData, indicesCount); comp._vertsDirty = false; } } initQuadIndices(indices, len) { let count = len / 6; for (let i = 0, idx = 0; i < count; i++) { let vertextID = i * 4; indices[idx++] = vertextID; indices[idx++] = vertextID+1; indices[idx++] = vertextID+2; indices[idx++] = vertextID+1; indices[idx++] = vertextID+3; indices[idx++] = vertextID+2; } } updateVerts(comp: SplineTrailRenderer) { let floatsPerVert = this._floatsPerVert; let vertices = comp._vertices; let sideDist = comp._sideDist; let dist = comp._dist; let vertexCount = vertices.length; let vData = this._flexBuffer.vData; let baseIndex: number = 0; for (let i=0, n=vertexCount; i<n; ++i) { baseIndex = i * floatsPerVert; vData[baseIndex++] = vertices.Get(i).x; vData[baseIndex++] = vertices.Get(i).y; vData[baseIndex++] = sideDist[i]; vData[baseIndex++] = dist[i]; // vData[baseIndex++] = color[i]; } this.updateWorldVerts(comp); } updateWorldVerts(comp) { if (CC_NATIVERENDERER) { // Native模式 if (this.useWorldPos) { this.updateWorldVertsNative(comp); } } else { // WegGL模式 // 如果vData表示的是世界坐标,需要转换成节点本地坐标 if (!this.useWorldPos) { this.updateWorldVertsWebGL(comp); } } } updateWorldVertsWebGL(comp) { let vData = this._flexBuffer.vData; let vertexCount = this._flexBuffer.usedVertices; let matrix = comp.node._worldMatrix; let matrixm = matrix.m, a = matrixm[0], b = matrixm[1], c = matrixm[4], d = matrixm[5], tx = matrixm[12], ty = matrixm[13]; // let vl = local[0], vr = local[2], // vb = local[1], vt = local[3]; /* m00 = 1, m01 = 0, m02 = 0, m03 = 0, m04 = 0, m05 = 1, m06 = 0, m07 = 0, m08 = 0, m09 = 0, m10 = 1, m11 = 0, m12 = 0, m13 = 0, m14 = 0, m15 = 1 */ // [a,b,c,d] = _worldMatrix[1,2,4,5] == [1,0,0,1] // _worldMatrix[12,13]是xy的平移量 // 即世界矩阵的左上角2x2是单元矩阵,说明在2D场景内没有出现旋转或者缩放 let justTranslate = a === 1 && b === 0 && c === 0 && d === 1; justTranslate = true; // todo: 目前强行认为没有旋转缩放 let floatsPerVert = this._floatsPerVert; if (justTranslate) { let baseIndex: number = 0; for (let i=0, n=vertexCount; i<n; ++i) { baseIndex = i * floatsPerVert; vData[baseIndex] += tx; vData[baseIndex+1] += ty; baseIndex += floatsPerVert; } } else { // // 4对xy分别乘以 [2,2]仿射矩阵,然后+平移量 // let al = a * vl, ar = a * vr, // bl = b * vl, br = b * vr, // cb = c * vb, ct = c * vt, // db = d * vb, dt = d * vt; // // left bottom // // newx = vl * a + vb * c + tx // // newy = vl * b + vb * d + ty // verts[index] = al + cb + tx; // verts[index+1] = bl + db + ty; // index += floatsPerVert; // // right bottom // verts[index] = ar + cb + tx; // verts[index+1] = br + db + ty; // index += floatsPerVert; // // left top // verts[index] = al + ct + tx; // verts[index+1] = bl + dt + ty; // index += floatsPerVert; // // right top // verts[index] = ar + ct + tx; // verts[index+1] = br + dt + ty; } } // native场景下使用的updateWorldVerts // copy from \jsb-adapter-master\engine\assemblers\assembler-2d.js protected _tmpVec2 = cc.v2(0, 0); updateWorldVertsNative(comp: SplineTrailRenderer) { // 将vdata做一个偏移,偏移量等于所在节点相对于世界坐标原点的偏移 // 因为Native里的vdata以节点anchor为原点 // TODO: 考虑旋转缩放 let baseIndex: number = 0; let vData = this._flexBuffer.vData; let vertexCount = this._flexBuffer.usedVertices; let floatsPerVert = this._floatsPerVert; let tmpVec2 = this._tmpVec2; tmpVec2.x = tmpVec2.y = 0; comp.node.convertToWorldSpaceAR(tmpVec2, tmpVec2); let tx = -tmpVec2.x; let ty = -tmpVec2.y; for (let i=0, n=vertexCount; i<n; ++i) { baseIndex = i * floatsPerVert; vData[baseIndex] += tx; vData[baseIndex+1] += ty; baseIndex += floatsPerVert; } } updateColor(comp, color) { // do nothing let k = 0; } // not necessary // get verticesFloats(): number { // return this._splineTrailComp._vertices.length * vfmtSplineTrail._bytes / 4; // } updateUVs(comp) { // do nothing let k = 0; } getVfmt() { return vfmtSplineTrail; } getBuffer() { //@ts-ignore return cc.renderer._handle.getBuffer("mesh", this.getVfmt()); } setRenderNode(node) { this._renderNode = node; } // 将准备好的顶点数据填充进 VertexBuffer 和 IndiceBuffer fillBuffers(comp, renderer) { let flexBuffer = this._flexBuffer; if (!flexBuffer?.usedVertices) return; let renderData = this._renderData; let vData = renderData.vDatas[0]; let iData = renderData.iDatas[0]; let buffer = this.getBuffer(/*renderer*/); let offsetInfo = buffer.request(flexBuffer.usedVertices, flexBuffer.usedIndices); // if (!this.useWorldPos) { // // vData里不是世界坐标,需要做一次转换 // if (renderer.worldMatDirty || !this._worldDatas[0]) { // // 从本地坐标更新成世界坐标 // this._updateWorldVertices(0, flexBuffer.usedVertices, vData, this.getVfmt(), comp.node._worldMatrix); // vData = this._worldDatas[0]; // } // } // fill vertices let vertexOffset = offsetInfo.byteOffset >> 2, vbuf = buffer._vData; if (vData.length + vertexOffset > vbuf.length) { vbuf.set(vData.subarray(0, vbuf.length - vertexOffset), vertexOffset); } else { vbuf.set(vData, vertexOffset); } // fill indices // 合批的情况下indiceOffset > 0 let ibuf = buffer._iData, indiceOffset = offsetInfo.indiceOffset, vertexId = offsetInfo.vertexOffset; // vertexId是已经在buffer里的顶点数,也是当前顶点序号的基数 for (let i = 0, l = iData.length; i < l; i++) { ibuf[indiceOffset++] = vertexId + iData[i]; } } protected _tmpVec3 = new cc.Vec3(); _updateWorldVertices(dataIndex, vertexCount, local, vtxFormat, wolrdMatrix) { let world = this._worldDatas[dataIndex]; if (!world) { world = this._worldDatas[dataIndex] = new Float32Array(local.length); // world.set(local); // not necessary } let floatCount = vtxFormat._bytes / 4; let elements = vtxFormat._elements; let tmpVec3 = this._tmpVec3; for (let i = 0, n = elements.length; i < n; i++) { let element = elements[i]; let attrOffset = element.offset / 4; if (element.name === gfx.ATTR_POSITION || element.name === gfx.ATTR_NORMAL) { let transformMat4 = element.name === gfx.ATTR_NORMAL ? cc.Vec3.transformMat4Normal : cc.Vec3.transformMat4; for (let j = 0; j < vertexCount; j++) { let offset = j * floatCount + attrOffset; tmpVec3.x = local[offset]; tmpVec3.y = local[offset + 1]; tmpVec3.z = local[offset + 2]; transformMat4(tmpVec3, tmpVec3, wolrdMatrix); world[offset] = tmpVec3.x; world[offset + 1] = tmpVec3.y; world[offset + 2] = tmpVec3.z; } } } } _drawDebugDatas(comp, renderer, name) { let debugDatas = comp._debugDatas[name]; if (!debugDatas) return; for (let i = 0; i < debugDatas.length; i++) { let debugData = debugDatas[i]; if (!debugData) continue; let material = debugData.material; renderer.material = material; renderer._flushIA(debugData.ia); } } } cc.Assembler.register(SplineTrailRenderer, SplineTrailRendererAssembler);
the_stack
import * as ts from 'typescript'; import { Dictionary } from './Dictionary'; import { warn, debug, docletDebugInfo } from './logger'; import { assertNever } from './assert_never'; import { isDocumentedDoclet, hasParamsDoclet, isClassDoclet, isClassDeclarationDoclet, isConstructorDoclet, isNamespaceDoclet, isEnumDoclet, isDefaultExportDoclet, isNamedExportDoclet, isExportsAssignmentDoclet } from './doclet_utils'; import { createClass, createClassMember, createClassMethod, createConstructor, createEnum, createFunction, createInterface, createInterfaceMember, createInterfaceMethod, createModule, createExportDefault, createNamespace, createNamespaceMember, createTypedef, } from './create_helpers'; import { generateTree, StringTreeNode, resolveTypeParameters } from './type_resolve_helpers'; export interface IDocletTreeNode { doclet: TDoclet; children: IDocletTreeNode[]; isNested?: boolean; /** * Helper flag for named export identification. */ isNamedExport?: boolean; /** * Flag set by the 'exported' generation strategy when Emitter._markExported() is called. */ isExported?: boolean; /** * Makes the node be exported with another name for export. * Prevails on `@ignore` tags when set. */ exportName?: string; } function shouldMoveOutOfClass(doclet: TDoclet): boolean { return isClassDoclet(doclet) || isNamespaceDoclet(doclet) || isEnumDoclet(doclet) || doclet.kind === 'typedef'; } export class Emitter { results: ts.Node[] = []; private _treeRoots: IDocletTreeNode[] = []; private _treeNodes: Dictionary<IDocletTreeNode> = {}; // resolutionNeeded: IResolutionMap; constructor(public readonly options: ITemplateConfig) { } parse(docs?: TAnyDoclet[]) { debug(`Emitter.parse()`); this.results = []; this._treeRoots = []; this._treeNodes = {}; if (!docs) return; this._createTreeNodes(docs); this._buildTree(docs); if (this.options.generationStrategy === 'exported') this._markExported(); this._parseTree(); } emit() { debug(`----------------------------------------------------------------`); debug(`Emitter.emit()`); const resultFile = ts.createSourceFile( 'types.d.ts', '', ts.ScriptTarget.Latest, false, ts.ScriptKind.TS); const printer = ts.createPrinter({ removeComments: false, newLine: ts.NewLineKind.LineFeed, }); let out2 = ''; for (let i = 0; i < this.results.length; ++i) { out2 += printer.printNode(ts.EmitHint.Unspecified, this.results[i], resultFile); out2 += '\n\n'; } return out2; } private _createTreeNodes(docs: TAnyDoclet[]) { debug(`----------------------------------------------------------------`); debug(`Emitter._createTreeNodes()`); for (let i = 0; i < docs.length; ++i) { const doclet = docs[i]; if (doclet.kind === 'package') { debug(`Emitter._createTreeNodes(): skipping ${docletDebugInfo(doclet)} (package)`); continue; } const node = this._treeNodes[doclet.longname]; if (!node) { debug(`Emitter._createTreeNodes(): adding ${docletDebugInfo(doclet)} to this._treeNodes`); this._treeNodes[doclet.longname] = { doclet, children: [] }; } else { debug(`Emitter._createTreeNodes(): skipping ${docletDebugInfo(doclet)} (doclet name already known)`); } } } private _buildTree(docs: TAnyDoclet[]) { debug(`----------------------------------------------------------------`); debug(`Emitter._buildTree()`); for (let i = 0; i < docs.length; ++i) { const doclet = docs[i]; this._buildTreeNode(docs, doclet); } } private _buildTreeNode(docs: TAnyDoclet[], doclet: TAnyDoclet) { if (doclet.kind === 'package') { debug(`Emitter._buildTreeNode(): skipping ${docletDebugInfo(doclet)} (package)`); return; } if (isClassDoclet(doclet) && isConstructorDoclet(doclet)) { // If this doclet is a constructor, do not watch the 'memberof' attribute: // - it usually has the same value as the owner class's declaration, // - it does not point to the owner class itself. // Use the 'longname' which equals to the owner class's 'longname'. const ownerClass = this._getNodeFromLongname(doclet.longname, (node: IDocletTreeNode) => isClassDeclarationDoclet(node.doclet)); if (!ownerClass) { warn(`Failed to find owner class of constructor '${doclet.longname}'.`, doclet); return; } // jsdoc@3.6.3 may generate multiple doclets for constructors. // Watch in the class children whether a constructor is already registered. if (this._checkDuplicateChild(doclet, ownerClass, (child: IDocletTreeNode) => isConstructorDoclet(child.doclet))) return; debug(`Emitter._buildTreeNode(): adding constructor ${docletDebugInfo(doclet)} to class declaration ${docletDebugInfo(ownerClass.doclet)}`); ownerClass.children.push({ doclet: doclet, children: [] }); // When this constructor is not documented, the 'params' field might not be set. // Inherit from the owner class when possible, in order to ensure constructor generation with the appropriate parameter list. if (!hasParamsDoclet(doclet) && isClassDoclet(ownerClass.doclet) && hasParamsDoclet(ownerClass.doclet)) { debug(`Emitter._buildTreeNode(): inheriting 'params' from owner class ${docletDebugInfo(ownerClass.doclet)} for undocumented constructor ${docletDebugInfo(doclet)}`); doclet.params = ownerClass.doclet.params; } // Done with this class/constructor. return; } let interfaceMerge: IDocletTreeNode | null = null; // Generate an interface of the same name as the class to perform // a namespace merge. if (doclet.kind === 'class') { const impls = doclet.implements || []; const mixes = doclet.mixes || []; const extras = impls.concat(mixes); if (extras.length) { const longname = this._getInterfaceKey(doclet.longname); interfaceMerge = this._treeNodes[longname] = { doclet: { kind: 'interface', name: doclet.name, scope: doclet.scope, longname: longname, augments: extras, memberof: doclet.memberof, }, children: [], }; debug(`Emitter._buildTreeNode(): merge interface ${docletDebugInfo(interfaceMerge.doclet)} created for ${docletDebugInfo(doclet)}`); } } let namespaceMerge: IDocletTreeNode | null = null; // Generate an namespace of the same name as the interface/mixin to perform // a namespace merge containing any static children (ex members and functions). if (doclet.kind === 'interface' || doclet.kind === 'mixin') { const staticChildren = docs.filter(d => (d as IDocletBase).memberof === doclet.longname && (d as IDocletBase).scope === 'static'); if (staticChildren.length) { const longname = this._getNamespaceKey(doclet.longname); namespaceMerge = this._treeNodes[longname] = { doclet: { kind: 'namespace', name: doclet.name, scope: doclet.scope, longname: longname, memberof: doclet.memberof, }, children: [], }; debug(`Emitter._buildTreeNode(): merge namespace ${docletDebugInfo(namespaceMerge.doclet)} created for ${docletDebugInfo(doclet)}`); staticChildren.forEach(c => (c as IDocletBase).memberof = longname); } } // Call isDefaultExportDoclet() a first time here, in order to fix the `.memberof` attribute if not set. isDefaultExportDoclet(doclet, this._treeNodes); if (doclet.memberof) { const parent = this._getNodeFromLongname(doclet.memberof, function(node: IDocletTreeNode) { // When the scope of the doclet is 'instance', look for something that is a class or so. if (doclet.scope === 'instance') return isClassDoclet(node.doclet); return true; }); if (!parent) { warn(`Failed to find parent of doclet '${doclet.longname}' using memberof '${doclet.memberof}', this is likely due to invalid JSDoc.`, doclet); return; } if (isDefaultExportDoclet(doclet, this._treeNodes)) { if (doclet.meta && doclet.meta.code.value && doclet.meta.code.value.startsWith('{')) { // 'module.exports = {name: ... }' named export pattern. debug(`Emitter._buildTreeNode(): 'module.exports = {name: ... }' named export pattern doclet ${docletDebugInfo(doclet)}: skipping doclet but scan the object members`); // This default export doclet is followed by doclets wich describe each field of the {name: ...} object, // but those are not named 'export' and thus cannot be detected as named exports by default. const value = JSON.parse(doclet.meta.code.value); for (const name in value) { this._resolveDocletType(name, parent, function(namedExportNode: IDocletTreeNode) { debug(`Emitter._buildTreeNode(): tagging ${docletDebugInfo(namedExportNode.doclet)} as a named export`); namedExportNode.isNamedExport = true; } ); } return; } else { // Export doclets may be twiced, escpecially in case of inline or lambda definitions. // Scan the parent module's children in order to avoid the addition of two doclets for the same default export purpose. const thisEmitter = this; if (this._checkDuplicateChild(doclet, parent, (child: IDocletTreeNode) => isDefaultExportDoclet(child.doclet, thisEmitter._treeNodes))) return; // No default export doclet yet in the parent module. debug(`Emitter._buildTreeNode(): adding default export ${docletDebugInfo(doclet)} to module ${docletDebugInfo(parent.doclet)}`); // The longname of default export doclets is the same as the one of the parent module itself. // Thus no tree node has been created yet. Let's create one. parent.children.push({ doclet: doclet, children: [] }); return; } } if (isExportsAssignmentDoclet(doclet, this._treeNodes)) { debug(`Emitter._buildTreeNode(): adding 'exports =' assignment ${docletDebugInfo(doclet)} to module ${docletDebugInfo(parent.doclet)}`); // The longname of 'exports =' assignment doclets is the same as the one of the parent module itself. // Thus no tree node has been created yet. Let's create one. parent.children.push({ doclet: doclet, children: [] }); return; } const obj = this._treeNodes[doclet.longname]; if (!obj) { warn('Failed to find doclet node when building tree, this is likely a bug.', doclet); return; } const isParentClassLike = isClassDoclet(parent.doclet); // We need to move this into a module of the same name as the parent if (isParentClassLike && shouldMoveOutOfClass(doclet)) { debug(`Emitter._buildTreeNode(): move out of class!`); const mod = this._getOrCreateClassNamespace(parent); if (interfaceMerge) { debug(`Emitter._buildTreeNode(): adding ${docletDebugInfo(interfaceMerge.doclet)} to ${docletDebugInfo(mod.doclet)}`); mod.children.push(interfaceMerge); } if (namespaceMerge) { debug(`Emitter._buildTreeNode(): adding ${docletDebugInfo(namespaceMerge.doclet)} to ${docletDebugInfo(mod.doclet)}`); mod.children.push(namespaceMerge); } debug(`Emitter._buildTreeNode(): adding ${docletDebugInfo(obj.doclet)} to ${docletDebugInfo(mod.doclet)}`); mod.children.push(obj); } else { if (this._checkDuplicateChild(doclet, parent, function(child: IDocletTreeNode) { if (child.doclet.kind !== doclet.kind) return false; if (child.doclet.longname === doclet.longname) return true; // Check also against the optional form of the doclet. const shortname = doclet.name || ''; const optionalLongname = doclet.longname.slice(0, doclet.longname.length - shortname.length) + `[${shortname}]`; if (child.doclet.longname === optionalLongname) return true; return false; } )) return; const isObjModuleLike = isNamespaceDoclet(doclet); const isParentModuleLike = isNamespaceDoclet(parent.doclet); if (isObjModuleLike && isParentModuleLike) { debug(`Emitter._buildTreeNode(): nested modules / namespaces!`); obj.isNested = true; } const isParentEnum = isEnumDoclet(parent.doclet); if (!isParentEnum) { if (interfaceMerge) { debug(`Emitter._buildTreeNode(): adding ${docletDebugInfo(interfaceMerge.doclet)} to ${docletDebugInfo(parent.doclet)}`); parent.children.push(interfaceMerge); } if (namespaceMerge) { debug(`Emitter._buildTreeNode(): adding ${docletDebugInfo(namespaceMerge.doclet)} to ${docletDebugInfo(parent.doclet)}`); parent.children.push(namespaceMerge); } debug(`Emitter._buildTreeNode(): adding ${docletDebugInfo(obj.doclet)} to ${docletDebugInfo(parent.doclet)}`); parent.children.push(obj); } } } else { const obj = this._treeNodes[doclet.longname]; if (!obj) { warn('Failed to find doclet node when building tree, this is likely a bug.', doclet); return; } if (interfaceMerge) { debug(`Emitter._buildTreeNode(): ${docletDebugInfo(interfaceMerge.doclet)} detected as a root`); this._treeRoots.push(interfaceMerge); } if (namespaceMerge) { debug(`Emitter._buildTreeNode(): ${docletDebugInfo(namespaceMerge.doclet)} detected as a root`); this._treeRoots.push(namespaceMerge); } debug(`Emitter._buildTreeNode(): ${docletDebugInfo(obj.doclet)} detected as a root`); this._treeRoots.push(obj); } } /** * Before adding the doclet as a child of a candidate parent, check whether it is a duplicate a an already known child. * In such a case, the most documented doclet is preferred, or the last one. * @param doclet Candidate child doclet. * @param parent Candidate parent node. * @param match Handler that tells whether an already known child is a duplicate for the previous candidate child `doclet`. * @returns `true` when a duplicate has been found, `false` otherwise. */ private _checkDuplicateChild(doclet: TDoclet, parent: IDocletTreeNode, match: (child: IDocletTreeNode) => boolean): boolean { // Check this doclet does not exist yet in the candidate parent's children. for (const child of parent.children) { if (match(child)) { if (!isDocumentedDoclet(doclet)) { // Do not add the undocumented doclet to the parent twice. debug(`Emitter._checkConcurrentChild(): skipping undocumented ${docletDebugInfo(doclet)} because ${docletDebugInfo(child.doclet)} is already known in parent ${docletDebugInfo(parent.doclet)}`); // At this point, we could be tempted to merge meta information between detached and actual doclets. // The code below has no particular use in the rest of the process, thus it is not activated yet, // but it could be of interest, so it is left as a comment: /*// Check whether the meta information can be merged between a detached and an actual doclet. if (doclet.meta && doclet.meta.range // <= is `doclet` an actual doclet? && (!child.doclet.meta || !child.doclet.meta.range)) // <= is `child.doclet` a detached doclet? { debug(`Emitter._buildTreeNode(): replacing ${docletDebugInfo(child.doclet)}'s meta info with ${docletDebugInfo(doclet)}'s one`); child.doclet.meta = doclet.meta; debug(`Emitter._buildTreeNode(): => is now ${docletDebugInfo(child.doclet)}`); }*/ } else { // Replace the previously known doclet by this new one in other cases. debug(`Emitter._buildTreeNode(): replacing ${docletDebugInfo(child.doclet)} with ${docletDebugInfo(doclet)} in ${docletDebugInfo(parent.doclet)}`); child.doclet = doclet; } return true; } } return false; } private _markExported() { debug(`----------------------------------------------------------------`); debug(`Emitter._markExported()`); // Ensure `_markExportedNode()` can be used as a callback function with the appropriate `this` context. this._markExportedNode = this._markExportedNode.bind(this); // Scan the tree root nodes, identify the 'module' ones, // and launch the recursive _markExportedNode() function on them. for (let i = 0; i < this._treeRoots.length; i++) { const node = this._treeRoots[i]; if (node.doclet.kind === 'module') this._markExportedNode(node); } } private _markExportedNode(node: IDocletTreeNode, markThisNode: boolean = true) { debug(`Emitter._markExportedNode(${docletDebugInfo(node.doclet)}, markThisNode=${markThisNode})`); // First of all, mark the node with the 'isExported' flag. const doProcessNode = (node.isExported === undefined); if (markThisNode) node.isExported = true; else if (! node.isExported) node.isExported = false; // Process the node once only in order to avoid infinite loops in cas of cyclic dependencies. if (! doProcessNode) return; // Then, for each kind of node, iterate over the related nodes. switch (node.doclet.kind) { // IClassDoclet: case 'class': case 'interface': case 'mixin': this._markExportedParams(node, node.doclet.params); if (node.doclet.augments) for (const augment of node.doclet.augments) this._resolveDocletType(augment, node, this._markExportedNode); if (node.doclet.implements) for (const implement of node.doclet.implements) this._resolveDocletType(implement, node, this._markExportedNode); if (node.doclet.mixes) for (const mix of node.doclet.mixes) this._resolveDocletType(mix, node, this._markExportedNode); this._markExportedChildren(node); break; // IFileDoclet: case 'file': this._markExportedParams(node, node.doclet.params); break; // IEventDoclet: case 'event': this._markExportedParams(node, node.doclet.params); break; // IFunctionDoclet: case 'callback': case 'function': if (node.doclet.this) this._resolveDocletType(node.doclet.this, node, this._markExportedNode); this._markExportedParams(node, node.doclet.params); this._markExportedReturns(node, node.doclet.returns); break; // IMemberDoclet: case 'member': case 'constant': if (isDefaultExportDoclet(node.doclet, this._treeNodes)) { if (node.doclet.meta && node.doclet.meta.code.value) { this._resolveDocletType(node.doclet.meta.code.value, node, this._markExportedNode); } } else if (isNamedExportDoclet(node.doclet, this._treeNodes) && node.doclet.meta && node.doclet.meta.code.value && (! isEnumDoclet(node.doclet))) { const thisEmitter = this; this._resolveDocletType(node.doclet.meta.code.value, node, function (refNode: IDocletTreeNode) { // Directly mark the referenced node for export (through this path at least), only if the exported name is changed. const markThisNode = node.doclet.meta && (node.doclet.meta.code.value === node.doclet.name); thisEmitter._markExportedNode(refNode, markThisNode); }, // Doclet filter: avoid cyclic loops in case this named export references a type with the same name. function(target: IDocletTreeNode) { return (target !== node); } ); } else { this._markExportedTypes(node, node.doclet.type); } break; // INamespaceDoclet: case 'module': // Search for export doclets in the module. for (const child of node.children) { if (isDefaultExportDoclet(child.doclet, this._treeNodes) || isNamedExportDoclet(child.doclet, this._treeNodes)) { this._markExportedNode(child); } } break; case 'namespace': this._markExportedChildren(node); break; // ITypedefDoclet: case 'typedef': this._markExportedTypes(node, node.doclet.type); // When the typedef is for a function, the doclet may have params and returns. this._markExportedParams(node, node.doclet.params); this._markExportedReturns(node, node.doclet.returns); break; default: return assertNever(node.doclet); } } private _markExportedTypes(node: IDocletTreeNode, types?: IDocletType) { if (types) { for (const typeName of types.names) { this._resolveDocletType(typeName, node, this._markExportedNode); } } } private _markExportedParams(node: IDocletTreeNode, params?: IDocletProp[]) { if (params) { for (const param of params) { if (param.type) { for (const paramType of param.type.names) { this._resolveDocletType(paramType, node, this._markExportedNode); } } } } } private _markExportedReturns(node: IDocletTreeNode, returns?: IDocletReturn[]) { if (returns) { for (const ret of returns) { for (const retType of ret.type.names) { this._resolveDocletType(retType, node, this._markExportedNode); } } } } private _markExportedChildren(node: IDocletTreeNode) { for (const child of node.children) { this._markExportedNode(child); } } private _parseTree() { debug(`----------------------------------------------------------------`); debug(`Emitter._parseTree()`); for (let i = 0; i < this._treeRoots.length; ++i) { const node = this._parseTreeNode(this._treeRoots[i]); if (node) this.results.push(node); } } private _parseTreeNode(node: IDocletTreeNode, parent?: IDocletTreeNode): ts.Node | null { if (this.options.generationStrategy === 'exported' && !node.isExported) { debug(`Emitter._parseTreeNode(${docletDebugInfo(node.doclet)}): skipping doclet, not exported`); return null; } if (!node.exportName // Check the `.exportName` flag before calling `_ignoreDoclet()` in order to avoid false debug lines. && this._ignoreDoclet(node.doclet)) { debug(`Emitter._parseTreeNode(${docletDebugInfo(node.doclet)}): skipping ignored doclet`); return null; } debug(`Emitter._parseTreeNode(${docletDebugInfo(node.doclet)}, parent=${parent ? docletDebugInfo(parent.doclet) : parent})`); const children: ts.Node[] = []; if (children) { for (let i = 0; i < node.children.length; ++i) { const childNode = this._parseTreeNode(node.children[i], node); if (childNode) children.push(childNode); } } switch (node.doclet.kind) { case 'class': if (isConstructorDoclet(node.doclet)) { // constructor in es6 classes with own doclet return createConstructor(node.doclet); } else { return createClass(node.doclet, children, node.exportName); } case 'constant': case 'member': if (isDefaultExportDoclet(node.doclet, this._treeNodes) && node.doclet.meta && node.doclet.meta.code.value) { return createExportDefault(node.doclet, node.doclet.meta.code.value); } if (isNamedExportDoclet(node.doclet, this._treeNodes) && node.doclet.meta && node.doclet.meta.code.value && !isEnumDoclet(node.doclet)) { if (node.doclet.meta.code.value !== node.doclet.name) { const thisEmitter = this; let tsRes: ts.Node | null = null; this._resolveDocletType(node.doclet.meta.code.value, node, function(refNode: IDocletTreeNode) { // Named export from a type with a different name. // Create a live IDocletTreeNode object with the `.exportName` attribute set. const namedRefNode: IDocletTreeNode = { doclet: refNode.doclet, children: refNode.children, isNested: refNode.isNested, isExported: true, exportName: node.doclet.name } tsRes = thisEmitter._parseTreeNode(namedRefNode, parent); }); return tsRes; } else { // Nothing to do. debug(`Emitter._parseTreeNode(): skipping named export with reference of the same name`); return null; } } if (isExportsAssignmentDoclet(node.doclet, this._treeNodes)) { // Nothing to do. debug(`Emitter._parseTreeNode(): skipping 'exports =' assignment`); return null; } if (node.doclet.isEnum) return createEnum(node.doclet, node.exportName); else if (parent && parent.doclet.kind === 'class') return createClassMember(node.doclet); else if (parent && parent.doclet.kind === 'interface') return createInterfaceMember(node.doclet); else // For both namespace and module members. `node.exportName` may be set. return createNamespaceMember(node.doclet, node.exportName); case 'callback': case 'function': if (node.doclet.memberof) { const parent = this._treeNodes[node.doclet.memberof]; if (parent && parent.doclet.kind === 'class') return createClassMethod(node.doclet); else if (parent && parent.doclet.kind === 'interface') return createInterfaceMethod(node.doclet); } return createFunction(node.doclet, node.exportName); case 'interface': return createInterface(node.doclet, children, node.exportName); case 'mixin': return createInterface(node.doclet, children, node.exportName); case 'module': return createModule(node.doclet, !!node.isNested, children); case 'namespace': return createNamespace(node.doclet, !!node.isNested, children, node.exportName); case 'typedef': return createTypedef(node.doclet, children, node.exportName); case 'file': return null; case 'event': // TODO: Handle Events. return null; default: return assertNever(node.doclet); } } private _ignoreDoclet(doclet: TAnyDoclet): boolean { // Constructors should be generated with their documentation whatever their access level. if (doclet.kind !== 'package' && isConstructorDoclet(doclet)) { return false; } let reason: string|undefined = undefined; if (doclet.kind === 'package') reason = 'package doclet'; else if (!!doclet.ignore) reason = 'doclet with an ignore flag'; else if (!this.options.private && doclet.access === 'private') reason = 'private access disabled'; // Disable method overrides. See [tsd-jsdoc#104](https://github.com/englercj/tsd-jsdoc/issues/104). else if (doclet.kind === 'function' && (doclet.override || doclet.overrides)) reason = 'overriding doclet'; if (reason || doclet.kind === 'package') // <= hack for typescript resolutions { debug(`Emitter._ignoreDoclet(doclet=${docletDebugInfo(doclet)}) => true (${reason})`); return true } if (doclet.access === undefined) { return false } const accessLevels = ["private", "package", "protected", "public"]; const ignored = accessLevels.indexOf(doclet.access.toString()) < accessLevels.indexOf(this.options.access || "package"); if (ignored) { debug(`Emitter._ignoreDoclet(doclet=${docletDebugInfo(doclet)}) => true (low access level)`); } return ignored; } private _getInterfaceKey(longname?: string): string { return longname ? longname + '$$interface$helper' : ''; } private _getNamespaceKey(longname?: string): string { return longname ? longname + '$$namespace$helper' : ''; } private _getOrCreateClassNamespace(obj: IDocletTreeNode): IDocletTreeNode { if (obj.doclet.kind === 'module' || obj.doclet.kind === 'namespace') { return obj; } const namespaceKey = this._getNamespaceKey(obj.doclet.longname); let mod = this._treeNodes[namespaceKey]; if (mod) { return mod; } mod = this._treeNodes[namespaceKey] = { doclet: { kind: 'namespace', name: obj.doclet.name, scope: 'static', longname: namespaceKey, }, children: [], }; if (obj.doclet.memberof) { const parent = this._treeNodes[obj.doclet.memberof]; if (!parent) { warn(`Failed to find parent of doclet '${obj.doclet.longname}' using memberof '${obj.doclet.memberof}', this is likely due to invalid JSDoc.`, obj.doclet); return mod; } let parentMod = this._getOrCreateClassNamespace(parent); debug(`Emitter._getOrCreateClassNamespace(): pushing ${docletDebugInfo(mod.doclet)} as a child of ${docletDebugInfo(parentMod.doclet)}`); mod.doclet.memberof = parentMod.doclet.longname; parentMod.children.push(mod); } else { debug(`Emitter._getOrCreateClassNamespace(): no memberof, pushing ${docletDebugInfo(mod.doclet)} as a root`); this._treeRoots.push(mod); } return mod; } /** * Search for a IDocletTreeNode from its longname. * Handles situations where default exported lambda types hold the same longname as the parent module. * @param longname Longname to search for. * @param filter Optional filter function that indicates whether a doclet is an appropriate candidate for what we search. */ private _getNodeFromLongname(longname: string, filter?: (node: IDocletTreeNode) => boolean): IDocletTreeNode | null { function _debug(msg: string) { /*debug(msg);*/ } const node = this._treeNodes[longname]; if (!node) { _debug(`Emitter._getNodeFromLongname('${longname}') => null`); warn(`No such doclet '${longname}'`); return null; } if (!filter || filter(node)) { _debug(`Emitter._getNodeFromLongname('${longname}') => ${docletDebugInfo(node.doclet)}`); return node; } if (node.doclet.kind === 'module') { // The searched item has the same longname as a mdoule. // This happens when the item is an inline or lambda class exported by default. // Look for the item in the module's children. for (const child of node.children) { if (child.doclet.longname === longname && filter(child)) { _debug(`Emitter._getNodeFromLongname('${longname}') => ${docletDebugInfo(child.doclet)}`); return child; } } _debug(`Emitter._getNodeFromLongname('${longname}') => null`); warn(`No such doclet '${longname}' in module`); return null; } else { _debug(`Emitter._getNodeFromLongname('${longname}') => null`); warn(`Unexpected doclet for longname '${longname}`, node.doclet); return null; } } /** * From the context of `currentNode`, search for the doclets which type name corresponds to `typeName`, and apply `callback` on them. * @param currentNode Starting context for type resolution. * @param typeName Type name to search for. * @param callback Callback to apply on each resolved doclet. * @param filter Optional filter function that indicates whether a doclet is an appropriate candidate for what we search. */ private _resolveDocletType( typeName: string, currentNode: IDocletTreeNode, callback: (node: IDocletTreeNode) => void, filter?: (node: IDocletTreeNode) => boolean): void { function _debug(msg: string) { /*debug(msg);*/ } _debug(`Emitter._resolveDocletType(typeName='${typeName}', currentNode=${docletDebugInfo(currentNode.doclet)})`); const tokens = generateTree(typeName); if (!tokens) { warn(`Could not resolve type '${typeName}' in current node:`, currentNode.doclet); return; } tokens.dump((msg: string) => _debug(`Emitter._resolveDocletType(): tokens = ${msg}`)); const thisEmitter = this; tokens.walkTypes(function(token: StringTreeNode) { _debug(`Emitter._resolveDocletType(): token = {name:${token.name}, type:${token.typeToString()}}`); typeName = token.name; if (typeName.match(/.*\[ *\].*/)) typeName = typeName.slice(0, typeName.indexOf('[')); _debug(`Emitter._resolveDocletType(): typeName = ${typeName}`); // Skip basic types. switch (typeName) { case 'void': case 'null': case 'string': case 'String': case 'boolean': case 'Boolean': case 'number': case 'Number': case 'function': case 'Function': case 'any': case 'object': case 'Object': // <= means 'any' in jsdoc case '*': // <= means 'any' in jsdoc case 'Array': case 'Union': case 'Promise': case 'HTMLElement': // <= Basic typescript type. return; } // Lookup for the target symbol through up the scopes. let scope: string | undefined = currentNode.doclet.longname; while (scope) { _debug(`Emitter._resolveDocletType(): scope='${scope}'`); const longnames = [ `${scope}.${typeName}`, `${scope}~${typeName}`, `${scope}~${typeName}$$interface$helper`, `${scope}~${typeName}$$namespace$helper`, ]; let targetFound = false; for (const longname of longnames) { _debug(`Emitter._resolveDocletType(): trying longname '${longname}'...`); const target = thisEmitter._treeNodes[longname]; if (target) { if (filter && (! filter(target))) { _debug(`Emitter._resolveDocletType(): filtered out ${docletDebugInfo(target.doclet)}`); } else { _debug(`Emitter._resolveDocletType(): found! ${docletDebugInfo(target.doclet)}`); callback(target); targetFound = true; } } } // When one target at least has been found within this scope, stop searching. if (targetFound) { _debug(`Emitter._resolveDocletType(): done`); return; } // Search for templates. // Does not work with jsdoc@3.6.3, as long as jsdoc@3.6.x does not support @template tags, nor generates "tags" sections anymore. const scopeNode: IDocletTreeNode | undefined = thisEmitter._treeNodes[scope]; if (! scopeNode) break; for (const tsTypeParameterDeclaration of resolveTypeParameters(scopeNode.doclet)) { if (tsTypeParameterDeclaration.name.text === typeName) { _debug(`Emitter._resolveDocletType(): template found! in ${docletDebugInfo(scopeNode.doclet)}`); // No doclet. Stop searching. return; } } scope = scopeNode.doclet.memberof; } warn(`Could not resolve type '${typeName}' in current node:`, currentNode.doclet); }); } }
the_stack
import {Camera, Object3D, Renderer, Scene as ThreeScene, WebGLRenderer} from 'three' /** * Allows rendering objects into one ore more visual layers that are stacked on * top of each other. Think of it like layers in Adobe Photoshop. */ export class VisualLayers { __layers: Array<Layer> = [] __renderer: Renderer __Scene: typeof ThreeScene /** * @param {THREE.Renderer} renderer The `THREE.Renderer` (f.e. `THREE.WebGLRenderer`) that * will be used to render the layers. * @param {typeof THREE.Scene} Scene The `THREE.Scene` class that will be used for each layer * (one per layer). If not provided, `THREE.Scene` is used by default. */ // IDEA: Optionally accept different Scene types per layer. constructor(renderer: Renderer, Scene = ThreeScene) { this.__renderer = renderer this.__Scene = Scene } /** * Deletes all defined layers -- hence un-references contained objects so * they can be garbage collected -- as if starting with a fresh new * VisualLayers. Generally you should call this if you are getting rid * of layering, or want to define a new set of layers, etc. */ dispose(): void { this.__layers.length = 0 } /** * Defines a new layer. * @param {LayerName} layerName The name to give the layer. * @param {number} order The order it will have. The newly-defined layer will * render above other layers that have lower numbers, and below other layers * that have higher order numbers. * @returns {Layer} The created object representing the layer. */ defineLayer(layerName: LayerName, order = 0): Layer { const layer = this.__getOrMakeLayer(layerName) const previousOrder = layer.order layer.order = order // Sort only if order changed. if (previousOrder !== layer.order) this.__layers.sort((a, b) => a.order - b.order) return layer } /** * Set the visibility of one or more layers. * @param {LayerNames} layerNames The name of a layer (or array of names of layers) that will have its (their) visibility set. * @param {boolean} visible A boolean indicating whether the layer or layers should be visible. */ setLayerVisible(layerNames: LayerNames, visible: boolean) { if (typeof layerNames == 'string') return this.__setLayerVisible(layerNames, visible) for (const name of layerNames) this.__setLayerVisible(name, visible) } __setLayerVisible(layerName: LayerName, visible: boolean) { const layer = this.__layers.find(l => l.name === layerName) if (!layer) throw new Error('Can not set visibility of layer that does not exist.') layer.visible = visible } /** Get a layer by name (if it doesn't exist, creates it with default order 0). */ __getOrMakeLayer(layerName: LayerName): Layer { let layer = this.__layers.find(l => l.name === layerName) if (!layer) { layer = {name: layerName, backingScene: new this.__Scene(), order: 0, visible: true} layer.backingScene.autoUpdate = false this.__layers.push(layer) } return layer } /** * Remove a layer. * @param {LayerName} layerName The name of the layer to remove. */ removeLayer(layerName: LayerName): void { const index = this.__layers.findIndex(l => { if (l.name === layerName) { l.backingScene.children.length = 0 return true } return false }) if (index >= 0) this.__layers.splice(index, 1) } /** * Check if a layer exists. * @param {LayerName} layerName The name of the layer to check existence of. * @returns {boolean} A boolean indicating if the layer exists. */ hasLayer(layerName: LayerName): boolean { return this.__layers.some(l => l.name === layerName) } /** * The number of layers. * @readonly * @type {number} */ get layerCount(): number { return this.__layers.length } /** * Add an object (anything that is or extends from THREE.Object3D) to the named layer (or named layers). * * @param {THREE.Object3D} obj The object to add. Must be an `instanceof THREE.Object3D`. * * @param {LayerNames} layerNames The name of a layer (or array of names of layers) that * the object will be added to. If an object is added to multiple layers, the * object will be rendered multiple times, once per layer. * * @param {boolean | undefined} withSubtree When true, this causes an object that was added into * specified layer(s) be rendered with its (grand)children, rather than it * being rendered only by itself without any of its (grand)children. * * It is useful for `withSubtree` to be set to `false` (the default) when you * want to have a hierarchy with different parts of the hierarchy rendered * in different layers * * On the other hand, sometimes you have a whole tree that you want to put in * a layer and don’t want to have to specify layers for all of the sub-nodes. * Set `withSubtree` to `true` in this case to add a root node to a layer * to render that whole subtree in that layer. * * It is easier to add a whole tree into a layer with `withSubtree` as * `true`. When `withSubtree` is `false` each node in a subtree would * need to be added to a layer manually, but this allows more fine grained control of * which parts of a tree will render in various layers. */ addObjectToLayer(obj: Object3D, layerNames: LayerNames, withSubtree = false): void { if (typeof layerNames == 'string') return this.__addObjectToLayer(obj, layerNames, withSubtree) for (const name of layerNames) this.__addObjectToLayer(obj, name, withSubtree) } /** * Similar to `addObjectToLayer`, but for adding multiple objects at once. * @param {THREE.Object3D[]} objects An array of objects that are `instanceof THREE.Object3D`. * @param {LayerNames} layerNames The layer or layers to add the objects to. * @param {boolean | undefined} withSubtree Whether rendering of the objects will also render their * children. See `withSubtree` of `addObjectToLayer` for more details. */ addObjectsToLayer(objects: Object3D[], layerNames: LayerNames, withSubtree = false): void { for (const obj of objects) this.addObjectToLayer(obj, layerNames, withSubtree) } /** * Add an object to all currently-defined layers. * @param {THREE.Object3D} obj The object to add. Must be an `instanceof THREE.Object3D`. * @param {boolean | undefined} withSubtree Whether rendering of the object will also render its * children. See `withSubtree` of `addObjectToLayer` for more details. */ addObjectToAllLayers(obj: Object3D, withSubtree = false): void { for (const layer of this.__layers) this.__addObjectToLayer(obj, layer.name, withSubtree) } /** * Add a set of objects to all currently-defined layers. * @param {THREE.Object3D[]} objects The list of `THREE.Object3D` instances to add. * @param {boolean | undefined} withSubtree Whether rendering of the objects will also render their * children. See `withSubtree` of `addObjectToLayer` for more details. */ addObjectsToAllLayers(objects: Object3D[], withSubtree = false): void { for (const obj of objects) this.addObjectToAllLayers(obj, withSubtree) } readonly __emptyArray = Object.freeze([]) __addObjectToLayer(obj: Object3D, layerName: LayerName, withSubtree: boolean): void { const layer = this.__getOrMakeLayer(layerName) if (!this.__layerHasObject(layer, obj)) { const proxy = Object.create(obj, withSubtree ? {} : {children: {get: () => this.__emptyArray}}) // We use `children.push()` here instead of `children.add()` so that the // added child will not be removed from its parent in its original scene. // This allows us to add an object to multiple layers, and to not // interfere with the user's original tree. layer.backingScene.children.push(proxy) } } __layerHasObject(layer: Layer, obj: Object3D): boolean { return layer.backingScene.children.some(proxy => (proxy as any).__proto__ === obj) } /** * Remove an object from a layer or set of layers. * @param {THREE.Object3D} obj The object to remove from the specified layer or layers. * @param {LayerNames} layerNames The layer or layers from which to remove the object from. */ removeObjectFromLayer(obj: Object3D, layerNames: LayerNames): void { if (typeof layerNames == 'string') { const layer = this.__layers.find(l => l.name === layerNames) return this.__removeObjectFromLayer(obj, layer) } for (const name of layerNames) { const layer = this.__layers.find(l => l.name === name) this.__removeObjectFromLayer(obj, layer) } } /** * Remove an object from a layer or set of layers. * @param {THREE.Object3D[]} objects The objects to remove from the specified layer or layers. * @param {LayerNames} layerNames The layer or layers from which to remove the object from. */ removeObjectsFromLayer(objects: Object3D[], layerNames: LayerNames): void { for (const obj of objects) this.removeObjectFromLayer(obj, layerNames) } /** * Remove the given object from all layers. * @param {THREE.Object3D} obj The object to remove. */ removeObjectFromAllLayers(obj: Object3D): void { for (const layer of this.__layers) this.__removeObjectFromLayer(obj, layer) } /** * Remove the given objects from all layers they may belong to. * @param {THREE.Object3D[]} objects The objects to remove. */ removeObjectsFromAllLayers(objects: Object3D[]): void { for (const obj of objects) this.removeObjectFromAllLayers(obj) } __removeObjectFromLayer(obj: Object3D, layer: Layer | undefined) { if (!layer) throw new Error('Can not remove object from layer that does not exist.') const children = layer.backingScene.children const index = children.findIndex(proxy => (proxy as any).__proto__ === obj) if (index >= 0) { children[index] = children[children.length - 1] children.pop() } } /** * Render visible layers. * * @param {THREE.Camera} camera A THREE.Camera to render all the layers with. * * @param {BeforeAllCallback | undefined} beforeAll Optional: Called before rendering all layers. If not * supplied, the default value will turn off the rendere's auto clearing, so that * each layer can be manually drawn stacked on top of each other. * * @param {BeforeEachCallback | undefined} beforeEach Optional: When the layers are being rendered in the order they are * defined to be in, this callback will be called right before a layer is * rendered. It will be passed the name of the layer that is about to be * rendered. By default, this does nothing. * * @param {AfterEachCallback | undefined} afterEach Optional: When the layers are being rendered in the order * they are defined to be in, this callback will be called right after a * layer is rendered. It will be passed the name of the layer that was just * rendered. The default is that `clearDepth()` will be called on a * `WebGLRenderer` to ensure layers render on top of each other from low * order to high order. If you provide your own callback, you'll have to * remember to call `clearDepth` manually, unless you wish for layers to blend into * the same 3D space rather than appaering as separate scenes stacked on * top of each other. */ // IDEA: Allow different cameras per layer? It may not be common, but could // be useful for, for example, making background effects, etc. render( camera: Camera, beforeAll: BeforeAllCallback = this.__defaultBeforeAllCallback, beforeEach: BeforeEachCallback = this.__defaultBeforeEachCallback, afterEach: AfterEachCallback = this.__defaultAfterEachCallback, ) { beforeAll() for (const layer of this.__layers) { if (!layer.visible) continue beforeEach(layer.name) this.__renderer.render(layer.backingScene, camera) afterEach(layer.name) } } __defaultBeforeAllCallback = () => { if (this.__renderer instanceof WebGLRenderer) { this.__renderer.autoClear = false this.__renderer.clear() } } __defaultBeforeEachCallback = () => {} __defaultAfterEachCallback = () => { // By default, the depth of a WebGLRenderer is cleared, so that layers // render on top of each other in order from lowest to highest order value. if (this.__renderer instanceof WebGLRenderer) this.__renderer.clearDepth() } } /** @typedef {string} LayerName */ type LayerName = string /** @typedef {LayerName | LayerName[]} LayerNames */ type LayerNames = LayerName | LayerName[] /** @typedef {{name: LayerName; backingScene: THREE.Scene; order: number; visible: boolean}} Layer */ type Layer = {name: LayerName; backingScene: THREE.Scene; order: number; visible: boolean} /** * @typedef { * @function * @param {LayerName} layerName * } BeforeEachCallback */ type BeforeEachCallback = (layerName: LayerName) => void /** * @typedef { * @function * } BeforeAllCallback */ type BeforeAllCallback = () => void /** * @typedef { * @function * @param {LayerName} layerName * @returns {void} * } AfterEachCallback */ type AfterEachCallback = (layerName: LayerName) => void
the_stack
import he from "he"; type EndOfLine = "lf" | "crlf" | "cr"; type EndOfLineVal = "\n" | "\r\n" | "\r"; interface Opts { fixBrokenEntities: boolean; removeWidows: boolean; convertEntities: boolean; convertDashes: boolean; convertApostrophes: boolean; replaceLineBreaks: boolean; removeLineBreaks: boolean; useXHTML: boolean; dontEncodeNonLatin: boolean; addMissingSpaces: boolean; convertDotsToEllipsis: boolean; stripHtml: boolean; eol: EndOfLine; stripHtmlButIgnoreTags: string[]; stripHtmlAddNewLine: string[]; cb: null | ((str: string) => string); } // default set of options const defaultOpts: Opts = { fixBrokenEntities: true, removeWidows: true, convertEntities: true, convertDashes: true, convertApostrophes: true, replaceLineBreaks: true, removeLineBreaks: false, useXHTML: true, dontEncodeNonLatin: true, addMissingSpaces: true, convertDotsToEllipsis: true, stripHtml: true, eol: "lf", stripHtmlButIgnoreTags: ["b", "strong", "i", "em", "br", "sup"], stripHtmlAddNewLine: ["li", "/ul"], cb: null, }; interface ApplicableOpts { fixBrokenEntities: boolean; removeWidows: boolean; convertEntities: boolean; convertDashes: boolean; convertApostrophes: boolean; replaceLineBreaks: boolean; removeLineBreaks: boolean; useXHTML: boolean; dontEncodeNonLatin: boolean; addMissingSpaces: boolean; convertDotsToEllipsis: boolean; stripHtml: boolean; eol: boolean; } interface Res { res: string; applicableOpts: ApplicableOpts; } interface State { onUrlCurrently: boolean; } const leftSingleQuote = "\u2018"; const rightSingleQuote = "\u2019"; const leftDoubleQuote = "\u201C"; const rightDoubleQuote = "\u201D"; const punctuationChars = [".", ",", ";", "!", "?"]; const rawNDash = "\u2013"; const rawMDash = "\u2014"; const rawNbsp = "\u00A0"; const rawEllipsis = "\u2026"; const rawhairspace = "\u200A"; const rawReplacementMark = "\uFFFD"; const widowRegexTest = /. ./g; const latinAndNonNonLatinRanges = [ [0, 880], [887, 890], [894, 900], [906, 908], [908, 910], [929, 931], [1319, 1329], [1366, 1369], [1375, 1377], [1415, 1417], [1418, 1423], [1423, 1425], [1479, 1488], [1514, 1520], [1524, 1536], [1540, 1542], [1563, 1566], [1805, 1807], [1866, 1869], [1969, 1984], [2042, 2048], [2093, 2096], [2110, 2112], [2139, 2142], [2142, 2208], [2208, 2210], [2220, 2276], [2302, 2304], [2423, 2425], [2431, 2433], [2435, 2437], [2444, 2447], [2448, 2451], [2472, 2474], [2480, 2482], [2482, 2486], [2489, 2492], [2500, 2503], [2504, 2507], [2510, 2519], [2519, 2524], [2525, 2527], [2531, 2534], [2555, 2561], [2563, 2565], [2570, 2575], [2576, 2579], [2600, 2602], [2608, 2610], [2611, 2613], [2614, 2616], [2617, 2620], [2620, 2622], [2626, 2631], [2632, 2635], [2637, 2641], [2641, 2649], [2652, 2654], [2654, 2662], [2677, 2689], [2691, 2693], [2701, 2703], [2705, 2707], [2728, 2730], [2736, 2738], [2739, 2741], [2745, 2748], [2757, 2759], [2761, 2763], [2765, 2768], [2768, 2784], [2787, 2790], [2801, 2817], [2819, 2821], [2828, 2831], [2832, 2835], [2856, 2858], [2864, 2866], [2867, 2869], [2873, 2876], [2884, 2887], [2888, 2891], [2893, 2902], [2903, 2908], [2909, 2911], [2915, 2918], [2935, 2946], [2947, 2949], [2954, 2958], [2960, 2962], [2965, 2969], [2970, 2972], [2972, 2974], [2975, 2979], [2980, 2984], [2986, 2990], [3001, 3006], [3010, 3014], [3016, 3018], [3021, 3024], [3024, 3031], [3031, 3046], [3066, 3073], [3075, 3077], [3084, 3086], [3088, 3090], [3112, 3114], [3123, 3125], [3129, 3133], [3140, 3142], [3144, 3146], [3149, 3157], [3158, 3160], [3161, 3168], [3171, 3174], [3183, 3192], [3199, 3202], [3203, 3205], [3212, 3214], [3216, 3218], [3240, 3242], [3251, 3253], [3257, 3260], [3268, 3270], [3272, 3274], [3277, 3285], [3286, 3294], [3294, 3296], [3299, 3302], [3311, 3313], [3314, 3330], [3331, 3333], [3340, 3342], [3344, 3346], [3386, 3389], [3396, 3398], [3400, 3402], [3406, 3415], [3415, 3424], [3427, 3430], [3445, 3449], [3455, 3458], [3459, 3461], [3478, 3482], [3505, 3507], [3515, 3517], [3517, 3520], [3526, 3530], [3530, 3535], [3540, 3542], [3542, 3544], [3551, 3570], [3572, 3585], [3642, 3647], [3675, 3713], [3714, 3716], [3716, 3719], [3720, 3722], [3722, 3725], [3725, 3732], [3735, 3737], [3743, 3745], [3747, 3749], [3749, 3751], [3751, 3754], [3755, 3757], [3769, 3771], [3773, 3776], [3780, 3782], [3782, 3784], [3789, 3792], [3801, 3804], [3807, 3840], [3911, 3913], [3948, 3953], [3991, 3993], [4028, 4030], [4044, 4046], [4058, 4096], [4293, 4295], [4295, 4301], [4301, 4304], [4680, 4682], [4685, 4688], [4694, 4696], [4696, 4698], [4701, 4704], [4744, 4746], [4749, 4752], [4784, 4786], [4789, 4792], [4798, 4800], [4800, 4802], [4805, 4808], [4822, 4824], [4880, 4882], [4885, 4888], [4954, 4957], [4988, 4992], [5017, 5024], [5108, 5120], [5788, 5792], [5872, 5888], [5900, 5902], [5908, 5920], [5942, 5952], [5971, 5984], [5996, 5998], [6000, 6002], [6003, 6016], [6109, 6112], [6121, 6128], [6137, 6144], [6158, 6160], [6169, 6176], [6263, 6272], [6314, 7936], [7957, 7960], [7965, 7968], [8005, 8008], [8013, 8016], [8023, 8025], [8025, 8027], [8027, 8029], [8029, 8031], [8061, 8064], [8116, 8118], [8132, 8134], [8147, 8150], [8155, 8157], [8175, 8178], [8180, 8182], [8190, 11904], [11929, 11931], [12019, 12032], [12245, 12288], [12351, 12353], [12438, 12441], [12543, 12549], [12589, 12593], [12686, 12688], [12730, 12736], [12771, 12784], [12830, 12832], [13054, 13056], [13312, 19893], [19893, 19904], [40869, 40908], [40908, 40960], [42124, 42128], [42182, 42192], [42539, 42560], [42647, 42655], [42743, 42752], [42894, 42896], [42899, 42912], [42922, 43000], [43051, 43056], [43065, 43072], [43127, 43136], [43204, 43214], [43225, 43232], [43259, 43264], [43347, 43359], [43388, 43392], [43469, 43471], [43481, 43486], [43487, 43520], [43574, 43584], [43597, 43600], [43609, 43612], [43643, 43648], [43714, 43739], [43766, 43777], [43782, 43785], [43790, 43793], [43798, 43808], [43814, 43816], [43822, 43968], [44013, 44016], [44025, 44032], [55203, 55216], [55238, 55243], [55291, 63744], [64109, 64112], [64217, 64256], [64262, 64275], [64279, 64285], [64310, 64312], [64316, 64318], [64318, 64320], [64321, 64323], [64324, 64326], [64449, 64467], [64831, 64848], [64911, 64914], [64967, 65008], [65021, 65136], [65140, 65142], [65276, 66560], [66717, 66720], [66729, 67584], [67589, 67592], [67592, 67594], [67637, 67639], [67640, 67644], [67644, 67647], [67669, 67671], [67679, 67840], [67867, 67871], [67897, 67903], [67903, 67968], [68023, 68030], [68031, 68096], [68099, 68101], [68102, 68108], [68115, 68117], [68119, 68121], [68147, 68152], [68154, 68159], [68167, 68176], [68184, 68192], [68223, 68352], [68405, 68409], [68437, 68440], [68466, 68472], [68479, 68608], [68680, 69216], [69246, 69632], [69709, 69714], [69743, 69760], [69825, 69840], [69864, 69872], [69881, 69888], [69940, 69942], [69955, 70016], [70088, 70096], [70105, 71296], [71351, 71360], [71369, 73728], [74606, 74752], [74850, 74864], [74867, 77824], [78894, 92160], [92728, 93952], [94020, 94032], [94078, 94095], [94111, 110592], [110593, 131072], [131072, 173782], [173782, 173824], [173824, 177972], [177972, 177984], [177984, 178205], [178205, 194560], ]; // https://html.spec.whatwg.org/multipage/syntax.html#elements-2 const voidTags = [ "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr", ]; // ----------------------------------------------------------------------------- function doConvertEntities( inputString: string, dontEncodeNonLatin: boolean ): string { if (dontEncodeNonLatin) { // console.log( // `427 doConvertEntities() - inside if (dontEncodeNonLatin) clauses` // ); // split, check, encode conditionally return Array.from(inputString) .map((char) => { // Separately check lower character indexes because statistically they are // most likely to be encountered. That's letters, quotes brackets and so on. // console.log( // `435 doConvertEntities() - char = "${char}"; ${`\u001b[${33}m${`char.charCodeAt(0)`}\u001b[${39}m`} = ${JSON.stringify( // char.charCodeAt(0), // null, // 4 // )}` // ); if ( char.charCodeAt(0) < 880 || latinAndNonNonLatinRanges.some( (rangeArr) => char.charCodeAt(0) > rangeArr[0] && char.charCodeAt(0) < rangeArr[1] ) ) { // console.log( // `450 doConvertEntities() - encoding to "${he.encode(char, { // useNamedReferences: true, // })}"` // ); return he.encode(char, { useNamedReferences: true, }); } return char; }) .join(""); } // console.log(`462 doConvertEntities() - outside if (dontEncodeNonLatin)`); // else, if dontEncodeNonLatin if off, just encode everything: return he.encode(inputString, { useNamedReferences: true, }); } // ----------------------------------------------------------------------------- // find postcodes, replace the space within them with '\u00a0' // function joinPostcodes(str: string): string { // return str.replace( // /([A-Z]{1,2}[0-9][0-9A-Z]?)\s?([0-9][A-Z]{2})/g, // "$1\u00a0$2" // ); // } // ----------------------------------------------------------------------------- function isNumber(something: any): boolean { return ( (typeof something === "string" && something.charCodeAt(0) >= 48 && something.charCodeAt(0) <= 57) || Number.isInteger(something) ); } function isLetter(str: any): boolean { return ( typeof str === "string" && str.length === 1 && str.toUpperCase() !== str.toLowerCase() ); } function isQuote(str: string): boolean { return ( str === '"' || str === "'" || str === leftSingleQuote || str === rightSingleQuote || str === leftDoubleQuote || str === rightDoubleQuote ); } function isLowercaseLetter(str: string): boolean { if (!isLetter(str)) { return false; } return str === str.toLowerCase() && str !== str.toUpperCase(); } function isUppercaseLetter(str: string): boolean { if (!isLetter(str)) { return false; } return str === str.toUpperCase() && str !== str.toLowerCase(); } function removeTrailingSlash(str: string): string { if (typeof str === "string" && str.length && str.endsWith("/")) { return str.slice(0, -1).trim(); } // default return - does nothing return str; } export { removeTrailingSlash, isLowercaseLetter, isUppercaseLetter, doConvertEntities, punctuationChars, rightSingleQuote, rightDoubleQuote, leftDoubleQuote, leftSingleQuote, Opts, defaultOpts, Res, State, EndOfLine, EndOfLineVal, ApplicableOpts, voidTags, isNumber, isLetter, isQuote, rawReplacementMark, rawNDash, rawMDash, rawNbsp, rawhairspace, rawEllipsis, widowRegexTest, };
the_stack
// namespace namespace cf { // interface export interface IChatResponseOptions extends IBasicElementOptions{ response: string; image: string; list: ChatList; isRobotResponse: boolean; tag: ITag; container: HTMLElement; } export const ChatResponseEvents = { USER_ANSWER_CLICKED: "cf-on-user-answer-clicked" } // class export class ChatResponse extends BasicElement { public static list: ChatList; private static THINKING_MARKUP: string = "<p class='show'><thinking><span>.</span><span>.</span><span>.</span></thinking></p>"; public isRobotResponse: boolean; public response: string; public originalResponse: string; // keep track of original response with id pipings public parsedResponse: string; private uiOptions: IUserInterfaceOptions; private textEl: Element; private image: string; private container: HTMLElement; private _tag: ITag; private readyTimer: any; private responseLink: ChatResponse; // robot reference from use private onReadyCallback: () => void; private onClickCallback: () => void; public get tag(): ITag{ return this._tag; } public get added() : boolean { return !!this.el || !!this.el.parentNode || !!this.el.parentNode.parentNode; } public get disabled() : boolean { return this.el.classList.contains("disabled"); } public set disabled(value : boolean) { if(value) this.el.classList.add("disabled"); else this.el.classList.remove("disabled"); } /** * We depend on scroll in a column-reverse flex container. This is where Edge and Firefox comes up short */ private hasFlexBug():boolean { return this.cfReference.el.classList.contains('browser-firefox') || this.cfReference.el.classList.contains('browser-edge'); } private animateIn() { const outer:HTMLElement = document.querySelector('scrollable'); const inner:HTMLElement = document.querySelector('.scrollableInner'); if (this.hasFlexBug()) inner.classList.remove('scroll'); requestAnimationFrame(() => { var height = this.el.scrollHeight; this.el.style.height = '0px'; requestAnimationFrame(() => { this.el.style.height = height + 'px'; this.el.classList.add('show'); // Listen for transitionend and set to height:auto try { const sm = window.getComputedStyle(document.querySelectorAll('p.show')[0]); const cssAnimationTime: number = +sm.animationDuration.replace('s', ''); // format '0.234234xs const cssAnimationDelayTime: number = +sm.animationDelay.replace('s', ''); setTimeout(() => { this.el.style.height = 'auto'; if (this.hasFlexBug() && inner.scrollHeight > outer.offsetHeight) { inner.classList.add('scroll'); inner.scrollTop = inner.scrollHeight; } }, (cssAnimationTime + cssAnimationDelayTime) * 1500); } catch(err) { // Fallback method. Assuming animations do not take longer than 1000ms setTimeout(() => { if (this.hasFlexBug() && inner.scrollHeight > outer.offsetHeight) { inner.classList.add('scroll'); inner.scrollTop = inner.scrollHeight; } this.el.style.height = 'auto'; }, 3000); } }); }); } public set visible(value: boolean){ } public get strippedSesponse():string{ var html = this.response; // use browsers native way of stripping var div = document.createElement("div"); div.innerHTML = html; return div.textContent || div.innerText || ""; } constructor(options: IChatResponseOptions){ super(options); this.container = options.container; this.uiOptions = options.cfReference.uiOptions; this._tag = options.tag; } public whenReady(resolve: () => void){ this.onReadyCallback = resolve; } public setValue(dto: FlowDTO = null){ // if(!this.visible){ // this.visible = true; // } const isThinking: boolean = this.el.hasAttribute("thinking"); if(!dto){ this.setToThinking(); }else{ // same same this.response = this.originalResponse = dto.text; this.processResponseAndSetText(); if(this.responseLink && !this.isRobotResponse){ // call robot and update for binding values -> this.responseLink.processResponseAndSetText(); } // check for if response type is file upload... if(dto && dto.controlElements && dto.controlElements[0]){ switch(dto.controlElements[0].type){ case "UploadFileUI" : this.textEl.classList.add("file-icon"); break; } } if(!this.isRobotResponse && !this.onClickCallback){ // edit this.onClickCallback = this.onClick.bind(this); this.el.addEventListener(Helpers.getMouseEvent("click"), this.onClickCallback, false); } } } public show(){ this.visible = true; this.disabled = false; if(!this.response){ this.setToThinking(); }else{ this.checkForEditMode(); } } public updateThumbnail(src: string){ const thumbEl: HTMLElement = <HTMLElement> this.el.getElementsByTagName("thumb")[0]; if(src.indexOf("text:") === 0){ const thumbElSpan: HTMLElement = <HTMLElement> thumbEl.getElementsByTagName("span")[0]; thumbElSpan.innerHTML = src.split("text:")[1]; thumbElSpan.setAttribute("length", src.length.toString()); } else { this.image = src; thumbEl.style.backgroundImage = 'url("' + this.image + '")'; } } public setLinkToOtherReponse(response: ChatResponse){ // link reponse to another one, keeping the update circle complete. this.responseLink = response; } public processResponseAndSetText(){ if(!this.originalResponse) return; var innerResponse: string = this.originalResponse; if(this._tag && this._tag.type == "password" && !this.isRobotResponse){ var newStr: string = ""; for (let i = 0; i < innerResponse.length; i++) { newStr += "*"; } innerResponse = newStr; } // if robot, then check linked response for binding values if(this.responseLink && this.isRobotResponse){ // one way data binding values: innerResponse = innerResponse.split("{previous-answer}").join(this.responseLink.parsedResponse); } if(this.isRobotResponse){ // Piping, look through IDs, and map values to dynamics const reponses: Array<ChatResponse> = ChatResponse.list.getResponses(); for (var i = 0; i < reponses.length; i++) { var response: ChatResponse = reponses[i]; if(response !== this){ if(response.tag){ // check for id, standard if(response.tag.id){ innerResponse = innerResponse.split("{" + response.tag.id + "}").join(<string> response.tag.value); } //fallback check for name if(response.tag.name){ innerResponse = innerResponse.split("{" + response.tag.name + "}").join(<string> response.tag.value); } } } } } // check if response contains an image as answer const responseContains: boolean = innerResponse.indexOf("contains-image") != -1; if(responseContains) this.textEl.classList.add("contains-image"); // now set it if(this.isRobotResponse){ this.textEl.innerHTML = ""; if(!this.uiOptions) this.uiOptions = this.cfReference.uiOptions; // On edit uiOptions are empty, so this mitigates the problem. Not ideal. let robotInitResponseTime: number = this.uiOptions.robot.robotResponseTime; if (robotInitResponseTime != 0){ this.setToThinking(); } // robot response, allow for && for multiple responses var chainedResponses: Array<string> = innerResponse.split("&&"); if(robotInitResponseTime === 0){ for (let i = 0; i < chainedResponses.length; i++) { let str: string = <string>chainedResponses[i]; this.textEl.innerHTML += "<p>" + str + "</p>"; } for (let i = 0; i < chainedResponses.length; i++) { setTimeout(() =>{ this.tryClearThinking(); const p: NodeListOf<HTMLElement> = this.textEl.getElementsByTagName("p"); p[i].classList.add("show"); this.scrollTo(); },chainedResponses.length > 1 && i > 0 ? robotInitResponseTime + ((i + 1) * this.uiOptions.robot.chainedResponseTime) : 0); } } else { for (let i = 0; i < chainedResponses.length; i++) { const revealAfter = robotInitResponseTime + (i * this.uiOptions.robot.chainedResponseTime); let str: string = <string>chainedResponses[i]; setTimeout(() =>{ this.tryClearThinking(); this.textEl.innerHTML += "<p>" + str + "</p>"; const p: NodeListOf<HTMLElement> = this.textEl.getElementsByTagName("p"); p[i].classList.add("show"); this.scrollTo(); }, revealAfter); } } this.readyTimer = setTimeout(() => { if(this.onReadyCallback) this.onReadyCallback(); // reset, as it can be called again this.onReadyCallback = null; if(this._tag && this._tag.skipUserInput === true){ setTimeout(() =>{ this._tag.flowManager.nextStep() this._tag.skipUserInput = false; // to avoid nextStep being fired again as this would make the flow jump too far when editing a response },this.uiOptions.robot.chainedResponseTime); } }, robotInitResponseTime + (chainedResponses.length * this.uiOptions.robot.chainedResponseTime)); } else { // user response, act normal this.tryClearThinking(); const hasImage = innerResponse.indexOf('<img') > -1; const imageRegex = new RegExp('<img[^>]*?>', 'g'); const imageTag = innerResponse.match(imageRegex); if (hasImage && imageTag) { innerResponse = innerResponse.replace(imageTag[0], ''); this.textEl.innerHTML = `<p class="hasImage">${imageTag}<span>${innerResponse}</span></p>`; } else { this.textEl.innerHTML = `<p>${innerResponse}</p>`; } const p: NodeListOf<HTMLElement> = this.textEl.getElementsByTagName("p"); p[p.length - 1].offsetWidth; p[p.length - 1].classList.add("show"); this.scrollTo(); } this.parsedResponse = innerResponse; // } // value set, so add element, if not added if ( this.uiOptions.robot && this.uiOptions.robot.robotResponseTime === 0 ) { this.addSelf(); } else { setTimeout(() => { this.addSelf(); }, 0); } // bounce this.textEl.removeAttribute("value-added"); setTimeout(() => { this.textEl.setAttribute("value-added", ""); this.el.classList.add("peak-thumb"); }, 0); this.checkForEditMode(); // update response // remove the double ampersands if present this.response = innerResponse.split("&&").join(" "); } public scrollTo(){ const y: number = this.el.offsetTop; const h: number = this.el.offsetHeight; if(!this.container && this.el) this.container = this.el; // On edit this.container is empty so this is a fix to reassign it. Not ideal, but... if ( this.container && this.container.parentElement && this.container.parentElement.scrollHeight ) { this.container.parentElement.scrollTop = y + h + this.container.parentElement.scrollHeight; } } private checkForEditMode(){ if(!this.isRobotResponse && !this.el.hasAttribute("thinking")){ this.el.classList.add("can-edit"); this.disabled = false; } } private tryClearThinking(){ if(this.el.hasAttribute("thinking")){ this.textEl.innerHTML = ""; this.el.removeAttribute("thinking"); } } private setToThinking(){ const canShowThinking: boolean = (this.isRobotResponse && this.uiOptions.robot.robotResponseTime !== 0) || (!this.isRobotResponse && this.cfReference.uiOptions.user.showThinking && !this._tag.skipUserInput); if(canShowThinking){ this.textEl.innerHTML = ChatResponse.THINKING_MARKUP; this.el.classList.remove("can-edit"); this.el.setAttribute("thinking", ""); } if(this.cfReference.uiOptions.user.showThinking || this.cfReference.uiOptions.user.showThumb){ this.addSelf(); } } /** * @name addSelf * add one self to the chat list */ private addSelf(): void { if(this.el.parentNode != this.container){ this.container.appendChild(this.el); this.animateIn(); } } /** * @name onClickCallback * click handler for el */ private onClick(event: MouseEvent): void { this.setToThinking(); ConversationalForm.illustrateFlow(this, "dispatch", ChatResponseEvents.USER_ANSWER_CLICKED, event); this.eventTarget.dispatchEvent(new CustomEvent(ChatResponseEvents.USER_ANSWER_CLICKED, { detail: this._tag })); } protected setData(options: IChatResponseOptions):void{ this.image = options.image; this.response = this.originalResponse = options.response; this.isRobotResponse = options.isRobotResponse; super.setData(options); } protected onElementCreated(){ this.textEl = <Element> this.el.getElementsByTagName("text")[0]; this.updateThumbnail(this.image); if(this.isRobotResponse || this.response != null){ // Robot is pseudo thinking, can also be user --> // , but if addUserChatResponse is called from ConversationalForm, then the value is there, therefore skip ... setTimeout(() =>{ this.setValue(<FlowDTO>{text: this.response}) }, 0); //ConversationalForm.animationsEnabled ? Helpers.lerp(Math.random(), 500, 900) : 0); }else{ if(this.cfReference.uiOptions.user.showThumb){ this.el.classList.add("peak-thumb"); } } } public dealloc(){ clearTimeout(this.readyTimer); this.container = null; this.uiOptions = null; this.onReadyCallback = null; if(this.onClickCallback){ this.el.removeEventListener(Helpers.getMouseEvent("click"), this.onClickCallback, false); this.onClickCallback = null; } super.dealloc(); } // template, can be overwritten ... public getTemplate () : string { return `<cf-chat-response class="` + (this.isRobotResponse ? "robot" : "user") + `"> <thumb><span></span></thumb> <text></text> </cf-chat-response>`; } } }
the_stack
export default escapeFactory import {Node, ReferenceNode} from '../node' import {CompilerOptions, CompilerContext} from './compiler' import entityPrefixLength from './entity-prefix-length' import LIST_BULLETS from './list-bullets' /** * Check whether `character` is alphanumeric. * * @param {string} character - Single character to check. * @return {boolean} - Whether `character` is alphanumeric. */ function isAlphanumeric (character: string): boolean { return /\w/.test(character) && character !== '_' } /* * Entities. */ const ENTITY_AMPERSAND = '&amp;' const ENTITY_BRACKET_OPEN = '&lt;' const ENTITY_COLON = '&#x3A;' /** * Checks if a string starts with HTML entity. * * @example * startsWithEntity('&copycat') // true * startsWithEntity('&foo &amp &bar') // false * * @param {string} value - Value to check. * @return {number} - Whether `value` starts an entity. */ function startsWithEntity (value: string): boolean { return entityPrefixLength(value) > 0 } /** * Check if `character` is a valid alignment row character. * * @example * isAlignmentRowCharacter(':') // true * isAlignmentRowCharacter('=') // false * * @param {string} character - Character to check. * @return {boolean} - Whether `character` is a valid * alignment row character. */ function isAlignmentRowCharacter (character: string): boolean { return character === ':' || character === '-' || character === ' ' || character === '|' } /** * Check if `index` in `value` is inside an alignment row. * * @example * isInAlignmentRow(':--:', 2) // true * isInAlignmentRow(':--:\n:-*-:', 9) // false * * @param {string} value - Value to check. * @param {number} index - Position in `value` to check. * @return {boolean} - Whether `index` in `value` is in * an alignment row. */ function isInAlignmentRow (value: string, index: number): boolean { const start = index while (++index < value.length) { const character = value.charAt(index) if (character === '\n') { break } if (!isAlignmentRowCharacter(character)) { return false } } index = start while (--index > -1) { const character = value.charAt(index) if (character === '\n') { break } if (!isAlignmentRowCharacter(character)) { return false } } return true } /** * Factory to escape characters. * * @example * var escape = escapeFactory({ commonmark: true }); * escape('x*x', { type: 'text', value: 'x*x' }) // 'x\\*x' * * @param {Object} options - Compiler options. * @return {function(value, node, parent): string} - Function which * takes a value and a node and (optionally) its parent and returns * its escaped value. */ function escapeFactory (context: CompilerContext, options: CompilerOptions): Function { /** * Escape punctuation characters in a node's value. * * @param {string} value - Value to escape. * @param {Object} node - Node in which `value` exists. * @param {Object} [parent] - Parent of `node`. * @return {string} - Escaped `value`. */ return function escape (value: string, node: Node, parent?: Node): string { const gfm = options.gfm const commonmark = options.commonmark const pedantic = options.pedantic const siblings = parent && parent.children const index = siblings && siblings.indexOf(node) const prev = siblings && siblings[index - 1] const next = siblings && siblings[index + 1] let length = value.length let position = -1 let queue: Array<string> = [] const escaped = queue let afterNewLine: boolean let character: string if (prev) { afterNewLine = prev.type === 'text' && /\n\s*$/.test(prev.value) } else if (parent) { afterNewLine = parent.type === 'paragraph' } while (++position < length) { character = value.charAt(position) if ( character === '\\' || character === '`' || character === '*' || character === '[' || ( character === '_' && /* * Delegate leading/trailing underscores * to the multinode version below. */ position > 0 && position < length - 1 && ( pedantic || !isAlphanumeric(value.charAt(position - 1)) || !isAlphanumeric(value.charAt(position + 1)) ) ) || (context.inLink && character === ']') || ( gfm && character === '|' && ( context.inTable || isInAlignmentRow(value, position) ) ) ) { afterNewLine = false queue.push('\\') } else if (character === '<') { afterNewLine = false if (commonmark) { queue.push('\\') } else { queue.push(ENTITY_BRACKET_OPEN) continue } } else if ( gfm && !context.inLink && character === ':' && ( queue.slice(-6).join('') === 'mailto' || queue.slice(-5).join('') === 'https' || queue.slice(-4).join('') === 'http' ) ) { afterNewLine = false if (commonmark) { queue.push('\\') } else { queue.push(ENTITY_COLON) continue } /* istanbul ignore if - Impossible to test with * the current set-up. We need tests which try * to force markdown content into the tree. */ } else if ( character === '&' && startsWithEntity(value.slice(position)) ) { afterNewLine = false if (commonmark) { queue.push('\\') } else { queue.push(ENTITY_AMPERSAND) continue } } else if ( gfm && character === '~' && value.charAt(position + 1) === '~' ) { queue.push('\\', '~') afterNewLine = false position += 1 } else if (character === '\n') { afterNewLine = true } else if (afterNewLine) { if ( character === '>' || character === '#' || LIST_BULLETS[character] ) { queue.push('\\') afterNewLine = false } else if ( character !== ' ' && character !== '\t' && character !== '\r' && character !== '\u000B' && character !== '\f' ) { afterNewLine = false } } queue.push(character) } /* * Multi-node versions. */ if (siblings && node.type === 'text') { /* * Check for an opening parentheses after a * link-reference (which can be joined by * white-space). */ if ( prev && (prev as ReferenceNode).referenceType === 'shortcut' ) { position = -1 length = escaped.length while (++position < length) { character = escaped[position] if (character === ' ' || character === '\t') { continue } if (character === '(') { escaped[position] = `\\${character}` } if (character === ':') { if (commonmark) { escaped[position] = `\\${character}` } else { escaped[position] = ENTITY_COLON } } break } } /* * Ensure non-auto-links are not seen as links. * This pattern needs to check the preceding * nodes too. */ if ( gfm && !context.inLink && prev && prev.type === 'text' && value.charAt(0) === ':' ) { const queue = prev.value.slice(-6) if ( queue === 'mailto' || queue.slice(-5) === 'https' || queue.slice(-4) === 'http' ) { if (commonmark) { escaped.unshift('\\') } else { escaped.splice(0, 1, ENTITY_COLON) } } } /* * Escape '&' if it would otherwise * start an entity. */ if ( next && next.type === 'text' && value.slice(-1) === '&' && startsWithEntity(`&${next.value}`) ) { if (commonmark) { escaped.splice(escaped.length - 1, 0, '\\') } else { escaped.push('amp', ';') } } /* * Escape double tildes in GFM. */ if ( gfm && next && next.type === 'text' && value.slice(-1) === '~' && next.value.charAt(0) === '~' ) { escaped.splice(escaped.length - 1, 0, '\\') } /* * Escape underscores, but not mid-word (unless * in pedantic mode). */ const wordCharBefore = ( prev && prev.type === 'text' && isAlphanumeric(prev.value.slice(-1)) ) const wordCharAfter = ( next && next.type === 'text' && isAlphanumeric(next.value.charAt(0)) ) if (length <= 1) { if ( value === '_' && ( pedantic || !wordCharBefore || !wordCharAfter ) ) { escaped.unshift('\\') } } else { if ( value.charAt(0) === '_' && ( pedantic || !wordCharBefore || /* istanbul ignore next - only for trees */ !isAlphanumeric(value.charAt(1)) ) ) { escaped.unshift('\\') } if ( value.slice(-1) === '_' && ( pedantic || !wordCharAfter || /* istanbul ignore next - only for trees */ !isAlphanumeric(value.slice(-2).charAt(0)) ) ) { escaped.splice(escaped.length - 1, 0, '\\') } } } return escaped.join('') } }
the_stack
import * as Assert from "assert"; import { ACAction, ACCarousel, ACColumn, ACColumnSet, ACContainer, ACInputChoiceSet, ACInputDate, ACInputNumber, ACInputText, ACInputTime, ACInputToggle, ACImage, ACElement } from "./card-element-utils"; import { TestUtils } from "./test-utils"; import { WaitUtils } from "./wait-utils"; describe("Mock function", function() { let utils: TestUtils; // This is a constant value for the wait time between pressing an action and retrieving // the input value. Only use this if you see some test flakiness. Value is given in ms const delayForCarouselTimer: number = 6000; const timeOutValueForCarousel: number = 30000; const timeOutValueForSuddenJumpTest: number = 20000; // Timeout of 10 minutes for the dev server to start up in the CI jobs, the dev-server // usually takes between 1 to 2 minutes but we have no way to determine when the server // is ready to run tests. This issues is being tracked in issue #6716 const timeoutForServerStartupInCIBuild: number = 600000; beforeAll(async() => { utils = TestUtils.getInstance(); await utils.initializeDriver(); }, timeoutForServerStartupInCIBuild); afterAll(async() => { await utils.stopDriver(); }); test("Test ActivityUpdate submit", (async() => { await utils.goToTestCase("v1.0/ActivityUpdate"); await ACAction.clickOnActionWithTitle("Set due date"); let dueDateInput = await ACInputDate.getInputWithId("dueDate"); await dueDateInput.setDate(1993, 2, 4); let commentInput = await ACInputText.getInputWithId("comment"); await commentInput.setData("A comment"); await ACAction.clickOnActionWithTitle("OK"); Assert.strictEqual(await utils.getInputFor("dueDate"), "1993-02-04"); Assert.strictEqual(await utils.getInputFor("comment"), "A comment"); })); test("Test TextInput get focus on invalid submit", (async() => { await utils.goToTestCase("v1.3/Input.Text.ErrorMessage"); const commentInput = await ACInputText.getInputWithId("id1"); Assert.strictEqual(await commentInput.getLabel(), "Required Input.Text *"); Assert.strictEqual(await commentInput.isRequired(), true); Assert.strictEqual(await commentInput.getErrorMessage(), undefined); Assert.strictEqual(await commentInput.isFocused(), false); await ACAction.clickOnActionWithTitle("Submit"); Assert.strictEqual(await commentInput.getErrorMessage(), "This is a required input"); Assert.strictEqual(await commentInput.isFocused(), true); })); test("Test interaction with Input.Number", (async() => { await utils.goToTestCase("v1.3/Input.Number.ErrorMessage"); let input1 = await ACInputNumber.getInputWithId("input1"); await input1.setData("1"); let input2 = await ACInputNumber.getInputWithId("input2"); await input2.setData("5"); let input3 = await ACInputNumber.getInputWithId("input3"); await input3.setData("10"); let input4 = await ACInputNumber.getInputWithId("input4"); await input4.setData("50"); await ACAction.clickOnActionWithTitle("Submit"); Assert.strictEqual(await utils.getInputFor("input1"), "1"); Assert.strictEqual(await utils.getInputFor("input2"), "5"); Assert.strictEqual(await utils.getInputFor("input3"), "10"); Assert.strictEqual(await utils.getInputFor("input4"), "50"); })); test("Input.ChoiceSet: Test input interaction", (async() => { await utils.goToTestCase("v1.3/Input.ChoiceSet.ErrorMessage"); let compactChoiceSet = await ACInputChoiceSet.getInputWithId("requiredCompactId", false, false); await compactChoiceSet.setData("Option 1"); let expandedChoiceSet = await ACInputChoiceSet.getInputWithId("requiredExpandedId", true, false); await expandedChoiceSet.setData("Option 2"); let multiselectChoiceSet = await ACInputChoiceSet.getInputWithId("requiredMultiselectId", true, true); await multiselectChoiceSet.setData("Option 1,Option 2"); await ACAction.clickOnActionWithTitle("OK"); Assert.strictEqual(await utils.getInputFor("requiredCompactId"), "1"); Assert.strictEqual(await utils.getInputFor("requiredExpandedId"), "2"); Assert.strictEqual(await utils.getInputFor("requiredMultiselectId"), "1,2"); })); test("Input.ChoiceSet: Test compact required validation", (async() => { await utils.goToTestCase("v1.3/Input.ChoiceSet.ErrorMessage"); const compactChoiceSet = await ACInputChoiceSet.getInputWithId("requiredCompactId", false, false); Assert.strictEqual(await compactChoiceSet.getLabel(), "Required Input.ChoiceSet label (compact) *"); Assert.strictEqual(await compactChoiceSet.isRequired(), true); Assert.strictEqual(await compactChoiceSet.getErrorMessage(), undefined); await ACAction.clickOnActionWithTitle("OK"); Assert.strictEqual(await compactChoiceSet.validationFailed(), true); Assert.strictEqual(await compactChoiceSet.getErrorMessage(), "This is a required input"); })); test("Input.ChoiceSet: Test expanded required validation", (async() => { await utils.goToTestCase("v1.3/Input.ChoiceSet.ErrorMessage"); const expandedChoiceSet = await ACInputChoiceSet.getInputWithId("requiredExpandedId", true, false); Assert.strictEqual(await expandedChoiceSet.getLabel(), "Required Input.ChoiceSet label (expanded) *"); Assert.strictEqual(await expandedChoiceSet.isRequired(), true); Assert.strictEqual(await expandedChoiceSet.getErrorMessage(), undefined); await ACAction.clickOnActionWithTitle("OK"); Assert.strictEqual(await expandedChoiceSet.validationFailed(), true); Assert.strictEqual(await expandedChoiceSet.getErrorMessage(), "This is a required input"); })); test("Input.ChoiceSet: Test multiselect required validation", (async() => { await utils.goToTestCase("v1.3/Input.ChoiceSet.ErrorMessage"); const multiselectChoiceSet = await ACInputChoiceSet.getInputWithId("requiredMultiselectId", true, true); Assert.strictEqual(await multiselectChoiceSet.getLabel(), "Required Input.ChoiceSet label (expanded, multiselect) *"); Assert.strictEqual(await multiselectChoiceSet.isRequired(), true); Assert.strictEqual(await multiselectChoiceSet.getErrorMessage(), undefined); await ACAction.clickOnActionWithTitle("OK"); Assert.strictEqual(await multiselectChoiceSet.validationFailed(), true); Assert.strictEqual(await multiselectChoiceSet.getErrorMessage(), "This is a required input"); })); test("Test interaction with Input.Time", (async() => { await utils.goToTestCase("v1.3/Input.Time.ErrorMessage"); let timeInput1 = await ACInputTime.getInputWithId("input1"); await timeInput1.setTime(1, 9); let timeInput4 = await ACInputTime.getInputWithId("input4"); await timeInput4.setTime(14, 30); await ACAction.clickOnActionWithTitle("OK"); Assert.strictEqual(await utils.getInputFor("input1"), "01:09"); Assert.strictEqual(await utils.getInputFor("input4"), "14:30"); })); test("Test interaction with Input.Toggle", (async() => { await utils.goToTestCase("v1.3/Input.Toggle.ErrorMessage"); let toggleInput = await ACInputToggle.getInputWithId("input2"); await toggleInput.set(); await ACAction.clickOnActionWithTitle("OK"); Assert.strictEqual(await utils.getInputFor("input2"), "true"); })); test("Action.ShowCard: Test hidden card is shown", (async() => { await utils.goToTestCase("v1.0/Action.ShowCard"); await ACAction.clickOnActionWithTitle("Action.ShowCard"); const neatAction: ACAction = await ACAction.getActionWithTitle("Neat!"); const neatActionIsVisible = async (params: any) => { let elements = params as ACElement[]; return (await elements[0].elementIsVisible()) || (await elements[0].elementIsCssVisible()); }; await WaitUtils.waitUntilPredicateIsTrue([neatAction], neatActionIsVisible); await neatAction.click(); Assert.strictEqual(await utils.getInputFor("neat"), "true"); })); test("Image: Test select action can be clicked", (async() => { await utils.goToTestCase("v1.0/Image.SelectAction"); let image = await ACImage.getImage("cool link"); await image.click(); Assert.strictEqual(await utils.getUrlInRetrievedInputs(), "https://www.youtube.com/watch?v=dQw4w9WgXcQ"); })); test("Column: Test select action can be clicked", (async() => { await utils.goToTestCase("v1.0/Column.SelectAction"); let firstColumn = await ACColumn.getContainerWithAction("cool link"); await firstColumn.click(); Assert.strictEqual(await utils.getUrlInRetrievedInputs(), "https://www.youtube.com/watch?v=dQw4w9WgXcQ"); })); test("ColumnSet: Test select action can be clicked", (async() => { await utils.goToTestCase("v1.0/ColumnSet.SelectAction"); let secondColumnSet = await ACColumnSet.getContainerWithAction("Remodel your kitchen with our new cabinet styles!"); await secondColumnSet.click(); Assert.strictEqual(await utils.getUrlInRetrievedInputs(), "https://www.AdaptiveCards.io"); })); test("Container: Test select action can be clicked", (async() => { await utils.goToTestCase("v1.0/Container.SelectAction"); let submitContainer = await ACContainer.getContainerWithAction("Submit action"); await submitContainer.click(); Assert.strictEqual(await utils.getInputFor("info"), "My submit action data"); let emphasisContainer = await ACContainer.getContainerWithAction("Go to a different url"); await emphasisContainer.click(); Assert.strictEqual(await utils.getUrlInRetrievedInputs(), "https://msn.com"); })); test("Carousel: Test actions are rendered and active", (async() => { await utils.goToTestCase("v1.6/Carousel.HostConfig"); await ACAction.clickOnActionWithTitle("See more"); Assert.strictEqual(await utils.getUrlInRetrievedInputs(), "https://adaptivecards.io"); })); test("Carousel: Test page limit is honoured", (async() => { await utils.goToTestCase("v1.6/Carousel.HostConfig"); await utils.assertElementWithIdDoesNotExist("page10"); })); test("Carousel: Unsupported elements are not rendered", (async() => { await utils.goToTestCase("v1.6/Carousel.ForbiddenElements"); await utils.assertElementWithIdDoesNotExist("id1"); await utils.assertElementWithIdDoesNotExist("id2"); await utils.assertElementWithIdDoesNotExist("id3"); await utils.assertElementWithIdDoesNotExist("id4"); await utils.assertElementWithIdDoesNotExist("id5"); await utils.assertElementWithIdDoesNotExist("id6"); await utils.assertElementWithIdDoesNotExist("id7"); })); test("Carousel: Verify left and right buttons work", (async() => { await utils.goToTestCase("v1.6/Carousel.ScenarioCards"); let firstPageIsVisible = await ACCarousel.isPageVisible("firstCarouselPage"); Assert.strictEqual(firstPageIsVisible, true); await ACCarousel.clickOnRightArrow(); await WaitUtils.waitUntilElementIsCssVisible("theSecondCarouselPage", delayForCarouselTimer); let secondPageIsVisible = await ACCarousel.isPageVisible("theSecondCarouselPage"); Assert.strictEqual(secondPageIsVisible, true); await ACCarousel.waitForAnimationsToEnd(); await ACCarousel.clickOnLeftArrow(); await WaitUtils.waitUntilElementIsCssVisible("firstCarouselPage"); firstPageIsVisible = await ACCarousel.isPageVisible("firstCarouselPage"); Assert.strictEqual(firstPageIsVisible, true); }), timeOutValueForSuddenJumpTest); test("Carousel: Unsupported actions are not rendered", (async() => { await utils.goToTestCase("v1.6/Carousel.ForbiddenActions"); let showCardAction = await ACAction.getActionWithTitle("Action.ShowCard"); Assert.strictEqual(showCardAction.elementWasFound(), false); let toggleVisibilityAction = await ACAction.getActionWithTitle("Action.ToggleVisibility"); Assert.strictEqual(toggleVisibilityAction.elementWasFound(), false); })); // Giving this test 7 seconds to run test("Carousel: Test autoplay is disabled", (async() => { await utils.goToTestCase("v1.6/Carousel.ScenarioCards"); let firstPageIsVisible = await ACCarousel.isPageVisible("firstCarouselPage"); Assert.strictEqual(firstPageIsVisible, true); // Await for 5 seconds and verify no change happened await WaitUtils.waitFor(5000); firstPageIsVisible = await ACCarousel.isPageVisible("firstCarouselPage"); Assert.strictEqual(firstPageIsVisible, true); }), 7000); // Giving this test 9 seconds to run test("Carousel: Test autoplay is applied", (async() => { await utils.goToTestCase("v1.6/Carousel.ScenarioCards.Timer"); let firstPageIsVisible = await ACCarousel.isPageVisible("firstCarouselPage"); Assert.strictEqual(firstPageIsVisible, true); // Await for 5 seconds and verify the first page is now hidden await WaitUtils.waitUntilElementIsNotVisible("firstCarouselPage"); firstPageIsVisible = await ACCarousel.isPageVisible("firstCarouselPage"); Assert.strictEqual(firstPageIsVisible, false); let secondPageIsVisible = await ACCarousel.isPageVisible("theSecondCarouselPage"); Assert.strictEqual(secondPageIsVisible, true); }), timeOutValueForCarousel); test("Carousel: Test click on navigation does not cause sudden jump", (async() => { await utils.goToTestCase("v1.6/Carousel"); let firstPageIsVisible = await ACCarousel.isPageVisible("firstCarouselPage"); Assert.strictEqual(firstPageIsVisible, true); // wait for 2 pages to turn await WaitUtils.waitUntilElementIsCssVisible("last-carousel-page", delayForCarouselTimer * 2); firstPageIsVisible = await ACCarousel.isPageVisible("firstCarouselPage"); Assert.strictEqual(firstPageIsVisible, false); let lastPageIsVisible = await ACCarousel.isPageVisible("last-carousel-page"); Assert.strictEqual(lastPageIsVisible, true); // cause the page to go the 2nd page await ACCarousel.waitForAnimationsToEnd(); await ACCarousel.clickOnLeftArrow(); await WaitUtils.waitUntilElementIsCssVisible("theSecondCarouselPage"); // make sure firstCarouselPage is hidden firstPageIsVisible = await ACCarousel.isPageVisible("firstCarouselPage"); Assert.strictEqual(firstPageIsVisible, false); }), timeOutValueForSuddenJumpTest); test("Carousel: Test rtl", (async() => { await utils.goToTestCase("v1.6/Carousel.rtl"); for (const page of [["firstCarouselPage", "rtl"], ["secondCarouselPage", "ltr"], ["thirdCarouselPage", "rtl"]]){ const pageDirection = await ACCarousel.getPageDirection(page[0]) Assert.strictEqual(pageDirection, page[1]); } }), timeOutValueForCarousel); });
the_stack
module WinJSTests { "use strict"; var pageSelectedEvent = "pagecompleted"; // Create NavigationTests object export class NavigationTests { // // Function: SetUp // setUp() { LiveUnit.LoggingCore.logComment("In setup"); Helper.getIEInfo(); // We want to recreate the flipper element between each test so we start fresh. FlipperUtils.addFlipperDom(); } // // Function: tearDown // tearDown() { LiveUnit.LoggingCore.logComment("In tearDown"); // We want to tear town the flipper element between each test so we start fresh. FlipperUtils.removeFlipperDom(); } // // Test: testFlipperNext // testFlipperNext = function (signalTestCaseCompleted) { var flipper = FlipperUtils.instantiate(FlipperUtils.basicFlipperID()); var currentPage = flipper.currentPage; LiveUnit.LoggingCore.logComment("Current Page Before Next: " + currentPage); LiveUnit.Assert.isTrue(currentPage === 0, "Flipper didn't start at Index 0"); var verify = LiveUnit.GetWrappedCallback(function () { flipper.removeEventListener(pageSelectedEvent, verify); if (!FlipperUtils.ensureNext(flipper, signalTestCaseCompleted)) { LiveUnit.Assert.fail("Unable to flip to next."); } }); flipper.addEventListener(pageSelectedEvent, verify); } // // Test: testFlipperPrevious // testFlipperPrevious = function (signalTestCaseCompleted) { var startPage = 5; var flipper = FlipperUtils.instantiate(FlipperUtils.basicFlipperID(), { currentPage: startPage }); var currentPage = flipper.currentPage; LiveUnit.Assert.areEqual(currentPage, startPage, "Failed to instantiate flipper with " + " a start page of " + startPage); LiveUnit.LoggingCore.logComment("Current Page Before Previous: " + currentPage); var verify = LiveUnit.GetWrappedCallback(function () { flipper.removeEventListener(pageSelectedEvent, verify); if (!FlipperUtils.ensurePrevious(flipper, signalTestCaseCompleted)) { LiveUnit.Assert.fail("Unable to flip to previous."); } }); flipper.addEventListener(pageSelectedEvent, verify); } // // Test: testFlipperCurrentPage via setting currentPage // testFlipperCurrentPage = function (signalTestCaseCompleted) { var flipper = FlipperUtils.instantiate(FlipperUtils.basicFlipperID()); var cachedPage = 2; var currentPage = flipper.currentPage; LiveUnit.LoggingCore.logComment("Attempting to flip to page in cache (" + cachedPage + ")..."); LiveUnit.LoggingCore.logComment("Current page before flip: " + currentPage); var verify = LiveUnit.GetWrappedCallback(function () { flipper.removeEventListener(pageSelectedEvent, verify); FlipperUtils.ensureCurrentPage(flipper, cachedPage, LiveUnit.GetWrappedCallback(TestCurrentPageInitial)); }); flipper.addEventListener(pageSelectedEvent, verify); function TestCurrentPageInitial() { currentPage = flipper.currentPage; LiveUnit.LoggingCore.logComment("Current page after flip: " + currentPage); LiveUnit.Assert.areEqual(cachedPage, flipper.currentPage, "Page after flip should be: " + cachedPage); LiveUnit.LoggingCore.logComment("Attempt to flip to adjacent page..."); FlipperUtils.ensureCurrentPage(flipper, cachedPage + 1, LiveUnit.GetWrappedCallback(TestCurrentPageAdjacent)); function TestCurrentPageAdjacent() { currentPage = flipper.currentPage; var notCachedPage = currentPage - (cachedPage + 1); LiveUnit.LoggingCore.logComment("Current page after flip: " + currentPage); LiveUnit.Assert.areEqual(cachedPage + 1, currentPage, "Page after flip should be: " + (cachedPage + 1)); LiveUnit.LoggingCore.logComment("Attempt to flip to page outside of cache: " + notCachedPage); FlipperUtils.ensureCurrentPage(flipper, notCachedPage, LiveUnit.GetWrappedCallback(TestCurrentPageNotCached)); function TestCurrentPageNotCached() { LiveUnit.LoggingCore.logComment("Current page after flip: " + flipper.currentPage); LiveUnit.Assert.areEqual(notCachedPage, flipper.currentPage, "Page after flip should be: " + notCachedPage); signalTestCaseCompleted(); } } } } // // Test: testFlipperJumpToSamePage via setting currentPage // testFlipperJumpToSamePage = function (signalTestCaseCompleted) { var flipper = FlipperUtils.instantiate(FlipperUtils.basicFlipperID()); var page = flipper.currentPage; var eventTriggered = false; var pageVisibilityEventTriggered = LiveUnit.GetWrappedCallback(function () { eventTriggered = true; flipper.removeEventListener("pagevisibilitychanged", pageVisibilityEventTriggered, false); LiveUnit.LoggingCore.logComment("Current Page: " + flipper.currentPage); LiveUnit.LoggingCore.logComment("Tried to jump to page " + page); LiveUnit.LoggingCore.logComment("Event for pagevisibility was fired which should not have occured."); }); var verify = LiveUnit.GetWrappedCallback(function () { flipper.removeEventListener(pageSelectedEvent, verify); LiveUnit.LoggingCore.logComment("Attempting to flip to same page (same as current): " + page); flipper.addEventListener("pagevisibilitychanged", pageVisibilityEventTriggered, false); flipper.currentPage = page; }); flipper.addEventListener(pageSelectedEvent, verify); setTimeout(LiveUnit.GetWrappedCallback(function () { flipper.removeEventListener("pagevisibilitychanged", pageVisibilityEventTriggered, false); if (eventTriggered) { LiveUnit.Assert.fail("Event for pagevisibility was fired which should not have occured."); } else { LiveUnit.LoggingCore.logComment("It appears that currentPage did not trigger the " + " pagevisibility event as expected."); signalTestCaseCompleted(); } }), FlipperUtils.NAVIGATION_TIMEOUT); } // // Test: testFlipperNextBorder // testFlipperNextBorder = function (signalTestCaseCompleted) { var flipper = FlipperUtils.instantiate(FlipperUtils.basicFlipperID(), { currentPage: 6 }); var curPage = flipper.currentPage; var eventTriggered = false; var returnValue; var pageVisibilityEventTriggered = LiveUnit.GetWrappedCallback(function () { eventTriggered = true; flipper.removeEventListener("pagevisibilitychanged", pageVisibilityEventTriggered, false); LiveUnit.LoggingCore.logComment("Current Page: " + flipper.currentPage); LiveUnit.LoggingCore.logComment("Tried to flip to next page."); }); if (curPage != 6) { LiveUnit.Assert.fail("Unable to stage for border test"); } var verify = LiveUnit.GetWrappedCallback(function () { flipper.removeEventListener(pageSelectedEvent, verify); LiveUnit.LoggingCore.logComment("Current Page Before flipping to Next page: " + curPage); flipper.addEventListener("pagevisibilitychanged", pageVisibilityEventTriggered, false); returnValue = flipper.next(); }); flipper.addEventListener(pageSelectedEvent, verify); setTimeout(LiveUnit.GetWrappedCallback(function () { flipper.removeEventListener("pagevisibilitychanged", pageVisibilityEventTriggered, false); LiveUnit.LoggingCore.logComment("Next method returned: " + returnValue); if (eventTriggered) { LiveUnit.Assert.fail("Event for pagevisibility was fired which should not have occured."); } else { LiveUnit.LoggingCore.logComment("It appears that next() did not trigger the pagevisibility event as expected."); } if (returnValue) { LiveUnit.Assert.fail("Next method should not have returned " + returnValue); } else { LiveUnit.LoggingCore.logComment("Current Page After Attempt To Flip: " + flipper.currentPage); LiveUnit.Assert.areEqual(flipper.currentPage, curPage, "Should not be able to flip past last page."); LiveUnit.LoggingCore.logComment("SUCCESS: Unable to flip to Next page."); signalTestCaseCompleted(); } }), FlipperUtils.NAVIGATION_TIMEOUT); } // // Test: testFlipperPreviousBorder // testFlipperPreviousBorder = function (signalTestCaseCompleted) { var flipper = FlipperUtils.instantiate(FlipperUtils.basicFlipperID()); var curPage = flipper.currentPage; var eventTriggered = false; var returnValue; var pageVisibilityEventTriggered = LiveUnit.GetWrappedCallback(function () { eventTriggered = true; flipper.removeEventListener("pagevisibilitychanged", pageVisibilityEventTriggered, false); LiveUnit.LoggingCore.logComment("Current Page: " + flipper.currentPage); LiveUnit.LoggingCore.logComment("Tried to flip to next page."); }); var verify = LiveUnit.GetWrappedCallback(function () { flipper.removeEventListener(pageSelectedEvent, verify); LiveUnit.LoggingCore.logComment("Current Page Before flipping to Previous page: " + curPage); flipper.addEventListener("pagevisibilitychanged", pageVisibilityEventTriggered, false); returnValue = flipper.previous(); }); flipper.addEventListener(pageSelectedEvent, verify); setTimeout(LiveUnit.GetWrappedCallback(function () { flipper.removeEventListener("pagevisibilitychanged", pageVisibilityEventTriggered, false); LiveUnit.LoggingCore.logComment("Previous method returned: " + returnValue); if (eventTriggered) { LiveUnit.Assert.fail("Event for pagevisibility was fired which should not have occured."); } else { LiveUnit.LoggingCore.logComment("It appears that previous() did not trigger the pagevisibility event as expected."); } if (returnValue) { LiveUnit.Assert.fail("Previous method should not have returned " + returnValue); } else { LiveUnit.LoggingCore.logComment("Current Page After Attempt To Flip: " + flipper.currentPage); LiveUnit.Assert.areEqual(flipper.currentPage, curPage, "Should not be able to flip before first page."); LiveUnit.LoggingCore.logComment("SUCCESS: Unable to flip to Previous page."); signalTestCaseCompleted(); } }), FlipperUtils.NAVIGATION_TIMEOUT); } // // Test: testFlipperJumpToInvalidPage via currentPage // testFlipperJumpToInvalidPage = function (signalTestCaseCompleted) { var flipper = FlipperUtils.instantiate(FlipperUtils.basicFlipperID()); var startPage = flipper.currentPage; var page = 500; var eventTriggered = false; var pageVisibilityEventTriggered = LiveUnit.GetWrappedCallback(function () { eventTriggered = true; flipper.removeEventListener("pagevisibilitychanged", pageVisibilityEventTriggered, false); LiveUnit.LoggingCore.logComment("Current Page: " + flipper.currentPage); LiveUnit.LoggingCore.logComment("Tried to jump to page " + page); }); var verify = LiveUnit.GetWrappedCallback(function () { flipper.removeEventListener(pageSelectedEvent, verify); flipper.addEventListener("pagevisibilitychanged", pageVisibilityEventTriggered, false); LiveUnit.LoggingCore.logComment("Attempt to set currentPage: " + page); LiveUnit.LoggingCore.logComment("Current Page Before Flip: " + flipper.currentPage); flipper.currentPage = page; }); flipper.addEventListener(pageSelectedEvent, verify); setTimeout(LiveUnit.GetWrappedCallback(function () { flipper.removeEventListener("pagevisibilitychanged", pageVisibilityEventTriggered, false); if (eventTriggered) { // There are 7 pages in the flipper var lastPageIndex = 6; LiveUnit.Assert.areEqual(lastPageIndex, flipper.currentPage, "Current page: " + flipper.currentPage + " after navigating to an out of range index is not the last page: " + lastPageIndex); signalTestCaseCompleted(); } else { LiveUnit.LoggingCore.logComment("It appears that setting the currentPage to " + page + " did not trigger the pagevisibility event as expected"); LiveUnit.LoggingCore.logComment("Current Page After Attempt To Flip: " + flipper.currentPage); } }), FlipperUtils.NAVIGATION_TIMEOUT); } // // Test: testFlipperJumpToRandom // testFlipperJumpToRandom = function (signalTestCaseCompleted) { var flipper = FlipperUtils.instantiate(FlipperUtils.basicFlipperID()); var flipperSize = 7; var jumpCount = 0; var oldPage = flipper.currentPage; var pageToJumpTo = pseudorandom(flipperSize); function pseudorandom(upto) { return Math.floor(Math.random() * upto); } var nextJumpCallBack = function () { LiveUnit.Assert.areEqual(flipper.currentPage, pageToJumpTo, "Jumped from " + oldPage + " to " + pageToJumpTo); if (jumpCount < 30) { jumpCount++; oldPage = flipper.currentPage; do { pageToJumpTo = pseudorandom(flipperSize); } while (pageToJumpTo === oldPage); LiveUnit.LoggingCore.logComment("Jumping from " + oldPage + " to " + pageToJumpTo); FlipperUtils.ensureCurrentPage(flipper, pageToJumpTo, nextJumpCallBack); } else { signalTestCaseCompleted(); } }; var verify = LiveUnit.GetWrappedCallback(function () { flipper.removeEventListener(pageSelectedEvent, verify); LiveUnit.Assert.areEqual(flipper.currentPage, 0, "Flipper started at current page"); LiveUnit.LoggingCore.logComment("Jumping from " + oldPage + " to " + pageToJumpTo); while (pageToJumpTo === oldPage) { pageToJumpTo = pseudorandom(flipperSize); } FlipperUtils.ensureCurrentPage(flipper, pageToJumpTo, nextJumpCallBack); }); flipper.addEventListener(pageSelectedEvent, verify); } // // Test: testFlipperItemVisible // testFlipperItemVisible = function (signalTestCaseCompleted) { var flipper = FlipperUtils.instantiate(FlipperUtils.basicFlipperID()), pages = FlipperUtils.basicFlipperHtmlIDs(); var checkVisibleItems = LiveUnit.GetWrappedCallback(function (flipDir) { var currentPage = flipper.currentPage; LiveUnit.LoggingCore.logComment("Current Page After Flip " + flipDir + ": " + currentPage); LiveUnit.LoggingCore.logComment("Check all pages, ensure " + pages[currentPage] + " is the only page that is visible via DOM."); for (var pageIndex in pages) { LiveUnit.LoggingCore.logComment("Testing " + pages[pageIndex] + " vs. " + pages[currentPage]); if (FlipperUtils.isFlipperItemVisible(pages[pageIndex])) { if (pages[pageIndex] !== pages[currentPage]) { LiveUnit.Assert.fail(pages[pageIndex] + ": Should NOT be in view, but it is."); } } else { if (pages[pageIndex] === pages[currentPage]) { LiveUnit.Assert.fail(pages[pageIndex] + ": Should be in view, but it is not."); } } } if (flipDir === 'next') { if (currentPage < pages.length - 1) { if (FlipperUtils.ensureNext(flipper, nextCompleted)) { LiveUnit.LoggingCore.logComment("Flip to next page returned true."); } else { LiveUnit.Assert.fail("Flip to next page failed."); } } else { if (FlipperUtils.ensurePrevious(flipper, previousCompleted)) { LiveUnit.LoggingCore.logComment("Flip to previous page returned true."); } else { LiveUnit.Assert.fail("Flip to previous page failed."); } } } else { if (currentPage > 0) { if (FlipperUtils.ensurePrevious(flipper, previousCompleted)) { LiveUnit.LoggingCore.logComment("Flip to previous page returned true."); } else { LiveUnit.Assert.fail("Flip to previous page failed."); } } else { signalTestCaseCompleted(); } } }); var nextCompleted = LiveUnit.GetWrappedCallback(function () { checkVisibleItems("next"); }); var previousCompleted = LiveUnit.GetWrappedCallback(function () { checkVisibleItems("previous"); }); var verify = LiveUnit.GetWrappedCallback(function () { flipper.removeEventListener(pageSelectedEvent, verify); if (FlipperUtils.ensureNext(flipper, nextCompleted)) { LiveUnit.LoggingCore.logComment("Flip to next page returned true."); } else { LiveUnit.Assert.fail("Flip to next page failed."); } }); flipper.addEventListener(pageSelectedEvent, verify); } } } // Register the object as a test class by passing in the name LiveUnit.registerTestClass("WinJSTests.NavigationTests");
the_stack
export namespace StandardAdditions { // Default Application export interface Application {} // Class /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A file object specified with a POSIX (slash)-style pathname. */ export interface POSIXFile { /** * the POSIX (slash)-style path of a file or alias object */ POSIXPath(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A Uniform Resource Locator or Uniform Resource ID (URI) */ export interface URL { /** * property that allows getting and setting of multiple properties */ properties(): any; /** * a name given to this URL, usually the name of the page it refers to */ name(): string; /** * the access scheme */ scheme(): any; /** * the host specified by this URL */ host(): any; /** * the location of the target on the host */ path(): string; /** * the user name by which to access this URL */ userName(): string; /** * the password by which to access this URL */ password(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An Internet or Intranet address for the TCP/IP protocol */ export interface InternetAddress { /** * property that allows getting and setting of multiple properties */ properties(): any; /** * the Domain Name System form of the address (e.g. apple.com) */ DNSForm(): string; /** * the dotted-decimal form of the address (e.g. 17.255.1.1) */ dottedDecimalForm(): string; /** * the port number of the requested TCP/IP service */ port(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A web page in HyperText Markup Language form */ export interface WebPage { /** * property that allows getting and setting of multiple properties */ properties(): any; /** * the name of the web page */ name(): string; /** * the universal resource locator for this page */ URL(): any; /** * the text encoding method used for this page */ textEncoding(): string; } // CLass Extension // Records /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Reply record for the ‘display alert’ command */ export interface AlertReply { /** * name of button chosen (empty if ‘giving up after’ was supplied and alert timed out) */ buttonReturned(): string; /** * Did the alert time out? (present only if ‘giving up after’ was supplied) */ gaveUp(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Reply record for the ‘display dialog’ command */ export interface DialogReply { /** * name of button chosen (empty if ‘giving up after’ was supplied and dialog timed out) */ buttonReturned(): string; /** * text entered (present only if ‘default answer’ was supplied) */ textReturned(): string; /** * Did the dialog time out? (present only if ‘giving up after’ was supplied) */ gaveUp(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Reply record for the ‘info for’ command */ export interface FileInformation { /** * the name of the item */ name(): string; /** * the user-visible name of the item */ displayedName(): string; /** * the short name (CFBundleName) of the item (if the item is an application) */ shortName(): string; /** * the name extension of the item (such as “txt”) */ nameExtension(): string; /** * the item’s bundle identifier (if the item is a package) */ bundleIdentifier(): string; /** * the item’s type identifier */ typeIdentifier(): string; /** * the kind of the item */ kind(): string; /** * the application that normally opens this kind of item */ defaultApplication(): any; /** * the date the item was created */ creationDate(): any; /** * the date the item was last modified */ modificationDate(): any; /** * the file type of the item */ fileType(): string; /** * the creator type of the item */ fileCreator(): string; /** * the item’s short version string (from the Finder’s ‘Get Info’ box) */ shortVersion(): string; /** * the item’s long version string (from the Finder’s ‘Get Info’ box) */ longVersion(): string; /** * the size of the item in bytes */ size(): number; /** * Is the item an alias file? */ alias(): boolean; /** * Is the item a folder? */ folder(): boolean; /** * Is the item a package (a folder treated as a file?) */ packageFolder(): boolean; /** * Is the item’s name extension hidden from the user? */ extensionHidden(): boolean; /** * Is the item visible? */ visible(): boolean; /** * Is the item locked? */ locked(): boolean; /** * Is the item currently in use? */ busyStatus(): boolean; /** * the coordinates of the folder’s window (if the item is a folder) */ folderWindow(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Reply record for the ‘get volume settings’ command */ export interface VolumeSettings { /** * the sound output volume */ outputVolume(): number; /** * the sound input volume */ inputVolume(): number; /** * the alert volume (as a percentage of the output volume) */ alertVolume(): number; /** * Is the sound output muted? */ outputMuted(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Reply record for the ‘system info’ command */ export interface SystemInformation { /** * the AppleScript version */ appleScriptVersion(): string; /** * the AppleScript Studio version */ appleScriptStudioVersion(): string; /** * the system version */ systemVersion(): string; /** * the current user’s short name */ shortUserName(): string; /** * the current user’s long name */ longUserName(): string; /** * the current user’s ID */ userID(): number; /** * the current user’s locale */ userLocale(): string; /** * the current user’s home directory */ homeDirectory(): any; /** * the boot volume */ bootVolume(): string; /** * the computer name */ computerName(): string; /** * the host name */ hostName(): string; /** * the IPv4 address */ IPv4Address(): string; /** * the primary Ethernet address */ primaryEthernetAddress(): string; /** * the CPU type */ CPUType(): string; /** * the clock speed of the CPU in MHz */ CPUSpeed(): number; /** * the amount of physical RAM in MB */ physicalMemory(): number; } // Function options /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ChooseApplicationOptionalParameter { /** * the dialog window title */ withTitle?: string; /** * the prompt to be displayed in the dialog box */ withPrompt?: string; /** * Allow multiple items to be selected? (default is false) */ multipleSelectionsAllowed?: boolean; /** * the desired type of result. May be application (the default) or alias. */ as?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ChooseColorOptionalParameter { /** * the default color */ defaultColor?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ChooseFileOptionalParameter { /** * the prompt to be displayed in the dialog box */ withPrompt?: string; /** * a list of file types or type identifiers. Only files of the specified types will be selectable. */ ofType?: any; /** * the default file location */ defaultLocation?: any; /** * Show invisible files and folders? (default is false) */ invisibles?: boolean; /** * Allow multiple items to be selected? (default is false) */ multipleSelectionsAllowed?: boolean; /** * Show the contents of packages? (Packages will be treated as folders. Default is false.) */ showingPackageContents?: boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ChooseFileNameOptionalParameter { /** * the prompt to be displayed in the dialog box */ withPrompt?: string; /** * the default name for the new file */ defaultName?: string; /** * the default file location */ defaultLocation?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ChooseFolderOptionalParameter { /** * the prompt to be displayed in the dialog box */ withPrompt?: string; /** * the default folder location */ defaultLocation?: any; /** * Show invisible files and folders? (default is false) */ invisibles?: boolean; /** * Allow multiple items to be selected? (default is false) */ multipleSelectionsAllowed?: boolean; /** * Show the contents of packages? (Packages will be treated as folders. Default is false.) */ showingPackageContents?: boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ChooseFromListOptionalParameter { /** * the dialog window title */ withTitle?: string; /** * the prompt to be displayed in the dialog box */ withPrompt?: string; /** * a list of items to initially select (an empty list if no selection) */ defaultItems?: any; /** * the name of the OK button */ OKButtonName?: string; /** * the name of the Cancel button */ cancelButtonName?: string; /** * Allow multiple items to be selected? */ multipleSelectionsAllowed?: boolean; /** * Can the user make no selection and then choose OK? */ emptySelectionAllowed?: boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ChooseRemoteApplicationOptionalParameter { /** * the dialog window title */ withTitle?: string; /** * the prompt to be displayed above the list of applications */ withPrompt?: string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ChooseUrlOptionalParameter { /** * which network services to show */ showing?: any; /** * Allow user to type in a URL? */ editableURL?: boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface DisplayAlertOptionalParameter { /** * the explanatory message (will be displayed in small system font) */ message?: string; /** * the type of alert (default is informational) */ as?: any; /** * a list of up to three button names */ buttons?: any; /** * the name or number of the default button */ defaultButton?: any; /** * the name or number of the cancel button */ cancelButton?: any; /** * number of seconds to wait before automatically dismissing the alert */ givingUpAfter?: number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface DisplayDialogOptionalParameter { /** * the default editable text */ defaultAnswer?: string; /** * Should editable text be displayed as bullets? (default is false) */ hiddenAnswer?: boolean; /** * a list of up to three button names */ buttons?: any; /** * the name or number of the default button */ defaultButton?: any; /** * the name or number of the cancel button */ cancelButton?: any; /** * the dialog window title */ withTitle?: string; /** * …or an alias or file reference to a ‘.icns’ file */ withIcon?: any; /** * number of seconds to wait before automatically dismissing the dialog */ givingUpAfter?: number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface DisplayNotificationOptionalParameter { /** * the title of the notification (default is the name of the calling application). */ withTitle?: string; /** * the subtitle of the notification */ subtitle?: string; /** * the name of the sound to play */ soundName?: string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface SayOptionalParameter { /** * the text to display in the feedback window (if different). Ignored unless Speech Recognition is on. */ displaying?: string; /** * the voice to speak with. (Default is the system voice.) */ using?: string; /** * the rate of speech in words per minute. Average human speech occurs at a rate of 180 to 220 words per minute. (Default depends on the voice used. If “using” is not given, the system speaking rate is the default.) */ speakingRate?: number; /** * the base pitch frequency, a real number from 0 to 127. Values correspond to MIDI note values, where 60 is equal to middle C. Typical pitches range from around 30 to 40 for a low-pitched male voice to perhaps 55 to 65 for a high-pitched child’s voice. */ pitch?: number; /** * the pitch modulation, a real number from 0 to 127. A value of 0 corresponds to a monotone in which all speech is at the base speech pitch. Given a pitch value of 46, a modulation of 2 means the widest range of pitches would be 44 to 48. */ modulation?: number; /** * the volume, a real number from 0 to 1 (default is the system volume). */ volume?: number; /** * stop any current speech before starting (default is false). When false, “say” waits for previous speech commands to complete before beginning to speak. */ stoppingCurrentSpeech?: boolean; /** * wait for speech to complete before returning (default is true). */ waitingUntilCompletion?: boolean; /** * the alias, file reference or path string of an AIFF file (existing or not) to contain the sound output. */ savingTo?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface InfoForOptionalParameter { /** * Return the size of the file or folder? (default is true) */ size?: boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ListFolderOptionalParameter { /** * List invisible files? (default is true) */ invisibles?: boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface MountVolumeOptionalParameter { /** * the server on which the volume resides; omit if URL path provided */ onServer: string; /** * the AppleTalk zone in which the server resides; omit if URL path provided */ inAppleTalkZone?: string; /** * the user name with which to log in to the server; omit for guest access */ asUserName?: string; /** * the password for the user name; omit for guest access */ withPassword?: string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface PathToOptionalParameter { /** * the type to return: alias or string (default is alias) */ as?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface PathToOptionalParameter1 { /** * where to look for the indicated folder */ from?: any; /** * the type to return: alias or string (default is alias) */ as?: any; /** * Create the folder if it doesn’t exist? (default is true) */ folderCreation?: boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface PathToResourceOptionalParameter { /** * an alias or file reference to the bundle containing the resource (default is the target application or current script bundle) */ inBundle?: any; /** * the name of a subdirectory in the bundle’s “Resources” directory */ inDirectory?: string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface LocalizedStringOptionalParameter { /** * the name of the strings file excluding the “.strings” suffix (default is “Localizable”) */ fromTable?: string; /** * an alias or file reference to the bundle containing the strings file (default is the current application/script bundle) */ inBundle?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface OffsetOptionalParameter { /** * the source text to find the position of */ of: string; /** * the target text to search in */ in: string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface SummarizeOptionalParameter { /** * the number of sentences desired in the summary */ in?: number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface TheClipboardOptionalParameter { /** * the type of data desired */ as?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ClipboardInfoOptionalParameter { /** * restricts to information about only this data type */ for?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface OpenForAccessOptionalParameter { /** * whether to allow writing to the file. */ writePermission?: boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ReadOptionalParameter { /** * starting from this position; if omitted, start at last position read from */ from?: number; /** * the number of bytes to read from current position; if omitted, read until the end of the file… */ for?: number; /** * …or stop at this position… */ to?: number; /** * …or read up to but not including this character… */ before?: string; /** * …or read up to and including this character */ until?: string; /** * the value that separates items to read… */ usingDelimiter?: string; /** * …or a list of values that separate items to read */ usingDelimiters?: any; /** * the form in which to read and return data */ as?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface WriteOptionalParameter { /** * the file reference number, alias, or file reference of the file to write to */ to: any; /** * start writing at this position in the file */ startingAt?: number; /** * the number of bytes to write; if not specified, write all the data provided */ for?: number; /** * how to write the data: as text, data, list, etc. */ as?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface SetEofOptionalParameter { /** * the new length of the file, in bytes. Any data beyond this position is lost. */ to: number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface StoreScriptOptionalParameter { /** * an alias or file reference to the file to store the script object in */ in?: any; /** * control display of the Save As dialog */ replacing?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface RunScriptOptionalParameter { /** * a list of parameters */ withParameters?: any; /** * the scripting component to use; default is the current scripting component */ in?: string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface DoShellScriptOptionalParameter { /** * the desired type of result; default is text (UTF-8) */ as?: any; /** * execute the command as the administrator */ administratorPrivileges?: boolean; /** * use this administrator account to avoid a password dialog (If this parameter is specified, the “password” parameter must also be specified.) */ userName?: string; /** * use this administrator password to avoid a password dialog */ password?: string; /** * the prompt to be displayed in the password dialog when the name and password are not specified or are incorrect */ withPrompt?: string; /** * change all line endings to Mac-style and trim a trailing one (default true) */ alteringLineEndings?: boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface RandomNumberOptionalParameter { /** * the lowest number to return (default is 0.0) */ from?: number; /** * the highest number to return (default is 1.0) */ to?: number; /** * a starting point for a repeatable sequence of random numbers. A value of 0 will use a random seed. */ withSeed?: number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface RoundOptionalParameter { /** * the rounding direction; if omitted, rounds to nearest. “to nearest” rounds .5 cases to the nearest even integer in order to decrease cumulative errors. To always round .5 away from zero, use “as taught in school.” */ rounding?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface SetVolumeOptionalParameter { /** * the sound output volume, an integer from 0 to 100 */ outputVolume?: number; /** * the sound input volume, an integer from 0 to 100 */ inputVolume?: number; /** * the alert volume, an integer from 0 to 100 */ alertVolume?: number; /** * Should the sound output be muted? */ outputMuted?: boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface SystemAttributeOptionalParameter { /** * test specific bits of response (ignored for environment variables) */ has?: number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface MovingFolderWindowForOptionalParameter { /** * the previous coordinates of folder window (you can get the new coordinates from the Finder) */ from: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface AddingFolderItemsToOptionalParameter { /** * a list of the items the folder received */ afterReceiving: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface RemovingFolderItemsFromOptionalParameter { /** * a list of the items the folder lost. For permanently deleted items, only the names (in strings) are provided. */ afterLosing: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface OpenLocationOptionalParameter { /** * Should error conditions be reported in a dialog? */ errorReporting?: boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface HandleCgiRequestOptionalParameter { /** * the data for the GET method or data after the ‘?’ in a POST method */ searchingFor?: string; /** * the POST arguments */ withPostedData?: string; /** * the MIME content type of POST arguments */ ofContentType?: string; /** * either ‘GET’ or ‘POST’ */ usingAccessMethod?: string; /** * the IP address of the entity making the request */ fromAddress?: string; /** * the user name associated with the request */ fromUser?: string; /** * the password sent with the request */ usingPassword?: string; /** * additional information about the user, usually the email address */ withUserInfo?: string; /** * the name of the server application sending this request */ fromServer?: string; /** * the IP port number of the server */ viaPort?: string; /** * the path to the script executing this CGI, in URL form */ executingBy?: string; /** * the URL of the page the client used to link to the CGI */ referredBy?: string; /** * the name of the client software */ fromBrowser?: string; /** * the path to the file or CGI */ usingAction?: string; /** * either PREPROCESSOR, POSTPROCESSOR, CGI, or ACGI */ ofActionType?: string; /** * the Internet address of the client */ fromClientIPAddress?: string; /** * the full request as sent to the server */ withFullRequest?: string; /** * the ID of the connection from the server to the client */ withConnectionID?: number; /** * the URL of the root folder of the virtual host */ fromVirtualHost?: string; } } export interface StandardAdditions extends StandardAdditions.Application { // Functions /** * Beep 1 or more times * @param directParameter number of times to beep * */ beep(directParameter?: number, ): void; /** * Choose an application on this machine or the network * @param option * @return the chosen application */ chooseApplication(option?: StandardAdditions.ChooseApplicationOptionalParameter): any; /** * Choose a color * @param option * @return the chosen color */ chooseColor(option?: StandardAdditions.ChooseColorOptionalParameter): any; /** * Choose a file on a disk or server * @param option * @return the chosen file */ chooseFile(option?: StandardAdditions.ChooseFileOptionalParameter): any; /** * Get a new file reference from the user, without creating the file * @param option * @return the file the user specified */ chooseFileName(option?: StandardAdditions.ChooseFileNameOptionalParameter): any; /** * Choose a folder on a disk or server * @param option * @return the chosen folder */ chooseFolder(option?: StandardAdditions.ChooseFolderOptionalParameter): any; /** * Choose one or more items from a list * @param directParameter a list of items to display * @param option * @return the list of selected items */ chooseFromList(directParameter: {}, option?: StandardAdditions.ChooseFromListOptionalParameter): void; /** * Choose a running application on a remote machine or on this machine * @param option * @return the chosen application */ chooseRemoteApplication(option?: StandardAdditions.ChooseRemoteApplicationOptionalParameter): any; /** * Choose a service on the Internet * @param option * @return the chosen URL */ chooseURL(option?: StandardAdditions.ChooseUrlOptionalParameter): StandardAdditions.URL; /** * Pause for a fixed amount of time * @param directParameter the number of seconds to delay (default is 0) * */ delay(directParameter?: number, ): void; /** * Display an alert * @param directParameter the alert text (will be displayed in emphasized system font) * @param option * @return a record containing the button clicked */ displayAlert(directParameter: string, option?: StandardAdditions.DisplayAlertOptionalParameter): StandardAdditions.AlertReply; /** * Display a dialog box, optionally requesting user input * @param directParameter the text to display in the dialog box * @param option * @return a record containing the button clicked and text entered (if any) */ displayDialog(directParameter: string, option?: StandardAdditions.DisplayDialogOptionalParameter): StandardAdditions.DialogReply; /** * Display a notification. At least one of the body text and the title must be specified. * @param directParameter the body text of the notification * @param option * */ displayNotification(directParameter?: string, option?: StandardAdditions.DisplayNotificationOptionalParameter): void; /** * Speak the given text * @param directParameter the text to speak, which can include intonation characters * @param option * */ say(directParameter: string, option?: StandardAdditions.SayOptionalParameter): void; /** * Return information for a file or folder * @param directParameter an alias or file reference to the file or folder * @param option * @return a record containing the information for the specified file or folder */ infoFor(directParameter: any, option?: StandardAdditions.InfoForOptionalParameter): StandardAdditions.FileInformation; /** * Return a list of the currently mounted volumes * @return a list of the currently mounted volumes. */ listDisks(): void; /** * Return the contents of a specified folder * @param directParameter an alias or file reference to the folder * @param option * @return a list of the items in the specified folder */ listFolder(directParameter: any, option?: StandardAdditions.ListFolderOptionalParameter): void; /** * Mount the specified server volume * @param directParameter the name or URL path (e.g. ‘afp://server/volume/’) of the volume to mount * @param option * @return a specifier for the mounted volume */ mountVolume(directParameter: string, option?: StandardAdditions.MountVolumeOptionalParameter): any; /** * Return the full path to the specified application or script * @param directParameter the item path to return; e.g., current application, frontmost application, application “AppName”, me, it * @param option * @return the path to the specified item */ pathTo(directParameter: {}, option?: StandardAdditions.PathToOptionalParameter): void; /** * Return the full path to the specified folder * @param directParameter the folder to return * @param option * @return the path to the specified folder */ pathTo(directParameter: any, option?: StandardAdditions.PathToOptionalParameter1): any; /** * Return the full path to the specified resource * @param directParameter the name of the requested resource * @param option * @return the path to the resource */ pathToResource(directParameter: string, option?: StandardAdditions.PathToResourceOptionalParameter): any; /** * Convert a number to a character * @param directParameter the code point of the specified character * @return the character */ ASCIICharacter(directParameter: number, ): string; /** * Convert a character to a number * @param directParameter the character * @return the code point of the specified character */ ASCIINumber(directParameter: string, ): number; /** * Return the localized string for the specified key * @param directParameter the key * @param option * @return the localized string */ localizedString(directParameter: string, option?: StandardAdditions.LocalizedStringOptionalParameter): string; /** * Find one piece of text inside another * @param option * @return the position of the source text in the target, or 0 if not found */ offset(option?: StandardAdditions.OffsetOptionalParameter): number; /** * Summarize the specified text or text file * @param directParameter the text (or an alias to a text file) to summarize * @param option * @return a summarized version of the text or file */ summarize(directParameter: {}, option?: StandardAdditions.SummarizeOptionalParameter): string; /** * Place data on an application’s clipboard. Use inside a ‘tell’ block and activate the application first * @param directParameter the data to place on the clipboard * */ setTheClipboardTo(directParameter: any, ): void; /** * Return the contents of an application’s clipboard. Use in a ‘tell’ block after activating the application * @param option * @return the data */ theClipboard(option?: StandardAdditions.TheClipboardOptionalParameter): any; /** * Return information about the clipboard * @param option * @return a list of {data type, size} for each type of data on the clipboard */ clipboardInfo(option?: StandardAdditions.ClipboardInfoOptionalParameter): void; /** * Open a disk file for the read and write commands * @param directParameter the file or alias to open for access. If the file does not exist, a new file is created. * @param option * @return a file reference number; use for ‘read’, ‘write’, and ‘close access’ */ openForAccess(directParameter: any, option?: StandardAdditions.OpenForAccessOptionalParameter): number; /** * Close a file that was opened for access * @param directParameter the file reference number, alias, or file reference of the file to close * */ closeAccess(directParameter: any, ): void; /** * Read data from a file that has been opened for access * @param directParameter the file reference number, alias, or file reference of the file to read * @param option * @return the data read from the file */ read(directParameter: any, option?: StandardAdditions.ReadOptionalParameter): any; /** * Write data to a file that was opened for access with write permission * @param directParameter the data to write to the file * @param option * */ write(directParameter: any, option?: StandardAdditions.WriteOptionalParameter): void; /** * Return the length, in bytes, of a file * @param directParameter a file reference number, alias, or file reference of a file * @return the total number of bytes in the file */ getEof(directParameter: any, ): number; /** * Set the length, in bytes, of a file * @param directParameter a file reference number, alias, or file reference of a file * @param option * */ setEof(directParameter: any, option?: StandardAdditions.SetEofOptionalParameter): void; /** * Return a script object loaded from a specified file * @param directParameter an alias or file reference to the file containing the script object * @return the script object. You can get this object’s properties or call its handlers as if it were a local script object. */ loadScript(directParameter: any, ): any; /** * Store a script object into a file * @param directParameter the script object to store * @param option * */ storeScript(directParameter?: any, option?: StandardAdditions.StoreScriptOptionalParameter): void; /** * Run a specified script or script file * @param directParameter the script text (or an alias or file reference to a script file) to run * @param option * @return the result of running the script */ runScript(directParameter: any, option?: StandardAdditions.RunScriptOptionalParameter): any; /** * Return a list of all scripting components (e.g. AppleScript) * @return a list of installed scripting components */ scriptingComponents(): void; /** * Return the current date and time * @return the current date and time. Use ‘month of (current date)’, etc. to get individual parts. */ currentDate(): any; /** * Execute a shell script using the ‘sh’ shell * @param directParameter the shell script to execute. * @param option * @return the command output */ doShellScript(directParameter: string, option?: StandardAdditions.DoShellScriptOptionalParameter): string; /** * Get the sound output and input volume settings * @return a record containing the sound output and input volume settings */ getVolumeSettings(): StandardAdditions.VolumeSettings; /** * Generate a random number * @param directParameter the upper limit (Default is 1.0. If this parameter is specified, the “from” and “to” parameters will be ignored.) * @param option * @return a number between the “from” and “to” limits, including limit values. If all specified limits are integers, the result is an integer. Otherwise, the result is a real. */ randomNumber(directParameter?: number, option?: StandardAdditions.RandomNumberOptionalParameter): number; /** * Round number to integer * @param directParameter the number to round * @param option * @return the rounded value */ round(directParameter: any, option?: StandardAdditions.RoundOptionalParameter): number; /** * Set the sound output and/or input volume * @param directParameter the sound output volume, a real number from 0 to 7 (This parameter is deprecated; if specified, all other parameters will be ignored.) * @param option * */ setVolume(directParameter?: number, option?: StandardAdditions.SetVolumeOptionalParameter): void; /** * Test attributes of this computer * @param directParameter the attribute to test (either a “Gestalt” value or a shell environment variable). * @param option * @return the result of the query (or a list of all environment variables, if no attribute is provided) */ systemAttribute(directParameter?: any, option?: StandardAdditions.SystemAttributeOptionalParameter): any; /** * Get information about the system * @return a record containing the system information */ systemInfo(): StandardAdditions.SystemInformation; /** * Return the difference between local time and GMT (Universal Time) * @return the difference between current time zone and Universal Time, in seconds */ timeToGMT(): number; /** * Called after a folder has been opened into a window * @param directParameter the folder that was opened * */ openingFolder(directParameter: any, ): void; /** * Called after a folder window has been closed * @param directParameter the folder that was closed * */ closingFolderWindowFor(directParameter: any, ): void; /** * Called after a folder window has been moved or resized * @param directParameter the folder whose window was moved or resized * @param option * */ movingFolderWindowFor(directParameter: any, option?: StandardAdditions.MovingFolderWindowForOptionalParameter): void; /** * Called after new items have been added to a folder * @param directParameter Folder receiving the new items * @param option * */ addingFolderItemsTo(directParameter: any, option?: StandardAdditions.AddingFolderItemsToOptionalParameter): void; /** * Called after items have been removed from a folder * @param directParameter the folder losing the items * @param option * */ removingFolderItemsFrom(directParameter: any, option?: StandardAdditions.RemovingFolderItemsFromOptionalParameter): void; /** * Opens a URL with the appropriate program * @param directParameter the URL to open * @param option * */ openLocation(directParameter?: string, option?: StandardAdditions.OpenLocationOptionalParameter): void; /** * Sent to a script to process a Common Gateway Interface request * @param directParameter the path of the URL * @param option * @return An HTML page resulting from the CGI execution */ handleCGIRequest(directParameter: string, option?: StandardAdditions.HandleCgiRequestOptionalParameter): StandardAdditions.WebPage; }
the_stack
import * as React from "react"; import * as moment from "moment"; import { ITimelineGroup, ITimelineItem, ITeam, ProgressTrackingCriteria, IProject } from "../../Contracts"; import Timeline, { TimelineHeaders, DateHeader } from "react-calendar-timeline"; import "./PlanTimeline.scss"; import { IPortfolioPlanningState } from "../../Redux/Contracts"; import { getTimelineGroups, getTimelineItems, getProjectNames, getTeamNames, getIndexedProjects } from "../../Redux/Selectors/EpicTimelineSelectors"; import { EpicTimelineActions } from "../../Redux/Actions/EpicTimelineActions"; import { connect } from "react-redux"; import { ProgressDetails } from "../../Common/Components/ProgressDetails"; import { getSelectedPlanOwner } from "../../Redux/Selectors/PlanDirectorySelectors"; import { IdentityRef } from "VSS/WebApi/Contracts"; import { ZeroData, ZeroDataActionType } from "azure-devops-ui/ZeroData"; import { PortfolioTelemetry } from "../../Common/Utilities/Telemetry"; import { Image, IImageProps, ImageFit } from "office-ui-fabric-react/lib/Image"; import { Slider } from "office-ui-fabric-react/lib/Slider"; import { Button } from "azure-devops-ui/Button"; import { PlanSummary } from "./PlanSummary"; import { MenuButton } from "azure-devops-ui/Menu"; import { IconSize } from "azure-devops-ui/Icon"; import { DetailsDialog } from "./DetailsDialog"; import { ConnectedDependencyPanel } from "./DependencyPanel"; const day = 60 * 60 * 24 * 1000; const week = day * 7; const sliderSteps = 50; const maxZoomIn = 20 * day; type Unit = `second` | `minute` | `hour` | `day` | `month` | `year`; interface LabelFormat { long: string; mediumLong: string; medium: string; short: string; } interface IPlanTimelineMappedProps { planId: string; groups: ITimelineGroup[]; projectNames: string[]; teamNames: string[]; teams: { [teamId: string]: ITeam }; items: ITimelineItem[]; selectedItemId: number; planOwner: IdentityRef; exceptionMessage: string; setDatesDialogHidden: boolean; progressTrackingCriteria: ProgressTrackingCriteria; projects: { [projectIdKey: string]: IProject }; } interface IPlanTimelineState { sliderValue: number; visibleTimeStart: moment.Moment; visibleTimeEnd: moment.Moment; contextMenuItem: ITimelineItem; dependencyPanelOpen: boolean; } export type IPlanTimelineProps = IPlanTimelineMappedProps & typeof Actions; export class PlanTimeline extends React.Component<IPlanTimelineProps, IPlanTimelineState> { private defaultTimeStart: moment.Moment; private defaultTimeEnd: moment.Moment; constructor() { super(); this.state = { sliderValue: 0, visibleTimeStart: undefined, visibleTimeEnd: undefined, contextMenuItem: undefined, dependencyPanelOpen: false }; } public render(): JSX.Element { return ( <> <div className="plan-timeline-summary-container"> {this._renderSummary()} {this._renderZoomControls()} </div> {this._renderTimeline()} {this._renderItemDetailsDialog()} {this._renderDependencyPanel()} </> ); } private _renderSummary(): JSX.Element { return ( <PlanSummary projectNames={this.props.projectNames} teamNames={this.props.teamNames} owner={this.props.planOwner} /> ); } private _renderItemDetailsDialog = (): JSX.Element => { if (this.state.contextMenuItem) { return ( <DetailsDialog key={Date.now()} // TODO: Is there a better way to reset the state? id={this.state.contextMenuItem.id} title={this.state.contextMenuItem.title} startDate={this.state.contextMenuItem.start_time} endDate={this.state.contextMenuItem.end_time} hidden={this.props.setDatesDialogHidden} save={(id, startDate, endDate) => { this.props.onUpdateDates(id, startDate, endDate); }} close={() => { this.props.onToggleSetDatesDialogHidden(true); }} /> ); } }; private _renderDependencyPanel(): JSX.Element { if (this.state.contextMenuItem && this.state.dependencyPanelOpen) { return ( <ConnectedDependencyPanel workItem={this.state.contextMenuItem} projectInfo={this.props.projects[this.state.contextMenuItem.projectId.toLowerCase()]} progressTrackingCriteria={this.props.progressTrackingCriteria} onDismiss={() => this.setState({ dependencyPanelOpen: false })} /> ); } } private _renderZoomControls(): JSX.Element { if (this.props.items.length > 0) { return ( <div className="plan-timeline-zoom-controls"> <div className="plan-timeline-zoom-slider"> <Slider min={-sliderSteps} max={sliderSteps} step={1} showValue={false} value={this.state.sliderValue} disabled={this.props.items.length === 0} onChange={(value: number) => { const middlePoint = moment( (this.state.visibleTimeEnd.valueOf() + this.state.visibleTimeStart.valueOf()) / 2 ); let newVisibleTimeStart: moment.Moment; let newVisibleTimeEnd: moment.Moment; const maxMinDifference = (this.defaultTimeEnd.valueOf() - this.defaultTimeStart.valueOf()) / 2; if (value === 0) { // Zoom fit zoom level newVisibleTimeStart = moment(middlePoint).add(-maxMinDifference, "milliseconds"); newVisibleTimeEnd = moment(middlePoint).add(maxMinDifference, "milliseconds"); } else if (value < 0) { // Zoom out const stepSize = (365 * day) / sliderSteps; newVisibleTimeStart = moment(middlePoint) .add(-maxMinDifference, "milliseconds") .add(stepSize * value); newVisibleTimeEnd = moment(middlePoint) .add(maxMinDifference, "milliseconds") .add(-stepSize * value); } else { // Zoom in const maxTimeStart = moment(middlePoint).add(-maxMinDifference, "milliseconds"); const maxTimeEnd = moment(middlePoint).add(maxMinDifference, "milliseconds"); const minTimeEnd = moment(middlePoint).add(maxZoomIn, "milliseconds"); const stepSize = (maxTimeEnd.valueOf() - minTimeEnd.valueOf()) / sliderSteps; newVisibleTimeStart = moment(maxTimeStart).add(value * stepSize, "milliseconds"); newVisibleTimeEnd = moment(maxTimeEnd).add(-value * stepSize, "milliseconds"); } this.setState({ sliderValue: value, visibleTimeStart: newVisibleTimeStart, visibleTimeEnd: newVisibleTimeEnd }); }} /> </div> <div className="plan-timeline-zoom-fit-button"> <Button text="Zoom fit" disabled={this.props.items.length === 0} onClick={() => { const [timeStart, timeEnd] = this._getDefaultTimes(this.props.items); this.defaultTimeStart = moment(timeStart); this.defaultTimeEnd = moment(timeEnd); this.setState({ sliderValue: 0, visibleTimeStart: timeStart, visibleTimeEnd: timeEnd }); }} /> </div> </div> ); } } private _renderTimeline(): JSX.Element { if (this.props.items.length > 0) { if (!this.defaultTimeStart || !this.defaultTimeEnd) { [this.defaultTimeStart, this.defaultTimeEnd] = this._getDefaultTimes(this.props.items); } return ( <div className="plan-timeline-container"> <Timeline groups={this.props.groups} items={this.props.items} defaultTimeStart={this.defaultTimeStart} defaultTimeEnd={this.defaultTimeEnd} visibleTimeStart={this.state.visibleTimeStart} visibleTimeEnd={this.state.visibleTimeEnd} onTimeChange={this._handleTimeChange} canChangeGroup={false} stackItems={true} dragSnap={day} minZoom={week} canResize={"both"} minResizeWidth={50} onItemResize={this._onItemResize} onItemMove={this._onItemMove} moveResizeValidator={this._validateResize} selected={[this.props.selectedItemId]} lineHeight={50} onItemSelect={itemId => this.props.onSetSelectedItemId(itemId)} onCanvasClick={() => this.props.onSetSelectedItemId(undefined)} itemRenderer={({ item, itemContext, getItemProps }) => this._renderItem(item, itemContext, getItemProps) } groupRenderer={group => this._renderGroup(group.group)} > <TimelineHeaders> <div onClickCapture={this._onHeaderClick}> <DateHeader unit="primaryHeader" intervalRenderer={({ getIntervalProps, intervalContext, data }) => { return ( <div className="date-header" {...getIntervalProps()}> {intervalContext.intervalText} </div> ); }} /> <DateHeader labelFormat={this._renderDateHeader} style={{ height: 50 }} intervalRenderer={({ getIntervalProps, intervalContext, data }) => { return ( <div className="date-header" {...getIntervalProps()}> {intervalContext.intervalText} </div> ); }} /> </div> </TimelineHeaders> </Timeline> </div> ); } else { return ( // TODO: Add zero data images <ZeroData imagePath="" imageAltText="" primaryText="This plan is empty" secondaryText="Use the &quot;+&quot; button to add items to this plan" actionText="Add items" actionType={ZeroDataActionType.ctaButton} onActionClick={this.props.onZeroDataCtaClicked} /> ); } } private _onHeaderClick = event => { // Disable header zoom in and out event.stopPropagation(); }; private _renderDateHeader( [startTime, endTime]: [moment.Moment, moment.Moment], unit: Unit, labelWidth: number, formatOptions: LabelFormat ): string { const small = 35; const medium = 100; const large = 150; let formatString: string; switch (unit) { case "year": { formatString = "YYYY"; break; } case "month": { if (labelWidth < small) { formatString = "M"; } else if (labelWidth < medium) { formatString = "MMM"; } else if (labelWidth < large) { formatString = "MMMM"; } else { formatString = "MMMM YYYY"; } break; } case "day": { if (labelWidth < medium) { formatString = "D"; } else if (labelWidth < large) { formatString = "dd D"; } else { formatString = "dddd D"; } break; } } return startTime.format(formatString); } private _renderGroup(group: ITimelineGroup) { return <div className="plan-timeline-group">{group.title}</div>; } private _renderItem = (item, itemContext, getItemProps) => { let borderStyle = {}; if (itemContext.selected) { borderStyle = { borderWidth: "2px", borderStyle: "solid", borderColor: "#106ebe" }; } else { borderStyle = { border: "none" }; } const imageProps: IImageProps = { src: item.iconUrl, className: "iconClass", imageFit: ImageFit.contain, maximizeFrame: true }; return ( <div {...getItemProps({ className: "plan-timeline-item", style: { background: item.canMove ? "white" : "#f8f8f8", fontWeight: item.canMove ? 600 : 900, color: "black", ...borderStyle, borderRadius: "4px" } })} > <div className="details"> <Image {...imageProps as any} /> <div className="title">{itemContext.title}</div> <div className="progress-indicator"> <ProgressDetails completed={item.itemProps.completed} total={item.itemProps.total} onClick={() => {}} /> </div> <MenuButton className="item-context-menu-button" iconProps={{ iconName: "More", size: IconSize.small }} disabled={!item.canMove} subtle={true} hideDropdownIcon={true} onClick={() => this.setState({ contextMenuItem: item as ITimelineItem })} contextualMenuProps={{ menuProps: { id: `item-context-menu-${item.id}`, items: [ { id: "set-dates", text: "Set dates", iconProps: { iconName: "Calendar" }, onActivate: () => this.props.onToggleSetDatesDialogHidden(false) }, { id: "drill-down", text: "Drill down", iconProps: { iconName: "BacklogList" }, onActivate: () => this.navigateToEpicRoadmap(item) }, { id: "view-dependencies", text: "View dependencies", iconProps: { iconName: "Link" }, onActivate: () => this.setState({ dependencyPanelOpen: true }) }, { id: "remove-item", text: "Remove item", iconProps: { iconName: "Delete" }, onActivate: () => this.props.onRemoveItem({ itemIdToRemove: item.id, planId: this.props.planId }) } ] } }} /> </div> </div> ); }; private _handleTimeChange = (visibleTimeStart, visibleTimeEnd, updateScrollCanvas): void => { // Disable zoom using wheel if ( (visibleTimeStart < this.state.visibleTimeStart.valueOf() && visibleTimeEnd > this.state.visibleTimeEnd.valueOf()) || (visibleTimeStart > this.state.visibleTimeStart.valueOf() && visibleTimeEnd < this.state.visibleTimeEnd.valueOf()) ) { // do nothing } else { this.setState({ visibleTimeStart: moment(visibleTimeStart), visibleTimeEnd: moment(visibleTimeEnd) }); } }; private _validateResize(action: string, item: ITimelineItem, time: number, resizeEdge: string) { if (action === "resize") { if (resizeEdge === "right") { const difference = time - item.start_time.valueOf(); if (difference < day) { time = item.start_time.valueOf() + day; } } else { const difference = item.end_time.valueOf() - time; if (difference < day) { time = item.end_time.valueOf() - day; } } } else if (action === "move") { // TODO: Any validation for moving? } return time; } private _onItemResize = (itemId: number, time: number, edge: string): void => { const itemToUpdate = this.props.items.find(item => item.id === itemId); if (edge == "left") { this.props.onUpdateDates(itemId, moment(time), itemToUpdate.end_time); } else { // "right" this.props.onUpdateDates(itemId, itemToUpdate.start_time, moment(time)); } }; private _onItemMove = (itemId: number, time: number): void => { this.props.onShiftItem(itemId, moment(time)); }; private _getDefaultTimes(items: ITimelineItem[]): [moment.Moment, moment.Moment] { let startTime: moment.Moment; let endTime: moment.Moment; if (!items || items.length == 0) { startTime = moment().add(-1, "months"); endTime = moment().add(1, "months"); } else { for (const item of items) { if (item.start_time < startTime || !startTime) { startTime = moment(item.start_time); } if (item.end_time > endTime || !endTime) { endTime = moment(item.end_time); } } // Add small buffer on both sides of plan const buffer = (endTime.valueOf() - startTime.valueOf()) / 10; startTime.add(-buffer, "milliseconds"); endTime.add(buffer, "milliseconds"); startTime.add(-maxZoomIn, "milliseconds"); endTime.add(maxZoomIn, "milliseconds"); } this.setState({ visibleTimeStart: startTime, visibleTimeEnd: endTime }); return [startTime, endTime]; } private navigateToEpicRoadmap(item: ITimelineItem) { const collectionUri = VSS.getWebContext().collection.uri; const extensionContext = VSS.getExtensionContext(); const projectName = item.group; const teamId = item.teamId; const backlogLevel = item.backlogLevel; const workItemId = item.id; const targerUrl = `${collectionUri}${projectName}/_backlogs/${extensionContext.publisherId}.${ extensionContext.extensionId }.workitem-epic-roadmap/${teamId}/${backlogLevel}#${workItemId}`; VSS.getService<IHostNavigationService>(VSS.ServiceIds.Navigation).then( client => { PortfolioTelemetry.getInstance().TrackAction("NavigateToEpicRoadMap"); client.navigate(targerUrl); }, error => { PortfolioTelemetry.getInstance().TrackException(error); alert(error); } ); } } function mapStateToProps(state: IPortfolioPlanningState): IPlanTimelineMappedProps { return { planId: state.planDirectoryState.selectedPlanId, groups: getTimelineGroups(state.epicTimelineState), projectNames: getProjectNames(state), teamNames: getTeamNames(state), teams: state.epicTimelineState.teams, items: getTimelineItems(state.epicTimelineState), selectedItemId: state.epicTimelineState.selectedItemId, planOwner: getSelectedPlanOwner(state), exceptionMessage: state.epicTimelineState.exceptionMessage, setDatesDialogHidden: state.epicTimelineState.setDatesDialogHidden, progressTrackingCriteria: state.epicTimelineState.progressTrackingCriteria, projects: getIndexedProjects(state.epicTimelineState) }; } const Actions = { onUpdateDates: EpicTimelineActions.updateDates, onShiftItem: EpicTimelineActions.shiftItem, onToggleSetDatesDialogHidden: EpicTimelineActions.toggleItemDetailsDialogHidden, onSetSelectedItemId: EpicTimelineActions.setSelectedItemId, onZeroDataCtaClicked: EpicTimelineActions.openAddItemPanel, onRemoveItem: EpicTimelineActions.removeItems }; export const ConnectedPlanTimeline = connect( mapStateToProps, Actions )(PlanTimeline);
the_stack
import { CompilableProgram, CompileTimeComponent, HighLevelBuilderOpcode, LayoutWithContext, MachineOp, NamedBlocks, WireFormat, Option, Op, InternalComponentCapability, } from '@glimmer/interfaces'; import { hasCapability } from '@glimmer/manager'; import { $s0, $s1, $sp, SavedRegister } from '@glimmer/vm'; import { EMPTY_STRING_ARRAY } from '@glimmer/util'; import { PushExpressionOp, PushStatementOp } from '../../syntax/compilers'; import { namedBlocks } from '../../utils'; import { labelOperand, layoutOperand, symbolTableOperand, isStrictMode } from '../operands'; import { InvokeStaticBlock, PushYieldableBlock, YieldBlock } from './blocks'; import { Replayable } from './conditional'; import { expr } from './expr'; import { CompileArgs, CompilePositional } from './shared'; export const ATTRS_BLOCK = '&attrs'; interface AnyComponent { elementBlock: Option<WireFormat.SerializedInlineBlock>; positional: WireFormat.Core.Params; named: WireFormat.Core.Hash; blocks: NamedBlocks; } // {{component}} export interface DynamicComponent extends AnyComponent { definition: WireFormat.Expression; atNames: boolean; curried: boolean; } // <Component> export interface StaticComponent extends AnyComponent { capabilities: InternalComponentCapability; layout: CompilableProgram; } // chokepoint export interface Component extends AnyComponent { // either we know the capabilities statically or we need to be conservative and assume // that the component requires all capabilities capabilities: InternalComponentCapability | true; // are the arguments supplied as atNames? atNames: boolean; // do we have the layout statically or will we need to look it up at runtime? layout?: CompilableProgram; } export function InvokeComponent( op: PushStatementOp, component: CompileTimeComponent, _elementBlock: WireFormat.Core.ElementParameters, positional: WireFormat.Core.Params, named: WireFormat.Core.Hash, _blocks: WireFormat.Core.Blocks ): void { let { compilable, capabilities, handle } = component; let elementBlock = _elementBlock ? ([_elementBlock, []] as WireFormat.SerializedInlineBlock) : null; let blocks = Array.isArray(_blocks) || _blocks === null ? namedBlocks(_blocks) : _blocks; if (compilable) { op(Op.PushComponentDefinition, handle); InvokeStaticComponent(op, { capabilities: capabilities, layout: compilable, elementBlock, positional, named, blocks, }); } else { op(Op.PushComponentDefinition, handle); InvokeNonStaticComponent(op, { capabilities: capabilities, elementBlock, positional, named, atNames: true, blocks, }); } } export function InvokeDynamicComponent( op: PushStatementOp, definition: WireFormat.Core.Expression, _elementBlock: WireFormat.Core.ElementParameters, positional: WireFormat.Core.Params, named: WireFormat.Core.Hash, _blocks: WireFormat.Core.Blocks, atNames: boolean, curried: boolean ): void { let elementBlock = _elementBlock ? ([_elementBlock, []] as WireFormat.SerializedInlineBlock) : null; let blocks = Array.isArray(_blocks) || _blocks === null ? namedBlocks(_blocks) : _blocks; Replayable( op, () => { expr(op, definition); op(Op.Dup, $sp, 0); return 2; }, () => { op(Op.JumpUnless, labelOperand('ELSE')); if (curried) { op(Op.ResolveCurriedComponent); } else { op(Op.ResolveDynamicComponent, isStrictMode()); } op(Op.PushDynamicComponentInstance); InvokeNonStaticComponent(op, { capabilities: true, elementBlock, positional, named, atNames, blocks, }); op(HighLevelBuilderOpcode.Label, 'ELSE'); } ); } function InvokeStaticComponent( op: PushStatementOp, { capabilities, layout, elementBlock, positional, named, blocks }: StaticComponent ): void { let { symbolTable } = layout; let bailOut = symbolTable.hasEval || hasCapability(capabilities, InternalComponentCapability.PrepareArgs); if (bailOut) { InvokeNonStaticComponent(op, { capabilities, elementBlock, positional, named, atNames: true, blocks, layout, }); return; } op(Op.Fetch, $s0); op(Op.Dup, $sp, 1); op(Op.Load, $s0); op(MachineOp.PushFrame); // Setup arguments let { symbols } = symbolTable; // As we push values onto the stack, we store the symbols associated with them // so that we can set them on the scope later on with SetVariable and SetBlock let blockSymbols: number[] = []; let argSymbols: number[] = []; let argNames: string[] = []; // First we push the blocks onto the stack let blockNames = blocks.names; // Starting with the attrs block, if it exists and is referenced in the component if (elementBlock !== null) { let symbol = symbols.indexOf(ATTRS_BLOCK); if (symbol !== -1) { PushYieldableBlock(op, elementBlock); blockSymbols.push(symbol); } } // Followed by the other blocks, if they exist and are referenced in the component. // Also store the index of the associated symbol. for (let i = 0; i < blockNames.length; i++) { let name = blockNames[i]; let symbol = symbols.indexOf(`&${name}`); if (symbol !== -1) { PushYieldableBlock(op, blocks.get(name)); blockSymbols.push(symbol); } } // Next up we have arguments. If the component has the `createArgs` capability, // then it wants access to the arguments in JavaScript. We can't know whether // or not an argument is used, so we have to give access to all of them. if (hasCapability(capabilities, InternalComponentCapability.CreateArgs)) { // First we push positional arguments let count = CompilePositional(op, positional); // setup the flags with the count of positionals, and to indicate that atNames // are used let flags = count << 4; flags |= 0b1000; let names: string[] = EMPTY_STRING_ARRAY as string[]; // Next, if named args exist, push them all. If they have an associated symbol // in the invoked component (e.g. they are used within its template), we push // that symbol. If not, we still push the expression as it may be used, and // we store the symbol as -1 (this is used later). if (named !== null) { names = named[0]; let val = named[1]; for (let i = 0; i < val.length; i++) { let symbol = symbols.indexOf(names[i]); expr(op, val[i]); argSymbols.push(symbol); } } // Finally, push the VM arguments themselves. These args won't need access // to blocks (they aren't accessible from userland anyways), so we push an // empty array instead of the actual block names. op(Op.PushArgs, names, EMPTY_STRING_ARRAY, flags); // And push an extra pop operation to remove the args before we begin setting // variables on the local context argSymbols.push(-1); } else if (named !== null) { // If the component does not have the `createArgs` capability, then the only // expressions we need to push onto the stack are those that are actually // referenced in the template of the invoked component (e.g. have symbols). let names = named[0]; let val = named[1]; for (let i = 0; i < val.length; i++) { let name = names[i]; let symbol = symbols.indexOf(name); if (symbol !== -1) { expr(op, val[i]); argSymbols.push(symbol); argNames.push(name); } } } op(Op.BeginComponentTransaction, $s0); if (hasCapability(capabilities, InternalComponentCapability.DynamicScope)) { op(Op.PushDynamicScope); } if (hasCapability(capabilities, InternalComponentCapability.CreateInstance)) { op(Op.CreateComponent, (blocks.has('default') as any) | 0, $s0); } op(Op.RegisterComponentDestructor, $s0); if (hasCapability(capabilities, InternalComponentCapability.CreateArgs)) { op(Op.GetComponentSelf, $s0); } else { op(Op.GetComponentSelf, $s0, argNames); } // Setup the new root scope for the component op(Op.RootScope, symbols.length + 1, Object.keys(blocks).length > 0 ? 1 : 0); // Pop the self reference off the stack and set it to the symbol for `this` // in the new scope. This is why all subsequent symbols are increased by one. op(Op.SetVariable, 0); // Going in reverse, now we pop the args/blocks off the stack, starting with // arguments, and assign them to their symbols in the new scope. for (let i = argSymbols.length - 1; i >= 0; i--) { let symbol = argSymbols[i]; if (symbol === -1) { // The expression was not bound to a local symbol, it was only pushed to be // used with VM args in the javascript side op(Op.Pop, 1); } else { op(Op.SetVariable, symbol + 1); } } // if any positional params exist, pop them off the stack as well if (positional !== null) { op(Op.Pop, positional.length); } // Finish up by popping off and assigning blocks for (let i = blockSymbols.length - 1; i >= 0; i--) { let symbol = blockSymbols[i]; op(Op.SetBlock, symbol + 1); } op(Op.Constant, layoutOperand(layout)); op(Op.CompileBlock); op(MachineOp.InvokeVirtual); op(Op.DidRenderLayout, $s0); op(MachineOp.PopFrame); op(Op.PopScope); if (hasCapability(capabilities, InternalComponentCapability.DynamicScope)) { op(Op.PopDynamicScope); } op(Op.CommitComponentTransaction); op(Op.Load, $s0); } export function InvokeNonStaticComponent( op: PushStatementOp, { capabilities, elementBlock, positional, named, atNames, blocks: namedBlocks, layout }: Component ): void { let bindableBlocks = !!namedBlocks; let bindableAtNames = capabilities === true || hasCapability(capabilities, InternalComponentCapability.PrepareArgs) || !!(named && named[0].length !== 0); let blocks = namedBlocks.with('attrs', elementBlock); op(Op.Fetch, $s0); op(Op.Dup, $sp, 1); op(Op.Load, $s0); op(MachineOp.PushFrame); CompileArgs(op, positional, named, blocks, atNames); op(Op.PrepareArgs, $s0); invokePreparedComponent(op, blocks.has('default'), bindableBlocks, bindableAtNames, () => { if (layout) { op(Op.PushSymbolTable, symbolTableOperand(layout.symbolTable)); op(Op.Constant, layoutOperand(layout)); op(Op.CompileBlock); } else { op(Op.GetComponentLayout, $s0); } op(Op.PopulateLayout, $s0); }); op(Op.Load, $s0); } export function WrappedComponent( op: PushStatementOp, layout: LayoutWithContext, attrsBlockNumber: number ): void { op(HighLevelBuilderOpcode.StartLabels); WithSavedRegister(op, $s1, () => { op(Op.GetComponentTagName, $s0); op(Op.PrimitiveReference); op(Op.Dup, $sp, 0); }); op(Op.JumpUnless, labelOperand('BODY')); op(Op.Fetch, $s1); op(Op.PutComponentOperations); op(Op.OpenDynamicElement); op(Op.DidCreateElement, $s0); YieldBlock(op, attrsBlockNumber, null); op(Op.FlushElement); op(HighLevelBuilderOpcode.Label, 'BODY'); InvokeStaticBlock(op, [layout.block[0], []]); op(Op.Fetch, $s1); op(Op.JumpUnless, labelOperand('END')); op(Op.CloseElement); op(HighLevelBuilderOpcode.Label, 'END'); op(Op.Load, $s1); op(HighLevelBuilderOpcode.StopLabels); } export function invokePreparedComponent( op: PushStatementOp, hasBlock: boolean, bindableBlocks: boolean, bindableAtNames: boolean, populateLayout: Option<() => void> = null ): void { op(Op.BeginComponentTransaction, $s0); op(Op.PushDynamicScope); op(Op.CreateComponent, (hasBlock as any) | 0, $s0); // this has to run after createComponent to allow // for late-bound layouts, but a caller is free // to populate the layout earlier if it wants to // and do nothing here. if (populateLayout) { populateLayout(); } op(Op.RegisterComponentDestructor, $s0); op(Op.GetComponentSelf, $s0); op(Op.VirtualRootScope, $s0); op(Op.SetVariable, 0); op(Op.SetupForEval, $s0); if (bindableAtNames) op(Op.SetNamedVariables, $s0); if (bindableBlocks) op(Op.SetBlocks, $s0); op(Op.Pop, 1); op(Op.InvokeComponentLayout, $s0); op(Op.DidRenderLayout, $s0); op(MachineOp.PopFrame); op(Op.PopScope); op(Op.PopDynamicScope); op(Op.CommitComponentTransaction); } export function InvokeBareComponent(op: PushStatementOp): void { op(Op.Fetch, $s0); op(Op.Dup, $sp, 1); op(Op.Load, $s0); op(MachineOp.PushFrame); op(Op.PushEmptyArgs); op(Op.PrepareArgs, $s0); invokePreparedComponent(op, false, false, true, () => { op(Op.GetComponentLayout, $s0); op(Op.PopulateLayout, $s0); }); op(Op.Load, $s0); } export function WithSavedRegister( op: PushExpressionOp, register: SavedRegister, block: () => void ): void { op(Op.Fetch, register); block(); op(Op.Load, register); }
the_stack
import { IndexedCollection } from '@esfx/collection-core'; import { HashMap } from '@esfx/collections-hashmap'; import { HashSet } from '@esfx/collections-hashset'; import { Comparer, Comparison, Equaler, EqualityComparison } from '@esfx/equatable'; import * as assert from "@esfx/internal-assert"; import { Index } from "@esfx/interval"; import * as fn from "@esfx/iter-fn"; import { ConsumeOptions } from "@esfx/iter-fn"; import { Grouping, HierarchyGrouping } from '@esfx/iter-grouping'; import { Hierarchical, HierarchyIterable, HierarchyProvider, OrderedHierarchyIterable } from '@esfx/iter-hierarchy'; import { Lookup } from '@esfx/iter-lookup'; import { OrderedIterable } from "@esfx/iter-ordered"; import { HierarchyPage, Page } from '@esfx/iter-page'; export { ConsumeOptions }; const kSource = Symbol("[[Source]]"); export type UnorderedQueryFlow<S, T> = S extends Hierarchical<infer TNode> ? HierarchyQuery<TNode, TNode & T> : Query<T>; export type OrderedQueryFlow<S, T> = S extends Hierarchical<infer TNode> ? OrderedHierarchyQuery<TNode, TNode & T> : OrderedQuery<T>; export type QueryFlow<S, T> = S extends OrderedIterable<any> ? OrderedQueryFlow<S, T> : UnorderedQueryFlow<S, T>; export type PagedQueryFlow<S, T> = S extends Hierarchical<infer TNode> ? Query<HierarchyPage<TNode, TNode & T>> : Query<Page<T>>; export type GroupedQueryFlow<S, K, T> = S extends Hierarchical<infer TNode> ? Query<HierarchyGrouping<K, TNode, TNode & T>> : Query<Grouping<K, T>>; export type HierarchyQueryFlow<S, TNode extends (T extends TNode ? unknown : never), T> = S extends OrderedIterable<any> ? OrderedHierarchyQuery<TNode, TNode & T> : HierarchyQuery<TNode, TNode & T>; export type MergeQueryFlow<L, R, T> = L extends Hierarchical<infer LTNode> ? R extends Hierarchical<infer RTNode> ? HierarchyQuery<LTNode | RTNode, LTNode & T | RTNode & T> : HierarchyQuery<LTNode, LTNode & T> : R extends Hierarchical<infer RTNode> ? HierarchyQuery<RTNode, RTNode & T> : Query<T>; /** * Creates a `Query` from a `Iterable` source. */ export function from<TNode, T extends TNode>(source: OrderedHierarchyIterable<TNode, T>): OrderedHierarchyQuery<TNode, T>; export function from<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>): HierarchyQuery<TNode, T>; export function from<TNode, T extends TNode>(source: OrderedIterable<T>, provider: HierarchyProvider<TNode>): OrderedHierarchyQuery<TNode, T>; export function from<TNode, T extends TNode>(source: Iterable<T>, provider: HierarchyProvider<TNode>): HierarchyQuery<TNode, T>; export function from<T>(source: OrderedIterable<T>): OrderedQuery<T>; export function from<T extends readonly unknown[] | []>(source: Iterable<T>): Query<T>; export function from<T>(source: Iterable<T>): Query<T>; export function from<TNode, T extends TNode>(source: Iterable<T>, provider?: HierarchyProvider<TNode>): Query<T> { return Query.from(source, provider!); } function getSource<TNode, T extends TNode>(source: OrderedHierarchyIterable<TNode, T>): OrderedHierarchyIterable<TNode, T>; function getSource<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>): HierarchyIterable<TNode, T>; function getSource<T>(source: OrderedIterable<T>): OrderedIterable<T>; function getSource<T>(source: Iterable<T>): Iterable<T>; function getSource<T>(source: Iterable<T>): Iterable<T> { if (source instanceof Query) { return source[kSource]; } return source; } function wrapResultSelector<I, O, R>(query: Query<any>, selector: ((inner: I, outer: Query<O>) => R)): ((inner: I, outer: Iterable<O>) => R); function wrapResultSelector<I, O, R>(query: Query<any>, selector: ((inner: I, outer: Query<O>) => R) | undefined): ((inner: I, outer: Iterable<O>) => R) | undefined; function wrapResultSelector<I, O, R>(query: Query<any>, selector: ((inner: I, outer: Query<O>) => R) | undefined) { if (typeof selector === "function") { return (inner: I, outer: Iterable<O>) => selector(inner, query["_from"](outer)); } return selector; } function wrapPageSelector<T, R>(query: Query<any>, selector: ((page: number, offset: number, values: Query<T>) => R)): (page: number, offset: number, values: Iterable<T>) => R; function wrapPageSelector<T, R>(query: Query<any>, selector: ((page: number, offset: number, values: Query<T>) => R) | undefined): ((page: number, offset: number, values: Iterable<T>) => R) | undefined; function wrapPageSelector<T, R>(query: Query<any>, selector: ((page: number, offset: number, values: Query<T>) => R) | undefined) { if (typeof selector === "function") { return (page: number, offset: number, values: Iterable<T>) => selector(page, offset, query["_from"](values)); } return selector; } /** * A `Query` represents a series of operations that act upon an `Iterable` or ArrayLike. Evaluation of * these operations is deferred until the either a scalar value is requested from the `Query` or the * `Query` is iterated. */ export class Query<T> implements Iterable<T> { private [kSource]: Iterable<T>; /** * Creates a `Query` from a `Iterable` source. * * @param source A `Iterable` object. */ constructor(source: Iterable<T>) { assert.mustBeIterableObject(source, "source"); this[kSource] = getSource(source); } // #region Query /** * Creates a `Query` from a `Iterable` source. * @category Query */ static from<TNode, T extends TNode>(source: OrderedHierarchyIterable<TNode, T>): OrderedHierarchyQuery<TNode, T>; static from<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>): HierarchyQuery<TNode, T>; static from<TNode, T extends TNode>(source: OrderedIterable<T>, provider: HierarchyProvider<TNode>): OrderedHierarchyQuery<TNode, T>; static from<TNode, T extends TNode>(source: Iterable<T>, provider: HierarchyProvider<TNode>): HierarchyQuery<TNode, T>; static from<T>(source: OrderedIterable<T>): OrderedQuery<T>; static from<T extends readonly unknown[] | []>(source: Iterable<T>): Query<T>; static from<T>(source: Iterable<T>): Query<T>; static from(source: Iterable<any>, provider?: HierarchyProvider<any>): Query<any> { assert.mustBeIterableObject(source, "source"); assert.mustBeTypeOrUndefined(HierarchyProvider.hasInstance, provider, "provider"); if (provider) source = fn.toHierarchy(source, provider); return source instanceof Query ? source : OrderedHierarchyIterable.hasInstance(source) ? new OrderedHierarchyQuery(source) : HierarchyIterable.hasInstance(source) ? new HierarchyQuery(source) : OrderedIterable.hasInstance(source) ? new OrderedQuery(source) : new Query(source); } /** * Creates a `Query` for the provided elements. * * @param elements The elements of the `Query`. * @category Query */ static of<T>(...elements: T[]): Query<T>; static of<T>(): Query<T> { return this.from(arguments); } /** * Creates a `Query` with no elements. * * @category Query */ static empty<T>(): Query<T> { return this.from(fn.empty<T>()); } /** * Creates a `Query` over a single element. * * @param value The only element for the `Query`. * @category Query */ static once<T>(value: T): Query<T> { return this.from(fn.once(value)); } /** * Creates a `Query` for a value repeated a provided number of times. * * @param value The value for each element of the `Query`. * @param count The number of times to repeat the value. * @category Query */ static repeat<T>(value: T, count: number): Query<T> { return this.from(fn.repeat(value, count)); } /** * Creates a `Query` over a range of numbers. * * @param start The starting number of the range. * @param end The ending number of the range. * @param increment The amount by which to change between each itereated value. * @category Query */ static range(start: number, end: number, increment?: number) { return this.from(fn.range(start, end, increment)); } /** * Creates a `Query` that repeats the provided value forever. * * @param value The value for each element of the `Query`. * @category Query */ static continuous<T>(value: T) { return this.from(fn.continuous(value)); } /** * Creates a `Query` whose values are provided by a callback executed a provided number of * times. * * @param count The number of times to execute the callback. * @param generator The callback to execute. * @category Query */ static generate<T>(count: number, generator: (offset: number) => T) { return this.from(fn.generate(count, generator)); } /** * Creates a `Query` that, when iterated, consumes the provided `Iterator`. * * @param iterator An `Iterator` object. * @category Query */ static consume<T>(iterator: Iterator<T>, options?: ConsumeOptions) { return this.from(fn.consume(iterator, options)); } // /** // * Creates a `Query` that iterates the elements from one of two sources based on the result of a // * lazily evaluated condition. // * // * @param condition A callback used to choose a source. // * @param thenIterable The source to use when the callback evaluates to `true`. // * @param elseIterable The source to use when the callback evaluates to `false`. // * @category Query // */ // static if<T>(condition: () => boolean, thenIterable: Iterable<T>, elseIterable?: Iterable<T>): Query<T> { // return this.from(fn.if(condition, thenIterable, elseIterable)); // } // /** // * Creates a `Query` that iterates the elements from sources picked from a list based on the // * result of a lazily evaluated choice. // * // * @param chooser A callback used to choose a source. // * @param choices A list of sources // * @param otherwise A default source to use when another choice could not be made. // * @category Query // */ // static choose<K, V>(chooser: () => K, choices: Iterable<Choice<K, V>>, otherwise?: Iterable<V>): Query<V> { // return this.from(fn.choose(chooser, choices, otherwise)); // } // /** // * Creates a `Query` for the own property keys of an object. // * // * @param source An object. // * @category Query // */ // static objectKeys<T extends object>(source: T): Query<Extract<keyof T, string>> { // return this.from(fn.objectKeys(source)); // } // /** // * Creates a `Query` for the own property values of an object. // * // * @param source An object. // * @category Query // */ // static objectValues<T extends object>(source: T): Query<T[Extract<keyof T, string>]> { // return this.from(fn.objectValues(source)); // } // /** // * Creates a `Query` for the own property key-value pairs of an object. // * // * @param source An object. // * @category Query // */ // static objectEntries<T extends object>(source: T): Query<KeyValuePair<T, Extract<keyof T, string>>> { // return this.from(fn.objectEntries(source)); // } // #endregion Query // #region Subquery /** * Creates a subquery whose elements match the supplied predicate. * * @param predicate A callback used to match each element. * @param predicate.element The element to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ filter<U extends T>(predicate: (element: T, offset: number) => element is U): UnorderedQueryFlow<this, U>; /** * Creates a subquery whose elements match the supplied predicate. * * @param predicate A callback used to match each element. * @param predicate.element The element to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ filter(predicate: (element: T, offset: number) => boolean): UnorderedQueryFlow<this, T>; filter(predicate: (element: T, offset: number) => boolean) { return this._from(fn.filter(getSource(this), predicate)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery where the selected key for each element matches the supplied predicate. * * @param keySelector A callback used to select the key for each element. * @param keySelector.element The element from which to select a key. * @param predicate A callback used to match each key. * @param predicate.key The key to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ filterBy<K>(keySelector: (element: T) => K, predicate: (key: K, offset: number) => boolean): UnorderedQueryFlow<this, T> { return this._from(fn.filterBy(getSource(this), keySelector, predicate)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery whose elements are neither `null` nor `undefined`. * * @category Subquery */ filterDefined(): UnorderedQueryFlow<this, NonNullable<T>> { return this._from(fn.filterDefined(getSource(this))) as UnorderedQueryFlow<this, NonNullable<T>>; } /** * Creates a subquery where the selected key for each element is neither `null` nor `undefined`. * * @param keySelector A callback used to select the key for each element. * @param keySelector.element The element from which to select a key. * @category Subquery */ filterDefinedBy<K>(keySelector: (element: T) => K): UnorderedQueryFlow<this, T> { return this._from(fn.filterDefinedBy(getSource(this), keySelector)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery whose elements match the supplied predicate. * * NOTE: This is an alias for `filter`. * * @param predicate A callback used to match each element. * @param predicate.element The element to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ where<U extends T>(predicate: (element: T, offset: number) => element is U): UnorderedQueryFlow<this, U>; /** * Creates a subquery whose elements match the supplied predicate. * * NOTE: This is an alias for `filter`. * * @param predicate A callback used to match each element. * @param predicate.element The element to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ where(predicate: (element: T, offset: number) => boolean): UnorderedQueryFlow<this, T>; where(predicate: (element: T, offset: number) => boolean) { return this.filter(predicate); } /** * Creates a subquery where the selected key for each element matches the supplied predicate. * * NOTE: This is an alias for `filterBy`. * * @param keySelector A callback used to select the key for each element. * @param keySelector.element The element from which to select a key. * @param predicate A callback used to match each key. * @param predicate.key The key to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ whereBy<K>(keySelector: (element: T) => K, predicate: (key: K, offset: number) => boolean): UnorderedQueryFlow<this, T> { return this.filterBy(keySelector, predicate); } /** * Creates a subquery whose elements are neither `null` nor `undefined`. * * NOTE: This is an alias for `filterDefined`. * * @category Subquery */ whereDefined(): UnorderedQueryFlow<this, NonNullable<T>> { return this.filterDefined(); } /** * Creates a subquery where the selected key for each element is neither `null` nor `undefined`. * * NOTE: This is an alias for `filterDefinedBy`. * * @param keySelector A callback used to select the key for each element. * @param keySelector.element The element from which to select a key. * @category Subquery */ whereDefinedBy<K>(keySelector: (element: T) => K): UnorderedQueryFlow<this, T> { return this.filterDefinedBy(keySelector); } /** * Creates a subquery whose elements do not match the supplied predicate. * * @param predicate A callback used to match each element. * @param predicate.element The element to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ filterNot<U extends T>(predicate: (element: T, offset: number) => element is U): UnorderedQueryFlow<this, U>; /** * Creates a subquery whose elements do not match the supplied predicate. * * @param predicate A callback used to match each element. * @param predicate.element The element to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ filterNot(predicate: (element: T, offset: number) => boolean): UnorderedQueryFlow<this, T>; filterNot(predicate: (element: T, offset: number) => boolean) { return this._from(fn.filterNot(getSource(this), predicate)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery where the selected key for each element does not match the supplied predicate. * * @param keySelector A callback used to select the key for each element. * @param keySelector.element The element from which to select a key. * @param predicate A callback used to match each key. * @param predicate.key The key to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ filterNotBy<K>(keySelector: (element: T) => K, predicate: (key: K, offset: number) => boolean): UnorderedQueryFlow<this, T> { return this._from(fn.filterNotBy(getSource(this), keySelector, predicate)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery where the selected key for each element is either `null` or `undefined`. * * @param keySelector A callback used to select the key for each element. * @param keySelector.element The element from which to select a key. * @category Subquery */ filterNotDefinedBy<K>(keySelector: (element: T) => K): UnorderedQueryFlow<this, T> { return this._from(fn.filterNotDefinedBy(getSource(this), keySelector)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery whose elements do not match the supplied predicate. * * NOTE: This is an alias for `filterNot`. * * @param predicate A callback used to match each element. * @param predicate.element The element to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ whereNot<U extends T>(predicate: (element: T, offset: number) => element is U): UnorderedQueryFlow<this, U>; /** * Creates a subquery whose elements do not match the supplied predicate. * * NOTE: This is an alias for `filterNot`. * * @param predicate A callback used to match each element. * @param predicate.element The element to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ whereNot(predicate: (element: T, offset: number) => boolean): UnorderedQueryFlow<this, T>; whereNot(predicate: (element: T, offset: number) => boolean) { return this.filterNot(predicate); } /** * Creates a subquery where the selected key for each element does not match the supplied predicate. * * NOTE: This is an alias for `filterNotBy`. * * @param keySelector A callback used to select the key for each element. * @param keySelector.element The element from which to select a key. * @param predicate A callback used to match each key. * @param predicate.key The key to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ whereNotBy<K>(keySelector: (element: T) => K, predicate: (key: K, offset: number) => boolean): UnorderedQueryFlow<this, T> { return this.filterNotBy(keySelector, predicate); } /** * Creates a subquery where the selected key for each element is either `null` or `undefined`. * * NOTE: This is an alias for `filterNotDefinedBy`. * * @param keySelector A callback used to select the key for each element. * @param keySelector.element The element from which to select a key. * @category Subquery */ whereNotDefinedBy<K>(keySelector: (element: T) => K): UnorderedQueryFlow<this, T> { return this.filterNotDefinedBy(keySelector); } /** * Creates a subquery by applying a callback to each element. * * @param selector A callback used to map each element. * @param selector.element The element to map. * @param selector.offset The offset from the start of the source iterable. * @category Subquery */ map<U>(selector: (element: T, offset: number) => U): Query<U> { return this._from(fn.map(getSource(this), selector)); } /** * Creates a subquery by applying a callback to each element. * * NOTE: This is an alias for `map`. * * @param selector A callback used to map each element. * @param selector.element The element to map. * @param selector.offset The offset from the start of the source `Iterable`. * @category Subquery */ select<U>(selector: (element: T, offset: number) => U): Query<U> { return this.map(selector); } /** * Creates a subquery that iterates the results of applying a callback to each element. * * @param projection A callback used to map each element into a `Iterable`. * @param projection.element The element to map. * @category Subquery */ flatMap<U>(projection: (element: T) => Iterable<U>): Query<U>; /** * Creates a subquery that iterates the results of applying a callback to each element. * * @param projection A callback used to map each element into a `Iterable`. * @param projection.element The outer element to map. * @param resultSelector An optional callback used to map the outer and projected inner elements. * @param resultSelector.element The outer element to map. * @param resultSelector.innerElement An inner element produced by the `projection` of the outer element. * @category Subquery */ flatMap<U, R>(projection: (element: T) => Iterable<U>, resultSelector: (element: T, innerElement: U) => R): Query<R>; flatMap<U, R>(projection: (element: T) => Iterable<U>, resultSelector?: (element: T, innerElement: U) => R) { return this._from(fn.flatMap(getSource(this), projection, resultSelector!)); } /** * Creates a subquery that iterates the results of applying a callback to each element. * * NOTE: This is an alias for `flatMap`. * * @param projection A callback used to map each element into an iterable. * @param projection.element The element to map. * @category Subquery */ selectMany<U>(projection: (element: T) => Iterable<U>): Query<U>; /** * Creates a subquery that iterates the results of applying a callback to each element. * * NOTE: This is an alias for `flatMap`. * * @param projection A callback used to map each element into an iterable. * @param projection.element The element to map. * @param resultSelector An optional callback used to map the outer and projected inner elements. * @param resultSelector.element The outer element to map. * @param resultSelector.innerElement An inner element produced by the `projection` of the outer element. * @category Subquery */ selectMany<U, R>(projection: (element: T) => Iterable<U>, resultSelector: (element: T, innerElement: U) => R): Query<R>; selectMany<U, R>(projection: (element: T) => Iterable<U>, resultSelector?: (element: T, innerElement: U) => R) { return this.flatMap(projection, resultSelector!); } // /** // * Creates a subquery that iterates the results of recursively expanding the // * elements of the source. // * // * @param projection A callback used to recusively expand each element. // * @param projection.element The element to expand. // * @category Subquery // */ // expand(projection: (element: T) => Iterable<T>): Query<T> { // return this._from(fn.expand(getSource(this), projection)); // } /** * Lazily invokes a callback as each element of the `Query` is iterated. * * @param callback The callback to invoke. * @param callback.element An element of the source. * @param callback.offset The offset from the start of the source iterable. * @category Subquery */ tap(callback: (element: T, offset: number) => void): UnorderedQueryFlow<this, T> { return this._from(fn.tap(getSource(this), callback)) as any; } /** * Creates a subquery whose elements are in the reverse order. * * @category Subquery */ reverse(): UnorderedQueryFlow<this, T> { return this._from(fn.reverse(getSource(this))) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery with every instance of the specified value removed. * * @param values The values to exclude. * @category Subquery */ exclude(...values: [T, ...T[]]): UnorderedQueryFlow<this, T> { return this._from(fn.exclude(getSource(this), ...values)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery containing all elements except the first elements up to the supplied * count. * * @param count The number of elements to drop. * @category Subquery */ drop(count: number): UnorderedQueryFlow<this, T> { return this._from(fn.drop(getSource(this), count)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery containing all elements except the last elements up to the supplied * count. * * @param count The number of elements to drop. * @category Subquery */ dropRight(count: number): UnorderedQueryFlow<this, T> { return this._from(fn.dropRight(getSource(this), count)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery containing all elements except the first elements that match * the supplied predicate. * * @param predicate A callback used to match each element. * @param predicate.element The element to match. * @category Subquery */ dropWhile(predicate: (element: T) => boolean): UnorderedQueryFlow<this, T> { return this._from(fn.dropWhile(getSource(this), predicate)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery containing all elements except the first elements that don't match * the supplied predicate. * * @param predicate A callback used to match each element. * @param predicate.element The element to match. * @category Subquery */ dropUntil(predicate: (element: T) => boolean): UnorderedQueryFlow<this, T> { return this._from(fn.dropUntil(getSource(this), predicate)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery containing all elements except the first elements up to the supplied * count. * * NOTE: This is an alias for `drop`. * * @param count The number of elements to skip. * @category Subquery */ skip(count: number) { return this.drop(count); } /** * Creates a subquery containing all elements except the last elements up to the supplied * count. * * NOTE: This is an alias for `dropRight`. * * @param count The number of elements to skip. * @category Subquery */ skipRight(count: number) { return this.dropRight(count); } /** * Creates a subquery containing all elements except the first elements that match * the supplied predicate. * * NOTE: This is an alias for `dropWhile`. * * @param predicate A callback used to match each element. * @param predicate.element The element to match. * @category Subquery */ skipWhile(predicate: (element: T) => boolean) { return this.dropWhile(predicate); } /** * Creates a subquery containing all elements except the first elements that don't match * the supplied predicate. * * NOTE: This is an alias for `dropUntil`. * * @param predicate A callback used to match each element. * @param predicate.element The element to match. * @category Subquery */ skipUntil(predicate: (element: T) => boolean) { return this.dropUntil(predicate); } /** * Creates a subquery containing the first elements up to the supplied * count. * * @param count The number of elements to take. * @category Subquery */ take(count: number): UnorderedQueryFlow<this, T> { return this._from(fn.take(getSource(this), count)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery containing the last elements up to the supplied * count. * * @param count The number of elements to take. * @category Subquery */ takeRight(count: number): UnorderedQueryFlow<this, T> { return this._from(fn.takeRight(getSource(this), count)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery containing the first elements that match the supplied predicate. * * @param predicate A callback used to match each element. * @param predicate.element The element to match. * @category Subquery */ takeWhile<U extends T>(predicate: (element: T) => element is U): UnorderedQueryFlow<this, U>; /** * Creates a subquery containing the first elements that match the supplied predicate. * * @param predicate A callback used to match each element. * @param predicate.element The element to match. */ takeWhile(predicate: (element: T) => boolean): UnorderedQueryFlow<this, T>; takeWhile(predicate: (element: T) => boolean) { return this._from(fn.takeWhile(getSource(this), predicate)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery containing the first elements that do not match the supplied predicate. * * @param predicate A callback used to match each element. * @param predicate.element The element to match. * @category Subquery */ takeUntil(predicate: (element: T) => boolean): UnorderedQueryFlow<this, T> { return this._from(fn.takeUntil(getSource(this), predicate)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery for the set intersection of this `Query` and another `Iterable`. * * @param right A `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ intersect<R extends Iterable<T>>(right: R, equaler?: Equaler<T>): MergeQueryFlow<this, R, T>; intersect(right: Iterable<T>, equaler?: Equaler<T>): Query<T>; intersect(right: Iterable<T>, equaler?: Equaler<T>): any { return this._from(fn.intersect(getSource(this), right, equaler)); } /** * Creates a subquery for the set intersection of this `Query` and another `Iterable`, where set identity is determined by the selected key. * * @param right A `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keySelector.element An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ intersectBy<K, R extends Iterable<T>>(right: R, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): MergeQueryFlow<this, R, T>; /** * Creates a subquery for the set intersection of this `Query` and another `Iterable`, where set identity is determined by the selected key. * * @param right A `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keySelector.element An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ intersectBy<K>(right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Query<T>; intersectBy<K>(right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): any { return this._from(fn.intersectBy(getSource(this), getSource(right), keySelector, keyEqualer)); } /** * Creates a subquery for the set union of this `Query` and another `Iterable`. * * @param right A `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ union<R extends Iterable<T>>(right: R, equaler?: Equaler<T>): MergeQueryFlow<this, R, T>; /** * Creates a subquery for the set union of this `Query` and another `Iterable`. * * @param right A `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ union(right: Iterable<T>, equaler?: Equaler<T>): Query<T>; union(right: Iterable<T>, equaler?: Equaler<T>): any { return this._from(fn.union(getSource(this), getSource(right), equaler)); } /** * Creates a subquery for the set union of this `Query` and another `Iterable`, where set identity is determined by the selected key. * * @param right A `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keySelector.element An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ unionBy<K, R extends Iterable<T>>(right: R, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): MergeQueryFlow<this, R, T>; /** * Creates a subquery for the set union of this `Query` and another `Iterable`, where set identity is determined by the selected key. * * @param right A `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keySelector.element An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ unionBy<K>(right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Query<T>; unionBy<K>(right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): any { return this._from(fn.unionBy(getSource(this), getSource(right), keySelector, keyEqualer)); } /** * Creates a subquery for the set difference between this and another `Iterable`. * * @param right A `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ except(right: Iterable<T>, equaler?: Equaler<T>): UnorderedQueryFlow<this, T> { return this._from(fn.except(getSource(this), getSource(right), equaler)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery for the set difference between this and another `Iterable`, where set identity is determined by the selected key. * * @param right A `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keySelector.element An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ exceptBy<K>(right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): UnorderedQueryFlow<this, T> { return this._from(fn.exceptBy(getSource(this), getSource(right), keySelector, keyEqualer)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery for the set difference between this and another `Iterable`. * * NOTE: This is an alias for `except`. * * @param right A `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ relativeComplement(right: Iterable<T>, equaler?: Equaler<T>): UnorderedQueryFlow<this, T> { return this.except(right, equaler); } /** * Creates a subquery for the set difference between this and another `Iterable`, where set identity is determined by the selected key. * * NOTE: This is an alias for `exceptBy`. * * @param right A `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keySelector.element An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ relativeComplementBy<K>(right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): UnorderedQueryFlow<this, T> { return this.exceptBy(right, keySelector, keyEqualer); } /** * Creates a subquery for the symmetric difference between this and another `Iterable`. * * @param right A `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ symmetricDifference<R extends Iterable<T>>(right: R, equaler?: Equaler<T>): MergeQueryFlow<this, R, T>; /** * Creates a subquery for the symmetric difference between this and another `Iterable`. * * @param right A `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ symmetricDifference(right: Iterable<T>, equaler?: Equaler<T>): Query<T>; symmetricDifference(right: Iterable<T>, equaler?: Equaler<T>): any { return this._from(fn.symmetricDifference(getSource(this), getSource(right), equaler)); } /** * Creates a subquery for the symmetric difference between this and another `Iterable`, where set identity is determined by the selected key. * * @param right A `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keySelector.element An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ symmetricDifferenceBy<K, R extends Iterable<T>>(right: R, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): MergeQueryFlow<this, R, T>; /** * Creates a subquery for the symmetric difference between this and another `Iterable`, where set identity is determined by the selected key. * * @param right A `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keySelector.element An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ symmetricDifferenceBy<K>(right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Query<T>; symmetricDifferenceBy<K>(right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): any { return this._from(fn.symmetricDifferenceBy(getSource(this), getSource(right), keySelector, keyEqualer)); } /** * Creates a subquery that concatenates this `Query` with another `Iterable`. * * @param right A `Iterable` object. * @category Subquery */ concat<R extends Iterable<T>>(right: R): MergeQueryFlow<this, R, T>; /** * Creates a subquery that concatenates this `Query` with another `Iterable`. * * @param right A `Iterable` object. * @category Subquery */ concat(right: Iterable<T>): Query<T>; concat(right: Iterable<T>): any { return this._from(fn.concat(getSource(this), getSource(right))); } /** * Creates a subquery for the distinct elements of this `Query`. * @param equaler An `Equaler` object used to compare key equality. * @category Subquery */ distinct(equaler?: Equaler<T>): UnorderedQueryFlow<this, T> { return this._from(fn.distinct(getSource(this), equaler)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery for the distinct elements of this `Query`. * * @param keySelector A callback used to select the key to determine uniqueness. * @param keySelector.value An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ distinctBy<K>(keySelector: (value: T) => K, keyEqualer?: Equaler<K>): UnorderedQueryFlow<this, T> { return this._from(fn.distinctBy(getSource(this), keySelector, keyEqualer)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery for the elements of this `Query` with the provided value appended to the end. * * @param value The value to append. * @category Subquery */ append(value: T): UnorderedQueryFlow<this, T> { return this._from(fn.append(getSource(this), value)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery for the elements of this `Query` with the provided value prepended to the beginning. * * @param value The value to prepend. * @category Subquery */ prepend(value: T): UnorderedQueryFlow<this, T> { return this._from(fn.prepend(getSource(this), value)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery for the elements of this `Query` with the provided range * patched into the results. * * @param start The offset at which to patch the range. * @param skipCount The number of elements to skip from start. * @param range The range to patch into the result. * @category Subquery */ patch(start: number, skipCount?: number, range?: Iterable<T>): UnorderedQueryFlow<this, T> { return this._from(fn.patch(getSource(this), start, skipCount, range && getSource(range))) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery that contains the provided default value if this `Query` * contains no elements. * * @param defaultValue The default value. * @category Subquery */ defaultIfEmpty(defaultValue: T): UnorderedQueryFlow<this, T> { return this._from(fn.defaultIfEmpty(getSource(this), defaultValue)) as UnorderedQueryFlow<this, T>; } /** * Creates a subquery that splits this `Query` into one or more pages. * While advancing from page to page is evaluated lazily, the elements of the page are * evaluated eagerly. * * @param pageSize The number of elements per page. * @category Subquery */ pageBy(pageSize: number): PagedQueryFlow<this, T>; /** * Creates a subquery that splits this `Query` into one or more pages. * While advancing from page to page is evaluated lazily, the elements of the page are * evaluated eagerly. * * @param pageSize The number of elements per page. * @category Subquery */ pageBy<R>(pageSize: number, pageSelector: (page: number, offset: number, values: UnorderedQueryFlow<this, T>) => R): Query<R>; pageBy<R>(pageSize: number, pageSelector?: (page: number, offset: number, values: UnorderedQueryFlow<this, T>) => R) { return this._from(fn.pageBy(getSource(this), pageSize, wrapPageSelector(this, pageSelector as (page: number, offset: number, values: Query<T>) => R))); } /** * Creates a subquery whose elements are the contiguous ranges of elements that share the same key. * * @param keySelector A callback used to select the key for an element. * @param keySelector.element An element from which to select a key. * @category Subquery */ spanMap<K>(keySelector: (element: T) => K, keyEqualer?: Equaler<K>): GroupedQueryFlow<this, K, T>; /** * Creates a subquery whose values are computed from each element of the contiguous ranges of elements that share the same key. * * @param keySelector A callback used to select the key for an element. * @param keySelector.element An element from which to select a key. * @param elementSelector A callback used to select a value for an element. * @param elementSelector.element An element from which to select a value. * @category Subquery */ spanMap<K, V>(keySelector: (element: T) => K, elementSelector: (element: T) => V, keyEqualer?: Equaler<K>): GroupedQueryFlow<this, K, V>; /** * Creates a subquery whose values are computed from the contiguous ranges of elements that share the same key. * * @param keySelector A callback used to select the key for an element. * @param keySelector.element An element from which to select a key. * @param elementSelector A callback used to select a value for an element. * @param elementSelector.element An element from which to select a value. * @param spanSelector A callback used to select a result from a contiguous range. * @param spanSelector.key The key for the span. * @param spanSelector.elements The elements for the span. * @category Subquery */ spanMap<K, V, R>(keySelector: (element: T) => K, elementSelector: (element: T) => V, spanSelector: (key: K, elements: Query<V>) => R, keyEqualer?: Equaler<K>): Query<R>; /** * Creates a subquery whose values are computed from the contiguous ranges of elements that share the same key. * * @param keySelector A callback used to select the key for an element. * @param keySelector.element An element from which to select a key. * @param elementSelector A callback used to select a value for an element. * @param elementSelector.element An element from which to select a value. * @param spanSelector A callback used to select a result from a contiguous range. * @param spanSelector.key The key for the span. * @param spanSelector.elements The elements for the span. * @category Subquery */ spanMap<K, R>(keySelector: (element: T) => K, elementSelector: undefined, spanSelector: (key: K, elements: Query<T>) => R, keyEqualer?: Equaler<K>): Query<R>; spanMap<K, V, R>(keySelector: (element: T) => K, elementSelector?: ((element: T) => T | V) | Equaler<K>, spanSelector?: ((key: K, elements: Query<T | V>) => Grouping<K, T | V> | R) | Equaler<K>, keyEqualer?: Equaler<K>) { if (typeof elementSelector === "object") { keyEqualer = elementSelector; elementSelector = fn.identity; } if (typeof spanSelector === "object") { keyEqualer = spanSelector; spanSelector = Grouping.from; } return this._from(fn.spanMap(getSource(this), keySelector, elementSelector!, wrapResultSelector(this, spanSelector!), keyEqualer)); } /** * Groups each element of this `Query` by its key. * * @param keySelector A callback used to select the key for an element. * @param keySelector.element An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ groupBy<K>(keySelector: (element: T) => K, keyEqualer?: Equaler<K>): GroupedQueryFlow<this, K, T>; /** * Groups each element by its key. * * @param keySelector A callback used to select the key for an element. * @param keySelector.element An element from which to select a key. * @param elementSelector A callback used to select a value for an element. * @param elementSelector.element An element from which to select a value. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ groupBy<K, V>(keySelector: (element: T) => K, elementSelector: (element: T) => V, keyEqualer?: Equaler<K>): GroupedQueryFlow<this, K, V>; /** * Groups each element by its key. * * @param keySelector A callback used to select the key for an element. * @param keySelector.element An element from which to select a key. * @param elementSelector A callback used to select a value for an element. * @param elementSelector.element An element from which to select a value. * @param resultSelector A callback used to select a result from a group. * @param resultSelector.key The key for the group. * @param resultSelector.elements The elements for the group. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ groupBy<K, V, R>(keySelector: (element: T) => K, elementSelector: (element: T) => V, resultSelector: (key: K, elements: Query<V>) => R, keyEqualer?: Equaler<K>): Query<R>; /** * Groups each element by its key. * * @param keySelector A callback used to select the key for an element. * @param keySelector.element An element from which to select a key. * @param elementSelector A callback used to select a value for an element. * @param elementSelector.element An element from which to select a value. * @param resultSelector A callback used to select a result from a group. * @param resultSelector.key The key for the group. * @param resultSelector.elements The elements for the group. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ groupBy<K, R>(keySelector: (element: T) => K, elementSelector: undefined, resultSelector: (key: K, elements: Query<T>) => R, keyEqualer?: Equaler<K>): Query<R>; groupBy<K, V, R>(keySelector: (element: T) => K, elementSelector?: ((element: T) => V) | Equaler<K>, resultSelector?: ((key: K, elements: Query<V>) => R) | Equaler<K>, keyEqualer?: Equaler<K>) { if (typeof elementSelector === "object") { resultSelector = elementSelector; elementSelector = undefined; } if (typeof resultSelector === "object") { keyEqualer = resultSelector; resultSelector = undefined; } return this._from(fn.groupBy(getSource(this), keySelector, elementSelector!, wrapResultSelector(this, resultSelector!), keyEqualer)); } /** * Creates a subquery containing the cumulative results of applying the provided callback to each element. * * @param accumulator The callback used to compute each result. * @param accumulator.current The current accumulated value. * @param accumulator.element The value to accumulate. * @param accumulator.offset The offset from the start of the underlying `Iterable`. * @category Subquery */ scan(accumulator: (current: T, element: T, offset: number) => T): Query<T>; /** * Creates a subquery containing the cumulative results of applying the provided callback to each element. * * @param accumulator The callback used to compute each result. * @param accumulator.current The current accumulated value. * @param accumulator.element The value to accumulate. * @param accumulator.offset The offset from the start of the underlying `Iterable`. * @param seed An optional seed value. * @category Subquery */ scan<U>(accumulator: (current: U, element: T, offset: number) => U, seed: U): Query<U>; scan(accumulator: (current: T, element: T, offset: number) => T, seed?: T): Query<T> { return this._from(arguments.length > 1 ? fn.scan(getSource(this), accumulator, seed as T) : fn.scan(getSource(this), accumulator)); } /** * Creates a subquery containing the cumulative results of applying the provided callback to each element in reverse. * * @param accumulator The callback used to compute each result. * @param accumulator.current The current accumulated value. * @param accumulator.element The value to accumulate. * @param accumulator.offset The offset from the start of the underlying `Iterable`. * @category Subquery */ scanRight(accumulator: (current: T, element: T, offset: number) => T): Query<T>; /** * Creates a subquery containing the cumulative results of applying the provided callback to each element in reverse. * * @param accumulator The callback used to compute each result. * @param accumulator.current The current accumulated value. * @param accumulator.element The value to accumulate. * @param accumulator.offset The offset from the start of the underlying `Iterable`. * @param seed An optional seed value. * @category Subquery */ scanRight<U>(accumulator: (current: U, element: T, offset: number) => U, seed?: U): Query<U>; scanRight(accumulator: (current: T, element: T, offset: number) => T, seed?: T): Query<T> { return this._from(arguments.length > 1 ? fn.scanRight(getSource(this), accumulator, seed as T) : fn.scanRight(getSource(this), accumulator)); } /** * Pass the entire `Query` to the provided callback, creating a new `Query` from the result. * * @param callback A callback function. * @param callback.source The outer `Query`. * @category Subquery */ through<R extends Iterable<any>>(callback: (source: this) => R): QueryFlow<R, R extends Iterable<infer U> ? U : unknown> { return this._from(this.into(callback)) as QueryFlow<R, R extends Iterable<infer U> ? U : unknown>; } /** * Eagerly evaluate the `Query`, returning a new `Query`. * @category Subquery */ materialize(): UnorderedQueryFlow<this, T> { return this._from(fn.materialize(getSource(this))) as UnorderedQueryFlow<this, T>; } // #endregion Subquery // #region Join /** * Creates a grouped subquery for the correlated elements of this `Query` and another `Iterable` object. * * @param inner A `Iterable` object. * @param outerKeySelector A callback used to select the key for an element in this `Query`. * @param innerKeySelector A callback used to select the key for an element in the other `Iterable` object. * @param resultSelector A callback used to select the result for the correlated elements. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Join */ groupJoin<I, K, R>(inner: Iterable<I>, outerKeySelector: (element: T) => K, innerKeySelector: (element: I) => K, resultSelector: (outer: T, inner: Query<I>) => R, keyEqualer?: Equaler<K>): Query<R> { return this._from(fn.groupJoin(getSource(this), getSource(inner), outerKeySelector, innerKeySelector, wrapResultSelector(this, resultSelector), keyEqualer)); } /** * Creates a subquery for the correlated elements of this `Query` and another `Iterable`. * * @param inner A `Iterable` object. * @param outerKeySelector A callback used to select the key for an element in this `Query`. * @param innerKeySelector A callback used to select the key for an element in the other Iterable. * @param resultSelector A callback used to select the result for the correlated elements. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Join */ join<I, K, R>(inner: Iterable<I>, outerKeySelector: (element: T) => K, innerKeySelector: (element: I) => K, resultSelector: (outer: T, inner: I) => R, keyEqualer?: Equaler<K>): Query<R> { return this._from(fn.join(getSource(this), getSource(inner), outerKeySelector, innerKeySelector, resultSelector, keyEqualer)); } /** * Creates a subquery for the correlated elements of this `Query` and another `Iterable`. * * @param inner A `Iterable` object. * @param outerKeySelector A callback used to select the key for an element in this `Query`. * @param innerKeySelector A callback used to select the key for an element in the other Iterable. * @param resultSelector A callback used to select the result for the correlated elements. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Join */ fullJoin<I, K, R>(inner: Iterable<I>, outerKeySelector: (element: T) => K, innerKeySelector: (element: I) => K, resultSelector: (outer: T | undefined, inner: I | undefined) => R, keyEqualer?: Equaler<K>): Query<R> { return this._from(fn.fullJoin(getSource(this), getSource(inner), outerKeySelector, innerKeySelector, resultSelector, keyEqualer)); } /** * Creates a subquery that combines this `Query` with another `Iterable` by combining elements * in tuples. * * @param right A `Iterable` object. * @category Join */ zip<U>(right: Iterable<U>): Query<[T, U]>; /** * Creates a subquery that combines this `Query` with another `Iterable` by combining elements * using the supplied callback. * * @param right A `Iterable` object. * @param selector A callback used to combine two elements. * @category Join */ zip<U, R>(right: Iterable<U>, selector: (left: T, right: U) => R): Query<R>; zip<U, R>(right: Iterable<U>, selector?: (left: T, right: U) => R): Query<R> { return this._from(fn.zip(getSource(this), getSource(right), selector!)); } // #endregion Join // #region Order /** * Creates an ordered subquery whose elements are sorted in ascending order by the provided key. * * @param keySelector A callback used to select the key for an element. * @param comparer An optional callback used to compare two keys. * @category Order */ orderBy<K>(keySelector: (element: T) => K, comparer?: Comparison<K> | Comparer<K>): OrderedQueryFlow<this, T> { return this._from(fn.orderBy(getSource(this), keySelector, comparer)) as OrderedQueryFlow<this, T>; } /** * Creates an ordered subquery whose elements are sorted in descending order by the provided key. * * @param keySelector A callback used to select the key for an element. * @param comparer An optional callback used to compare two keys. * @category Order */ orderByDescending<K>(keySelector: (element: T) => K, comparer?: Comparison<K> | Comparer<K>): OrderedQueryFlow<this, T> { return this._from(fn.orderByDescending(getSource(this), keySelector, comparer)) as OrderedQueryFlow<this, T>; } // #endregion Order // #region Hierarchy /** * Creates a `HierarchyQuery` using the provided `HierarchyProvider`. * * @param provider A `HierarchyProvider`. * @category Hierarchy */ toHierarchy<TNode extends (T extends TNode ? unknown : never)>(provider: HierarchyProvider<TNode>): HierarchyQueryFlow<this, TNode, T> { return this._from(fn.toHierarchy(getSource(this) as Iterable<TNode & T>, provider)) as HierarchyQueryFlow<this, TNode, T>; } // #endregion Hierarchy // #region Scalar /** * Computes a scalar value by applying an accumulator callback over each element. * * @param accumulator the callback used to compute the result. * @param accumulator.current The current accumulated value. * @param accumulator.element The value to accumulate. * @param accumulator.offset The offset from the start of the underlying `Iterable`. * @category Scalar */ reduce(accumulator: (current: T, element: T, offset: number) => T): T; /** * Computes a scalar value by applying an accumulator callback over each element. * * @param accumulator the callback used to compute the result. * @param accumulator.current The current accumulated value. * @param accumulator.element The value to accumulate. * @param accumulator.offset The offset from the start of the underlying `Iterable`. * @param seed An optional seed value. * @category Scalar */ reduce<U>(accumulator: (current: U, element: T, offset: number) => U, seed: U, resultSelector?: (result: U, count: number) => U): U; /** * Computes a scalar value by applying an accumulator callback over each element. * * @param accumulator the callback used to compute the result. * @param accumulator.current The current accumulated value. * @param accumulator.element The value to accumulate. * @param accumulator.offset The offset from the start of the underlying `Iterable`. * @param seed An optional seed value. * @param resultSelector An optional callback used to compute the final result. * @category Scalar */ reduce<U, R>(accumulator: (current: U, element: T, offset: number) => U, seed: U, resultSelector: (result: U, count: number) => R): R; reduce(accumulator: (current: T, element: T, offset: number) => T, seed?: T, resultSelector?: (result: T, count: number) => T): T { return arguments.length > 1 ? fn.reduce(getSource(this), accumulator, seed as T, resultSelector!) : fn.reduce(getSource(this), accumulator); } /** * Computes a scalar value by applying an accumulator callback over each element in reverse. * * @param accumulator the callback used to compute the result. * @category Scalar */ reduceRight(accumulator: (current: T, element: T, offset: number) => T): T; /** * Computes a scalar value by applying an accumulator callback over each element in reverse. * * @param accumulator the callback used to compute the result. * @param seed An optional seed value. * @category Scalar */ reduceRight<U>(accumulator: (current: U, element: T, offset: number) => U, seed: U, resultSelector?: (result: U, count: number) => U): U; /** * Computes a scalar value by applying an accumulator callback over each element in reverse. * * @param accumulator the callback used to compute the result. * @param seed An optional seed value. * @param resultSelector An optional callback used to compute the final result. * @category Scalar */ reduceRight<U, R>(accumulator: (current: U, element: T, offset: number) => U, seed: U, resultSelector: (result: U, count: number) => R): R; reduceRight(accumulator: (current: T, element: T, offset: number) => T, seed?: T, resultSelector?: (result: T, count: number) => T): T { return arguments.length > 1 ? fn.reduceRight(getSource(this), accumulator, seed as T, resultSelector!) : fn.reduceRight(getSource(this), accumulator); } /** * Counts the number of elements in the `Query`, optionally filtering elements using the supplied * callback. * * @param predicate An optional callback used to match each element. * @category Scalar */ count(predicate?: (element: T) => boolean): number { return fn.count(getSource(this), predicate); } /** * Gets the first element in the `Query`, optionally filtering elements using the supplied * callback. * * @param predicate An optional callback used to match each element. * @category Scalar */ first<U extends T>(predicate: (element: T) => element is U): U | undefined; /** * Gets the first element in the `Query`, optionally filtering elements using the supplied * callback. * * @param predicate An optional callback used to match each element. * @category Scalar */ first(predicate?: (element: T) => boolean): T | undefined; first(predicate?: (element: T) => boolean): T | undefined { return fn.first(getSource(this), predicate); } /** * Gets the last element in the `Query`, optionally filtering elements using the supplied * callback. * * @param predicate An optional callback used to match each element. * @category Scalar */ last<U extends T>(predicate: (element: T) => element is U): U | undefined; /** * Gets the last element in the `Query`, optionally filtering elements using the supplied * callback. * * @param predicate An optional callback used to match each element. * @category Scalar */ last(predicate?: (element: T) => boolean): T | undefined; last(predicate?: (element: T) => boolean): T | undefined { return fn.last(getSource(this), predicate); } /** * Gets the only element in the `Query`, or returns `undefined`. * * @param predicate An optional callback used to match each element. * @category Scalar */ single<U extends T>(predicate: (element: T) => element is U): U | undefined; /** * Gets the only element in the `Query`, or returns undefined. * * @param predicate An optional callback used to match each element. * @category Scalar */ single(predicate?: (element: T) => boolean): T | undefined; single(predicate?: (element: T) => boolean): T | undefined { return fn.single(getSource(this), predicate); } /** * Gets the minimum element in the `Query`, optionally comparing elements using the supplied * callback. * * @param comparer An optional callback used to compare two elements. * @category Scalar */ min(comparer?: Comparison<T> | Comparer<T>): T | undefined { return fn.min(getSource(this), comparer); } /** * Gets the minimum element by its key in the `Query`, optionally comparing the keys of each element using the supplied callback. * * @param keySelector A callback used to choose the key to compare. * @param keyComparer An optional callback used to compare the keys. * @category Scalar */ minBy<K>(keySelector: (element: T) => K, keyComparer?: Comparison<K> | Comparer<K>): T | undefined { return fn.minBy(getSource(this), keySelector, keyComparer); } /** * Gets the maximum element in the `Query`, optionally comparing elements using the supplied * callback. * * @param comparer An optional callback used to compare two elements. * @category Scalar */ max(comparer?: Comparison<T> | Comparer<T>): T | undefined { return fn.max(getSource(this), comparer); } /** * Gets the maximum element by its key in the `Query`, optionally comparing the keys of each element using the supplied callback. * * @param keySelector A callback used to choose the key to compare. * @param keyComparer An optional callback used to compare the keys. * @category Scalar */ maxBy<K>(keySelector: (element: T) => K, keyComparer?: Comparison<K> | Comparer<K>): T | undefined { return fn.maxBy(getSource(this), keySelector, keyComparer); } /** * Computes the sum for a series of numbers. * * @category Scalar */ sum(): T extends number ? number : never; /** * Computes the sum for a series of numbers. * * @category Scalar */ sum(elementSelector: (element: T) => number): number; sum(elementSelector?: (element: T) => number): number { return fn.sum(getSource(this), elementSelector!); } /** * Computes the average for a series of numbers. * * @category Scalar */ average(): T extends number ? number : never; /** * Computes the average for a series of numbers. * * @category Scalar */ average(elementSelector: (element: T) => number): number; average(elementSelector?: (element: T) => number): number { return fn.average(getSource(this), elementSelector!); } /** * Computes a scalar value indicating whether the `Query` contains any elements, * optionally filtering the elements using the supplied callback. * * @param predicate An optional callback used to match each element. * @category Scalar */ some(predicate?: (element: T) => boolean): boolean { return fn.some(getSource(this), predicate); } /** * Computes a scalar value indicating whether all elements of the `Query` * match the supplied callback. * * @param predicate A callback used to match each element. * @category Scalar */ every<U extends T>(predicate: (element: T) => element is U): this is Query<U>; /** * Computes a scalar value indicating whether all elements of the `Query` * match the supplied callback. * * @param predicate A callback used to match each element. * @category Scalar */ every(predicate: (element: T) => boolean): boolean; every(predicate: (element: T) => boolean): boolean { return fn.every(getSource(this), predicate); } /** * Computes a scalar value indicating whether every element in this `Query` corresponds to a matching element * in another `Iterable` at the same position. * * @param right A `Iterable` object. * @param equaler An optional callback used to compare the equality of two elements. * @category Scalar */ corresponds(right: Iterable<T>, equaler?: EqualityComparison<T> | Equaler<T>): boolean; /** * Computes a scalar value indicating whether every element in this `Query` corresponds to a matching element * in another `Iterable` at the same position. * * @param right A `Iterable` object. * @param equaler An optional callback used to compare the equality of two elements. * @category Scalar */ corresponds<U>(right: Iterable<U>, equaler: (left: T, right: U) => boolean): boolean; corresponds(right: Iterable<T>, equaler?: EqualityComparison<T> | Equaler<T>): boolean { return fn.corresponds(getSource(this), getSource(right), equaler!); } /** * Computes a scalar value indicating whether every element in this `Query` corresponds to a matching element * in another `Iterable` at the same position. * * @param right A `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keyEqualer An `Equaler` used to compare the equality of two keys. * @category Scalar */ correspondsBy<K>(right: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): boolean; /** * Computes a scalar value indicating whether the key for every element in this `Query` corresponds to a matching key * in `right` at the same position. * * @param right A `Iterable` object. * @param leftKeySelector A callback used to select the key for each element in this `Query`. * @param rightKeySelector A callback used to select the key for each element in `right`. * @param keyEqualer An optional callback used to compare the equality of two keys. * @category Scalar */ correspondsBy<U, K>(right: Iterable<U>, leftKeySelector: (element: T) => K, rightKeySelector: (element: U) => K, keyEqualer?: EqualityComparison<K> | Equaler<K>): boolean; correspondsBy<U, K>(right: Iterable<U>, leftKeySelector: (element: T) => K, rightKeySelector?: ((element: U) => K) | Equaler<K>, keyEqualer?: EqualityComparison<K> | Equaler<K>): boolean { if (typeof rightKeySelector === "object") { keyEqualer = rightKeySelector; rightKeySelector = undefined; } return fn.correspondsBy(getSource(this), getSource(right), leftKeySelector, rightKeySelector!, keyEqualer); } /** * Computes a scalar value indicating whether the provided value is included in the `Query`. * * @param value A value. * @param equaler An optional callback used to compare the equality of two elements. * @category Scalar */ includes(value: T, equaler?: EqualityComparison<T> | Equaler<T>): boolean; /** * Computes a scalar value indicating whether the provided value is included in the `Query`. * * @param value A value. * @param equaler An optional callback used to compare the equality of two elements. * @category Scalar */ includes<U>(value: U, equaler: (left: T, right: U) => boolean): boolean; includes(value: T, equaler?: EqualityComparison<T> | Equaler<T>): boolean { return fn.includes(getSource(this), value, equaler!); } /** * Computes a scalar value indicating whether the elements of this `Query` include * an exact sequence of elements from another `Iterable`. * * @param right A `Iterable` object. * @param equaler A callback used to compare the equality of two elements. * @category Scalar */ includesSequence(right: Iterable<T>, equaler?: EqualityComparison<T> | Equaler<T>): boolean; /** * Computes a scalar value indicating whether the elements of this `Query` include * an exact sequence of elements from another `Iterable`. * * @param right A `Iterable` object. * @param equaler A callback used to compare the equality of two elements. * @category Scalar */ includesSequence<U>(right: Iterable<U>, equaler: (left: T, right: U) => boolean): boolean; includesSequence(right: Iterable<T>, equaler?: EqualityComparison<T> | Equaler<T>): boolean { return fn.includesSequence(getSource(this), getSource(right), equaler!); } /** * Computes a scalar value indicating whether the elements of this `Query` start * with the same sequence of elements in another `Iterable`. * * @param right A `Iterable` object. * @param equaler A callback used to compare the equality of two elements. * @category Scalar */ startsWith(right: Iterable<T>, equaler?: EqualityComparison<T> | Equaler<T>): boolean; /** * Computes a scalar value indicating whether the elements of this `Query` start * with the same sequence of elements in another `Iterable`. * * @param right A `Iterable` object. * @param equaler A callback used to compare the equality of two elements. * @category Scalar */ startsWith<U>(right: Iterable<U>, equaler: (left: T, right: U) => boolean): boolean; startsWith(right: Iterable<T>, equaler?: EqualityComparison<T> | Equaler<T>): boolean { return fn.startsWith(getSource(this), getSource(right), equaler!); } /** * Computes a scalar value indicating whether the elements of this `Query` end * with the same sequence of elements in another `Iterable`. * * @param right A `Iterable` object. * @param equaler A callback used to compare the equality of two elements. * @category Scalar */ endsWith(right: Iterable<T>, equaler?: EqualityComparison<T> | Equaler<T>): boolean; /** * Computes a scalar value indicating whether the elements of this `Query` end * with the same sequence of elements in another `Iterable`. * * @param right A `Iterable` object. * @param equaler A callback used to compare the equality of two elements. * @category Scalar */ endsWith<U>(right: Iterable<U>, equaler: (left: T, right: U) => boolean): boolean; endsWith(right: Iterable<T>, equaler?: EqualityComparison<T> | Equaler<T>): boolean { return fn.endsWith(getSource(this), getSource(right), equaler!); } /** * Finds the value in the `Query` at the provided offset. A negative offset starts from the * last element. * * @param offset An offset. * @category Scalar */ elementAt(offset: number | Index): T | undefined { return fn.elementAt(getSource(this), offset); } /** * Finds the value in the `Query` at the provided offset. A negative offset starts from the * last element. * * NOTE: This is an alias for `elementAt`. * * @param offset An offset. * @category Scalar */ nth(offset: number | Index): T | undefined { return fn.nth(getSource(this), offset); } /** * Creates a tuple whose first element is a subquery containing the first span of * elements that match the supplied predicate, and whose second element is a subquery * containing the remaining elements. * * The first subquery is eagerly evaluated, while the second subquery is lazily * evaluated. * * @param predicate The predicate used to match elements. * @category Scalar */ span<U extends T>(predicate: (element: T, offset: number) => element is U): [UnorderedQueryFlow<this, U>, UnorderedQueryFlow<this, T>]; /** * Creates a tuple whose first element is a subquery containing the first span of * elements that match the supplied predicate, and whose second element is a subquery * containing the remaining elements. * * The first subquery is eagerly evaluated, while the second subquery is lazily * evaluated. * * @param predicate The predicate used to match elements. * @category Scalar */ span(predicate: (element: T, offset: number) => boolean): [UnorderedQueryFlow<this, T>, UnorderedQueryFlow<this, T>]; span(predicate: (element: T, offset: number) => boolean): [UnorderedQueryFlow<this, T>, UnorderedQueryFlow<this, T>] { const [left, right] = fn.span(getSource(this), predicate); return [from(left) as UnorderedQueryFlow<this, T>, from(right) as UnorderedQueryFlow<this, T>]; } /** * Creates a tuple whose first element is a subquery containing the first span of * elements that do not match the supplied predicate, and whose second element is a subquery * containing the remaining elements. * * The first subquery is eagerly evaluated, while the second subquery is lazily * evaluated. * * @param predicate The predicate used to match elements. * @category Scalar */ spanUntil(predicate: (element: T, offset: number) => boolean): [UnorderedQueryFlow<this, T>, UnorderedQueryFlow<this, T>] { const [left, right] = fn.spanUntil(getSource(this), predicate); return [from(left) as UnorderedQueryFlow<this, T>, from(right) as UnorderedQueryFlow<this, T>]; } /** * Creates a tuple whose first element is a subquery containing the first span of * elements that do not match the supplied predicate, and whose second element is a subquery * containing the remaining elements. * * The first subquery is eagerly evaluated, while the second subquery is lazily * evaluated. * * NOTE: This is an alias for `spanUntil`. * * @param predicate The predicate used to match elements. * @category Scalar */ break(predicate: (element: T, offset: number) => boolean): [UnorderedQueryFlow<this, T>, UnorderedQueryFlow<this, T>] { return this.spanUntil(predicate); } /** * Invokes a callback for each element of the `Query`. * * @param callback The callback to invoke. * @category Scalar */ forEach(callback: (element: T, offset: number) => void): void { fn.forEach(getSource(this), callback); } // /** // * Iterates over all of the elements in the `Query`, ignoring the results. // * @category Scalar // */ // drain(): void { // fn.drain(getSource(this)); // } /** * Unzips a sequence of tuples into a tuple of sequences. * @param source A `Iterable` * @category Scalar */ unzip(): T extends [any, ...any[]] ? { [I in keyof T]: T[I][]; } : unknown[]; /** * Unzips a sequence of tuples into a tuple of sequences. * @param source A `Iterable` * @param partSelector A callback that converts a result into a tuple. * @category Scalar */ unzip<U extends [any, ...any[]]>(partSelector: (value: T) => U): { [I in keyof U]: U[I][]; }; unzip<U extends [any, ...any[]]>(partSelector?: (value: T) => U): any { return fn.unzip(getSource(this), partSelector!); } /** * Creates an Array for the elements of the `Query`. * @category Scalar */ toArray(): T[]; /** * Creates an Array for the elements of the `Query`. * * @param elementSelector A callback that selects a value for each element. * @category Scalar */ toArray<V>(elementSelector: (element: T) => V): V[]; toArray<V>(elementSelector?: (element: T) => V): V[] { return fn.toArray(getSource(this), elementSelector!); } /** * Creates a `Set` for the elements of the `Query`. * @category Scalar */ toSet(): Set<T>; /** * Creates a `Set` for the elements of the `Query`. * * @param elementSelector A callback that selects a value for each element. * @category Scalar */ toSet<V>(elementSelector: (element: T) => V): Set<V>; toSet<V>(elementSelector?: ((element: T) => T | V) | Equaler<T>): Set<T | V> { return fn.toSet(getSource(this), elementSelector as (element: T) => T | V); } /** * Creates a `HashSet` for the elements of the `Query`. * * @param equaler An `Equaler` object used to compare equality. * @category Scalar */ toHashSet(equaler?: Equaler<T>): HashSet<T>; /** * Creates a `HashSet` for the elements of the `Query`. * * @param elementSelector A callback that selects a value for each element. * @param equaler An `Equaler` object used to compare equality. * @category Scalar */ toHashSet<V>(elementSelector: (element: T) => V, equaler?: Equaler<V>): HashSet<V>; toHashSet<V>(elementSelector?: ((element: T) => T | V) | Equaler<T>, equaler?: Equaler<T>): HashSet<T | V> { return fn.toHashSet(getSource(this), elementSelector as (element: T) => T | V, equaler!); } /** * Creates a `Map` for the elements of the `Query`. * * @param keySelector A callback used to select a key for each element. * @category Scalar */ toMap<K>(keySelector: (element: T) => K): Map<K, T>; /** * Creates a `Map` for the elements of the `Query`. * * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @category Scalar */ toMap<K, V>(keySelector: (element: T) => K, elementSelector: (element: T) => V): Map<K, V>; toMap<K>(keySelector: (element: T) => K, elementSelector?: (element: T) => T) { return fn.toMap(getSource(this), keySelector, elementSelector!); } /** * Creates a `Map` for the elements of the `Query`. * * @param keySelector A callback used to select a key for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Scalar */ toHashMap<K>(keySelector: (element: T) => K, keyEqualer?: Equaler<K>): HashMap<K, T>; /** * Creates a `Map` for the elements of the `Query`. * * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Scalar */ toHashMap<K, V>(keySelector: (element: T) => K, elementSelector: (element: T) => V, keyEqualer?: Equaler<K>): HashMap<K, V>; toHashMap<K, V>(keySelector: (element: T) => K, elementSelector?: ((element: T) => T | V) | Equaler<K>, keyEqualer?: Equaler<K>) { return fn.toHashMap(getSource(this), keySelector, elementSelector as (element: T) => T | V, keyEqualer!); } /** * Creates a `Lookup` for the elements of the `Query`. * * @param keySelector A callback used to select a key for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Scalar */ toLookup<K>(keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Lookup<K, T>; /** * Creates a `Lookup` for the elements of the `Query`. * * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Scalar */ toLookup<K, V>(keySelector: (element: T) => K, elementSelector: (element: T) => V, keyEqualer?: Equaler<K>): Lookup<K, V>; toLookup<K, V>(keySelector: (element: T) => K, elementSelector?: ((element: T) => V) | Equaler<K>, keyEqualer?: Equaler<K>): Lookup<K, V> { return fn.toLookup(getSource(this), keySelector, elementSelector as (element: T) => V, keyEqualer!); } /** * Creates an Object for the elements of the `Query`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = from(`"`, 1], ["y", 2]]).toObject(undefined, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = from(`"`, 1], ["y", 2]]).toObject(baseObject, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * obj.toString(); // "x",1:"y",2 * * // with a null prototype * const obj = from(`"`, 1], ["y", 2]]).toObject(null, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // undefined * ``` * * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @category Scalar */ toObject<TProto extends object, K extends PropertyKey>(prototype: TProto, keySelector: (element: T) => K): TProto & Record<K, T>; /** * Creates an Object for the elements of the `Query`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = from(`"`, 1], ["y", 2]]).toObject(undefined, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = from(`"`, 1], ["y", 2]]).toObject(baseObject, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * obj.toString(); // "x",1:"y",2 * * // with a null prototype * const obj = from(`"`, 1], ["y", 2]]).toObject(null, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // undefined * ``` * * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @category Scalar */ toObject<TProto extends object>(prototype: TProto, keySelector: (element: T) => PropertyKey): TProto & Record<PropertyKey, T>; /** * Creates an Object for the elements of the `Query`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = from(`"`, 1], ["y", 2]]).toObject(undefined, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = from(`"`, 1], ["y", 2]]).toObject(baseObject, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * obj.toString(); // "x",1:"y",2 * * // with a null prototype * const obj = from(`"`, 1], ["y", 2]]).toObject(null, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // undefined * ``` * * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @category Scalar */ toObject<K extends PropertyKey>(prototype: object | null | undefined, keySelector: (element: T) => K): Record<K, T>; /** * Creates an Object for the elements of the `Query`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = from(`"`, 1], ["y", 2]]).toObject(undefined, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = from(`"`, 1], ["y", 2]]).toObject(baseObject, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * obj.toString(); // "x",1:"y",2 * * // with a null prototype * const obj = from(`"`, 1], ["y", 2]]).toObject(null, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // undefined * ``` * * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @category Scalar */ toObject(prototype: object | null | undefined, keySelector: (element: T) => PropertyKey): Record<PropertyKey, T>; /** * Creates an Object for the elements the `Query`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = from(`"`, 1], ["y", 2]]).toObject(undefined, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = from(`"`, 1], ["y", 2]]).toObject(baseObject, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * obj.toString(); // 1:2 * * // with a null prototype * const obj = from(`"`, 1], ["y", 2]]).toObject(null, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // undefined * ``` * * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param descriptorSelector A callback that defines the `PropertyDescriptor` for each property. * @category Scalar */ toObject<TProto extends object, K extends PropertyKey, V>(prototype: TProto, keySelector: (element: T) => K, elementSelector: (element: T) => V, descriptorSelector?: (key: K, element: V) => TypedPropertyDescriptor<V>): TProto & Record<K, V>; /** * Creates an Object for the elements the `Query`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = from(`"`, 1], ["y", 2]]).toObject(undefined, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = from(`"`, 1], ["y", 2]]).toObject(baseObject, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * obj.toString(); // 1:2 * * // with a null prototype * const obj = from(`"`, 1], ["y", 2]]).toObject(null, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // undefined * ``` * * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param descriptorSelector A callback that defines the `PropertyDescriptor` for each property. * @category Scalar */ toObject<TProto extends object, V>(prototype: TProto, keySelector: (element: T) => PropertyKey, elementSelector: (element: T) => V, descriptorSelector?: (key: PropertyKey, element: V) => TypedPropertyDescriptor<V>): TProto & Record<PropertyKey, V>; /** * Creates an Object for the elements the `Query`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = from(`"`, 1], ["y", 2]]).toObject(undefined, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = from(`"`, 1], ["y", 2]]).toObject(baseObject, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * obj.toString(); // 1:2 * * // with a null prototype * const obj = from(`"`, 1], ["y", 2]]).toObject(null, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // undefined * ``` * * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param descriptorSelector A callback that defines the `PropertyDescriptor` for each property. * @category Scalar */ toObject<K extends PropertyKey, V>(prototype: object | null | undefined, keySelector: (element: T) => K, elementSelector: (element: T) => V, descriptorSelector?: (key: K, element: V) => TypedPropertyDescriptor<V>): Record<K, V>; /** * Creates an Object for the elements the `Query`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = from(`"`, 1], ["y", 2]]).toObject(undefined, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = from(`"`, 1], ["y", 2]]).toObject(baseObject, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * obj.toString(); // 1:2 * * // with a null prototype * const obj = from(`"`, 1], ["y", 2]]).toObject(null, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // undefined * ``` * * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param descriptorSelector A callback that defines the `PropertyDescriptor` for each property. * @category Scalar */ toObject<V>(prototype: object | null | undefined, keySelector: (element: T) => PropertyKey, elementSelector: (element: T) => V, descriptorSelector?: (key: PropertyKey, element: V) => TypedPropertyDescriptor<V>): Record<PropertyKey, V>; /** * Creates an Object for the elements the `Query`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = from(`"`, 1], ["y", 2]]).toObject(undefined, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = from(`"`, 1], ["y", 2]]).toObject(baseObject, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * obj.toString(); // 1:2 * * // with a null prototype * const obj = from(`"`, 1], ["y", 2]]).toObject(null, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // undefined * ``` * * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param descriptorSelector A callback that defines the `PropertyDescriptor` for each property. * @category Scalar */ toObject<V>(prototype: object | null | undefined, keySelector: (element: T) => PropertyKey, elementSelector: (element: T) => V, descriptorSelector?: (key: PropertyKey, element: V) => PropertyDescriptor): object; toObject<V>(prototype: object | null | undefined, keySelector: (element: T) => PropertyKey, elementSelector?: (element: T) => V, descriptorSelector?: (key: PropertyKey, element: V) => PropertyDescriptor): object { return fn.toObject(getSource(this), prototype, keySelector, elementSelector!, descriptorSelector); } /** * Writes each element to a destination. The destination must already * have enough space to write the requested number of elements (i.e. * arrays are *not* resized). * * @param dest The destination array. * @param start The offset into the array at which to start writing. * @param count The number of elements to write to the array. * @category Scalar */ copyTo(dest: T[], start?: number, count?: number): T[]; /** * Writes each element to a destination. The destination must already * have enough space to write the requested number of elements (i.e. * arrays are *not* resized). * * @param dest The destination array. * @param start The offset into the array at which to start writing. * @param count The number of elements to write to the array. * @category Scalar */ copyTo<U extends IndexedCollection<T>>(dest: U, start?: number, count?: number): U; copyTo<U extends IndexedCollection<T> | T[]>(dest: U, start?: number, count?: number): U { return fn.copyTo(getSource(this), dest, start, count); } /** * Pass the entire `Query` to the provided callback, returning the result. * * @param callback A callback function. * @param callback.source The outer `Query`. * @category Scalar */ into<R>(callback: (source: this) => R) { return fn.into(this, callback); } toJSON() { return this.toArray(); } // #endregion Scalar [Symbol.iterator](): Iterator<T> { return this[kSource][Symbol.iterator](); } protected _from<TNode, T extends TNode>(source: OrderedHierarchyIterable<TNode, T>): OrderedHierarchyQuery<TNode, T>; protected _from<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>): HierarchyQuery<TNode, T>; protected _from<TNode, T extends TNode>(source: OrderedIterable<T>, provider: HierarchyProvider<TNode>): OrderedHierarchyQuery<TNode, T>; protected _from<TNode, T extends TNode>(source: Iterable<T>, provider: HierarchyProvider<TNode>): HierarchyQuery<TNode, T>; protected _from<T>(source: OrderedIterable<T>): OrderedQuery<T>; protected _from<T extends readonly unknown[] | []>(source: Iterable<T>): Query<T>; protected _from<T>(source: Iterable<T>): Query<T>; protected _from<TNode, T extends TNode>(source: Iterable<T>, provider?: HierarchyProvider<TNode>): Query<T> { return (this.constructor as typeof Query).from(source, provider!); } } // Inline aliases to simplify call stacks Query.prototype.where = Query.prototype.filter; Query.prototype.whereBy = Query.prototype.filterBy; Query.prototype.whereDefined = Query.prototype.filterDefined; Query.prototype.whereDefinedBy = Query.prototype.filterDefinedBy; Query.prototype.whereNot = Query.prototype.filterNot; Query.prototype.whereNotBy = Query.prototype.filterNotBy; Query.prototype.whereNotDefinedBy = Query.prototype.filterNotDefinedBy; Query.prototype.select = Query.prototype.map; Query.prototype.selectMany = Query.prototype.flatMap; Query.prototype.skip = Query.prototype.drop; Query.prototype.skipRight = Query.prototype.dropRight; Query.prototype.skipWhile = Query.prototype.dropWhile; Query.prototype.skipUntil = Query.prototype.dropUntil; Query.prototype.relativeComplement = Query.prototype.except; Query.prototype.relativeComplementBy = Query.prototype.exceptBy; Query.prototype.nth = Query.prototype.elementAt; Query.prototype.break = Query.prototype.spanUntil; /** * Represents an ordered sequence of elements. */ export class OrderedQuery<T> extends Query<T> implements OrderedIterable<T> { constructor(source: OrderedIterable<T>) { assert.mustBeType(OrderedIterable.hasInstance, source, "source"); super(source); } // #region Order /** * Creates a subsequent ordered subquery whose elements are sorted in ascending order by the provided key. * * @param keySelector A callback used to select the key for an element. * @param comparer An optional callback used to compare two keys. * @category Order */ thenBy<K>(keySelector: (element: T) => K, comparer?: Comparison<K> | Comparer<K>): OrderedQuery<T> { return this._from(fn.thenBy(getSource(this), keySelector, comparer)); } /** * Creates a subsequent ordered subquery whose elements are sorted in descending order by the provided key. * * @param keySelector A callback used to select the key for an element. * @param comparer An optional callback used to compare two keys. * @category Order */ thenByDescending<K>(keySelector: (element: T) => K, comparer?: Comparison<K> | Comparer<K>): OrderedQuery<T> { return this._from(fn.thenByDescending(getSource(this), keySelector, comparer)); } // #endregion Order [OrderedIterable.thenBy]<K>(keySelector: (element: T) => K, comparer: Comparison<K> | Comparer<K>, descending: boolean): OrderedIterable<T> { return getSource(this)[OrderedIterable.thenBy](keySelector, comparer, descending); } } /** * Represents a sequence of hierarchically organized values. */ export class HierarchyQuery<TNode, T extends TNode = TNode> extends Query<T> implements HierarchyIterable<TNode, T> { constructor(source: HierarchyIterable<TNode, T>); constructor(source: Iterable<T>, provider: HierarchyProvider<TNode>); constructor(source: Iterable<T> | HierarchyIterable<TNode, T>, provider?: HierarchyProvider<TNode>) { if (provider !== undefined) { assert.mustBeIterableObject(source, "source"); assert.mustBeType(HierarchyProvider.hasInstance, provider, "provider"); source = fn.toHierarchy(source, provider); } else { assert.mustBeType(HierarchyIterable.hasInstance, source, "source"); } super(source); } // #region Hierarchy /** * Creates a subquery for the roots of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ root<U extends TNode>(predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the roots of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ root(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode>; root(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode> { return this._from(fn.root(getSource(this), predicate)); } /** * Creates a subquery for the ancestors of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ ancestors<U extends TNode>(predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the ancestors of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ ancestors(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode>; ancestors(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode> { return this._from(fn.ancestors(getSource(this), predicate)); } /** * Creates a subquery for the ancestors of each element as well as each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ ancestorsAndSelf<U extends TNode>(predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the ancestors of each element as well as each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ ancestorsAndSelf(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode>; ancestorsAndSelf(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode> { return this._from(fn.ancestorsAndSelf(getSource(this), predicate)); } /** * Creates a subquery for the descendants of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ descendants<U extends TNode>(predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the descendants of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ descendants(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode>; descendants(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode> { return this._from(fn.descendants(getSource(this), predicate)); } /** * Creates a subquery for the descendants of each element as well as each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ descendantsAndSelf<U extends TNode>(predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the descendants of each element as well as each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ descendantsAndSelf(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode>; descendantsAndSelf(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode> { return this._from(fn.descendantsAndSelf(getSource(this), predicate)); } /** * Creates a subquery for the parents of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ parents<U extends TNode>(predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the parents of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ parents(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode>; parents(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode> { return this._from(fn.parents(getSource(this), predicate)); } /** * Creates a subquery for this `query`. * * @param predicate A callback used to filter the results. * @category Hierarchy */ self<U extends T>(predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for this `query`. * * @param predicate A callback used to filter the results. * @category Hierarchy */ self<U extends TNode>(predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for this `query`. * * @param predicate A callback used to filter the results. * @category Hierarchy */ self(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode>; self(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode> { return this._from(fn.self(getSource(this), predicate)); } /** * Creates a subquery for the siblings of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ siblings<U extends TNode>(predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the siblings of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ siblings(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode>; siblings(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode> { return this._from(fn.siblings(getSource(this), predicate)); } /** * Creates a subquery for the siblings of each element as well as each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ siblingsAndSelf<U extends TNode>(predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the siblings of each element as well as each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ siblingsAndSelf(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode>; siblingsAndSelf(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode> { return this._from(fn.siblingsAndSelf(getSource(this), predicate)); } /** * Creates a subquery for the children of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ children<U extends TNode>(predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the children of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ children(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode>; children(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode> { return this._from(fn.children(getSource(this), predicate)); } /** * Creates a subquery for the siblings before each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ precedingSiblings<U extends TNode>(predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the siblings before each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ precedingSiblings(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode>; precedingSiblings(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode> { return this._from(fn.precedingSiblings(getSource(this), predicate)); } /** * Creates a subquery for the siblings before each element in the hierarchy. * * NOTE: This is an alias for `precedingSiblings`. * * @param predicate A callback used to filter the results. * @category Hierarchy */ siblingsBeforeSelf<U extends TNode>(predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the siblings before each element in the hierarchy. * * NOTE: This is an alias for `precedingSiblings`. * * @param predicate A callback used to filter the results. * @category Hierarchy */ siblingsBeforeSelf(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode>; siblingsBeforeSelf(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode> { return this.precedingSiblings(predicate); } /** * Creates a subquery for the siblings after each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ followingSiblings<U extends TNode>(predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the siblings after each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ followingSiblings(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode>; followingSiblings(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode> { return this._from(fn.followingSiblings(getSource(this), predicate)); } /** * Creates a subquery for the siblings after each element in the hierarchy. * * NOTE: This is an alias for `followingSiblings`. * * @param predicate A callback used to filter the results. * @category Hierarchy */ siblingsAfterSelf<U extends TNode>(predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the siblings after each element in the hierarchy. * * NOTE: This is an alias for `followingSiblings`. * * @param predicate A callback used to filter the results. * @category Hierarchy */ siblingsAfterSelf(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode>; siblingsAfterSelf(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode> { return this.followingSiblings(predicate); } /** * Creates a subquery for the nodes preceding each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ preceding<U extends TNode>(predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the nodes preceding each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ preceding(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode>; preceding(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode> { return this._from(fn.preceding(getSource(this), predicate)); } /** * Creates a subquery for the nodes following each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ following<U extends TNode>(predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the nodes following each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ following(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode>; following(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode> { return this._from(fn.following(getSource(this), predicate)); } /** * Creates a subquery for the first child of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ firstChild<U extends TNode>(predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the first child of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ firstChild(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode>; firstChild(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode> { return this._from(fn.firstChild(getSource(this), predicate)); } /** * Creates a subquery for the last child of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ lastChild<U extends TNode>(predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the last child of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ lastChild(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode>; lastChild(predicate?: (element: TNode) => boolean): HierarchyQuery<TNode> { return this._from(fn.lastChild(getSource(this), predicate)); } /** * Creates a subquery for the child of each element at the specified offset. A negative offset * starts from the last child. * * @param offset The offset for the child. * @category Hierarchy */ nthChild<U extends TNode>(offset: number, predicate: (element: TNode) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the child of each element at the specified offset. A negative offset * starts from the last child. * * @param offset The offset for the child. * @category Hierarchy */ nthChild(offset: number, predicate?: (element: TNode) => boolean): HierarchyQuery<TNode>; nthChild(offset: number, predicate?: (element: TNode) => boolean): HierarchyQuery<TNode> { return this._from(fn.nthChild(getSource(this), offset, predicate)); } /** * Creates a subquery for the top-most elements. Elements that are a descendant of any other * element are removed. * @category Hierarchy */ topMost<U extends T>(predicate: (element: T) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the top-most elements. Elements that are a descendant of any other * element are removed. * @category Hierarchy */ topMost(predicate?: (element: T) => boolean): HierarchyQuery<TNode, T>; topMost(predicate?: (element: T) => boolean): HierarchyQuery<TNode, T> { return this._from(fn.topMost(getSource(this), predicate)); } /** * Creates a subquery for the bottom-most elements. Elements that are an ancestor of any other * element are removed. * @category Hierarchy */ bottomMost<U extends T>(predicate: (element: T) => element is U): HierarchyQuery<TNode, U>; /** * Creates a subquery for the bottom-most elements. Elements that are an ancestor of any other * element are removed. * @category Hierarchy */ bottomMost(predicate?: (element: T) => boolean): HierarchyQuery<TNode, T>; bottomMost(predicate?: (element: T) => boolean): HierarchyQuery<TNode, T> { return this._from(fn.bottomMost(getSource(this), predicate)); } // #endregion Hierarchy [Hierarchical.hierarchy](): HierarchyProvider<TNode> { return getSource(this)[Hierarchical.hierarchy](); } } // Inline aliases to simplify call stacks HierarchyQuery.prototype.siblingsBeforeSelf = HierarchyQuery.prototype.precedingSiblings; HierarchyQuery.prototype.siblingsAfterSelf = HierarchyQuery.prototype.followingSiblings; /** * Represents an ordered sequence of hierarchically organized values. */ export class OrderedHierarchyQuery<TNode, T extends TNode = TNode> extends HierarchyQuery<TNode, T> implements OrderedHierarchyIterable<TNode, T> { constructor(source: OrderedHierarchyIterable<TNode, T>); constructor(source: OrderedIterable<T>, provider: HierarchyProvider<TNode>); constructor(source: OrderedIterable<T> | OrderedHierarchyIterable<TNode, T>, provider?: HierarchyProvider<TNode>) { if (provider !== undefined) { assert.mustBeType(OrderedIterable.hasInstance, source, "source"); super(source, provider); } else { assert.mustBeType(OrderedHierarchyIterable.hasInstance, source, "source"); super(source); } } // #region Order /** * Creates a subsequent ordered subquery whose elements are sorted in ascending order by the provided key. * * @param keySelector A callback used to select the key for an element. * @param comparison An optional callback used to compare two keys. * @category Order */ thenBy<K>(keySelector: (element: T) => K, comparison?: Comparison<K> | Comparer<K>): OrderedHierarchyQuery<TNode, T> { return this._from(fn.thenBy(getSource(this), keySelector, comparison)); } /** * Creates a subsequent ordered subquery whose elements are sorted in descending order by the provided key. * * @param keySelector A callback used to select the key for an element. * @param comparison An optional callback used to compare two keys. * @category Order */ thenByDescending<K>(keySelector: (element: T) => K, comparison?: Comparison<K> | Comparer<K>): OrderedHierarchyQuery<TNode, T> { return this._from(fn.thenByDescending(getSource(this), keySelector, comparison)); } // #endregion Order [OrderedIterable.thenBy]<K>(keySelector: (element: T) => K, comparison: Comparison<K> | Comparer<K>, descending: boolean): OrderedHierarchyIterable<TNode, T> { return getSource(this)[OrderedIterable.thenBy](keySelector, comparison, descending); } }
the_stack
import { aws_dynamodb, aws_events, CfnMapping, CfnParameter, Duration, Fn, Lazy, RemovalPolicy, SecretValue, Stack, Token, } from "aws-cdk-lib"; // eslint-disable-next-line import/no-extraneous-dependencies import { Lambda } from "aws-sdk"; import { Construct } from "constructs"; import { $AWS, EventBus, Event, ExpressStepFunction, Function, FunctionProps, StepFunction, Table, } from "../src"; import { clientConfig, localstackTestSuite } from "./localstack"; const lambda = new Lambda(clientConfig); // inject the localstack client config into the lambda clients // without this configuration, the functions will try to hit AWS proper const localstackClientConfig: FunctionProps = { timeout: Duration.seconds(20), clientConfigRetriever: () => ({ endpoint: `http://${process.env.LOCALSTACK_HOSTNAME}:4566`, }), }; interface TestFunctionBase { < I, O, // Forces typescript to infer O from the Function and not from the expect argument. OO extends O | { errorMessage: string; errorType: string }, Outputs extends Record<string, string> = Record<string, string> >( name: string, func: ( parent: Construct ) => Function<I, O> | { func: Function<I, O>; outputs: Outputs }, expected: OO extends void ? null : OO | ((context: Outputs) => OO extends void ? null : O), payload?: I | ((context: Outputs) => I) ): void; } interface TestFunctionResource extends TestFunctionBase { skip: < I, O, // Forces typescript to infer O from the Function and not from the expect argument. OO extends O | { errorMessage: string; errorType: string }, Outputs extends Record<string, string> = Record<string, string> >( name: string, func: ( parent: Construct ) => Function<I, O> | { func: Function<I, O>; outputs: Outputs }, expected: OO extends void ? null : OO | ((context: Outputs) => OO extends void ? null : O), payload?: I | ((context: Outputs) => I) ) => void; only: < I, O, // Forces typescript to infer O from the Function and not from the expect argument. OO extends O | { errorMessage: string; errorType: string }, Outputs extends Record<string, string> = Record<string, string> >( name: string, func: ( parent: Construct ) => Function<I, O> | { func: Function<I, O>; outputs: Outputs }, expected: OO extends void ? null : OO | ((context: Outputs) => OO extends void ? null : O), payload?: I | ((context: Outputs) => I) ) => void; } localstackTestSuite("functionStack", (testResource, _stack, _app) => { const _testFunc: ( f: typeof testResource | typeof testResource.only ) => TestFunctionBase = (f) => (name, func, expected, payload) => { f( name, (parent) => { const res = func(parent); const [funcRes, outputs] = res instanceof Function ? [res, {}] : [res.func, res.outputs]; return { outputs: { function: funcRes.resource.functionName, ...outputs, }, }; }, async (context) => { const exp = // @ts-ignore typeof expected === "function" ? expected(context) : expected; // @ts-ignore const pay = typeof payload === "function" ? payload(context) : payload; await testFunction(context.function, pay, exp); } ); }; const test = _testFunc(testResource) as TestFunctionResource; test.skip = (name, _func, _expected, _payload?) => testResource.skip( name, () => {}, async () => {} ); test.only = _testFunc(testResource.only); test( "Call Lambda", (parent) => { return new Function( parent, "func2", { timeout: Duration.seconds(20), }, async (event) => event ); }, {} ); test( "Call Lambda from closure", (parent) => { const create = () => new Function( parent, "function", { timeout: Duration.seconds(20), }, async (event) => event ); return create(); }, {} ); test( "Call Lambda from closure with variables", (parent) => { const create = () => { const val = "a"; return new Function( parent, "function", { timeout: Duration.seconds(20), }, async () => val ); }; return create(); }, "a" ); test( "Call Lambda from closure with parameter", (parent) => { const create = (val: string) => { return new Function( parent, "func5", { timeout: Duration.seconds(20), }, async () => val ); }; return create("b"); }, "b" ); const create = (parent: Construct, id: string, val: string) => { return new Function( parent, id, { timeout: Duration.seconds(20), }, async () => val ); }; test( "Call Lambda from closure with parameter using the same method", (parent) => create(parent, "func6", "c"), "c" ); test( "Call Lambda from closure with parameter using the same method part 2", (parent) => create(parent, "func7", "d"), "d" ); test("Call Lambda with object", (parent) => { const create = () => { const obj = { val: 1 }; return new Function( parent, "function", { timeout: Duration.seconds(20), }, async () => obj.val ); }; return create(); }, 1); test( "Call Lambda with math", (parent) => new Function( parent, "function", { timeout: Duration.seconds(20), }, async () => { const v1 = 1 + 2; // 3 const v2 = v1 * 3; // 9 return v2 - 4; // 5 } ), 5 ); test( "Call Lambda payload", (parent) => new Function( parent, "function", { timeout: Duration.seconds(20), }, async (event: { val: string }) => { return `value: ${event.val}`; } ), "value: hi", { val: "hi" } ); test( "Call Lambda throw error", (parent) => new Function( parent, "function", { timeout: Duration.seconds(20), }, async () => { throw Error("AHHHHHHHHH"); } ), { errorMessage: "AHHHHHHHHH", errorType: "Error" } ); test( "Call Lambda return arns", (parent) => { return new Function( parent, "function", { timeout: Duration.seconds(20), }, async (_, context) => { return context.functionName; } ); }, (context) => context.function ); test( "Call Lambda return arns", (parent) => { const bus = new EventBus(parent, "bus"); const busbus = new aws_events.EventBus(parent, "busbus"); const func = new Function( parent, "function", { timeout: Duration.seconds(20), }, async () => { return `${bus.eventBusArn} ${busbus.eventBusArn}`; } ); return { func, outputs: { bus: bus.eventBusArn, busbus: busbus.eventBusArn, }, }; }, (context) => `${context.bus} ${context.busbus}` ); test( "templated tokens", (parent) => { const token = Token.asString("hello"); return new Function( parent, "function", { timeout: Duration.seconds(20), }, async () => { return `${token} stuff`; } ); }, "hello stuff" ); test("numeric tokens", (parent) => { const token = Token.asNumber(1); return new Function( parent, "function", { timeout: Duration.seconds(20), }, async () => { return token; } ); }, 1); test( "function tokens", (parent) => { const bus = new EventBus(parent, "bus"); const split = Fn.select(1, Fn.split(":", bus.eventBusArn)); const join = Fn.join("-", Fn.split(":", bus.eventBusArn, 6)); const base64 = Fn.base64("data"); const mapping = new CfnMapping(parent, "mapping", { mapping: { map1: { test: "value" }, }, }); const mapToken = Fn.findInMap(mapping.logicalId, "map1", "test"); const param = new CfnParameter(parent, "param", { default: "paramValue", }); const ref = Fn.ref(param.logicalId); return { func: new Function( parent, "function", { timeout: Duration.seconds(20), }, async () => { return { split, join, base64, mapToken, ref, }; } ), outputs: { bus: bus.eventBusArn }, }; }, (output) => ({ split: "aws", join: output.bus.split(":").join("-"), base64: "ZGF0YQ==", mapToken: "value", ref: "paramValue", }) ); test( "function token strings", (parent) => { const bus = new EventBus(parent, "bus"); const split = Fn.select(1, Fn.split(":", bus.eventBusArn)).toString(); const join = Fn.join("-", Fn.split(":", bus.eventBusArn, 6)).toString(); const base64 = Fn.base64("data").toString(); const mapping = new CfnMapping(parent, "mapping", { mapping: { map1: { test: "value" }, }, }); const mapToken = Fn.findInMap(mapping.logicalId, "map1", "test"); const param = new CfnParameter(parent, "param", { default: "paramValue", }); const ref = Fn.ref(param.logicalId).toString(); return { func: new Function( parent, "function", { timeout: Duration.seconds(20), }, async () => { return { split, join, base64, mapToken, ref, }; } ), outputs: { bus: bus.eventBusArn }, }; }, (output) => ({ split: "aws", join: output.bus.split(":").join("-"), base64: "ZGF0YQ==", mapToken: "value", ref: "paramValue", }) ); test( "Call Lambda put events", (parent) => { const bus = new EventBus(parent, "bus"); return new Function( parent, "function", localstackClientConfig, async () => { bus.putEvents({ "detail-type": "detail", source: "lambda", detail: {}, }); } ); }, null ); test("Call Lambda AWS SDK put event to bus with reference", (parent) => { const bus = new EventBus<any>(parent, "bus"); // Necessary to keep the bundle small and stop the test from failing. // See https://github.com/functionless/functionless/pull/122 const putEvents = $AWS.EventBridge.putEvents; const func = new Function( parent, "function", localstackClientConfig, async () => { const result = putEvents({ Entries: [ { EventBusName: bus.eventBusArn, Source: "MyEvent", DetailType: "DetailType", Detail: "{}", }, ], }); return result.FailedEntryCount; } ); bus.resource.grantPutEventsTo(func.resource); return func; }, 0); // See https://github.com/functionless/functionless/pull/122 test.skip("Call Lambda AWS SDK put event to bus without reference", (parent) => { const bus = new EventBus<Event>(parent, "bus"); return new Function( parent, "function", localstackClientConfig, async () => { const result = $AWS.EventBridge.putEvents({ Entries: [ { EventBusName: bus.eventBusArn, Source: "MyEvent", DetailType: "DetailType", Detail: "{}", }, ], }); return result.FailedEntryCount; } ); }, 0); test( "Call Lambda AWS SDK put event to bus with in closure reference", (parent) => { const bus = new EventBus<Event>(parent, "bus"); return new Function( parent, "function", localstackClientConfig, async () => { const busbus = bus; busbus.putEvents({ "detail-type": "anyDetail", source: "anySource", detail: {}, }); } ); }, null ); test( "Call Lambda AWS SDK integration from destructured object aa", (parent) => { const buses = { bus: new EventBus<Event>(parent, "bus") }; return new Function( parent, "function", localstackClientConfig, async () => { const { bus } = buses; bus.putEvents({ "detail-type": "anyDetail", source: "anySource", detail: {}, }); } ); }, null ); test( "Call Lambda invoke client", (parent) => { const func1 = new Function<undefined, string>( parent, "func1", async () => "hi" ); return new Function( parent, "function", localstackClientConfig, async () => { // TODO should be awaited? return func1(); } ); }, "hi" ); // https://github.com/functionless/functionless/issues/173 test.skip( "Call Self", (parent) => { let func1: Function<number, string> | undefined; func1 = new Function( parent, "function", localstackClientConfig, async (count) => { if (count === 0) return "hi"; // TODO should be awaited? return func1 ? func1(count - 1) : "huh"; } ); return func1; }, "hi", 2 ); // https://github.com/functionless/functionless/issues/173 test.skip( "Call Self", (parent) => { let func1: Function<number, string> | undefined; const func2 = new Function<number, string>( parent, "func2", async (count) => { if (!func1) throw Error(); return func1(count - 1); } ); func1 = new Function( parent, "function", localstackClientConfig, async (count) => { if (count === 0) return "hi"; // TODO should be awaited? return func2(count); } ); return func1; }, "hi", 2 ); test( "step function integration", (parent) => { const func1 = new StepFunction<undefined, string>( parent, "func1", () => "hi" ); return new Function( parent, "function", localstackClientConfig, async () => { // TODO should be awaited? func1({}); return "started!"; } ); }, "started!" ); test( "tokens", (parent) => { const token = Token.asString("hello"); const obj = { iam: "object" }; const token2 = Token.asAny(obj); const obj2 = { iam: Token.asString("token") }; const nestedToken = Token.asAny(obj2); const numberToken = Token.asNumber(1); const listToken = Token.asList(["1", "2"]); const nestedListToken = Token.asList([Token.asString("hello")]); return new Function( parent, "function", localstackClientConfig, async () => { return { string: token, object: token2 as unknown as typeof obj, nested: nestedToken as unknown as typeof obj2, number: numberToken, list: listToken, nestedList: nestedListToken, }; } ); }, { string: "hello", object: { iam: "object" }, nested: { iam: "token" }, number: 1, list: ["1", "2"], nestedList: ["hello"], } ); test( "serialize entire table", (parent) => { const table = new aws_dynamodb.Table(parent, "table", { partitionKey: { name: "key", type: aws_dynamodb.AttributeType.STRING, }, }); const get = $AWS.DynamoDB.GetItem; table.addGlobalSecondaryIndex({ indexName: "testIndex", partitionKey: { name: "key", type: aws_dynamodb.AttributeType.STRING, }, }); const flTable = Table.fromTable(table); return new Function( parent, "function", localstackClientConfig, async () => { get({ TableName: flTable, Key: { key: { S: "hi" }, }, }); } ); }, null ); test( "serialize entire function", (parent) => { const func = new Function<undefined, string>(parent, "func", async () => { return "hello"; }); return new Function( parent, "function", localstackClientConfig, async () => { const hello = func; return hello(); } ); }, "hello" ); test( "serialize token with nested string", (parent) => { const table = new aws_dynamodb.Table(parent, "table", { partitionKey: { name: "key", type: aws_dynamodb.AttributeType.STRING, }, }); const obj = { key: table.tableArn }; const token = Token.asAny(obj); return { func: new Function( parent, "function", localstackClientConfig, async () => { return (token as unknown as typeof obj).key; } ), outputs: { table: table.tableArn }, }; }, (outputs) => { return outputs.table; } ); // test.skip( "serialize token with lazy should return", (parent) => { const obj = { key: Lazy.any({ produce: () => "value" }) as unknown as string, }; const token = Token.asAny(obj); return new Function( parent, "function", localstackClientConfig, async () => { return (token as unknown as typeof obj).key; } ); }, "value" ); test( "step function integration and wait for completion", (parent) => { const func1 = new StepFunction<undefined, string>( parent, "func1", () => "hi" ); return new Function( parent, "function", localstackClientConfig, async () => { // TODO should be awaited? const result = func1({}); let status = "RUNNING"; while (true) { const state = func1.describeExecution(result.executionArn); status = state.status; if (status !== "RUNNING") { return state.output; } // wait for 100 ms await new Promise((resolve) => setTimeout(resolve, 100)); } } ); }, `"hi"` ); // Localstack doesn't support start sync // https://github.com/localstack/localstack/issues/5258 test.skip( "express step function integration", (parent) => { const func1 = new ExpressStepFunction<undefined, string>( parent, "func1", () => "hi" ); return new Function( parent, "function", localstackClientConfig, async () => { // TODO should be awaited? const result = func1({}); return result.status === "SUCCEEDED" ? result.output : result.error; } ); }, "hi" ); test( "dynamo integration aws dynamo functions", (parent) => { const table = Table.fromTable<{ key: string; value: string }, "key">( new aws_dynamodb.Table(parent, "table", { partitionKey: { name: "key", type: aws_dynamodb.AttributeType.STRING, }, removalPolicy: RemovalPolicy.DESTROY, }) ); const { GetItem, DeleteItem, PutItem, Query, Scan, UpdateItem } = $AWS.DynamoDB; return new Function( parent, "function", localstackClientConfig, async () => { PutItem({ TableName: table, Item: { key: { S: "key" }, value: { S: "wee" }, }, }); const item = GetItem({ TableName: table, Key: { key: { S: "key", }, }, ConsistentRead: true, }); UpdateItem({ TableName: table, Key: { key: { S: "key" }, }, UpdateExpression: "set #value = :value", ExpressionAttributeValues: { ":value": { S: "value" }, }, ExpressionAttributeNames: { "#value": "value", }, }); DeleteItem({ TableName: table, Key: { key: { S: "key", }, }, }); Query({ TableName: table, KeyConditionExpression: "#key = :key", ExpressionAttributeValues: { ":key": { S: "key" }, }, ExpressionAttributeNames: { "#key": "key", }, }); Scan({ TableName: table, }); return item.Item?.key.S; } ); }, "key" ); }); const testFunction = async ( functionName: string, payload: any, expected: any ) => { const result = await lambda .invoke({ FunctionName: functionName, Payload: JSON.stringify(payload), }) .promise(); try { expect( result.Payload ? JSON.parse(result.Payload.toString()) : undefined ).toEqual(expected); } catch (e) { console.error(result); throw e; } }; test("should not create new resources in lambda", async () => { await expect(async () => { const stack = new Stack(); new Function( stack, "function", { timeout: Duration.seconds(20), }, async () => { const bus = new aws_events.EventBus(stack, "busbus"); return bus.eventBusArn; } ); await Promise.all(Function.promises); }).rejects.toThrow( `Cannot initialize new CDK resources in a native function, found EventBus.` ); }); test("should not create new functionless resources in lambda", async () => { await expect(async () => { const stack = new Stack(); new Function( stack, "function", { timeout: Duration.seconds(20), }, async () => { const bus = new EventBus(stack, "busbus"); return bus.eventBusArn; } ); await Promise.all(Function.promises); }).rejects.toThrow( "Cannot initialize new resources in a native function, found EventBus." ); }); test("should not use SecretValues in lambda", async () => { await expect(async () => { const stack = new Stack(); const secret = SecretValue.unsafePlainText("sshhhhh"); new Function( stack, "function", { timeout: Duration.seconds(20), }, async () => { return secret; } ); await Promise.all(Function.promises); }).rejects.toThrow(`Found unsafe use of SecretValue token in a Function.`); }); test("should not use SecretValues as string in lambda", async () => { await expect(async () => { const stack = new Stack(); const secret = SecretValue.unsafePlainText("sshhhhh").toString(); new Function( stack, "function", { timeout: Duration.seconds(20), }, async () => { return secret; } ); await Promise.all(Function.promises); }).rejects.toThrow(`Found unsafe use of SecretValue token in a Function.`); });
the_stack
import clone from "lodash-es/clone" import { rgbaToHex, NSrgbaToHex, isURL, formatLink, indent, expandCSS, contractCSS, isCircle } from "./helpers" import { template } from "./layout" export function convert(artboard: MSArtboardGroup, command: MSPluginCommand, sketchVersion: number){ // Get all visible layers from the artboard const data = sketchToLayers(artboard.layers(), null, command) let offset ={ minX: artboard.frame().width(), maxX: 0, } // Append layer to the layer containing it for(var i = data.layers.length - 1; i >= 0; i--){ if(data.layers[i].x1 < offset.minX) offset.minX = data.layers[i].x1 if(data.layers[i].x2 > offset.maxX) offset.maxX = data.layers[i].x2 const layer = clone(data.layers[i]) data.layers.splice(i, 1) appendLayers(data.layers, layer) } // Change absolute positions to relative const layout = relatativePosition(data.layers, {x: 0, y: 0}) // Create the table layout let table = createTable(layout, { width: offset.maxX, height: artboard.frame().height(), originalWidth: offset.maxX, originalHeight: artboard.frame().height(), offsetX: 0, offsetY: 0, depth: 3 }) const bodyBackground = (sketchVersion < 44) ? artboard.backgroundColorGeneric() : artboard.backgroundColor() return { table: template(rgbaToHex(bodyBackground), table), assets: data.assets } } function createTable(layers: Layer[], size: TableSize){ // Sort layers to start from upper left position layers = layers.sort((a, b) => a.x1 - b.x1) layers = layers.sort((a, b) => a.y1 - b.y1) // Filter layers to current table viewport layers = layers.filter(layer => (layer.x1 >= size.offsetX && layer.x2 <= size.width + size.offsetX && layer.y1 >= size.offsetY && layer.y2 <= size.height + size.offsetY)) // Adjust the new coords if(size.offsetX || size.offsetY){ for(var i=0; i < layers.length; i++){ layers[i].x1 -= size.offsetX layers[i].x2 -= size.offsetX layers[i].y1 -= size.offsetY layers[i].y2 -= size.offsetY } } // Table holds the final table columns and rows let table = { columns : [0, size.width], rows: [0, size.height] } // Add table column and row position based on layer position layers.forEach(layer => { if(table.rows.indexOf(layer.y1) < 0) table.rows.push(layer.y1) if(table.rows.indexOf(layer.y2) < 0) table.rows.push(layer.y2) if(table.columns.indexOf(layer.x1) < 0) table.columns.push(layer.x1) if(table.columns.indexOf(layer.x2) < 0) table.columns.push(layer.x2) }) table.rows = table.rows.sort((a, b) => a - b) table.columns = table.columns.sort((a, b) => a - b) // Table grid holds final table cell content let tableGrid = [] for(var row = 0; row < table.rows.length - 1; row ++){ for(var column = 0; column < table.columns.length - 1; column ++){ let cellContent = null layers.forEach((layer, layerIndex) => { if (layer.x1 < table.columns[column+1] && layer.x2 > table.columns[column] && layer.y1 < table.rows[row+1] && layer.y2 > table.rows[row]){ cellContent = layerIndex } }) if(!tableGrid[row]) tableGrid[row] = [] tableGrid[row].push(cellContent) } } // Start result with table wrapper let result = indent(size.depth, `<table style="border-collapse:collapse;table-layout:fixed;width:${size.width}px;height:${size.height}px;margin:auto;" border="0" width="${size.width}" height="${size.height}">`) // Append <col> widths to result if(table.columns.length > 2){ result += indent(size.depth + 1, `<colgroup>`) var cols = "" for(var column = 0; column < table.columns.length - 1; column ++){ let cellWidth = table.columns[column + 1] - table.columns[column] if(column === 0 && table.columns[0] > 0) cellWidth += table.columns[0] cols += `<col style="width:${cellWidth}px;"/>` } result += indent(size.depth + 2, cols) result += indent(size.depth + 1, "</colgroup>") } // Parse the tableGrid content tableGrid.forEach((row, rowIndex) => { result += indent(size.depth + 1, `<tr>`) let colspan = 1 row.forEach((cell, colIndex) => { // The cell is part of a cell with rowspan > 1, ignore it if(cell === "rowspanned"){ } else // An empty cell, fill with &shy if(typeof cell !== "number"){ var cellWidth = table.columns[colIndex + 1] - table.columns[colIndex + 1 - colspan] if(colIndex == tableGrid[0].length - 1 || (typeof tableGrid[rowIndex][colIndex + 1] === "number" || tableGrid[rowIndex][colIndex + 1] === "rowspanned" )){ result += indent(size.depth + 2, `<td colspan="${colspan}" style="width:${cellWidth}px;height:${table.rows[rowIndex + 1] - table.rows[rowIndex]}px">&shy;</td>`) colspan = 1 } else { colspan ++ } } else // The next cell is the same, don't output anything yet if(colIndex < tableGrid[0].length - 1 && tableGrid[rowIndex][colIndex + 1] === cell){ colspan ++ } else // Finally, output the cells content { // Calculate rowspan let rowspan = 1 for(var i = rowIndex + 1; i < tableGrid.length; i ++){ if(tableGrid[i][colIndex] === cell && tableGrid[i][colIndex + 1] !== cell){ var isFilled = true for(var z = 0; z < colspan; z++){ if(tableGrid[i][colIndex - z] !== cell) isFilled = false } if(isFilled){ for(var z = 0; z < colspan; z++){ tableGrid[i][colIndex - z] = "rowspanned" } rowspan++ } else { break } } else { break } } // Caluclate cell size var cellWidth = table.columns[colIndex + 1] - table.columns[colIndex + 1 - colspan] var cellHeight = table.rows[rowIndex + rowspan] - table.rows[rowIndex] // Calculate the offset of the content let cellOffsetX = (colIndex - (colspan - 1) === 0 && table.columns[0] > 0) ? table.columns[0] : 0 let cellOffsetY = (layers[cell].y1 - table.rows[rowIndex] > 0) ? layers[cell].y1 - table.rows[rowIndex] : 0 let cellStyle = "vertical-align:top;padding:0px;" cellStyle += `width:${cellWidth}px;` cellStyle += `height:${cellHeight}px;` //Caluclate child's size if(cellOffsetX) cellWidth -= cellOffsetX if(cellOffsetY) cellHeight -= cellOffsetY const childTableSize = { width: cellWidth, height: cellHeight, originalWidth: layers[cell].x2 - layers[cell].x1, originalHeight: layers[cell].y2 - layers[cell].y1, offsetX: table.columns[colIndex - colspan + 1] - layers[cell].x1, offsetY: table.rows[rowIndex] - layers[cell].y1, depth: size.depth + 4 } // Prepare cell's content const cellContent = (layers[cell].children.length === 0) ? getCellContent(layers[cell], size.depth, childTableSize) : createTable(layers[cell].children, childTableSize) result += indent(size.depth + 2, `<td style="${cellStyle}" colspan="${colspan}" rowspan="${rowspan}">`) if(layers[cell].url) result += indent(size.depth + 3, `<a href="${formatLink(layers[cell].url)}" style="text-decoration:none;">`) result += indent(size.depth + 3, `<div style="${getCellStyle(layers[cell], childTableSize, {x: cellOffsetX, y: cellOffsetY})}">`) result += cellContent result += indent(size.depth + 3, `</div>`) if(layers[cell].url) result += indent(size.depth + 3, `</a>`) result += indent(size.depth + 2, `</td>`) colspan = 1 } }) result += indent(size.depth + 1, `</tr>`) }) return `${result}${indent(size.depth, `</table>`)}` } function relatativePosition(layout: Layer[], offset: {x: number, y: number}){ for(var i=0; i < layout.length; i++){ if(layout[i].children.length > 0){ layout[i].children = relatativePosition(layout[i].children, {x: layout[i].x1 + layout[i].border, y: layout[i].y1 + layout[i].border}) } layout[i].x1 -= offset.x layout[i].x2 -= offset.x layout[i].y1 -= offset.y layout[i].y2 -= offset.y } return layout } function getCellContent(layer: Layer, depth: number, size: TableSize){ depth += 4 if(size.offsetX > 0 || size.offsetY >0 ) return "" if(layer.source && layer.source.length > 0){ return indent(depth, `<img src="${layer.source}" style="display:block;" width="${layer.x2 - layer.x1 - layer.border*2}" height="${layer.y2 - layer.y1 - layer.border*2}" alt="${layer.title}"/>`) } if(layer.content && layer.content.length > 0){ let content = "" layer.content.forEach(textLayer => { let style = "" let linkStyle = "text-decoration:none;" for (var attribute in textLayer.css) { if(!textLayer.css.hasOwnProperty(attribute)) continue if(attribute == "text-decoration") linkStyle = `` style += `${attribute}:${textLayer.css[attribute]};` } const isLink = isURL(textLayer.text) if(isLink && !layer.url){ content += indent(depth, `<a href="${formatLink(textLayer.text)}" style="${linkStyle}${style}" style="${style}">${textLayer.text}</a>`) } else { content += indent(depth, `<span style="${style}">${textLayer.text.replace("\n","<br/>")}</span>`) } }) return content } return "" } function getCellStyle(layer: Layer, size: TableSize, offset: {x: number, y: number}){ let style = "display:block;" let width = size.width let height = size.height if(offset.x) style += `margin-left:${offset.x}px;` if(offset.y) style += `margin-top:${offset.y}px;` for (var attribute in layer.css) { if(!layer.css.hasOwnProperty(attribute)) continue if(layer.source && attribute == "background-color") continue let value = layer.css[attribute] + ";" // For split cells, fix style that does not happen in current viewport if(attribute == "border-radius"){ let values = expandCSS(layer.css[attribute]) if(size.offsetX) { values[0] = "0" values[3] = "0" } if(size.offsetY) { values[0] = "0" values[1] = "0" } if(size.originalWidth > size.width + size.offsetX) { values[1] = "0" values[2] = "0" } if(size.originalHeight > size.height + size.offsetY) { values[2] = "0" values[3] = "0" } style += `${attribute}:${contractCSS(values)};` } else if(attribute == "border"){ if(size.width != size.originalWidth || size.height != size.originalHeight){ let values = [] if(!size.offsetX) { values.push(`border-left:${value}`) width -= layer.border } if(!size.offsetY) { values.push(`border-top:${value}`) height -= layer.border } if(size.originalWidth <= size.width + size.offsetX) { values.push(`border-right:${value}`) width -= layer.border } if(size.originalHeight <= size.height + size.offsetY) { values.push(`border-bottom:${value}`) height -= layer.border } style += values.join(";") } else { width -= layer.border*2 height -= layer.border*2 style += `${attribute}:${value}` } } else style += `${attribute}:${value}` } if(layer.children.length > 0 && layer.source){ let backgroundSize = Math.floor(size.originalWidth/size.width)*100 style += `background-image:url(${layer.source});background-size: ${backgroundSize}% auto;` if(size.offsetX || size.offsetY){ style += `background-position:-${size.offsetX}px -${size.offsetY}px;` } } style += `width:${width}px;` style += `height:${height}px;` return style } function appendLayers(layout: Layer[], currentLayer: Layer){ var appended = false for(var i = layout.length - 1; i >= 0; i--){ if(currentLayer.x1 >= layout[i].x1 && currentLayer.y1 >= layout[i].y1 && currentLayer.x2 <= layout[i].x2 && currentLayer.y2 <= layout[i].y2) { appendLayers(layout[i].children, currentLayer) appended = true break } } if(!appended) layout.push(currentLayer) } function sketchToLayers(layerGroup: MSLayer[], offset?: {x: number, y: number}, command: MSPluginCommand){ let layers: Layer[] = [] let assets: string[] = [] layerGroup.forEach((layer, type) => { if(layer.isVisible() && (!offset || !layer.parentGroup().isLayerExportable())){ if(layer.class() == MSSymbolInstance && !layer.isLayerExportable()){ const children = sketchToLayers( layer.symbolMaster().layers(), {x: layer.frame().x() + ((offset) ? offset.x : 0), y: layer.frame().y() + ((offset) ? offset.y : 0)}, command) layers = layers.concat(children.layers) assets = assets.concat(children.assets) } else if(layer.class() == MSLayerGroup && !layer.isLayerExportable()){ if(!offset){ const children = sketchToLayers(layer.children(), {x: layer.frame().x(), y: layer.frame().y()}, command) layers = layers.concat(children.layers) assets = assets.concat(children.assets) } } else { if([MSLayerGroup, MSTextLayer, MSShapeGroup, MSBitmapLayer].indexOf(layer.class()) > -1){ const layerCSS = getCSS(layer) const borderWidth = (layerCSS["border"]) ? parseFloat(layerCSS["border"].split(" ")[0]) : 0 const url = unescape(command.valueForKey_onLayer("hrefURL", layer)) layers.unshift({ id: unescape(layer.objectID()), title: unescape(layer.name()), url: (url.length > 0 && url !== "null") ? url : null, x1: Math.round(layer.frame().x() + ((offset) ? offset.x : 0)), y1: Math.round(layer.frame().y() + ((offset) ? offset.y : 0)), x2: Math.round(layer.frame().x() + layer.frame().width() + ((offset) ? offset.x : 0)), y2: Math.round(layer.frame().y() + layer.frame().height() + ((offset) ? offset.y : 0)), border: borderWidth, css: layerCSS, content: (layer.class() == MSTextLayer) ? splitText(layer) : null, source: (layer.isLayerExportable()) ? `assets/${unescape(layer.objectID())}@2x.png` : null, children: [] }) } if(layer.isLayerExportable()){ assets.push(unescape(layer.objectID())) } } } }) return {layers: layers, assets: assets} } function splitText(layer: MSLayer){ const fontWeights = ["thin", "extralight", "light", "normal", "medium", "semibold", "bold", "extrabold", "black"] const fontStyles = ["italic", "oblique"] const hasFill = (layer.style().fills().firstObject()) ? true : null var textElements: { text: string, css: any }[] = [] const attributes = layer.attributedStringValue().treeAsDictionary().attributes attributes.forEach((attribute)=>{ const font = attribute.NSFont const fontFamily = unescape(font.family) const fontName = unescape(font.name) const fontVariants = fontName.substr(fontFamily.length + 1).split(" ") const fontWeight = fontVariants.filter(variant => fontWeights.indexOf(variant.toLowerCase()) > -1) const fontStyle = fontVariants.filter(variant => fontStyles.indexOf(variant.toLowerCase()) > -1) const fontColor = layer.attributedStringValue().attribute_atIndex_effectiveRange_("NSColor", attribute.location, null) let css = { "font-weight": (fontWeight.length == 1) ? (fontWeights.indexOf(fontWeight[0].toLowerCase()) + 1) * 100 + "" : null, "font-style": (fontStyle.length == 1) ? fontStyle[0].toLowerCase() : null, "text-decoration": (layer.attributedStringValue().attribute_atIndex_effectiveRange_("NSUnderline", attribute.location, null)) ? "underline" : null, "font-family": `'${fontFamily}'`, "font-size": font.attributes.NSFontSizeAttribute + 'px', "color": (!hasFill && fontColor) ? NSrgbaToHex(fontColor) : null, } for (var propName in css) { if (css[propName] === null || css[propName] === undefined) { delete css[propName] } } textElements.push({ text: unescape(attribute.text), css: css }) }) return textElements } function getCSS(layer: MSLayer){ var properties = parseCSSAttributes(layer.CSSAttributes().slice(1)) if(layer.style().fills().firstObject()){ properties["color"] = rgbaToHex(layer.style().fills().firstObject().color()) } if(layer.class() === MSTextLayer){ const textAlignment = [ 'left', 'right', 'center', 'justify' ][layer.textAlignment()] if(textAlignment) properties["text-align"] = textAlignment var textDecoration: string = null if(layer.styleAttributes().NSStrikethrough) textDecoration = 'line-through' if(layer.styleAttributes().NSUnderline) textDecoration = 'underline' if(textDecoration) properties["text-decoration"] = textDecoration var textTransform: string = null if(layer.styleAttributes().MSAttributedStringTextTransformAttribute === 1) textTransform = 'uppercase' if(layer.styleAttributes().MSAttributedStringTextTransformAttribute === 2) textTransform = 'lowercase' if(textTransform) properties["text-transform"] = textTransform } if(isCircle(layer)){ properties["border-radius"] = "100%" } return properties } function parseCSSAttributes(attributes){ var result = {} attributes.forEach(function (property) { var parts = property.split(': ') if (parts.length !== 2) return var propName = parts[0] var propValue = parts[1].replace(';', '') switch (propName) { case "background": propName = "background-color" break } result[propName] = propValue }) return result }
the_stack
import angular, {IAugmentedJQuery, IDocumentService, IScope, ITimeoutService} from 'angular' import moment from 'moment' import {GanttApi} from './api/api.factory' import {GanttOptions} from './api/options.factory' import {GanttCalendar} from './calendar/calendar.factory' import {GanttCurrentDateManager} from './calendar/currentDateManager.factory' import {GanttObjectModel} from './model/objectModel.factory' import {GanttRowsManager} from './row/rowsManager.factory' import {GanttColumnsManager} from './column/columnsManager.factory' import {GanttTimespansManager} from './timespan/timespansManager.factory' import GanttArrays from './util/arrays.service' import {GanttScroll} from './template/scroll.factory' import {GanttBody} from './template/body.factory' import {GanttHeader} from './template/header.factory' import {GanttSide} from './template/side.factory' import {GanttRowModel} from './row/row.factory' // Gantt logic. Manages the columns, rows and sorting functionality. export class Gantt { static $document: IDocumentService static ganttArrays: GanttArrays static $timeout: ITimeoutService options: GanttOptions $scope: IScope $element: IAugmentedJQuery api: GanttApi calendar: GanttCalendar objectModel: GanttObjectModel columnMagnetValue: number columnMagnetUnit: string shiftColumnMagnetValue: number shiftColumnMagnetUnit: string shiftKey: boolean scroll: GanttScroll body: GanttBody header: GanttHeader side: GanttSide rowsManager: GanttRowsManager columnsManager: GanttColumnsManager timespansManager: GanttTimespansManager currentDateManager: GanttCurrentDateManager originalWidth: number width: number rendered = false isRefreshingColumns = false constructor ($scope: IScope, $element: IAugmentedJQuery) { this.$scope = $scope this.$element = $element this.options = new GanttOptions($scope, { // tslint:disable:no-empty 'api': function () {}, 'data': [], 'timespans': [], 'viewScale': 'day', 'columnMagnet': '15 minutes', 'timeFramesMagnet': true, 'showSide': true, 'allowSideResizing': true, 'currentDate': 'line', 'currentDateValue': moment, 'autoExpand': 'none', 'taskOutOfRange': 'truncate', 'taskContent': '{{task.model.name}}', 'rowContent': '{{row.model.name}}', 'maxHeight': 0, 'timeFrames': [], 'dateFrames': [], 'timeFramesWorkingMode': 'hidden', 'timeFramesNonWorkingMode': 'visible', 'taskLimitThreshold': 100, 'columnLimitThreshold': 500 }) this.api = new GanttApi(this) this.api.registerEvent('core', 'ready') this.api.registerEvent('core', 'rendered') this.api.registerEvent('directives', 'controller') this.api.registerEvent('directives', 'preLink') this.api.registerEvent('directives', 'postLink') this.api.registerEvent('directives', 'new') this.api.registerEvent('directives', 'destroy') this.api.registerEvent('data', 'change') this.api.registerEvent('data', 'load') this.api.registerEvent('data', 'remove') this.api.registerEvent('data', 'clear') this.api.registerMethod('core', 'getDateByPosition', this.getDateByPosition, this) this.api.registerMethod('core', 'getPositionByDate', this.getPositionByDate, this) this.api.registerMethod('data', 'load', this.loadData, this) this.api.registerMethod('data', 'remove', this.removeData, this) this.api.registerMethod('data', 'clear', this.clearData, this) this.api.registerMethod('data', 'get', this.getData, this) this.calendar = new GanttCalendar() this.calendar.registerTimeFrames(this.options.value('timeFrames')) this.calendar.registerDateFrames(this.options.value('dateFrames')) this.api.registerMethod('timeframes', 'registerTimeFrames', this.calendar.registerTimeFrames, this.calendar) this.api.registerMethod('timeframes', 'clearTimeframes', this.calendar.clearTimeFrames, this.calendar) this.api.registerMethod('timeframes', 'registerDateFrames', this.calendar.registerDateFrames, this.calendar) this.api.registerMethod('timeframes', 'clearDateFrames', this.calendar.clearDateFrames, this.calendar) this.api.registerMethod('timeframes', 'registerTimeFrameMappings', this.calendar.registerTimeFrameMappings, this.calendar) this.api.registerMethod('timeframes', 'clearTimeFrameMappings', this.calendar.clearTimeFrameMappings, this.calendar) $scope.$watchGroup(['timeFrames', 'dateFrames'], (newValues, oldValues) => { if (newValues !== oldValues) { let timeFrames = newValues[0] let dateFrames = newValues[1] let oldTimeFrames = oldValues[0] let oldDateFrames = oldValues[1] let framesChanged = false if (!angular.equals(timeFrames, oldTimeFrames)) { this.calendar.clearTimeFrames() this.calendar.registerTimeFrames(timeFrames) framesChanged = true } if (!angular.equals(dateFrames, oldDateFrames)) { this.calendar.clearDateFrames() this.calendar.registerDateFrames(dateFrames) framesChanged = true } if (framesChanged) { this.columnsManager.generateColumns() } } }) $scope.$watch('columnMagnet', () => { let splittedColumnMagnet let columnMagnet = this.options.value('columnMagnet') if (columnMagnet) { splittedColumnMagnet = columnMagnet.trim().split(' ') } if (splittedColumnMagnet && splittedColumnMagnet.length > 1) { this.columnMagnetValue = parseFloat(splittedColumnMagnet[0]) this.columnMagnetUnit = moment.normalizeUnits(splittedColumnMagnet[splittedColumnMagnet.length - 1]) } else { this.columnMagnetValue = 1 this.columnMagnetUnit = moment.normalizeUnits(columnMagnet) } }) $scope.$watchGroup(['shiftColumnMagnet', 'viewScale'], () => { let splittedColumnMagnet let shiftColumnMagnet = this.options.value('shiftColumnMagnet') if (shiftColumnMagnet) { splittedColumnMagnet = shiftColumnMagnet.trim().split(' ') } if (splittedColumnMagnet !== undefined && splittedColumnMagnet.length > 1) { this.shiftColumnMagnetValue = parseFloat(splittedColumnMagnet[0]) this.shiftColumnMagnetUnit = moment.normalizeUnits(splittedColumnMagnet[splittedColumnMagnet.length - 1]) } else { this.shiftColumnMagnetValue = 1 this.shiftColumnMagnetUnit = moment.normalizeUnits(shiftColumnMagnet) } }) Gantt.$document.on('keyup keydown', this.keyHandler) $scope.$on('$destroy', () => { Gantt.$document.off('keyup keydown', this.keyHandler) }) this.scroll = new GanttScroll(this) this.body = new GanttBody(this) this.header = new GanttHeader(this) this.side = new GanttSide(this) this.objectModel = new GanttObjectModel(this.api) this.rowsManager = new GanttRowsManager(this) this.columnsManager = new GanttColumnsManager(this) this.timespansManager = new GanttTimespansManager(this) this.currentDateManager = new GanttCurrentDateManager(this) this.originalWidth = 0 this.width = 0 if (typeof this.$scope.api === 'function') { this.$scope.api(this.api) } let hasRowModelOrderChanged = (data1, data2) => { if (data2 === undefined || data1.length !== data2.length) { return true } // tslint:disable:one-variable-per-declaration for (let i = 0, l = data1.length; i < l; i++) { if (data1[i].id !== data2[i].id) { return true } } return false } $scope.$watchCollection('data', (newData: GanttRowModel[], oldData: GanttRowModel[]) => { if (oldData !== undefined) { let toRemoveIds = Gantt.ganttArrays.getRemovedIds(newData, oldData) if (toRemoveIds.length === oldData.length) { this.rowsManager.removeAll(); // DEPRECATED (this.api as any).data.raise.clear() } else { for (let i = 0, l = toRemoveIds.length; i < l; i++) { let toRemoveId = toRemoveIds[i] this.rowsManager.removeRow(toRemoveId) } // DEPRECATED let removedRows = [] for (let i = 0, l = oldData.length; i < l; i++) { if (toRemoveIds.indexOf(oldData[i].id) > -1) { removedRows.push(oldData[i]) } } (this.api as any).data.raise.remove(removedRows) } } if (newData !== undefined) { let modelOrderChanged = hasRowModelOrderChanged(newData, oldData) if (modelOrderChanged) { this.rowsManager.resetNonModelLists() } for (let j = 0, k = newData.length; j < k; j++) { let rowData = newData[j] this.rowsManager.addRow(rowData, modelOrderChanged) } (this.api as any).data.raise.change(newData, oldData); // DEPRECATED (this.api as any).data.raise.load(newData) } }) } private keyHandler (e) { this.shiftKey = e.shiftKey return true } /** * Get the magnet value and unit considering the current gantt state. * * @returns {[*,*]} */ getMagnetValueAndUnit () { if (this.shiftKey) { if (this.shiftColumnMagnetValue !== undefined && this.shiftColumnMagnetUnit !== undefined) { return [this.shiftColumnMagnetValue, this.shiftColumnMagnetUnit] } else { let viewScale = this.options.value('viewScale') viewScale = viewScale.trim() let viewScaleValue let viewScaleUnit let splittedViewScale if (viewScale) { splittedViewScale = viewScale.split(' ') } if (splittedViewScale && splittedViewScale.length > 1) { viewScaleValue = parseFloat(splittedViewScale[0]) viewScaleUnit = moment.normalizeUnits(splittedViewScale[splittedViewScale.length - 1]) } else { viewScaleValue = 1 viewScaleUnit = moment.normalizeUnits(viewScale) } return [viewScaleValue * 0.25, viewScaleUnit] } } else { return [this.columnMagnetValue, this.columnMagnetUnit] } } // Get the date transformed by magnet feature. getMagnetDate (date, disableExpand) { if (date === undefined) { return undefined } if (!moment.isMoment(moment)) { date = moment(date) } let column = this.columnsManager.getColumnByDate(date, disableExpand) let magnetValueAndUnit = this.getMagnetValueAndUnit() let magnetValue = magnetValueAndUnit[0] let magnetUnit = magnetValueAndUnit[1] return column.getMagnetDate(date, magnetValue, magnetUnit, this.options.value('timeFramesMagnet')) } // Returns the exact column date at the given position x (in em) getDateByPosition (x: number, magnet?: boolean, disableExpand?: boolean) { let column = this.columnsManager.getColumnByPosition(x, disableExpand) if (column !== undefined) { let magnetValue let magnetUnit if (magnet) { let magnetValueAndUnit = this.getMagnetValueAndUnit() magnetValue = magnetValueAndUnit[0] magnetUnit = magnetValueAndUnit[1] } return column.getDateByPosition(x - column.left, magnetValue, magnetUnit, this.options.value('timeFramesMagnet')) } else { return undefined } } getBodyAvailableWidth () { let scrollWidth = this.getWidth() - this.side.getWidth() let borderWidth = this.scroll.getBordersWidth() let availableWidth = scrollWidth - (borderWidth !== undefined ? this.scroll.getBordersWidth() : 0) // Remove 1 pixel because of rounding issue in some cases. availableWidth = availableWidth - 1 return availableWidth } // Returns the position inside the Gantt calculated by the given date getPositionByDate (date, disableExpand?: boolean) { if (date === undefined) { return undefined } if (!moment.isMoment(moment)) { date = moment(date) } let column = this.columnsManager.getColumnByDate(date, disableExpand) if (column !== undefined) { return column.getPositionByDate(date) } else { return undefined } } // DEPRECATED - Use $data instead. loadData (data: GanttRowModel | GanttRowModel[]) { if (!Array.isArray(data)) { data = data !== undefined ? [data] : [] } if (this.$scope.data === undefined) { this.$scope.data = data } else { for (let i = 0, l = data.length; i < l; i++) { let row = data[i] let j = Gantt.ganttArrays.indexOfId(this.$scope.data, row.id) if (j > -1) { this.$scope.data[j] = row } else { this.$scope.data.push(row) } } } let w = this.side.getWidth() if (w > 0) { this.options.set('sideWidth', w) } } getData () { return this.$scope.data } // DEPRECATED - Use $data instead. removeData (data) { if (!Array.isArray(data)) { data = data !== undefined ? [data] : [] } if (this.$scope.data !== undefined) { for (let i = 0, l = data.length; i < l; i++) { let rowToRemove = data[i] let j = Gantt.ganttArrays.indexOfId(this.$scope.data, rowToRemove.id) if (j > -1) { if (rowToRemove.tasks === undefined || rowToRemove.tasks.length === 0) { // Remove complete row this.$scope.data.splice(j, 1) } else { // Remove single tasks let row = this.$scope.data[j] for (let ti = 0, tl = rowToRemove.tasks.length; ti < tl; ti++) { let taskToRemove = rowToRemove.tasks[ti] let tj = Gantt.ganttArrays.indexOfId(row.tasks, taskToRemove.id) if (tj > -1) { row.tasks.splice(tj, 1) } } } } } } } // DEPRECATED - Use $data instead. clearData () { this.$scope.data = undefined } getWidth () { return this.$scope.ganttElementWidth } getHeight () { return this.$scope.ganttElementHeight } getContainerWidth () { return this.$scope.ganttContainerWidth } getContainerHeight () { return this.$scope.ganttContainerHeight } initialized () { // Gantt is initialized. Signal that the Gantt is ready. (this.api as any).core.raise.ready(this.api) this.rendered = true this.columnsManager.generateColumns() Gantt.$timeout(() => { let w = this.side.getWidth() if (w > 0) { this.options.set('sideWidth', w) } (this.api as any).core.raise.rendered(this.api) }) } } export default function (GanttApi: { new(gantt: Gantt): GanttApi }, GanttOptions: { new(values: { [option: string]: any; }, defaultValues: { [option: string]: any; }): GanttOptions }, GanttCalendar: { new(): GanttCalendar }, GanttScroll: { new(gantt: Gantt): GanttScroll }, GanttBody: { new(gantt: Gantt): GanttBody }, GanttHeader: { new(gantt: Gantt): GanttHeader }, GanttSide: { new(gantt: Gantt): GanttSide }, GanttObjectModel: { new(gantt: Gantt): GanttObjectModel }, GanttRowsManager: { new(gantt: Gantt): GanttRowsManager }, GanttColumnsManager: { new(gantt: Gantt): GanttColumnsManager }, GanttTimespansManager: { new(gantt: Gantt): GanttTimespansManager }, GanttCurrentDateManager: { new(gantt: Gantt): GanttCurrentDateManager }, ganttArrays: GanttArrays, $document: IDocumentService, $timeout: ITimeoutService) { 'ngInject' Gantt.ganttArrays = ganttArrays Gantt.$document = $document Gantt.$timeout = $timeout return Gantt }
the_stack
import { Duck } from '../..'; import Debug from '../debug/debug'; import Game from '../game'; import Group from '../group/group'; import clamp from '../math/clamp'; import Vector2 from '../math/vector2'; import Scene from '../scene'; import Collider from './collider'; import Hitbox from './models/hitbox'; /** * @class PhysicsBody * @classdesc Creates a DuckEngine PhysicsBody * @description The PhysicsBody Class. The GameObject class extends this class * @since 2.0.0 */ export default class PhysicsBody<textureType extends Duck.Types.Texture.Type> { /** * @memberof PhysicsBody * @description The unique identifier for a GameObject * @type string * @since 2.0.0 */ public readonly id: string; /** * @memberof PhysicsBody * @description The shape of the GameObject, 'rect', 'circle', 'roundrect', or 'sprite' * @type Duck.Types.Collider.ShapeString * @since 2.0.0 */ public readonly shape: Duck.Types.Collider.ShapeString; /** * @memberof PhysicsBody * @description The current global position of the GameObject * @type Vector2 * @since 2.0.0 */ public position: Vector2; /** * @memberof PhysicsBody * @description The width of the GameObject * @type number * @since 2.0.0 */ public w: number; /** * @memberof PhysicsBody * @description The height of the GameObject * @type number * @since 2.0.0 */ public h: number; /** * @memberof PhysicsBody * @description The radius of the GameObject * @type number * @since 2.0.0 */ public r: number; /** * @memberof PhysicsBody * @description PhysicsBody config, includes: type - KinematicBody | RigidBody | StaticBody * * defaults: { type: 'KinematicBody'} * * @type Duck.Types.PhysicsBody.Config * @since 2.0.0 */ public options: Duck.Types.PhysicsBody.Config; /** * @memberof PhysicsBody * @description The Game instance * @type Game * @since 2.0.0 */ public game: Game; /** * @memberof PhysicsBody * @description The Scene instance * @type Game * @since 2.0.0 */ public scene: Scene; /** * @memberof PhysicsBody * @description The Collider instance of the PhysicsBody * @type Collider | undefined * @since 2.0.0 */ public collider: Collider | undefined; /** * @memberof PhysicsBody * @description An array or group of GameObjects that can collide with the PhysicsBody * @type Duck.TypeClasses.GameObjects.GameObject<textureType>[] | Group<Duck.TypeClasses.GameObjects.GameObject<textureType>> * @since 2.0.0 */ public collidesWith: | Duck.TypeClasses.GameObjects.GameObject<textureType>[] | Group<Duck.TypeClasses.GameObjects.GameObject<textureType>>; /** * @memberof PhysicsBody * @description The Collider Hitbox of the PhysicsBody * @type Hitbox | undefined * @since 2.0.0 */ public hitbox: Hitbox | undefined; /** * @memberof PhysicsBody * @description The velocity of the PhysicsBody * @type Vector2 * @since 2.0.0 */ public velocity: Vector2; /** * @memberof PhysicsBody * @description The bounds of the PhysicsBody * @type Duck.Types.Math.BoundsLike * @since 2.0.0 */ public bounds: Duck.Types.Math.BoundsLike; /** * @memberof PhysicsBody * @description Determines if the PhysicsBody._update is called by the Scene.physicsServer used by Scene.physicsList * , changing this value does nothing, must use PhysicsBody.setEnabled * @type boolean * @since 2.0.0 */ public enabled: boolean; /** * @memberof PhysicsBody * @description Determines if the PhysicsBody is attached to another PhysicsBody * @type boolean * @since 2.0.0 */ public isAttached: boolean; /** * @memberof PhysicsBody * @description PhysicsBodies that are attached * @type PhysicsBody<Duck.Types.Texture.Type>[] * @since 2.0.0 */ public attachedChildren: PhysicsBody<Duck.Types.Texture.Type>[]; /** * @memberof PhysicsBody * @description The offset between the PhysicsBody that self is attached to * @type Vector2 * @since 2.0.0 */ public attachOffset: Vector2; /** * @memberof PhysicsBody * @description Object that has all the physics method * @type { addCollider: (collidesWith: Duck.TypeClasses.GameObjects.GameObject[]) => Collider; * setBounds: (x: number, y: number, w: number, h: number) => void * } * @since 2.0.0 */ public physics: { /** * @memberof PhysicsBody#physics * @description Adds a collider to the PhysicsBody * @param {Duck.TypeClasses.GameObjects.GameObject<textureType>[]} collidesWith What the GameObject collides with * @since 2.0.0 */ addCollider: ( collidesWith: Duck.TypeClasses.GameObjects.GameObject<textureType>[] ) => Collider | undefined; /** * @memberof PhysicsBody#physics * @description Adds a hitbox to the PhysicsBody * @param {number} [w] Width of hitbox, optional -> defaults: PhysicsBody.w or PhysicsBody.r * 2 * @param {number} [h] Height of hitbox, optional -> defaults: PhysicsBody.h or PhysicsBody.r * 2 * @param {Vector2} [offset=Vector2.ZERO] Offset of hitbox, optional -> defaults: Vector2.ZERO * @since 2.0.0 */ addHitbox: (w?: number, h?: number, offset?: Vector2) => Hitbox; /** * @memberof GameObject#physics * @description Adds bounds to the GameObject * @param {number} x X position * @param {number} y Y position * @param {number} w Width of the bounds * @param {number} h Height of the bounds * @since 2.0.0 */ setBounds: (x: number, y: number, w: number, h: number) => void; }; /** * @constructor PhysicsBody * @description Creates a PhysicsBody instance. Extended by GameObject * @param {Duck.Types.Collider.ShapeString} shape Shape of PhysicsBody * @param {number} id ID from GameObject ID * @param {number} x X position * @param {number} y Y position * @param {number} w Width * @param {number} h Height * @param {number} r Radius * @param {Game} game Game instance * @param {Scene} scene Scene instance * @since 2.0.0 */ constructor( shape: Duck.Types.Collider.ShapeString, id: string, x: number, y: number, w: number, h: number, r: number, game: Game, scene: Scene ) { this.shape = shape; this.id = id; this.position = new Vector2(x, y); this.w = w; this.h = h; this.r = r; this.options = { type: 'KinematicBody', }; this.game = game; this.scene = scene; this.velocity = Vector2.ZERO; this.collider = undefined; this.collidesWith = []; this.enabled = true; this.isAttached = false; this.attachedChildren = []; this.attachOffset = Vector2.ZERO; this.bounds = { x: -Infinity, y: -Infinity, w: Infinity, h: Infinity, }; // methods this.physics = { addCollider: ( collidesWith: | Duck.Types.GameObject<textureType>[] | Group<Duck.Types.GameObject<textureType>> ) => { if (!this.hitbox) { new Debug.Error( 'Cannot add collider to PhysicsObject. No hitbox exists. Create a hitbox first using PhysicsObject.physics.addHitbox' ); return undefined; } if (!this.game.config.physics?.enabled) { new Debug.Error( 'Cannot add collider to PhysicsObject. Game Config.physics.enabled must be truthy!' ); } this.collidesWith = collidesWith; this.collider = new Collider( this.hitbox, collidesWith, this.game ); return this.collider; }, addHitbox: ( w?: number, h?: number, offset = Vector2.ZERO, debugColor?: string ) => { if (!this.game.config.physics?.enabled) { new Debug.Error( 'Cannot add hitbox to PhysicsObject. Game Config.physics.enabled must be truthy!' ); } this.hitbox = new Hitbox( this.position, w || 0, h || 0, offset, this, this.game, this.scene, debugColor ); if (!w && !h) { this.hitbox.auto(offset); } this.scene.displayList.add(this.hitbox); return this.hitbox; }, setBounds: (x: number, y: number, w: number, h: number) => { this.bounds.x = x; this.bounds.y = y; this.bounds.w = w; this.bounds.h = h; }, }; } public setEnabled(enabled: boolean) { this.enabled = enabled; return this.enabled; } /** * @memberof PhysicsBody * @description Updates the PhysicsBody's position by the velocity. Sets velocity to 0 on every tick. * Clamps position to bounds if exists. Rounds pixels if roundPixels game config is set to true. * Updates hitbox.collisionState if hitbox exists. * * DO NOT CALL MANUALLY, CALLED IN SCENE.__tick * * @since 2.0.0 */ public _update() { this.position.x += this.velocity.x * this.game.smoothDeltaTime; this.position.y += this.velocity.y * this.game.smoothDeltaTime; // clamp to bounds this.position.x = clamp(this.position.x, this.bounds.x, this.bounds.w); this.position.y = clamp(this.position.y, this.bounds.y, this.bounds.h); // set to none this.velocity.x = 0; this.velocity.y = 0; // roundPixels if (this.game.config.roundPixels) { this.position.round(); } // apply gravity if (this.game.config.physics?.gravity) { if ( this.options.type === 'KinematicBody' || this.options.type === 'RigidBody' ) { this.applyGravity( Vector2.fromVector2Like(this.game.config.physics.gravity) ); } } // update attached children position this.attachedChildren.forEach((object) => { const pos = this.position.clone(); pos.subtract(object.attachOffset); object.position = pos; if (object.hitbox) { object.hitbox.position = object.position .clone() .add(object.hitbox.offset); } }); if (this.hitbox) { if (Array.isArray(this.collidesWith)) { this.collidesWith.forEach((obj) => { if (obj.hitbox) { this.hitbox?.intersectsFaceWith(obj.hitbox); } }); } else { this.collidesWith.each((obj) => { if (obj.hitbox) { this.hitbox?.intersectsFaceWith(obj.hitbox); } }); } } } /** * @memberof PhysicsBody * @description Sets the PhysicsBody type, PhysicsBody type determines what can be applied and what effects the body * @param {Duck.Types.PhysicsBody.Type} type The type of the PhysicsBody, 'KinematicBody' | 'RigidBody' | 'StaticBody' * @since 2.0.0 */ public setType(type: Duck.Types.PhysicsBody.Type) { this.options.type = type; return this.options; } /** * @memberof PhysicsBody * @description Attaches self to another PhysicsBody, makes self unmovable and follows the PhysicsBody accordingly * @param {PhysicsBody<Duck.Types.Texture.Type>} object PhysicsBody to attach to * @param {Vector2} [diffOffset=Vector2] A different offset, optional -> defaults: Difference in positions from PhysicsBody to self * @since 2.0.0 */ public attachTo( object: PhysicsBody<Duck.Types.Texture.Type>, diffOffset?: Vector2 ) { const offset = diffOffset || Vector2.fromVec(object.position).subtract(this.position); this.isAttached = true; this.attachOffset = offset; object.attachedChildren.push(this); } /** * @memberof PhysicsBody * @description Attaches a child PhysicsBody to self, makes child unmovable and follows the self accordingly * @param {PhysicsBody<Duck.Types.Texture.Type>} object PhysicsBody to attach * @param {Vector2} [diffOffset=Vector2] A different offset, optional -> defaults: Difference in positions from self to PhysicsBody * @since 2.0.0 */ public attachChild( object: PhysicsBody<Duck.Types.Texture.Type>, diffOffset?: Vector2 ) { const offset = diffOffset || Vector2.fromVec(this.position).subtract(object.position); object.isAttached = true; object.attachOffset = offset; this.attachedChildren.push(object); } /** * @memberof PhysicsBody * @description Detaches self from another PhysicsBody * @param {PhysicsBody<Duck.Types.Texture.Type>} object PhysicsBody to detach from * @since 2.0.0 */ public detachFrom(object: PhysicsBody<Duck.Types.Texture.Type>) { const f = object.attachedChildren.find((o) => o.id === this.id); if (f) { this.isAttached = false; this.attachOffset = Vector2.ZERO; object.attachedChildren.splice( object.attachedChildren.findIndex((o) => o.id === this.id), 1 ); } else { new Debug.Error( 'Cannot detachFrom from object, PhysicsBody is not attached to anything.' ); } } /** * @memberof PhysicsBody * @description Detaches PhysicsBody from self * @param {PhysicsBody<Duck.Types.Texture.Type>} object PhysicsBody to detach * @since 2.0.0 */ public detachChild(object: PhysicsBody<Duck.Types.Texture.Type>) { const f = this.attachedChildren.find((o) => o.id === object.id); if (f) { object.isAttached = false; object.attachOffset = Vector2.ZERO; this.attachedChildren.splice( this.attachedChildren.findIndex((o) => o.id === object.id), 1 ); } else { new Debug.Error( 'Cannot detachChild from PhysicsBody, object is not attached to anything.' ); } } /** * @memberof PhysicsBody * @description Sets the velocity based on an axis, PhysicsBody.options.type must be KinematicBody * @param {'x'|'y'} axis The axis to set the velocity of * @param {number} pxPerSecond The value to set the velocity axis as, in pixels per second * @since 2.0.0 */ public setVelocity(axis: 'x' | 'y', pxPerSecond: number) { if (this.options.type !== 'KinematicBody') { new Debug.Error( `Cannot set velocity as PhysicsBody.options.type is ${this.options.type} instead of KinematicBody.` ); return; } if (this.isAttached) { new Debug.Error( 'Cannot set velocity as PhysicsBody is attached to another PhysicsBody.' ); return; } if (axis === 'x') { this.velocity.x = pxPerSecond; } if (axis === 'y') { this.velocity.y = pxPerSecond; } } /** * @memberof PhysicsBody * @description Sets the velocity.x, PhysicsBody.options.type must be KinematicBody * @param {number} pxPerSecond The value to set the velocity axis as, in pixels per second * @since 2.0.0 */ public setVelocityX(pxPerSecond: number) { if (this.options.type !== 'KinematicBody') { new Debug.Error( `Cannot set velocity X as PhysicsBody.options.type is ${this.options.type} instead of KinematicBody.` ); return; } if (this.isAttached) { new Debug.Error( 'Cannot set velocity X as PhysicsBody is attached to another PhysicsBody.' ); return; } this.velocity.x = pxPerSecond; } /** * @memberof PhysicsBody * @description Sets the velocity.y, PhysicsBody.options.type must be KinematicBody * @param {number} pxPerSecond The value to set the velocity.y as, in pixels per second * @since 2.0.0 */ public setVelocityY(pxPerSecond: number) { if (this.options.type !== 'KinematicBody') { new Debug.Error( `Cannot set velocity Y as PhysicsBody.options.type is ${this.options.type} instead of KinematicBody.` ); return; } if (this.isAttached) { new Debug.Error( 'Cannot set velocity Y as PhysicsBody is attached to another PhysicsBody.' ); return; } this.velocity.y = pxPerSecond; } /** * @memberof PhysicsBody * @description Accelerates the velocity by an amount, PhysicsBody.options.type must be KinematicBody * @param {Vector2} target The target velocity * @param {number} amount The value to increase the velocity by * @since 2.0.0 */ public accelerateVelocity(target: Vector2, amount: number) { if (this.options.type !== 'KinematicBody') { new Debug.Error( `Cannot accelerate velocity as PhysicsBody.options.type is ${this.options.type} instead of KinematicBody.` ); return; } if (this.isAttached) { new Debug.Error( 'Cannot accelerate velocity as PhysicsBody is attached to another PhysicsBody.' ); return; } this.velocity.moveTowards(this.velocity, target, amount); } /** * @memberof PhysicsBody * @description Applies friction to the velocity by an amount, PhysicsBody.options.type must be KinematicBody or RigidBody * @param {number} frictionAmount The value to decrease the velocity by * @since 2.0.0 */ public applyFriction(frictionAmount: Vector2) { if ( this.options.type !== 'KinematicBody' && this.options.type !== 'RigidBody' ) { new Debug.Error( `Cannot apply friction as PhysicsBody.options.type is ${this.options.type} instead of KinematicBody or RigidBody.` ); return; } if (this.isAttached) { new Debug.Error( 'Cannot apply friction as PhysicsBody is attached to another PhysicsBody.' ); return; } this.velocity.subtract(frictionAmount).clampMin(0); } /** * @memberof PhysicsBody * @description Applies gravity to the velocity by a Vector2, PhysicsBody.options.type must be KinematicBody or RigidBody * @param {Vector2} gravity The Vector2 to add to the velocity by * @since 2.0.0 */ public applyGravity(gravity: Vector2) { if ( this.options.type !== 'KinematicBody' && this.options.type !== 'RigidBody' ) { new Debug.Error( `Cannot apply gravity as PhysicsBody.options.type is ${this.options.type} instead of KinematicBody or RigidBody.` ); return; } if (this.isAttached) { new Debug.Error( 'Cannot apply gravity as PhysicsBody is attached to another PhysicsBody.' ); return; } if (gravity.x !== 0) { this.velocity.x += gravity.x; } if (gravity.y !== 0) { this.velocity.y += gravity.y; } } /** * @memberof PhysicsBody * @description Applies gravity to the velocity by a Vector2, PhysicsBody.options.type must be KinematicBody or RigidBody * @param {Duck.Types.Math.BoundsLike} [bounds=PhysicsBody.bounds] The bounds of the PhysicsBody, optional -> defaults: PhysicsBody.bounds, if none * are set, it is infinite * @param {number} [restitution=1] How much energy is lost when bouncing, a number between 0-1 to loose energy, * 1-any to increase energy, 1 = none, must be a positive number * @since 2.0.0 */ public bounceVelocityBounds(bounds = this.bounds, restitution = 1) { if ( this.options.type !== 'KinematicBody' && this.options.type !== 'RigidBody' ) { new Debug.Error( `Cannot bounce velocity as PhysicsBody.options.type is ${this.options.type} instead of KinematicBody or RigidBody.` ); return; } if (this.isAttached) { new Debug.Error( 'Cannot bounce velocity as PhysicsBody is attached to another PhysicsBody.' ); return; } if (this.position.x > bounds.w || this.position.x < bounds.x) { this.velocity.x = this.velocity.x * -restitution; } if (this.position.y > bounds.h || this.position.y < bounds.y) { this.velocity.y = this.velocity.y * -restitution; } } /** * @memberof PhysicsBody * @description Reflects the velocity, sets the velocity as the opposite value of the velocity, PhysicsBody.options.type must be KinematicBody or RigidBody * * @example myPhysicsBody.setVelocity('x', 3); * myPhysicsBody.reflect(); // velocity: 0, -3 * * @since 2.0.0 */ public reflectVelocity() { if ( this.options.type !== 'KinematicBody' && this.options.type !== 'RigidBody' ) { new Debug.Error( `Cannot reflect velocity as PhysicsBody.options.type is ${this.options.type} instead of KinematicBody or RigidBody.` ); return; } if (this.isAttached) { new Debug.Error( 'Cannot reflect velocity as PhysicsBody is attached to another PhysicsBody.' ); return; } this.velocity.reflect(); } /** * @memberof PhysicsBody * @description Auto scales the PhysicsBody.hitbox to fit the shape * @param {Vector2} [offset] Position offset, optional -> defaults: undefined * @since 2.0.0 */ public autoFitHitbox(offset?: Vector2) { this.hitbox?.auto(offset); } /** * @memberof PhysicsBody * @description Scales the PhysicsBody.hitbox * @param {Vector2} scale Scale Vector2, x is width, y is height * @since 2.0.0 */ public scaleHitbox(scale: Vector2) { this.hitbox?.scale(scale); } /** * @memberof PhysicsBody * @description Gets the top most coordinate of the PhysicsBody * @returns number * @since 2.0.0 */ public getTop() { return this.position.y; } /** * @memberof PhysicsBody * @description Gets the bottom most coordinate of the PhysicsBody * @returns number * @since 2.0.0 */ public getBottom() { return this.position.y + this.h; } /** * @memberof PhysicsBody * @description Gets the left most coordinate of the PhysicsBody * @returns number * @since 2.0.0 */ public getLeft() { return this.position.x; } /** * @memberof PhysicsBody * @description Gets the right most coordinate of the PhysicsBody * @returns number * @since 2.0.0 */ public getRight() { return this.position.x + this.w; } /** * @memberof PhysicsBody * @description Gets the center coordinates of the PhysicsBody * @returns Vector2 * @since 2.0.0 */ public getCenter() { if (this.shape === 'circle') { return new Vector2(this.position.x, this.position.y); } else { return new Vector2( this.position.x + this.w / 2, this.position.y + this.h / 2 ); } } /** * @memberof PhysicsBody * @description Gets the centerY coordinate of the PhysicsBody * @returns number * @since 2.0.0 */ public getCenterY() { if (this.shape === 'circle') { return this.position.y + this.r; } else { return this.position.y + this.h / 2; } } /** * @memberof PhysicsBody * @description Gets the centerX coordinate of the PhysicsBody * @returns number * @since 2.0.0 */ public getCenterX() { if (this.shape === 'circle') { return this.position.x + this.r; } else { return this.position.x + this.w / 2; } } /** * @memberof PhysicsBody * @description Checks and returns the Collision Type if two hitboxes are colliding * @param {PhysicsBody<Duck.Types.Texture.Type>} obj PhysicsBody to check their hitbox with * @returns false | Duck.Types.Collider.CollisionResponseType | undefined * @since 2.0.0 */ public isColliding(obj: PhysicsBody<Duck.Types.Texture.Type>) { if (obj.hitbox) { return this.hitbox?.intersectsFaceWith(obj.hitbox) !== 'none' ? this.hitbox?.intersectsFaceWith(obj.hitbox) : false; } else { return false; } } /** * @memberof PhysicsBody * @description Checks and returns the Collision Type if multiple hitboxes are colliding * @param {Group<PhysicsBody<Duck.Types.Texture.Type>> | PhysicsBody<Duck.Types.Texture.Type>[]} objects PhysicsBodies to check their hitbox with * @returns false | Duck.Types.Collider.CollisionResponseType * @since 2.0.0 */ public isCollidingGroup( objects: | Group<PhysicsBody<Duck.Types.Texture.Type>> | PhysicsBody<Duck.Types.Texture.Type>[] ) { const hitboxes: Hitbox[] = []; if (Array.isArray(objects)) { objects.forEach((obj) => { if (obj.hitbox) { hitboxes.push(obj.hitbox); } }); } else { objects.each((obj) => { if (obj.hitbox) { hitboxes.push(obj.hitbox); } }); } const states = this.hitbox?.groupIntersectsFaceWith(hitboxes); return states?.includes('top') ? 'top' : false || states?.includes('bottom') ? 'bottom' : false || states?.includes('left') ? 'left' : false || states?.includes('right') ? 'right' : false; } }
the_stack
import * as path from "path"; import "should"; import * as vscode from "vscode"; import { addText, clearActiveTextEditor, fixturePath, newTextDocument } from "./helpers"; import { waitForBSLLSActivation } from "../src/extension"; let textDocument: vscode.TextDocument; async function getCompletionListFromCurrentPosition(): Promise<vscode.CompletionList> { const position = vscode.window.activeTextEditor.selection.anchor; const completionList = await vscode.commands.executeCommand<vscode.CompletionList>( "vscode.executeCompletionItemProvider", textDocument.uri, position ); return completionList; } // Defines a Mocha test suite to group tests of similar kind together // tslint:disable-next-line:only-arrow-functions describe("Completion", function() { this.timeout("5m"); before(async () => { const uriEmptyFile = vscode.Uri.file(path.join(fixturePath, "emptyFile.bsl")); textDocument = await newTextDocument(uriEmptyFile); const extension = vscode.extensions.getExtension("1c-syntax.language-1c-bsl"); await extension.activate(); await waitForBSLLSActivation(); }); beforeEach(async () => { await clearActiveTextEditor(); }); // Defines a Mocha unit test it("should show global functions", async () => { await addText("Сообщит"); const completionList = await getCompletionListFromCurrentPosition(); const completions = completionList.items; completions.should.have.length(1, "wrong completions length"); const messageFunction = completions[0]; messageFunction.label.should.be.equal("Сообщить"); messageFunction.kind.should.be.equal(vscode.CompletionItemKind.Function); messageFunction.insertText.should.be.equal("Сообщить("); }); it("should show functions in document", async () => { await addText("Процедура МояПроцедура()\n\nКонецПроцедуры\n"); await addText("Мояп"); const completionList = await getCompletionListFromCurrentPosition(); const completions = completionList.items; completions.should.have.length(1); const completion = completions[0]; completion.label.should.be.equal("МояПроцедура"); completion.kind.should.be.equal(vscode.CompletionItemKind.Function); }); it("should show public methods from configuration module", async () => { await addText("CommonModule."); const completionList = await getCompletionListFromCurrentPosition(); const completions = completionList.items; completions.should.matchAny((value: vscode.CompletionItem) => { value.should.has.a.key("label").which.is.equal("ЭкспортнаяПроцедура"); value.should.has.a.key("kind").which.is.equal(vscode.CompletionItemKind.Function); }); }); it("should show info about function with several signatures", async () => { await addText("ЗаписатьXML"); const completionList = await getCompletionListFromCurrentPosition(); const completions = completionList.items; completions.should.have.length(1); const completion = completions[0]; completion.label.should.be.equal("ЗаписатьXML"); completion.detail.should.match(/.*\d вариантa синтаксиса.*/gm); completion.kind.should.be.equal(vscode.CompletionItemKind.Function); }); it("should show global variables", async () => { await addText("БиблиотекаСт"); const completionList = await getCompletionListFromCurrentPosition(); const completions = completionList.items; completions.should.have.length(1); const completion = completions[0]; completion.label.should.be.equal("БиблиотекаСтилей"); completion.kind.should.be.equal(vscode.CompletionItemKind.Variable); }); it("should show global keywords", async () => { await addText("ВызватьИск"); const completionList = await getCompletionListFromCurrentPosition(); const completions = completionList.items; completions.should.have.length(1); const completion = completions[0]; completion.label.should.be.equal("ВызватьИсключение"); completion.kind.should.be.equal(vscode.CompletionItemKind.Keyword); }); it("should show global enums after `=` sign", async () => { await addText("А = КодировкаТек"); const completionList = await getCompletionListFromCurrentPosition(); const completions = completionList.items; completions.should.matchAny((value: vscode.CompletionItem) => { value.should.has.a.key("label").which.is.equal("КодировкаТекста"); value.should.has.a.key("kind").which.is.equal(vscode.CompletionItemKind.Enum); }); }); it("should show global enums", async () => { await addText("КодировкаТ"); const completionList = await getCompletionListFromCurrentPosition(); const completions = completionList.items; completions.should.matchAny((value: vscode.CompletionItem) => { value.should.has.a.key("label").which.is.equal("КодировкаТекста"); value.should.has.a.key("kind").which.is.equal(vscode.CompletionItemKind.Enum); }); }); it("should show global enums values", async () => { await addText("КодировкаТекста."); const completionList = await getCompletionListFromCurrentPosition(); const completions = completionList.items; completions.should.matchAny((value: vscode.CompletionItem) => { value.should.has.a.key("label").which.is.equal("ANSI"); value.should.has.a.key("kind").which.is.equal(vscode.CompletionItemKind.Enum); value.should.has.a.key("documentation").which.match(/ANSI/); }); }); it("should show part of global enums values", async () => { await addText("КодировкаТекста.An"); const completionList = await getCompletionListFromCurrentPosition(); const completions = completionList.items; completions.should.matchAny((value: vscode.CompletionItem) => { value.should.has.a.key("label").which.is.equal("ANSI"); value.should.has.a.key("kind").which.is.equal(vscode.CompletionItemKind.Enum); value.should.has.a.key("documentation").which.match(/ANSI/); }); }); it("should show global classes after `= New`", async () => { await addText("А = Новый ТаблицаЗ"); const completionList = await getCompletionListFromCurrentPosition(); const completions = completionList.items; completions.should.matchAny((value: vscode.CompletionItem) => { value.should.has.a.key("label").which.is.equal("ТаблицаЗначений"); value.should.has.a.key("kind").which.is.equal(vscode.CompletionItemKind.Class); }); }); it("should show methods in manager module", async () => { await addText("Документы.Document."); const completionList = await getCompletionListFromCurrentPosition(); const completions = completionList.items; completions.should.matchAny((value: vscode.CompletionItem) => { value.should.has.a.key("label").which.is.equal("ПроцедураМодуляМенеджера"); value.should.has.a.key("kind").which.is.equal(vscode.CompletionItemKind.Function); }); }); it("should find methods in manager module by part of the method name", async () => { await addText("Документы.Document.ПроцедураМодуляМен"); const completionList = await getCompletionListFromCurrentPosition(); const completions = completionList.items; completions.should.have.length(1); const completion = completions[0]; completion.label.should.be.equal("ПроцедураМодуляМенеджера"); completion.kind.should.be.equal(vscode.CompletionItemKind.Function); }); it("should show work with en-keywords", async () => { await addText("Documents.Document."); const completionList = await getCompletionListFromCurrentPosition(); const completions = completionList.items; completions.should.matchAny((value: vscode.CompletionItem) => { value.should.has.a.key("label").which.is.equal("ПроцедураМодуляМенеджера"); value.should.has.a.key("kind").which.is.equal(vscode.CompletionItemKind.Function); }); }); it("should show metadata", async () => { await addText("Документы."); const completionList = await getCompletionListFromCurrentPosition(); const completions = completionList.items; completions.should.matchAny((value: vscode.CompletionItem) => { value.should.has.a.key("label").which.is.equal("Definition"); value.should.has.a.key("kind").which.is.equal(vscode.CompletionItemKind.Class); }); }); it("should show metadata from part of classname", async () => { await addText("Докум"); const completionList = await getCompletionListFromCurrentPosition(); const completions = completionList.items; completions.length.should.be.greaterThan(1); completions.should.matchAny((value: vscode.CompletionItem) => { value.should.has.a.key("label").which.is.equal("Документы"); value.should.has.a.key("kind").which.is.equal(vscode.CompletionItemKind.Variable); }); completions.should.matchAny((value: vscode.CompletionItem) => { value.should.has.a.key("label").which.is.equal("Документы.Document"); value.should.has.a.key("kind").which.is.equal(vscode.CompletionItemKind.Module); }); }); it("should show completion of oscript modules", async () => { await addText("СтроковыеФ"); const completionList = await getCompletionListFromCurrentPosition(); const completions = completionList.items; completions.should.matchAny((value: vscode.CompletionItem) => { value.should.has.a.key("label").which.is.equal("СтроковыеФункции"); value.should.has.a.key("kind").which.is.equal(vscode.CompletionItemKind.Module); }); }); it("should show completion of functions in oscript modules", async () => { await addText("СтроковыеФункции."); const completionList = await getCompletionListFromCurrentPosition(); const completions = completionList.items; completions.should.matchAny((value: vscode.CompletionItem) => { value.should.has.a.key("label").which.is.equal("РазложитьСтрокуВМассивПодстрок"); value.should.has.a.key("kind").which.is.equal(vscode.CompletionItemKind.Function); value.should.has.a.key("documentation").which.match(/Разбивает строку/); }); }); });
the_stack
declare module Microsoft.Win32.SafeHandles { } declare module System { export module Array { export var MaxArrayLength: number;// =2146435071; export var MaxByteArrayLength: number;// =2147483591; } export module Exception { var _COMPlusExceptionCode: number;// =-532462766; } export module TimeSpan { export var TicksPerMillisecond: number;// =10000; export var TicksPerSecond: number;// =10000000; export var TicksPerMinute: number;// =600000000; export var TicksPerHour: number;// =36000000000; export var TicksPerDay: number;// =864000000000; export var MaxSeconds: number;// =922337203685; export var MinSeconds: number;// =-922337203685; export var MaxMilliSeconds: number;// =922337203685477; export var MinMilliSeconds: number;// =-922337203685477; export var TicksPerTenthSecond: number;// =1000000; var MillisecondsPerTick: number;// =0.0001; var SecondsPerTick: number;// =1E-07; var MinutesPerTick: number;// =1.66666666666667E-09; var HoursPerTick: number;// =2.77777777777778E-11; var DaysPerTick: number;// =1.15740740740741E-12; var MillisPerSecond: number;// =1000; var MillisPerMinute: number;// =60000; var MillisPerHour: number;// =3600000; var MillisPerDay: number;// =86400000; } export module TimeZoneInfo { var c_timeZonesRegistryHive: string;// ="SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones"; var c_timeZonesRegistryHivePermissionList: string;// ="HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones"; var c_displayValue: string;// ="Display"; var c_daylightValue: string;// ="Dlt"; var c_standardValue: string;// ="Std"; var c_muiDisplayValue: string;// ="MUI_Display"; var c_muiDaylightValue: string;// ="MUI_Dlt"; var c_muiStandardValue: string;// ="MUI_Std"; var c_timeZoneInfoValue: string;// ="TZI"; var c_firstEntryValue: string;// ="FirstEntry"; var c_lastEntryValue: string;// ="LastEntry"; var c_utcId: string;// ="UTC"; var c_localId: string;// ="Local"; var c_maxKeyLength: number;// =255; var c_regByteLength: number;// =44; var c_ticksPerMillisecond: number;// =10000; var c_ticksPerSecond: number;// =10000000; var c_ticksPerMinute: number;// =600000000; var c_ticksPerHour: number;// =36000000000; var c_ticksPerDay: number;// =864000000000; var c_ticksPerDayRange: number;// =863999990000; } export module Type { export var DeclaredOnlyLookup: any; //System.Reflection.BindingFlags;// =DeclaredOnly, Instance, Static, Public, NonPublic; var DefaultLookup: any; //System.Reflection.BindingFlags;// =Instance, Static, Public; } export module Uri { export var c_MaxUriBufferSize: number;// =65520; export var c_DummyChar: string;// =￿; export var c_EOL: string;// =￾; var c_Max16BitUtf8SequenceLength: number;// =12; var c_MaxUriSchemeName: number;// =1024; var V1ToStringUnescape: any; //System.UriFormat;// =32767; } export module UriParser { export var NoDefaultPort: number;// =-1; var SchemeOnlyFlags: any; //System.UriSyntaxFlags;// =MayHavePath; var c_UpdatableFlags: any; //System.UriSyntaxFlags;// =UnEscapeDotsAndSlashes; var c_InitialTableSize: number;// =25; var c_MaxCapacity: number;// =512; var UnknownV1SyntaxFlags: any; //System.UriSyntaxFlags;// =OptionalAuthority, MayHaveUserInfo, MayHavePort, MayHavePath, MayHaveQuery, MayHaveFragment, AllowEmptyHost, AllowUncHost, AllowAnInternetHost, V1_UnknownUri, AllowDOSPath, PathIsRooted, ConvertPathSlashes, CompressPath, AllowIdn, AllowIriParsing; var FtpSyntaxFlags: any; //System.UriSyntaxFlags;// =MustHaveAuthority, MayHaveUserInfo, MayHavePort, MayHavePath, MayHaveFragment, AllowUncHost, AllowAnInternetHost, PathIsRooted, ConvertPathSlashes, CompressPath, CanonicalizeAsFilePath, AllowIdn, AllowIriParsing; var VsmacrosSyntaxFlags: any; //System.UriSyntaxFlags;// =MustHaveAuthority, MayHavePath, MayHaveFragment, AllowEmptyHost, AllowUncHost, AllowAnInternetHost, FileLikeUri, AllowDOSPath, ConvertPathSlashes, CompressPath, CanonicalizeAsFilePath, UnEscapeDotsAndSlashes, AllowIdn, AllowIriParsing; var GopherSyntaxFlags: any; //System.UriSyntaxFlags;// =MustHaveAuthority, MayHaveUserInfo, MayHavePort, MayHavePath, MayHaveFragment, AllowUncHost, AllowAnInternetHost, PathIsRooted, AllowIdn, AllowIriParsing; var NewsSyntaxFlags: any; //System.UriSyntaxFlags;// =MayHavePath, MayHaveFragment, AllowIriParsing; var NntpSyntaxFlags: any; //System.UriSyntaxFlags;// =MustHaveAuthority, MayHaveUserInfo, MayHavePort, MayHavePath, MayHaveFragment, AllowUncHost, AllowAnInternetHost, PathIsRooted, AllowIdn, AllowIriParsing; var TelnetSyntaxFlags: any; //System.UriSyntaxFlags;// =MustHaveAuthority, MayHaveUserInfo, MayHavePort, MayHavePath, MayHaveFragment, AllowUncHost, AllowAnInternetHost, PathIsRooted, AllowIdn, AllowIriParsing; var LdapSyntaxFlags: any; //System.UriSyntaxFlags;// =MustHaveAuthority, MayHaveUserInfo, MayHavePort, MayHavePath, MayHaveQuery, MayHaveFragment, AllowEmptyHost, AllowUncHost, AllowAnInternetHost, PathIsRooted, AllowIdn, AllowIriParsing; var MailtoSyntaxFlags: any; //System.UriSyntaxFlags;// =MayHaveUserInfo, MayHavePort, MayHavePath, MayHaveQuery, MayHaveFragment, AllowEmptyHost, AllowUncHost, AllowAnInternetHost, MailToLikeUri, AllowIdn, AllowIriParsing; var NetPipeSyntaxFlags: any; //System.UriSyntaxFlags;// =MustHaveAuthority, MayHavePath, MayHaveQuery, MayHaveFragment, AllowAnInternetHost, PathIsRooted, ConvertPathSlashes, CompressPath, CanonicalizeAsFilePath, UnEscapeDotsAndSlashes, AllowIdn, AllowIriParsing; var NetTcpSyntaxFlags: any; //System.UriSyntaxFlags;// =MustHaveAuthority, MayHavePort, MayHavePath, MayHaveQuery, MayHaveFragment, AllowAnInternetHost, PathIsRooted, ConvertPathSlashes, CompressPath, CanonicalizeAsFilePath, UnEscapeDotsAndSlashes, AllowIdn, AllowIriParsing; } export module Version { var ZERO_CHAR_VALUE: number;// =48; } } declare module System.Collections { export module ArrayList { var _defaultCapacity: number;// =4; } export module Hashtable { export var HashPrime: number;// =101; var InitialSize: number;// =3; var LoadFactorName: string;// ="LoadFactor"; var VersionName: string;// ="Version"; var ComparerName: string;// ="Comparer"; var HashCodeProviderName: string;// ="HashCodeProvider"; var HashSizeName: string;// ="HashSize"; var KeysName: string;// ="Keys"; var ValuesName: string;// ="Values"; var KeyComparerName: string;// ="KeyComparer"; } export module SortedList { var _defaultCapacity: number;// =16; } } //declare module System.Collections.Generic { // export module Dictionary<TKey, TValue> { // var VersionName: string;// ="Version"; // var HashSizeName: string;// ="HashSize"; // var KeyValuePairsName: string;// ="KeyValuePairs"; // var ComparerName: string;// ="Comparer"; // } // export module List<T> { // var _defaultCapacity: number;// =4; // } //} //declare module System.Collections.Generic.Dictionary`2 { //} declare module System.Collections.ObjectModel { } declare module System.Collections.Specialized { export module NameObjectCollectionBase { var ReadOnlyName: string;// ="ReadOnly"; var CountName: string;// ="Count"; var ComparerName: string;// ="Comparer"; var HashCodeProviderName: string;// ="HashProvider"; var KeysName: string;// ="Keys"; var ValuesName: string;// ="Values"; var KeyComparerName: string;// ="KeyComparer"; var VersionName: string;// ="Version"; } } declare module System.Collections.Specialized.NameObjectCollectionBase { } declare module System.ComponentModel { } declare module System.Globalization { export module Calendar { export var TicksPerMillisecond: number;// =10000; export var TicksPerSecond: number;// =10000000; export var TicksPerMinute: number;// =600000000; export var TicksPerHour: number;// =36000000000; export var TicksPerDay: number;// =864000000000; export var MillisPerSecond: number;// =1000; export var MillisPerMinute: number;// =60000; export var MillisPerHour: number;// =3600000; export var MillisPerDay: number;// =86400000; export var DaysPerYear: number;// =365; export var DaysPer4Years: number;// =1461; export var DaysPer100Years: number;// =36524; export var DaysPer400Years: number;// =146097; export var DaysTo10000: number;// =3652059; export var MaxMillis: number;// =315537897600000; export var CAL_GREGORIAN: number;// =1; export var CAL_GREGORIAN_US: number;// =2; export var CAL_JAPAN: number;// =3; export var CAL_TAIWAN: number;// =4; export var CAL_KOREA: number;// =5; export var CAL_HIJRI: number;// =6; export var CAL_THAI: number;// =7; export var CAL_HEBREW: number;// =8; export var CAL_GREGORIAN_ME_FRENCH: number;// =9; export var CAL_GREGORIAN_ARABIC: number;// =10; export var CAL_GREGORIAN_XLIT_ENGLISH: number;// =11; export var CAL_GREGORIAN_XLIT_FRENCH: number;// =12; export var CAL_JULIAN: number;// =13; export var CAL_JAPANESELUNISOLAR: number;// =14; export var CAL_CHINESELUNISOLAR: number;// =15; export var CAL_SAKA: number;// =16; export var CAL_LUNAR_ETO_CHN: number;// =17; export var CAL_LUNAR_ETO_KOR: number;// =18; export var CAL_LUNAR_ETO_ROKUYOU: number;// =19; export var CAL_KOREANLUNISOLAR: number;// =20; export var CAL_TAIWANLUNISOLAR: number;// =21; export var CAL_PERSIAN: number;// =22; export var CAL_UMALQURA: number;// =23; export var CurrentEra: number;// =0; } export module CompareInfo { export var NORM_LINGUISTIC_CASING: number;// =134217728; var ValidIndexMaskOffFlags: any; //any; //System.Globalization.CompareOptions;// =-32; var ValidCompareMaskOffFlags: any; //any; //System.Globalization.CompareOptions;// =-536870944; var ValidHashCodeOfStringMaskOffFlags: any; //any; //System.Globalization.CompareOptions;// =-32; var LINGUISTIC_IGNORECASE: number;// =16; var NORM_IGNORECASE: number;// =1; var NORM_IGNOREKANATYPE: number;// =65536; var LINGUISTIC_IGNOREDIACRITIC: number;// =32; var NORM_IGNORENONSPACE: number;// =2; var NORM_IGNORESYMBOLS: number;// =4; var NORM_IGNOREWIDTH: number;// =131072; var SORT_STRINGSORT: number;// =4096; var COMPARE_OPTIONS_ORDINAL: number;// =1073741824; var RESERVED_FIND_ASCII_STRING: number;// =536870912; var SORT_VERSION_WHIDBEY: number;// =4096; var SORT_VERSION_V4: number;// =393473; } export module CultureInfo { export var LOCALE_NEUTRAL: number;// =0; export var LOCALE_CUSTOM_DEFAULT: number;// =3072; export var LOCALE_CUSTOM_UNSPECIFIED: number;// =4096; export var LOCALE_INVARIANT: number;// =127; var LOCALE_USER_DEFAULT: number;// =1024; var LOCALE_SYSTEM_DEFAULT: number;// =2048; var LOCALE_TRADITIONAL_SPANISH: number;// =1034; var LOCALE_SORTID_MASK: number;// =983040; } export module DateTimeFormatInfo { export var rfc1123Pattern: string;// ="ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"; export var sortableDateTimePattern: string;// ="yyyy'-'MM'-'dd'T'HH':'mm':'ss"; export var universalSortableDateTimePattern: string;// ="yyyy'-'MM'-'dd HH':'mm':'ss'Z'"; export var InvalidDateTimeStyles: any;//System.Globalization.DateTimeStyles;// =-256; export var IgnorablePeriod: string;// ="."; export var IgnorableComma: string;// =","; export var CJKYearSuff: string;// ="年"; export var CJKMonthSuff: string;// ="月"; export var CJKDaySuff: string;// ="日"; export var KoreanYearSuff: string;// ="년"; export var KoreanMonthSuff: string;// ="월"; export var KoreanDaySuff: string;// ="일"; export var KoreanHourSuff: string;// ="시"; export var KoreanMinuteSuff: string;// ="분"; export var KoreanSecondSuff: string;// ="초"; export var CJKHourSuff: string;// ="時"; export var ChineseHourSuff: string;// ="时"; export var CJKMinuteSuff: string;// ="分"; export var CJKSecondSuff: string;// ="秒"; export var LocalTimeMark: string;// ="T"; export var KoreanLangName: string;// ="ko"; export var JapaneseLangName: string;// ="ja"; export var EnglishLangName: string;// ="en"; var DEFAULT_ALL_DATETIMES_SIZE: number;// =132; var TOKEN_HASH_SIZE: number;// =199; var SECOND_PRIME: number;// =197; var dateSeparatorOrTimeZoneOffset: string;// ="-"; var invariantDateSeparator: string;// ="/"; var invariantTimeSeparator: string;// =":"; } export module NumberFormatInfo { var InvalidNumberStyles: any;//System.Globalization.NumberStyles;// =-1024; } export module TextInfo { var wordSeparatorMask: number;// =536672256; } } declare module System.IO { export module Stream { var _DefaultCopyBufferSize: number;// =81920; } export module TextWriter { var InitialNewLine: string;// =""; } } declare module System.Net { export module CookieContainer { export var DefaultCookieLimit: number;// =300; export var DefaultPerDomainCookieLimit: number;// =20; export var DefaultCookieLengthLimit: number;// =4096; } export module IPAddress { export var LoopbackMask: number;// =255; export var IPv4AddressBytes: number;// =4; export var IPv6AddressBytes: number;// =16; export var NumberOfLabels: number;// =8; } export module WebHeaderCollection { var ApproxAveHeaderLineSize: number;// =30; var ApproxHighAvgNumHeaders: number;// =16; var c_AcceptRanges: number;// =0; var c_ContentLength: number;// =1; var c_CacheControl: number;// =2; var c_ContentType: number;// =3; var c_Date: number;// =4; var c_Expires: number;// =5; var c_ETag: number;// =6; var c_LastModified: number;// =7; var c_Location: number;// =8; var c_ProxyAuthenticate: number;// =9; var c_P3P: number;// =10; var c_SetCookie2: number;// =11; var c_SetCookie: number;// =12; var c_Server: number;// =13; var c_Via: number;// =14; var c_WwwAuthenticate: number;// =15; var c_XAspNetVersion: number;// =16; var c_XPoweredBy: number;// =17; } } declare module System.Net.Sockets { } declare module System.Reflection { export module module { var DefaultLookup: any; //System.Reflection.BindingFlags;// =Instance, Static, Public; } } declare module System.Resources { export module ResourceManager { export var ResFileExtension: string;// =".resources"; export var ResFileExtensionLength: number;// =10; } } declare module System.Runtime.ConstrainedExecution { } declare module System.Runtime.InteropServices { export module StructLayoutAttribute { var DEFAULT_PACKING_SIZE: number;// =8; } } declare module System.Security { export module PermissionSet { var s_str_PermissionSet: string;// ="PermissionSet"; var s_str_Permission: string;// ="Permission"; var s_str_IPermission: string;// ="IPermission"; var s_str_Unrestricted: string;// ="Unrestricted"; var s_str_PermissionUnion: string;// ="PermissionUnion"; var s_str_PermissionIntersection: string;// ="PermissionIntersection"; var s_str_PermissionUnrestrictedUnion: string;// ="PermissionUnrestrictedUnion"; var s_str_PermissionUnrestrictedIntersection: string;// ="PermissionUnrestrictedIntersection"; } } declare module System.Security.Cryptography { } declare module System.Security.Cryptography.X509Certificates { export module X509Certificate { var m_format: string;// ="X509"; } } declare module System.Security.Cryptography.Xml { export module EncryptedXml { export var XmlEncNamespaceUrl: string;// ="http://www.w3.org/2001/04/xmlenc#"; export var XmlEncElementUrl: string;// ="http://www.w3.org/2001/04/xmlenc#Element"; export var XmlEncElementContentUrl: string;// ="http://www.w3.org/2001/04/xmlenc#Content"; export var XmlEncEncryptedKeyUrl: string;// ="http://www.w3.org/2001/04/xmlenc#EncryptedKey"; export var XmlEncDESUrl: string;// ="http://www.w3.org/2001/04/xmlenc#des-cbc"; export var XmlEncTripleDESUrl: string;// ="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"; export var XmlEncAES128Url: string;// ="http://www.w3.org/2001/04/xmlenc#aes128-cbc"; export var XmlEncAES256Url: string;// ="http://www.w3.org/2001/04/xmlenc#aes256-cbc"; export var XmlEncAES192Url: string;// ="http://www.w3.org/2001/04/xmlenc#aes192-cbc"; export var XmlEncRSA15Url: string;// ="http://www.w3.org/2001/04/xmlenc#rsa-1_5"; export var XmlEncRSAOAEPUrl: string;// ="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"; export var XmlEncTripleDESKeyWrapUrl: string;// ="http://www.w3.org/2001/04/xmlenc#kw-tripledes"; export var XmlEncAES128KeyWrapUrl: string;// ="http://www.w3.org/2001/04/xmlenc#kw-aes128"; export var XmlEncAES256KeyWrapUrl: string;// ="http://www.w3.org/2001/04/xmlenc#kw-aes256"; export var XmlEncAES192KeyWrapUrl: string;// ="http://www.w3.org/2001/04/xmlenc#kw-aes192"; export var XmlEncSHA256Url: string;// ="http://www.w3.org/2001/04/xmlenc#sha256"; export var XmlEncSHA512Url: string;// ="http://www.w3.org/2001/04/xmlenc#sha512"; var m_capacity: number;// =4; } export module SignedXml { export var XmlDsigNamespaceUrl: string;// ="http://www.w3.org/2000/09/xmldsig#"; export var XmlDsigMinimalCanonicalizationUrl: string;// ="http://www.w3.org/2000/09/xmldsig#minimal"; export var XmlDsigCanonicalizationUrl: string;// ="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; export var XmlDsigCanonicalizationWithCommentsUrl: string;// ="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; export var XmlDsigSHA1Url: string;// ="http://www.w3.org/2000/09/xmldsig#sha1"; export var XmlDsigDSAUrl: string;// ="http://www.w3.org/2000/09/xmldsig#dsa-sha1"; export var XmlDsigRSASHA1Url: string;// ="http://www.w3.org/2000/09/xmldsig#rsa-sha1"; export var XmlDsigHMACSHA1Url: string;// ="http://www.w3.org/2000/09/xmldsig#hmac-sha1"; export var XmlDsigC14NTransformUrl: string;// ="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; export var XmlDsigC14NWithCommentsTransformUrl: string;// ="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; export var XmlDsigExcC14NTransformUrl: string;// ="http://www.w3.org/2001/10/xml-exc-c14n#"; export var XmlDsigExcC14NWithCommentsTransformUrl: string;// ="http://www.w3.org/2001/10/xml-exc-c14n#WithComments"; export var XmlDsigBase64TransformUrl: string;// ="http://www.w3.org/2000/09/xmldsig#base64"; export var XmlDsigXPathTransformUrl: string;// ="http://www.w3.org/TR/1999/REC-xpath-19991116"; export var XmlDsigXsltTransformUrl: string;// ="http://www.w3.org/TR/1999/REC-xslt-19991116"; export var XmlDsigEnvelopedSignatureTransformUrl: string;// ="http://www.w3.org/2000/09/xmldsig#enveloped-signature"; export var XmlDecryptionTransformUrl: string;// ="http://www.w3.org/2002/07/decrypt#XML"; export var XmlLicenseTransformUrl: string;// ="urn:mpeg:mpeg21:2003:01-REL-R-NS:licenseTransform"; var XmlDsigMoreHMACMD5Url: string;// ="http://www.w3.org/2001/04/xmldsig-more#hmac-md5"; var XmlDsigMoreHMACSHA256Url: string;// ="http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"; var XmlDsigMoreHMACSHA384Url: string;// ="http://www.w3.org/2001/04/xmldsig-more#hmac-sha384"; var XmlDsigMoreHMACSHA512Url: string;// ="http://www.w3.org/2001/04/xmldsig-more#hmac-sha512"; var XmlDsigMoreHMACRIPEMD160Url: string;// ="http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160"; } } declare module System.Security.Policy { export module Evidence { var LockTimeout: number;// =5000; } } declare module System.Text { export module Encoding { export var CodePageASCII: number;// =20127; export var ISO_8859_1: number;// =28591; var MIMECONTF_MAILNEWS: number;// =1; var MIMECONTF_BROWSER: number;// =2; var MIMECONTF_SAVABLE_MAILNEWS: number;// =256; var MIMECONTF_SAVABLE_BROWSER: number;// =512; var CodePageDefault: number;// =0; var CodePageNoOEM: number;// =1; var CodePageNoMac: number;// =2; var CodePageNoThread: number;// =3; var CodePageNoSymbol: number;// =42; var CodePageUnicode: number;// =1200; var CodePageBigEndian: number;// =1201; var CodePageWindows1252: number;// =1252; var CodePageMacGB2312: number;// =10008; var CodePageGB2312: number;// =20936; var CodePageMacKorean: number;// =10003; var CodePageDLLKorean: number;// =20949; var ISO2022JP: number;// =50220; var ISO2022JPESC: number;// =50221; var ISO2022JPSISO: number;// =50222; var ISOKorean: number;// =50225; var ISOSimplifiedCN: number;// =50227; var EUCJP: number;// =51932; var ChineseHZ: number;// =52936; var DuplicateEUCCN: number;// =51936; var EUCCN: number;// =936; var EUCKR: number;// =51949; var ISCIIAssemese: number;// =57006; var ISCIIBengali: number;// =57003; var ISCIIDevanagari: number;// =57002; var ISCIIGujarathi: number;// =57010; var ISCIIKannada: number;// =57008; var ISCIIMalayalam: number;// =57009; var ISCIIOriya: number;// =57007; var ISCIIPanjabi: number;// =57011; var ISCIITamil: number;// =57004; var ISCIITelugu: number;// =57005; var GB18030: number;// =54936; var ISO_8859_8I: number;// =38598; var ISO_8859_8_Visual: number;// =28598; var ENC50229: number;// =50229; var CodePageUTF7: number;// =65000; var CodePageUTF8: number;// =65001; var CodePageUTF32: number;// =12000; var CodePageUTF32BE: number;// =12001; } } declare module System.Threading { export module WaitHandle { export var WaitTimeout: number;// =258; var MAX_WAITHANDLES: number;// =64; var WAIT_OBJECT_0: number;// =0; var WAIT_ABANDONED: number;// =128; var WAIT_FAILED: number;// =2147483647; var ERROR_TOO_MANY_POSTS: number;// =298; } } declare module System.Uri { } declare module System.Xml { export module XmlDeclaration { var YES: string;// ="yes"; var NO: string;// ="no"; } export module XmlNamespaceManager { var MinDeclsCountForHashtable: number;// =16; } export module XmlWriter { var WriteNodeBufferSize: number;// =1024; } } declare module System.Xml.Schema { export module SchemaNotation { export var SYSTEM: number;// =0; export var PUBLIC: number;// =1; } export module XmlSchema { export var Namespace: string;// ="http://www.w3.org/2001/XMLSchema"; export var InstanceNamespace: string;// ="http://www.w3.org/2001/XMLSchema-instance"; } } declare module System.Xml.Schema.NamespaceList { } declare module System.Xml.Schema.SchemaAttDef { } declare module System.Xml.Schema.SchemaDeclBase { } declare module System.Xml.Serialization { } declare module System.Xml.XPath { }
the_stack
const PLATFORM: WxPlatform = new WxPlatform(); class WxKit { // private static code = ''; private static iv = ''; private static enctypecode = ''; /** * 调用login完成getUserInfo版登陆操作 */ public static async login() { let code = null; let userInfo = null; let result = null; await PLATFORM.login() .then((res: { code?}) => { code = res.code }) .catch(err => { console.warn(err) }); // 调用 wx.getUserInfo await PLATFORM.getUserInfo() .then(async (res: { iv?, enctypecode?}) => { let userInfo = JSON.parse(JSON.stringify(res)) WxKit.iv = userInfo.iv; WxKit.enctypecode = userInfo.encryptedData; // 调用自己的服务器登录接口 await PLATFORM.auth(code, userInfo.iv, userInfo.encryptedData) .then(res => { result = JSON.parse(JSON.stringify(res)); // 设置通讯token Api.setToken(result.data.token); // 存入用户数据 UserData.setUserData(result.data); console.log('login_success'); }) .catch(err => { console.warn(err) }); console.warn('get_user_info_success'); console.log(userInfo); }) .catch(async err => { // if方法进入旧版getUserInfo对应的重授权弹窗 if (typeof wx.createUserInfoButton != 'function') { // 重授权弹窗调用,若拒绝会再次弹出 await WxKit.reAuth() .then(async (res: { iv?, encryptedData?}) => { userInfo = JSON.parse(JSON.stringify(res)) // 授权成功后登录 await PLATFORM.auth(code, userInfo.iv, userInfo.encryptedData) .then(res => { result = JSON.parse(JSON.stringify(res)); Api.setToken(result.data.token); UserData.setUserData(result.data); console.log('login_success'); }) .catch(err => { console.warn(err); }); }); } else { // else 方法进入新版调用 createUserInfoButton授权弹窗 wx.hideLoading(); var button = wx.createUserInfoButton(WxLoginButton.btnSkin) button.show(); button.onTap(async (res) => { console.log(res); if (res.errMsg == 'getUserInfo:ok') { WxKit.iv = res.iv; WxKit.enctypecode = res.encryptedData; await PLATFORM.auth(code, WxKit.iv, WxKit.enctypecode) .then(res => { result = JSON.parse(JSON.stringify(res)); Api.setToken(result.data.token); UserData.setUserData(result.data); console.log('login_success'); }) .catch(err => { console.warn(err) }); button.hide(); } else { return false; } }); } }) return result; } /** * getUserInfo授权失败时重新弹出需授权弹窗,若拒绝则继续弹出 */ private static async reAuth() { wx.hideLoading(); return new Promise((resolve, reject) => { PLATFORM.showAuthModal() .then(async (res: { authSetting }) => { if (res.authSetting['scope.userInfo']) { await PLATFORM.getUserInfo().then(res => { resolve(res); }) } else { await WxKit.reAuth().then(res => { resolve(res); }); } }) }) } /** * 设置默认分享 */ public static setDefaultShare() { console.log('set_default_share'); wx.showShareMenu({ withShareTicket: true, success: (res) => { console.log('setting_success'); console.log(res); }, fail: (err) => { console.warn(err) } }); wx.onShareAppMessage(function () { return { title: GameConfig.getShareTitle() || '', imageUrl: GameConfig.getShareImg() || '' } }); } /** * @param {string} type? type可能取值 : groupRank(排行榜群排行) groupResult(结果页群排行) reborn(分享重生) normalShare(普通分享) * @param {string} title? * @param {string} imageUrl? */ public static async shareGame(type?: string, title?: string, imageUrl?: string) { // 不传type时,默认为普通分享 type || (type = 'normalShare'); // 不传title时,为默认title title || (title = GameConfig.getShareTitle()); // 不传imageUrl时,为默认image imageUrl || (imageUrl = GameConfig.getShareImg()); if (imageUrl == 'get') { imageUrl = await Api.getShareUrl(); } return new Promise((resolve, reject) => { wx.shareAppMessage({ title: title, imageUrl: imageUrl, query: type.match('group') ? 'groupRank=1' : '', success: res => { resolve(res); }, fail: (err) => { resolve(null); } }) }) } /** * 分享重生调用 * @param {string} title * @param {string} imgUrl? */ public static async rebornGame(title: string, imgUrl?: string) { let reborn_result = false; await WxKit.shareGame('reborn', title, imgUrl).then(res => { reborn_result = !!res; }) return reborn_result; } public static linkOpenData(message: {}, width?: number, height?: number) { let basic = { isDisplay: "true", token: Api.getToken(), userInfo: UserData.getUserData() } for (let key in message) { basic[key] = message[key]; } let open_data_container = new egret.Sprite(); let openDataContext = wx.getOpenDataContext(); const bitmapdata = new egret.BitmapData(window["sharedCanvas"]); bitmapdata.$deleteSource = false; const texture = new egret.Texture(); texture._setBitmapData(bitmapdata); let bitmap: egret.Bitmap; bitmap = new egret.Bitmap(texture); bitmap.width = width || GameConfig.getWidth(); bitmap.height = height || GameConfig.getHeight(); bitmap.name = "openData"; open_data_container.addChild(bitmap); egret.startTick((timeStarmp: number) => { egret.WebGLUtils.deleteWebGLTexture(bitmapdata.webGLTexture); bitmapdata.webGLTexture = null; return false; }, this); openDataContext.postMessage(basic); console.log('link_done'); return open_data_container; } // 上传成绩至开放数据域 public static async uploadScore(score: number) { await PLATFORM.setKVData({ "score": score + '', "date": Utils.getNowDate() }) .then(res => { }); return true; } /** * 设置回到前台事件处理音频及群排行 */ public static setOnShowRule() { wx.onShow(() => { Mp3.playBGM(); }) } /** * 流量主视频广告调用方法 * */ private static video_ads = {}; private static current_video_ad_id = ''; public static showVideoAd(ad_id: string, success_callback: Function, err_callback?: Function) { // 无ad_id时弹出警告 if (!(ad_id)) { wx.showModal({ title: '系统提示', content: "请填入ad_id", showCancel: false, cancelText: "", confirmText: "确定", success: () => { err_callback(); } }) return } // 低版本兼容方法 if (!(typeof wx.createRewardedVideoAd == 'function')) { wx.showModal({ title: '系统提示', content: "您的微信版本太低,暂时无法获取广告", showCancel: false, cancelText: "", confirmText: "确定", success: () => { success_callback(); } }) return } this.video_ads[ad_id] = wx.createRewardedVideoAd({ adUnitId: ad_id }) this.current_video_ad_id = ad_id; // 播放广告时暂停背景音乐 Mp3.stopBGM(); this.video_ads[ad_id].load() .then(() => { // 加载成功后播放视频 this.video_ads[ad_id].show(); }) // 加载失败时直接当作玩家视频广告观看成功 .catch(err => { wx.showModal({ title: '系统提示', content: "暂时无法获取广告", showCancel: false, cancelText: "", confirmText: "确定", success: () => { this.current_video_ad_id == ad_id && success_callback() && (this.current_video_ad_id = ''); } }) }); // 兼容新老版本广告关闭按钮 this.video_ads[ad_id].onClose(function onCloseFunc(status) { if (!status || status.isEnded) { // 用户完整观看广告 WxKit.current_video_ad_id == ad_id && success_callback() && (WxKit.current_video_ad_id = ''); } else { // 用户提前点击了【关闭广告】按钮,进入失败回调 err_callback && WxKit.current_video_ad_id == ad_id && err_callback() && (WxKit.current_video_ad_id = ''); } // 关闭后重开背景音乐 Mp3.playBGM(); // 停止监听close方法 WxKit.video_ads[ad_id].offClose(onCloseFunc); }) } /** * banner广告调用方法 */ public static showBannerAd(ad_id: string): any { // 无ad_id时弹出警告 if (!(ad_id)) { wx.showModal({ title: '系统提示', content: "请填入ad_id", showCancel: false, cancelText: "", confirmText: "确定", success: () => { } }) return null; } // 低版本兼容方法 let bannerAd = typeof wx.createBannerAd == 'function' ? wx.createBannerAd({ adUnitId: ad_id, style: { left: 0, top: 0, width: 350 } }) : null; if (bannerAd) { bannerAd.show(); let { screenWidth, screenHeight } = wx.getSystemInfoSync() bannerAd.onResize(res => { // banner广告放在底部 bannerAd.style.top = screenHeight - bannerAd.style.realHeight; }); bannerAd.style.width = screenWidth; } return bannerAd; } }
the_stack
import express from 'express'; import fetch from 'node-fetch'; import requests from 'supertest'; import { UIServer } from './app'; import { loadConfigs } from './configs'; import { TEST_ONLY as K8S_TEST_EXPORT } from './k8s-helper'; import { Server } from 'http'; import { commonSetup } from './integration-tests/test-helper'; jest.mock('node-fetch'); // TODO: move sections of tests here to individual files in `frontend/server/integration-tests/` // for better organization and shorter/more focused tests. const mockedFetch: jest.Mock = fetch as any; describe('UIServer apis', () => { let app: UIServer; const tagName = '1.0.0'; const commitHash = 'abcdefg'; const { argv, buildDate, indexHtmlContent } = commonSetup({ tagName, commitHash }); afterEach(() => { if (app) { app.close(); } }); describe('/', () => { it('responds with unmodified index.html if it is not a kubeflow deployment', done => { const expectedIndexHtml = ` <html> <head> <script> window.KFP_FLAGS.DEPLOYMENT=null window.KFP_FLAGS.HIDE_SIDENAV=false </script> <script id="kubeflow-client-placeholder"></script> </head> </html>`; const configs = loadConfigs(argv, {}); app = new UIServer(configs); const request = requests(app.start()); request .get('/') .expect('Content-Type', 'text/html; charset=utf-8') .expect(200, expectedIndexHtml, done); }); it('responds with a modified index.html if it is a kubeflow deployment and sets HIDE_SIDENAV', done => { const expectedIndexHtml = ` <html> <head> <script> window.KFP_FLAGS.DEPLOYMENT="KUBEFLOW" window.KFP_FLAGS.HIDE_SIDENAV=true </script> <script id="kubeflow-client-placeholder" src="/dashboard_lib.bundle.js"></script> </head> </html>`; const configs = loadConfigs(argv, { DEPLOYMENT: 'kubeflow' }); app = new UIServer(configs); const request = requests(app.start()); request .get('/') .expect('Content-Type', 'text/html; charset=utf-8') .expect(200, expectedIndexHtml, done); }); it('responds with flag DEPLOYMENT=MARKETPLACE if it is a marketplace deployment', done => { const expectedIndexHtml = ` <html> <head> <script> window.KFP_FLAGS.DEPLOYMENT="MARKETPLACE" window.KFP_FLAGS.HIDE_SIDENAV=false </script> <script id="kubeflow-client-placeholder"></script> </head> </html>`; const configs = loadConfigs(argv, { DEPLOYMENT: 'marketplace' }); app = new UIServer(configs); const request = requests(app.start()); request .get('/') .expect('Content-Type', 'text/html; charset=utf-8') .expect(200, expectedIndexHtml, done); }); }); it('responds with flag HIDE_SIDENAV=false even when DEPLOYMENT=KUBEFLOW', done => { const expectedIndexHtml = ` <html> <head> <script> window.KFP_FLAGS.DEPLOYMENT="KUBEFLOW" window.KFP_FLAGS.HIDE_SIDENAV=false </script> <script id="kubeflow-client-placeholder" src="/dashboard_lib.bundle.js"></script> </head> </html>`; const configs = loadConfigs(argv, { DEPLOYMENT: 'KUBEFLOW', HIDE_SIDENAV: 'false' }); app = new UIServer(configs); const request = requests(app.start()); request .get('/') .expect('Content-Type', 'text/html; charset=utf-8') .expect(200, expectedIndexHtml, done); }); describe('/apis/v1beta1/healthz', () => { it('responds with apiServerReady to be false if ml-pipeline api server is not ready.', done => { (fetch as any).mockImplementationOnce((_url: string, _opt: any) => ({ json: () => Promise.reject('Unknown error'), })); const configs = loadConfigs(argv, {}); app = new UIServer(configs); requests(app.start()) .get('/apis/v1beta1/healthz') .expect( 200, { apiServerReady: false, buildDate, frontendCommitHash: commitHash, frontendTagName: tagName, }, done, ); }); it('responds with both ui server and ml-pipeline api state if ml-pipeline api server is also ready.', done => { (fetch as any).mockImplementationOnce((_url: string, _opt: any) => ({ json: () => Promise.resolve({ commit_sha: 'commit_sha', tag_name: '1.0.0', multi_user: false, }), })); const configs = loadConfigs(argv, {}); app = new UIServer(configs); requests(app.start()) .get('/apis/v1beta1/healthz') .expect( 200, { apiServerCommitHash: 'commit_sha', apiServerTagName: '1.0.0', apiServerMultiUser: false, multi_user: false, apiServerReady: true, buildDate, frontendCommitHash: commitHash, frontendTagName: tagName, }, done, ); }); }); describe('/system', () => { describe('/cluster-name', () => { it('responds with cluster name data from gke metadata', done => { mockedFetch.mockImplementationOnce((url: string, _opts: any) => url === 'http://metadata/computeMetadata/v1/instance/attributes/cluster-name' ? Promise.resolve({ ok: true, text: () => Promise.resolve('test-cluster') }) : Promise.reject('Unexpected request'), ); app = new UIServer(loadConfigs(argv, {})); const request = requests(app.start()); request .get('/system/cluster-name') .expect('Content-Type', 'text/html; charset=utf-8') .expect(200, 'test-cluster', done); }); it('responds with 500 status code if corresponding endpoint is not ok', done => { mockedFetch.mockImplementationOnce((url: string, _opts: any) => url === 'http://metadata/computeMetadata/v1/instance/attributes/cluster-name' ? Promise.resolve({ ok: false, text: () => Promise.resolve('404 not found') }) : Promise.reject('Unexpected request'), ); app = new UIServer(loadConfigs(argv, {})); const request = requests(app.start()); request.get('/system/cluster-name').expect(500, 'Failed fetching GKE cluster name', done); }); it('responds with endpoint disabled if DISABLE_GKE_METADATA env is true', done => { const configs = loadConfigs(argv, { DISABLE_GKE_METADATA: 'true' }); app = new UIServer(configs); const request = requests(app.start()); request .get('/system/cluster-name') .expect(500, 'GKE metadata endpoints are disabled.', done); }); }); describe('/project-id', () => { it('responds with project id data from gke metadata', done => { mockedFetch.mockImplementationOnce((url: string, _opts: any) => url === 'http://metadata/computeMetadata/v1/project/project-id' ? Promise.resolve({ ok: true, text: () => Promise.resolve('test-project') }) : Promise.reject('Unexpected request'), ); app = new UIServer(loadConfigs(argv, {})); const request = requests(app.start()); request.get('/system/project-id').expect(200, 'test-project', done); }); it('responds with 500 status code if metadata request is not ok', done => { mockedFetch.mockImplementationOnce((url: string, _opts: any) => url === 'http://metadata/computeMetadata/v1/project/project-id' ? Promise.resolve({ ok: false, text: () => Promise.resolve('404 not found') }) : Promise.reject('Unexpected request'), ); app = new UIServer(loadConfigs(argv, {})); const request = requests(app.start()); request.get('/system/project-id').expect(500, 'Failed fetching GKE project id', done); }); it('responds with endpoint disabled if DISABLE_GKE_METADATA env is true', done => { app = new UIServer(loadConfigs(argv, { DISABLE_GKE_METADATA: 'true' })); const request = requests(app.start()); request.get('/system/project-id').expect(500, 'GKE metadata endpoints are disabled.', done); }); }); }); describe('/k8s/pod', () => { let request: requests.SuperTest<requests.Test>; beforeEach(() => { app = new UIServer(loadConfigs(argv, {})); request = requests(app.start()); }); it('asks for podname if not provided', done => { request.get('/k8s/pod').expect(422, 'podname argument is required', done); }); it('asks for podnamespace if not provided', done => { request .get('/k8s/pod?podname=test-pod') .expect(422, 'podnamespace argument is required', done); }); it('responds with pod info in JSON', done => { const readPodSpy = jest.spyOn(K8S_TEST_EXPORT.k8sV1Client, 'readNamespacedPod'); readPodSpy.mockImplementation(() => Promise.resolve({ body: { kind: 'Pod' }, // only body is used } as any), ); request .get('/k8s/pod?podname=test-pod&podnamespace=test-ns') .expect(200, '{"kind":"Pod"}', err => { expect(readPodSpy).toHaveBeenCalledWith('test-pod', 'test-ns'); done(err); }); }); it('responds with error when failed to retrieve pod info', done => { const readPodSpy = jest.spyOn(K8S_TEST_EXPORT.k8sV1Client, 'readNamespacedPod'); readPodSpy.mockImplementation(() => Promise.reject({ body: { message: 'pod not found', code: 404, }, } as any), ); const spyError = jest.spyOn(console, 'error').mockImplementation(() => null); request .get('/k8s/pod?podname=test-pod&podnamespace=test-ns') .expect(500, 'Could not get pod test-pod in namespace test-ns: pod not found', () => { expect(spyError).toHaveBeenCalledTimes(1); done(); }); }); }); describe('/k8s/pod/events', () => { let request: requests.SuperTest<requests.Test>; beforeEach(() => { app = new UIServer(loadConfigs(argv, {})); request = requests(app.start()); }); it('asks for podname if not provided', done => { request.get('/k8s/pod/events').expect(422, 'podname argument is required', done); }); it('asks for podnamespace if not provided', done => { request .get('/k8s/pod/events?podname=test-pod') .expect(422, 'podnamespace argument is required', done); }); it('responds with pod info in JSON', done => { const listEventSpy = jest.spyOn(K8S_TEST_EXPORT.k8sV1Client, 'listNamespacedEvent'); listEventSpy.mockImplementation(() => Promise.resolve({ body: { kind: 'EventList' }, // only body is used } as any), ); request .get('/k8s/pod/events?podname=test-pod&podnamespace=test-ns') .expect(200, '{"kind":"EventList"}', err => { expect(listEventSpy).toHaveBeenCalledWith( 'test-ns', undefined, undefined, undefined, 'involvedObject.namespace=test-ns,involvedObject.name=test-pod,involvedObject.kind=Pod', ); done(err); }); }); it('responds with error when failed to retrieve pod info', done => { const listEventSpy = jest.spyOn(K8S_TEST_EXPORT.k8sV1Client, 'listNamespacedEvent'); listEventSpy.mockImplementation(() => Promise.reject({ body: { message: 'no events', code: 404, }, } as any), ); const spyError = jest.spyOn(console, 'error').mockImplementation(() => null); request .get('/k8s/pod/events?podname=test-pod&podnamespace=test-ns') .expect( 500, 'Error when listing pod events for pod "test-pod" in "test-ns" namespace: no events', err => { expect(spyError).toHaveBeenCalledTimes(1); done(err); }, ); }); }); // TODO: Add integration tests for k8s helper related endpoints // describe('/k8s/pod/logs', () => {}); describe('/apis/v1beta1/', () => { let request: requests.SuperTest<requests.Test>; let kfpApiServer: Server; beforeEach(() => { const kfpApiPort = 3001; kfpApiServer = express() .all('/*', (_, res) => { res.status(200).send('KFP API is working'); }) .listen(kfpApiPort); app = new UIServer( loadConfigs(argv, { ML_PIPELINE_SERVICE_PORT: `${kfpApiPort}`, ML_PIPELINE_SERVICE_HOST: 'localhost', }), ); request = requests(app.start()); }); afterEach(() => { if (kfpApiServer) { kfpApiServer.close(); } }); it('rejects reportMetrics because it is not public kfp api', done => { const runId = 'a-random-run-id'; request .post(`/apis/v1beta1/runs/${runId}:reportMetrics`) .expect( 403, '/apis/v1beta1/runs/a-random-run-id:reportMetrics endpoint is not meant for external usage.', done, ); }); it('rejects reportWorkflow because it is not public kfp api', done => { const workflowId = 'a-random-workflow-id'; request .post(`/apis/v1beta1/workflows/${workflowId}`) .expect( 403, '/apis/v1beta1/workflows/a-random-workflow-id endpoint is not meant for external usage.', done, ); }); it('rejects reportScheduledWorkflow because it is not public kfp api', done => { const swf = 'a-random-swf-id'; request .post(`/apis/v1beta1/scheduledworkflows/${swf}`) .expect( 403, '/apis/v1beta1/scheduledworkflows/a-random-swf-id endpoint is not meant for external usage.', done, ); }); it('does not reject similar apis', done => { request // use reportMetrics as runId to see if it can confuse route parsing .post(`/apis/v1beta1/runs/xxx-reportMetrics:archive`) .expect(200, 'KFP API is working', done); }); it('proxies other run apis', done => { request .post(`/apis/v1beta1/runs/a-random-run-id:archive`) .expect(200, 'KFP API is working', done); }); }); });
the_stack
module androidui.widget{ import View = android.view.View; import MeasureSpec = View.MeasureSpec; import AttrBinder = androidui.attr.AttrBinder; /** * use a img element draw Image. It's better to use {@see ImageView} draw image on Canvas. */ export class HtmlImageView extends HtmlBaseView { private mScaleType:android.widget.ImageView.ScaleType; private mHaveFrame = false; private mAdjustViewBounds = false; private mMaxWidth = Number.MAX_SAFE_INTEGER; private mMaxHeight = Number.MAX_SAFE_INTEGER; private mAlpha = 255; private mDrawableWidth:number = 0; private mDrawableHeight:number = 0; private mAdjustViewBoundsCompat = false; private mImgElement:HTMLImageElement; constructor(context:android.content.Context, bindElement?:HTMLElement, defStyle?:Map<string, string>) { super(context, bindElement, defStyle); this.initImageView(); const a = context.obtainStyledAttributes(bindElement, defStyle); const src = a.getString('src'); if (src) { this.setImageURI(src); } this.setAdjustViewBounds(a.getBoolean('adjustViewBounds', false)); this.setMaxWidth(a.getDimensionPixelSize('maxWidth', this.mMaxWidth)); this.setMaxHeight(a.getDimensionPixelSize('maxHeight', this.mMaxHeight)); this.setScaleType(android.widget.ImageView.parseScaleType(a.getAttrValue('scaleType'), this.mScaleType)); this.setImageAlpha(a.getInt('drawableAlpha', this.mAlpha)); } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return super.createClassAttrBinder().set('src', { setter(v:HtmlImageView, value:any, attrBinder:AttrBinder) { v.setImageURI(value); }, getter(v:HtmlImageView) { return v.mImgElement.src; } }).set('adjustViewBounds', { setter(v:HtmlImageView, value:any, attrBinder:AttrBinder) { v.setAdjustViewBounds(attrBinder.parseBoolean(value, false)); }, getter(v:HtmlImageView) { return v.getAdjustViewBounds(); } }).set('maxWidth', { setter(v:HtmlImageView, value:any, attrBinder:AttrBinder) { v.setMaxWidth(attrBinder.parseNumberPixelSize(value, v.mMaxWidth)); }, getter(v:HtmlImageView) { return v.mMaxWidth; } }).set('maxHeight', { setter(v:HtmlImageView, value:any, attrBinder:AttrBinder) { v.setMaxHeight(attrBinder.parseNumberPixelSize(value, v.mMaxHeight)); }, getter(v:HtmlImageView) { return v.mMaxHeight; } }).set('scaleType', { setter(v:HtmlImageView, value:any, attrBinder:AttrBinder) { if (typeof value === 'number') { v.setScaleType(value); } else { v.setScaleType(android.widget.ImageView.parseScaleType(value, v.mScaleType)); } }, getter(v:HtmlImageView) { return v.mScaleType; } }).set('drawableAlpha', { setter(v: HtmlImageView, value: any, attrBinder:AttrBinder) { v.setImageAlpha(attrBinder.parseInt(value, v.mAlpha)); }, getter(v: HtmlImageView) { return v.mAlpha; } }); } private initImageView(){ this.mScaleType = android.widget.ImageView.ScaleType.FIT_CENTER; this.mImgElement = document.createElement('img'); this.mImgElement.style.position = "absolute"; this.mImgElement.onload = (()=>{ this.mImgElement.style.left = 0+'px'; this.mImgElement.style.top = 0+'px'; this.mImgElement.style.width = ''; this.mImgElement.style.height = ''; this.mDrawableWidth = this.mImgElement.width; this.mDrawableHeight = this.mImgElement.height; this.mImgElement.style.display = 'none'; this.mImgElement.style.opacity = ''; this.requestLayout(); }); this.bindElement.appendChild(this.mImgElement); } getAdjustViewBounds():boolean { return this.mAdjustViewBounds; } setAdjustViewBounds(adjustViewBounds:boolean) { this.mAdjustViewBounds = adjustViewBounds; if (adjustViewBounds) { this.setScaleType(android.widget.ImageView.ScaleType.FIT_CENTER); } } getMaxWidth():number { return this.mMaxWidth; } setMaxWidth(maxWidth:number) { this.mMaxWidth = maxWidth; } getMaxHeight():number { return this.mMaxHeight; } setMaxHeight(maxHeight:number) { this.mMaxHeight = maxHeight; } setImageURI(uri:string){ this.mDrawableWidth = -1; this.mDrawableHeight = -1; this.mImgElement.style.opacity = '0'; this.mImgElement.src = uri; } setScaleType(scaleType:android.widget.ImageView.ScaleType) { if (scaleType == null) { throw new Error('NullPointerException'); } if (this.mScaleType != scaleType) { this.mScaleType = scaleType; this.setWillNotCacheDrawing(scaleType == android.widget.ImageView.ScaleType.CENTER); this.requestLayout(); this.invalidate(); } } getScaleType():android.widget.ImageView.ScaleType { return this.mScaleType; } protected onMeasure(widthMeasureSpec, heightMeasureSpec):void { let w:number; let h:number; // Desired aspect ratio of the view's contents (not including padding) let desiredAspect = 0.0; // We are allowed to change the view's width let resizeWidth = false; // We are allowed to change the view's height let resizeHeight = false; const widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); const heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); if(!this.mImgElement.src || !this.mImgElement.complete){ // If no drawable, its intrinsic size is 0. this.mDrawableWidth = -1; this.mDrawableHeight = -1; w = h = 0; }else{ w = this.mDrawableWidth; h = this.mDrawableHeight; if (w <= 0) w = 1; if (h <= 0) h = 1; // We are supposed to adjust view bounds to match the aspect // ratio of our drawable. See if that is possible. if (this.mAdjustViewBounds) { resizeWidth = widthSpecMode != MeasureSpec.EXACTLY; resizeHeight = heightSpecMode != MeasureSpec.EXACTLY; desiredAspect = w / h; } } let pleft = this.mPaddingLeft; let pright = this.mPaddingRight; let ptop = this.mPaddingTop; let pbottom = this.mPaddingBottom; let widthSize:number; let heightSize:number; if (resizeWidth || resizeHeight) { /* If we get here, it means we want to resize to match the drawables aspect ratio, and we have the freedom to change at least one dimension. */ // Get the max possible width given our constraints widthSize = this.resolveAdjustedSize(w + pleft + pright, this.mMaxWidth, widthMeasureSpec); // Get the max possible height given our constraints heightSize = this.resolveAdjustedSize(h + ptop + pbottom, this.mMaxHeight, heightMeasureSpec); if (desiredAspect != 0) { // See what our actual aspect ratio is let actualAspect = (widthSize - pleft - pright) / (heightSize - ptop - pbottom); if (Math.abs(actualAspect - desiredAspect) > 0.0000001) { let done = false; // Try adjusting width to be proportional to height if (resizeWidth) { let newWidth = Math.floor(desiredAspect * (heightSize - ptop - pbottom)) + pleft + pright; // Allow the width to outgrow its original estimate if height is fixed. if (!resizeHeight && !this.mAdjustViewBoundsCompat) { widthSize = this.resolveAdjustedSize(newWidth, this.mMaxWidth, widthMeasureSpec); } if (newWidth <= widthSize) { widthSize = newWidth; done = true; } } // Try adjusting height to be proportional to width if (!done && resizeHeight) { let newHeight = Math.floor((widthSize - pleft - pright) / desiredAspect) + ptop + pbottom; // Allow the height to outgrow its original estimate if width is fixed. if (!resizeWidth && !this.mAdjustViewBoundsCompat) { heightSize = this.resolveAdjustedSize(newHeight, this.mMaxHeight, heightMeasureSpec); } if (newHeight <= heightSize) { heightSize = newHeight; } } } } } else { /* We are either don't want to preserve the drawables aspect ratio, or we are not allowed to change view dimensions. Just measure in the normal way. */ w += pleft + pright; h += ptop + pbottom; w = Math.max(w, this.getSuggestedMinimumWidth()); h = Math.max(h, this.getSuggestedMinimumHeight()); widthSize = HtmlImageView.resolveSizeAndState(w, widthMeasureSpec, 0); heightSize = HtmlImageView.resolveSizeAndState(h, heightMeasureSpec, 0); } this.setMeasuredDimension(widthSize, heightSize); } private resolveAdjustedSize(desiredSize:number, maxSize:number, measureSpec:number):number { let result = desiredSize; let specMode = MeasureSpec.getMode(measureSpec); let specSize = MeasureSpec.getSize(measureSpec); switch (specMode) { case MeasureSpec.UNSPECIFIED: /* Parent says we can be as big as we want. Just don't be larger than max size imposed on ourselves. */ result = Math.min(desiredSize, maxSize); break; case MeasureSpec.AT_MOST: // Parent says we can be as big as we want, up to specSize. // Don't be larger than specSize, and don't be larger than // the max size imposed on ourselves. result = Math.min(Math.min(desiredSize, specSize), maxSize); break; case MeasureSpec.EXACTLY: // No choice. Do what we are told. result = specSize; break; } return result; } protected setFrame(left:number, top:number, right:number, bottom:number):boolean { let changed = super.setFrame(left, top, right, bottom); this.mHaveFrame = true; this.configureBounds(); this.mImgElement.style.display = ''; return changed; } private configureBounds() { let dwidth = this.mDrawableWidth; let dheight = this.mDrawableHeight; let vwidth = this.getWidth() - this.mPaddingLeft - this.mPaddingRight; let vheight = this.getHeight() - this.mPaddingTop - this.mPaddingBottom; let fits = (dwidth < 0 || vwidth == dwidth) && (dheight < 0 || vheight == dheight); this.mImgElement.style.left = 0+'px'; this.mImgElement.style.top = 0+'px'; this.mImgElement.style.width = ''; this.mImgElement.style.height = ''; if (dwidth <= 0 || dheight <= 0) { /* If the drawable has no intrinsic size, or we're told to scaletofit, then we just fill our entire view. */ return; } if(this.mScaleType === android.widget.ImageView.ScaleType.FIT_XY){ this.mImgElement.style.width = vwidth+'px'; this.mImgElement.style.height = vheight+'px'; return; } // We need to do the scaling ourself, so have the drawable // use its native size. this.mImgElement.style.width = dwidth+'px'; this.mImgElement.style.height = dheight+'px'; if (android.widget.ImageView.ScaleType.MATRIX === this.mScaleType) { //nothing : MATRIX is not support }else if (fits) { // The bitmap fits exactly, no transform needed. } else if (android.widget.ImageView.ScaleType.CENTER === this.mScaleType) { // Center bitmap in view, no scaling. let left = Math.round((vwidth - dwidth) * 0.5); let top = Math.round((vheight - dheight) * 0.5); this.mImgElement.style.left = left+'px'; this.mImgElement.style.top = top+'px'; } else if (android.widget.ImageView.ScaleType.CENTER_CROP === this.mScaleType) { let scale; let dx = 0, dy = 0; if (dwidth * vheight > vwidth * dheight) { scale = vheight / dheight; dx = (vwidth - dwidth * scale) * 0.5; this.mImgElement.style.width = 'auto'; this.mImgElement.style.height = vheight+'px'; this.mImgElement.style.left = Math.round(dx)+'px'; this.mImgElement.style.top = '0px'; } else { scale = vwidth / dwidth; dy = (vheight - dheight * scale) * 0.5; this.mImgElement.style.width = vwidth+'px'; this.mImgElement.style.height = 'auto'; this.mImgElement.style.left = '0px'; this.mImgElement.style.top = Math.round(dy)+'px'; } } else if (android.widget.ImageView.ScaleType.CENTER_INSIDE === this.mScaleType) { let scale = 1; if (dwidth <= vwidth && dheight <= vheight) { //small nothing } else { let wScale = vwidth / dwidth; let hScale = vheight / dheight; if(wScale < hScale){ this.mImgElement.style.width = vwidth+'px'; this.mImgElement.style.height = 'auto'; }else{ this.mImgElement.style.width = 'auto'; this.mImgElement.style.height = vheight+'px'; } scale = Math.min(wScale, hScale); } let dx = Math.round((vwidth - dwidth * scale) * 0.5); let dy = Math.round((vheight - dheight * scale) * 0.5); this.mImgElement.style.left = dx + 'px'; this.mImgElement.style.top = dy+'px'; } else { let wScale = vwidth / dwidth; let hScale = vheight / dheight; if(wScale < hScale){ this.mImgElement.style.width = vwidth+'px'; this.mImgElement.style.height = 'auto'; }else{ this.mImgElement.style.width = 'auto'; this.mImgElement.style.height = vheight+'px'; } let scale = Math.min(wScale, hScale); if (android.widget.ImageView.ScaleType.FIT_CENTER === this.mScaleType) { let dx = Math.round((vwidth - dwidth * scale) * 0.5); let dy = Math.round((vheight - dheight * scale) * 0.5); this.mImgElement.style.left = dx + 'px'; this.mImgElement.style.top = dy+'px'; }else if (android.widget.ImageView.ScaleType.FIT_END === this.mScaleType) { let dx = Math.round((vwidth - dwidth * scale)); let dy = Math.round((vheight - dheight * scale)); this.mImgElement.style.left = dx + 'px'; this.mImgElement.style.top = dy+'px'; }else if (android.widget.ImageView.ScaleType.FIT_START === this.mScaleType) { //default is fit start } } } getImageAlpha():number { return this.mAlpha; } setImageAlpha(alpha:number) { this.setAlpha(alpha); } } }
the_stack
import { chimeeLog } from 'chimee-helper-log'; import { bind, isArray, isEmpty, isError, isFunction, isNil } from 'lodash'; import { runnable } from 'toxic-decorators'; import { dispatcherEventMethodMap, isDispatcherEventMethod, isDomEvent, isVideoEvent, selfProcessorEvents } from '../const/event'; import { isDomMethod, isKernelMethod } from '../const/method'; import { secondaryEventReg } from '../const/regExp'; import Dispatcher from '../dispatcher/index'; import { deletePropertyIfItIsEmpty, runRejectableQueue, runStoppableQueue } from '../helper/utils'; import { BinderTarget, EventStage } from '../typings/base'; function secondaryChecker(key: string) { if (key.match(secondaryEventReg)) { /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { chimeeLog.warn('bus', `Secondary Event "${key}" could not be call straightly by API.`); } return false; } return true; } function getKeyForOnceMap(eventName: string, stage: EventStage, pluginId: string) { return `${eventName}-${stage}-${pluginId}`; } /** * <pre> * event Bus class. Bus take charge of commuication between plugins and user. * Some of the event may trigger the kernel to do some task. * An event will run in four lifecycle * before -> processor -> main -> after -> side effect(_) * -------------------- emit period ---------------- * before: once an event emit, it will run through plugins in bubble to know is it possible to run. * processor: if sth need to be done on kernel. It will tell kernel. If kernel will trigger event later, it will break down here. Else will run into trigger period * -------------------- trigger period ----------------- * main: this procedure will trigger the main event in bubble, which means it can be stop in one plugin. * after: once event run through all events. It will trigger after event. This event will be trigger in broadcast way. * side effect(_): This events will always trigger once we bump into trigger period. So that you can know if the events been blocked. But it's not advice to listen on this effect. * </pre> */ export default class Bus { public dispatcher: Dispatcher; private events: { [eventName: string]: { [eventStage: string]: { [pluginId: string]: Array<(...args: any[]) => any>, }, }, }; private kind: BinderTarget; private onceMap: { [key: string]: Map<(...args: any[]) => any, Array<(...args: any[]) => any>>, }; /** * @param {Dispatcher} dispatcher bus rely on dispatcher, so you mush pass dispatcher at first when you generate Bus. * @return {Bus} */ constructor(dispatcher: Dispatcher, kind: BinderTarget) { /** * the referrence to dispatcher * @type {Dispatcher} */ this.dispatcher = dispatcher; this.kind = kind; this.events = {}; this.onceMap = {}; } /** * destroy hook which will be called when object destroy */ public destroy(): void { delete this.events; delete this.dispatcher; } /** * [Can only be called in dispatcher]emit an event, which will run before -> processor period. * It may stop in before period. * @param {string} key event's name * @param {anything} args other argument will be passed into handler * @return {Promise} this promise maybe useful if the event would not trigger kernel event. In that will you can know if it runs successful. But you can know if the event been stopped by the promise. */ @runnable(secondaryChecker) public emit(key: string, ...args: any): Promise<any> { const event = this.events[key]; if (isEmpty(event)) { if (selfProcessorEvents.indexOf(key) > -1) { return Promise.resolve(); } return this.eventProcessor(key, { sync: false }, ...args); } const beforeQueue = this.getEventQueue(event.before); return runRejectableQueue(beforeQueue, ...args) .then(() => { if (selfProcessorEvents.indexOf(key) > -1) { return; } return this.eventProcessor(key, { sync: false }, ...args); }) .catch((error) => { if (isError(error)) { this.dispatcher.throwError(error); } return Promise.reject(error); }); } /** * [Can only be called in dispatcher]emit an event, which will run before -> processor period synchronize. * It may stop in before period. * @param {string} key event's name * @param {anything} args other argument will be passed into handler * @return {Promise} this promise maybe useful if the event would not trigger kernel event. In that will you can know if it runs successful. But you can know if the event been stopped by the promise. */ @runnable(secondaryChecker, { backup() { return false; } }) public emitSync(key: string, ...args: any): boolean { const event = this.events[key]; if (isEmpty(event)) { if (selfProcessorEvents.indexOf(key) > -1) { return true; } return this.eventProcessor(key, { sync: true }, ...args); } const beforeQueue = this.getEventQueue(event.before); return runStoppableQueue(beforeQueue, ...args) && (selfProcessorEvents.indexOf(key) > -1 || this.eventProcessor(key, { sync: true }, ...args)); } public hasEvents() { return !isEmpty(this.events); } /** * [Can only be called in dispatcher]remove event off bus. Only suggest one by one. */ public off(pluginId: string, eventName: string, fn: (...args: any[]) => any, stage: EventStage) { const deleted = this.removeEvent({ eventName, fn, pluginId, stage, }); if (deleted) { return; } // if we can't find the normal events // maybe this event is bind once const handler = this.getFirstHandlerFromOnceMap({ eventName, fn, pluginId, stage, }); if (isFunction(handler)) { const deleted = this.removeEvent({ eventName, fn: handler, pluginId, stage, }); if (deleted) { this.removeFromOnceMap({ eventName, fn, handler, pluginId, stage, }); } } } /** * [Can only be called in dispatcher]bind event on bus. */ public on(pluginId: string, eventName: string, fn: (...args: any[]) => any, stage: EventStage) { this.addEvent({ eventName, stage, pluginId, fn }); } /** * [Can only be called in dispatcher]bind event on bus and remove it once event is triggered. */ public once(pluginId: string, eventName: string, fn: (...args: any[]) => any, stage: EventStage) { const bus = this; const handler = function(...args: any[]) { // keep the this so that it can run bind(fn, this)(...args); bus.removeEvent({ eventName, fn: handler, pluginId, stage, }); bus.removeFromOnceMap({ eventName, fn, handler, pluginId, stage, }); }; this.addEvent({ eventName, fn: handler, pluginId, stage, }); this.addToOnceMap({ eventName, fn, handler, pluginId, stage, }); } /** * [Can only be called in dispatcher]trigger an event, which will run main -> after -> side effect period * @param {string} key event's name * @param {anything} args * @return {Promise|undefined} you can know if event trigger finished~ However, if it's unlegal */ @runnable(secondaryChecker) public trigger(key: string, ...args: any): Promise<any> { const event = this.events[key]; if (isEmpty(event)) { return Promise.resolve(true); } const mainQueue = this.getEventQueue(event.main); return runRejectableQueue(mainQueue, ...args) .then(() => { const afterQueue = this.getEventQueue(event.after); return runRejectableQueue(afterQueue, ...args); }) .then(() => { return this.runSideEffectEvent(key, ...args); }) .catch((error) => { if (isError(error)) { this.dispatcher.throwError(error); } return this.runSideEffectEvent(key, ...args); }); } /** * [Can only be called in dispatcher]trigger an event, which will run main -> after -> side effect period in synchronize * @param {string} key event's name * @param {anything} args * @return {boolean} you can know if event trigger finished~ However, if it's unlegal */ @runnable(secondaryChecker, { backup() { return false; } }) public triggerSync(key: string, ...args: any): boolean { const event = this.events[key]; if (isEmpty(event)) { return true; } const mainQueue = this.getEventQueue(event.main); const afterQueue = this.getEventQueue(event.after); const result = runStoppableQueue(mainQueue, ...args) && runStoppableQueue(afterQueue, ...args); this.runSideEffectEvent(key, ...args); return result; } /** * add event into bus * @private * @param {Array} keys keys map pointing to position to put event handler * @param {function} fn handler to put */ private addEvent({ eventName, stage, pluginId, fn, }: { eventName: string, fn: (...args: any[]) => any, pluginId: string, stage: EventStage, }): void { this.events[eventName] = this.events[eventName] || {}; this.events[eventName][stage] = this.events[eventName][stage] || {}; this.events[eventName][stage][pluginId] = this.events[eventName][stage][pluginId] || ([] as Array<(...args: any[]) => any>); this.events[eventName][stage][pluginId].push(fn); } private addToOnceMap({ eventName, stage, pluginId, fn, handler, }: { eventName: string, fn: (...args: any[]) => any, handler: (...args: any[]) => any, pluginId: string, stage: EventStage, }): void { const key = getKeyForOnceMap(eventName, stage, pluginId); const map = this.onceMap[key] = this.onceMap[key] || new Map(); if (!map.has(fn)) { map.set(fn, []); } const handlers = map.get(fn); handlers.push(handler); } /** * event processor period. If event needs call kernel function. * I will called here. * If kernel will reponse. I will stop here. * Else I will trigger next period. * @param {string} key event's name * @param {boolean} options.sync we will take triggerSync if true, otherwise we will run trigger. default is false * @param {anything} args * @return {Promise|undefined} */ private eventProcessor(key: string, { sync }: {sync: true}, ...args: any[]): boolean; private eventProcessor(key: string, { sync }: {sync: false}, ...args: any[]): Promise<any>; private eventProcessor(key: string, { sync }: {sync: boolean}, ...args: any[]): Promise<any> | boolean { if (isDispatcherEventMethod(key)) { const methodName = dispatcherEventMethodMap[key]; // TODO: add type check // @ts-ignore: we do not check argument here, we will provide user a type check this.dispatcher[methodName](...args); } else if (isKernelMethod(key)) { // TODO: add type check // @ts-ignore: we do not check argument here, we will provide user a type ch this.dispatcher.kernel[key](...args); } else if (isDomMethod(key)) { // TODO: add type check // @ts-ignore: we do not check argument here, we will provide user a type ch this.dispatcher.dom[key](...args); } if (isVideoEvent(key) || isDomEvent(key)) { return true; } return this[sync ? 'triggerSync' : 'trigger'](key, ...args); } /** * get event handlers queue to run * @private * @param {Object} handlerSet the object include all handler * @param {Array} Array form of plugin id * @return {Array<Function>} event handler in queue to run */ private getEventQueue(handlerSet: { [pluginId: string]: Array<(...args: any[]) => any> }, customOrder: string[] | false = false): Array<(...args: any[]) => any> { // if user destroy the chimee in the event callback // the rest event callback may run into here // and throw an error if (this.dispatcher.destroyed) { return []; } // TODO: it may no to need to concat everytime const order = (customOrder || this.dispatcher.order).concat([ '_vm' ]); return isEmpty(handlerSet) ? [] : order.reduce((queue: Array<(...args: any[]) => any>, id: string) => { if (isEmpty(handlerSet[id]) || !isArray(handlerSet[id]) || // in case plugins is missed // _vm indicate the user. This is the function for user (!this.dispatcher.plugins[id] && id !== '_vm')) { return queue; } return queue.concat(handlerSet[id].map((fn) => { // bind context for plugin instance return bind(fn, this.dispatcher.plugins[id] || this.dispatcher.vm); })); }, []); } private getFirstHandlerFromOnceMap({ eventName, stage, pluginId, fn, }: { eventName: string, fn: (...args: any[]) => any, pluginId: string, stage: EventStage, }): (...args: any[]) => any | void { const key = getKeyForOnceMap(eventName, stage, pluginId); const map = this.onceMap[key]; if (isNil(map) || !map.has(fn)) { return; } const handlers = map.get(fn); return handlers[0]; } /** * remove event from bus * @private * @param {Array} keys keys map pointing to position to get event handler * @param {function} fn handler to put */ private removeEvent({ eventName, stage, pluginId, fn, }: { eventName: string, fn: (...args: any[]) => any, pluginId: string, stage: EventStage, }): boolean { const eventsForEventName = this.events[eventName]; if (!eventsForEventName) { return; } const eventsForStage = eventsForEventName[stage]; if (!eventsForStage) { return; } const eventsForPlugin = eventsForStage[pluginId]; if (!eventsForPlugin) { return; } const index = eventsForPlugin.indexOf(fn); const hasFn = index > -1; if (hasFn) { eventsForPlugin.splice(index, 1); } // if this plugin has no event binding, we remove this event session, which make us perform faster in emit & trigger period. deletePropertyIfItIsEmpty(eventsForStage, pluginId); deletePropertyIfItIsEmpty(eventsForEventName, stage); deletePropertyIfItIsEmpty(this.events, eventName); return hasFn; } private removeFromOnceMap({ eventName, stage, pluginId, fn, handler, }: { eventName: string, fn: (...args: any[]) => any, handler: (...args: any[]) => any, pluginId: string, stage: EventStage, }): void { const key = getKeyForOnceMap(eventName, stage, pluginId); const map = this.onceMap[key]; if (isNil(map) || !map.has(fn)) { return; } const handlers = map.get(fn); const index = handlers.indexOf(handler); handlers.splice(index, 1); if (isEmpty(handlers)) { map.delete(fn); } } /** * run side effect period * @param {string} key event's name * @param {args} args */ private runSideEffectEvent(key: string, ...args: any): boolean { const event = this.events[key]; if (isEmpty(event)) { return false; } const queue = this.getEventQueue(event._); queue.forEach((run) => run(...args)); return true; } }
the_stack
import { Component, OnInit, Input, ViewEncapsulation, OnDestroy, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; import { AssetGroupObservableService } from '../../../core/services/asset-group-observable.service'; import { ActivatedRoute, Router} from '@angular/router'; import { DataCacheService } from '../../../core/services/data-cache.service'; import { AutorefreshService } from '../../services/autorefresh.service'; import { AllPatchingProgressService } from '../../services/patching-progress.service'; import { environment } from './../../../../environments/environment'; import { Subscription } from 'rxjs/Subscription'; import { LoggerService } from '../../../shared/services/logger.service'; import { ErrorHandlingService } from '../../../shared/services/error-handling.service'; import { CommonResponseService } from '../../../shared/services/common-response.service'; @Component({ selector: 'app-patching-trend', templateUrl: './patching-trend.component.html', styleUrls: ['./patching-trend.component.css'], providers: [AllPatchingProgressService, AutorefreshService, CommonResponseService], encapsulation: ViewEncapsulation.None, // tslint:disable-next-line:use-host-property-decorator host: { '(window:resize)': 'onResize($event)' } }) export class PatchingTrendComponent implements OnInit, OnDestroy, AfterViewInit { @ViewChild('patchProgressContainer') widgetContainer: ElementRef; selectedAssetGroup: string; durationParams: any; autoRefresh: boolean; /* Subscription variables*/ private assetGroupSubscription: Subscription; private getPatchingSubscriptionQuarter: Subscription; private getPatchingQuarterData: Subscription; /* Variables for handling data and for calculations*/ checkBtn: any; private nonComplianceQuarter: any = {}; private ComplianceQuarter: any = {}; private compliantDataQuarter: any = {}; private dataStorage: any = []; private dataWholeSetQuarter1: any = {}; weekValue: any = []; weekNumber: any = []; quarterData: any = []; weekValueQuarter1: any = []; weekNumberQuarter1: any = []; dayQuarter: any; private monthQuarter: any; private amiavail_dateQuarter: any; private end_dateQuarter: any; private internal_targetQuarter: any; private quarterGraph1: any = []; showQuarter: any; private start: any; private end: any; private dataWholeSet: any; private selectedData: any; private showToday: any; year: any; private startDate: any; private endDate: any; yearArray: any = []; private quarterArray: any = []; quarterDataArray: any = []; private selected: any; /* Input variables for the graph*/ graphHeight: any; todayValue: boolean; graphWidth: any; graphData: any; graphDataQuarter1: any = []; amiavail_date: any; end_date: any; internal_target: any; lastDate: any; /* Boolean variables for setting the data*/ dataLoaded = false; error = false; loading = false; errorMessage: any = 'apiResponseError'; yAxisLabel = 'Instances'; showGraphLegend = true; showOpposite = false; tempLoader = false; currentQuarterViewed = false; private autorefreshInterval; @Input() hiddenComponent: string; constructor(private activatedRoute: ActivatedRoute, private assetGroupObservableService: AssetGroupObservableService, private dataStore: DataCacheService, private router: Router, private allPatchingProgressService: AllPatchingProgressService, private autorefreshService: AutorefreshService, private commonResponseService: CommonResponseService, private logger: LoggerService, private errorHandling: ErrorHandlingService) { /* On change of asset group, calls the init function to update the data*/ this.assetGroupSubscription = this.assetGroupObservableService.getAssetGroup().subscribe( assetGroupName => { this.selectedAssetGroup = assetGroupName; this.init(); this.durationParams = this.autorefreshService.getDuration(); this.durationParams = parseInt(this.durationParams, 10); this.autoRefresh = this.autorefreshService.autoRefresh; }); this.durationParams = this.autorefreshService.getDuration(); this.durationParams = parseInt(this.durationParams, 10); this.autoRefresh = this.autorefreshService.autoRefresh; } onResize() { const element = document.getElementById('current'); if (element) { this.graphWidth = parseInt((window.getComputedStyle(element, null).getPropertyValue('width')).split('px')[0], 10); } } /* Function to show/hide the dropdown container */ showOtherDiv() { this.showOpposite = !this.showOpposite; } /* Function to show current quarter data */ showCurrentQuarter() { const yearClass = document.getElementsByClassName('patching-each-year')[this.selected]; if (yearClass !== undefined) { yearClass.classList.remove('selected'); } this.currentQuarterViewed = true; this.setDataLoading(); this.tempLoader = true; let patchingData = this.dataStore.get('patchingAvailableQuarters-' + this.selectedAssetGroup); patchingData = patchingData ? JSON.parse(patchingData) : undefined; this.getIssues(patchingData); } /* Function to choose individual quarter and update graph according to that quarter */ showQuarterDiv(index, year) { this.showOpposite = !this.showOpposite; this.setDataLoading(); if (index === 1) { this.checkBtn = 1; } else if (index === 2) { this.checkBtn = 2; } else if (index === 3) { this.checkBtn = 3; } else { this.checkBtn = 4; } let patchingData = this.dataStore.get('patchingAvailableQuarters-' + this.selectedAssetGroup); patchingData = patchingData ? JSON.parse(patchingData) : undefined; this.getIssues(patchingData, year, index); } clearVariables(data) { this.graphData = undefined; this.weekNumber = undefined; this.weekValue = undefined; this.amiavail_date = undefined; this.end_date = undefined; this.internal_target = undefined; this.lastDate = undefined; this.year = undefined; this.showQuarter = undefined; } setGraphVariables(data) { this.graphData = data.data; this.weekNumber = data.weekNum; this.weekValue = data.weekVal; this.amiavail_date = data.ami; this.end_date = data.end; this.internal_target = data.int; this.lastDate = data.lastDate; this.year = data.year; this.showQuarter = data.key; this.setDataLoaded(); } isActive(item) { if (this.currentQuarterViewed === false ) { return this.selected === item; } } getMetaData(year?: any, index?: any) { try { this.currentQuarterViewed = false; if (index !== undefined) { this.selected = index; } this.tempLoader = true; this.yearArray = []; let yearlyQuarterData = this.dataStore.get('patchingAvailableQuarters-' + this.selectedAssetGroup); yearlyQuarterData = yearlyQuarterData ? JSON.parse(yearlyQuarterData) : undefined; if ((!yearlyQuarterData) || (yearlyQuarterData.length === 0)) { const patchingQuarterUrl = environment.patchingQuarter.url; const patchingQuarterMethod = environment.patchingQuarter.method; const payload = {}; const queryParams = { 'assetGroup': this.selectedAssetGroup }; this.getPatchingQuarterData = this.allPatchingProgressService.getQuarterData(payload, patchingQuarterUrl, patchingQuarterMethod, queryParams).subscribe( response => { try { if (response.length) { response.forEach(yearData => { this.yearArray.push(yearData.year); }); this.yearArray = Array.from(new Set(this.yearArray)); this.dataStore.set('patchingAvailableQuarters-' + this.selectedAssetGroup, JSON.stringify(response)); this.getIssues(response); } else { this.setError('noDataAvailable'); } } catch (error) { this.setError('jsError'); } }, error => { this.setError('apiResponseError'); } ); } else { yearlyQuarterData.forEach(yearData => { this.yearArray.push(yearData.year); }); this.yearArray = Array.from(new Set(this.yearArray)); if (yearlyQuarterData !== undefined) { if (year === new Date().getFullYear()) { this.getIssues(yearlyQuarterData, year, index); } else { this.getIssues(yearlyQuarterData, year); } } } } catch (error) { this.setError('jsError'); } } getIssues(data, year?: any, index?: any) { try { let patchingData = this.dataStore.get('patching_' + year); patchingData = patchingData ? JSON.parse(patchingData) : undefined; const patchingQuarterUrl = environment.patchingProgress.url; const patchingQuarterMethod = environment.patchingProgress.method; const payload = {}; this.getPatchingSubscriptionQuarter = this.allPatchingProgressService.getData(data, patchingQuarterUrl, patchingQuarterMethod, this.selectedAssetGroup, year).subscribe( response => { this.quarterDataArray = []; this.quarterDataArray = response; this.dataStore.set('patching_' + response[0].year, JSON.stringify(response)); if ((response[0].year === new Date().getFullYear()) && (index === undefined)) { this.checkBtn = response.length; } else if (index !== undefined) { this.checkBtn = index; } else { this.checkBtn = undefined; } if ((year === undefined) || ((index !== undefined) && (year !== new Date().getFullYear())) || ((index !== 0) && (year === new Date().getFullYear())) ) { this.setDataLoading(); this.clearVariables(response[this.checkBtn - 1]); this.setGraphVariables(response[this.checkBtn - 1]); } this.tempLoader = false; }, error => { this.setError(error); } ); } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.setError(error); } } getData() { this.getMetaData(); } init() { this.setDataLoading(); this.getData(); } setDataLoaded() { this.dataLoaded = true; this.loading = false; } setDataLoading() { this.dataLoaded = false; this.error = false; this.loading = true; } setError(message?: any) { this.dataLoaded = false; this.error = true; this.loading = false; if (message) { this.errorMessage = message; } } ngAfterViewInit() { const afterLoad = this; if (this.autoRefresh !== undefined ) { if ((this.autoRefresh === true ) || (this.autoRefresh.toString() === 'true')) { this.autorefreshInterval = setInterval(function() { afterLoad.init(); }, this.durationParams); } } } ngOnInit() { this.graphWidth = parseInt(window.getComputedStyle(this.widgetContainer.nativeElement, null).getPropertyValue('width'), 10); this.graphHeight = parseInt(window.getComputedStyle(this.widgetContainer.nativeElement, null).getPropertyValue('height'), 10); } ngOnDestroy() { try { this.assetGroupSubscription.unsubscribe(); clearInterval(this.autorefreshInterval); } catch (error) { } } }
the_stack
import { common } from '~front/barrels/common'; import { constants } from '~front/barrels/constants'; export function prepareReport(mconfig: common.Mconfig) { let chart = mconfig.chart; let defaultFilters: any; if (common.isDefined(mconfig.filters) && mconfig.filters.length > 0) { defaultFilters = {}; mconfig.filters.forEach(x => { let bricks: string[] = []; x.fractions.forEach(z => bricks.push(z.brick)); defaultFilters[x.fieldId] = bricks; }); } let rep = { title: chart.title, description: common.isDefined(chart.description) ? chart.description : undefined, model: mconfig.modelId, select: mconfig.select, sorts: common.isDefined(mconfig.sorts) ? mconfig.sorts : undefined, timezone: common.isDefined(mconfig.timezone) && mconfig.timezone !== common.UTC ? mconfig.timezone : undefined, limit: common.isDefined(mconfig.limit) && mconfig.limit !== Number(common.DEFAULT_LIMIT) ? mconfig.limit : undefined, default_filters: defaultFilters, type: chart.type, data: { x_field: constants.xFieldChartTypes.indexOf(chart.type) > -1 && common.isDefined(chart.xField) ? chart.xField : undefined, y_field: constants.yFieldChartTypes.indexOf(chart.type) > -1 && common.isDefined(chart.yField) ? chart.yField : undefined, y_fields: constants.yFieldsChartTypes.indexOf(chart.type) > -1 && common.isDefined(chart.yFields) && chart.yFields.length > 0 ? chart.yFields : undefined, hide_columns: constants.hideColumnsChartTypes.indexOf(chart.type) > -1 && common.isDefined(chart.hideColumns) && chart.hideColumns.length > 0 ? chart.hideColumns : undefined, multi_field: constants.multiFieldChartTypes.indexOf(chart.type) > -1 && common.isDefined(chart.multiField) ? chart.multiField : undefined, value_field: constants.valueFieldChartTypes.indexOf(chart.type) > -1 && common.isDefined(chart.valueField) ? chart.valueField : undefined, previous_value_field: constants.previousValueFieldChartTypes.indexOf(chart.type) > -1 && common.isDefined(chart.previousValueField) ? chart.previousValueField : undefined }, axis: { x_axis_label: constants.xAxisLabelChartTypes.indexOf(chart.type) > -1 && chart.xAxisLabel !== common.CHART_DEFAULT_X_AXIS_LABEL && common.isDefined(chart.xAxisLabel) ? chart.xAxisLabel : undefined, y_axis_label: constants.yAxisLabelChartTypes.indexOf(chart.type) > -1 && chart.yAxisLabel !== common.CHART_DEFAULT_Y_AXIS_LABEL && common.isDefined(chart.yAxisLabel) ? chart.yAxisLabel : undefined, show_x_axis_label: constants.showXAxisLabelChartTypes.indexOf(chart.type) > -1 && chart.showXAxisLabel !== common.CHART_DEFAULT_SHOW_X_AXIS_LABEL && common.isDefined(chart.showXAxisLabel) ? chart.showXAxisLabel : undefined, show_y_axis_label: constants.showYAxisLabelChartTypes.indexOf(chart.type) > -1 && chart.showYAxisLabel !== common.CHART_DEFAULT_SHOW_Y_AXIS_LABEL && common.isDefined(chart.showYAxisLabel) ? chart.showYAxisLabel : undefined, x_axis: constants.xAxisChartTypes.indexOf(chart.type) > -1 && chart.xAxis !== common.CHART_DEFAULT_X_AXIS && common.isDefined(chart.xAxis) ? chart.xAxis : undefined, y_axis: constants.yAxisChartTypes.indexOf(chart.type) > -1 && chart.yAxis !== common.CHART_DEFAULT_Y_AXIS && common.isDefined(chart.yAxis) ? chart.yAxis : undefined, show_axis: constants.showAxisChartTypes.indexOf(chart.type) > -1 && chart.showAxis !== common.CHART_DEFAULT_SHOW_AXIS && common.isDefined(chart.showAxis) ? chart.showAxis : undefined }, options: { color_scheme: constants.colorSchemeChartTypes.indexOf(chart.type) > -1 && chart.colorScheme !== common.CHART_DEFAULT_COLOR_SCHEME && common.isDefined(chart.colorScheme) ? chart.colorScheme : undefined, scheme_type: constants.schemeTypeChartTypes.indexOf(chart.type) > -1 && chart.schemeType !== common.CHART_DEFAULT_SCHEME_TYPE && common.isDefined(chart.schemeType) ? chart.schemeType : undefined, interpolation: constants.interpolationChartTypes.indexOf(chart.type) > -1 && chart.interpolation !== common.CHART_DEFAULT_INTERPOLATION && common.isDefined(chart.interpolation) ? chart.interpolation : undefined, card_color: constants.cardColorChartTypes.indexOf(chart.type) > -1 && chart.cardColor !== common.CHART_DEFAULT_CARD_COLOR && common.isDefined(chart.cardColor) ? chart.cardColor : undefined, empty_color: constants.emptyColorChartTypes.indexOf(chart.type) > -1 && chart.emptyColor !== common.CHART_DEFAULT_EMPTY_COLOR && common.isDefined(chart.emptyColor) ? chart.emptyColor : undefined, band_color: constants.bandColorChartTypes.indexOf(chart.type) > -1 && chart.bandColor !== common.CHART_DEFAULT_BAND_COLOR && common.isDefined(chart.bandColor) ? chart.bandColor : undefined, text_color: constants.textColorChartTypes.indexOf(chart.type) > -1 && chart.textColor !== common.CHART_DEFAULT_TEXT_COLOR && common.isDefined(chart.textColor) ? chart.textColor : undefined, units: constants.unitsChartTypes.indexOf(chart.type) > -1 && chart.units !== common.CHART_DEFAULT_UNITS && common.isDefined(chart.units) ? chart.units : undefined, legend_title: constants.legendTitleChartTypes.indexOf(chart.type) > -1 && chart.legendTitle !== common.CHART_DEFAULT_LEGEND_TITLE && common.isDefined(chart.legendTitle) ? chart.legendTitle : undefined, legend: constants.legendChartTypes.indexOf(chart.type) > -1 && chart.legend !== common.CHART_DEFAULT_LEGEND && common.isDefined(chart.legend) ? chart.legend : undefined, labels: constants.labelsChartTypes.indexOf(chart.type) > -1 && chart.labels !== common.CHART_DEFAULT_LABELS && common.isDefined(chart.labels) ? chart.labels : undefined, show_data_label: constants.showDataLabelChartTypes.indexOf(chart.type) > -1 && chart.showDataLabel !== common.CHART_DEFAULT_SHOW_DATA_LABEL && common.isDefined(chart.showDataLabel) ? chart.showDataLabel : undefined, format: constants.formatChartTypes.indexOf(chart.type) > -1 && chart.format !== common.CHART_DEFAULT_FORMAT && common.isDefined(chart.format) ? chart.format : undefined, tooltip_disabled: constants.tooltipDisabledChartTypes.indexOf(chart.type) > -1 && chart.tooltipDisabled !== common.CHART_DEFAULT_TOOLTIP_DISABLED && common.isDefined(chart.tooltipDisabled) ? chart.tooltipDisabled : undefined, round_edges: constants.roundEdgesChartTypes.indexOf(chart.type) > -1 && chart.roundEdges !== common.CHART_DEFAULT_ROUND_EDGES && common.isDefined(chart.roundEdges) ? chart.roundEdges : undefined, round_domains: constants.roundDomainsChartTypes.indexOf(chart.type) > -1 && chart.roundDomains !== common.CHART_DEFAULT_ROUND_DOMAINS && common.isDefined(chart.roundDomains) ? chart.roundDomains : undefined, show_grid_lines: constants.showGridLinesChartTypes.indexOf(chart.type) > -1 && chart.showGridLines !== common.CHART_DEFAULT_SHOW_GRID_LINES && common.isDefined(chart.showGridLines) ? chart.showGridLines : undefined, auto_scale: constants.autoScaleChartTypes.indexOf(chart.type) > -1 && chart.autoScale !== common.CHART_DEFAULT_AUTO_SCALE && common.isDefined(chart.autoScale) ? chart.autoScale : undefined, doughnut: constants.doughnutChartTypes.indexOf(chart.type) > -1 && chart.doughnut !== common.CHART_DEFAULT_DOUGHNUT && common.isDefined(chart.doughnut) ? chart.doughnut : undefined, explode_slices: constants.explodeSlicesChartTypes.indexOf(chart.type) > -1 && chart.explodeSlices !== common.CHART_DEFAULT_EXPLODE_SLICES && common.isDefined(chart.explodeSlices) ? chart.explodeSlices : undefined, gradient: constants.gradientChartTypes.indexOf(chart.type) > -1 && chart.gradient !== common.CHART_DEFAULT_GRADIENT && common.isDefined(chart.gradient) ? chart.gradient : undefined, animations: constants.animationsChartTypes.indexOf(chart.type) > -1 && chart.animations !== common.CHART_DEFAULT_ANIMATIONS && common.isDefined(chart.animations) ? chart.animations : undefined, page_size: constants.pageSizeChartTypes.indexOf(chart.type) > -1 && chart.pageSize !== common.CHART_DEFAULT_PAGE_SIZE && common.isDefined(chart.pageSize) ? chart.pageSize : undefined, arc_width: constants.arcWidthChartTypes.indexOf(chart.type) > -1 && chart.arcWidth !== common.CHART_DEFAULT_ARC_WIDTH && common.isDefined(chart.arcWidth) ? chart.arcWidth : undefined, bar_padding: constants.barPaddingChartTypes.indexOf(chart.type) > -1 && chart.barPadding !== common.CHART_DEFAULT_BAR_PADDING && common.isDefined(chart.barPadding) ? chart.barPadding : undefined, group_padding: constants.groupPaddingChartTypes.indexOf(chart.type) > -1 && chart.groupPadding !== common.CHART_DEFAULT_GROUP_PADDING && common.isDefined(chart.groupPadding) ? chart.groupPadding : undefined, inner_padding: constants.innerPaddingChartTypes.indexOf(chart.type) > -1 && chart.innerPadding !== common.CHART_DEFAULT_INNER_PADDING && common.isDefined(chart.innerPadding) ? chart.innerPadding : undefined, angle_span: constants.angleSpanChartTypes.indexOf(chart.type) > -1 && chart.angleSpan !== common.CHART_DEFAULT_ANGLE_SPAN && common.isDefined(chart.angleSpan) ? chart.angleSpan : undefined, start_angle: constants.startAngleChartTypes.indexOf(chart.type) > -1 && chart.startAngle !== common.CHART_DEFAULT_START_ANGLE && common.isDefined(chart.startAngle) ? chart.startAngle : undefined, big_segments: constants.bigSegmentsChartTypes.indexOf(chart.type) > -1 && chart.bigSegments !== common.CHART_DEFAULT_BIG_SEGMENTS && common.isDefined(chart.bigSegments) ? chart.bigSegments : undefined, small_segments: constants.smallSegmentsChartTypes.indexOf(chart.type) > -1 && chart.smallSegments !== common.CHART_DEFAULT_SMALL_SEGMENTS && common.isDefined(chart.smallSegments) ? chart.smallSegments : undefined, min: constants.minChartTypes.indexOf(chart.type) > -1 && chart.min !== common.CHART_DEFAULT_MIN && common.isDefined(chart.min) ? chart.min : undefined, max: constants.maxChartTypes.indexOf(chart.type) > -1 && chart.max !== common.CHART_DEFAULT_MAX && common.isDefined(chart.max) ? chart.max : undefined, y_scale_min: constants.yScaleMinChartTypes.indexOf(chart.type) > -1 && chart.yScaleMin !== common.CHART_DEFAULT_Y_SCALE_MIN && common.isDefined(chart.yScaleMin) ? chart.yScaleMin : undefined, y_scale_max: constants.yScaleMaxChartTypes.indexOf(chart.type) > -1 && chart.yScaleMax !== common.CHART_DEFAULT_Y_SCALE_MAX && common.isDefined(chart.yScaleMax) ? chart.yScaleMax : undefined, x_scale_max: constants.xScaleMaxChartTypes.indexOf(chart.type) > -1 && chart.xScaleMax !== common.CHART_DEFAULT_X_SCALE_MAX && common.isDefined(chart.xScaleMax) ? chart.xScaleMax : undefined, format_number_data_label: constants.formatNumberDataLabelChartTypes.indexOf(chart.type) > -1 && common.isDefined(chart.formatNumberDataLabel) ? chart.formatNumberDataLabel : undefined, format_number_value: constants.formatNumberValueChartTypes.indexOf(chart.type) > -1 && common.isDefined(chart.formatNumberValue) ? chart.formatNumberValue : undefined, format_number_axis_tick: constants.formatNumberAxisTickChartTypes.indexOf(chart.type) > -1 && common.isDefined(chart.formatNumberAxisTick) ? chart.formatNumberAxisTick : undefined, format_number_y_axis_tick: constants.formatNumberYAxisTickChartTypes.indexOf(chart.type) > -1 && common.isDefined(chart.formatNumberYAxisTick) ? chart.formatNumberYAxisTick : undefined, format_number_x_axis_tick: constants.formatNumberXAxisTickChartTypes.indexOf(chart.type) > -1 && common.isDefined(chart.formatNumberXAxisTick) ? chart.formatNumberXAxisTick : undefined // timeline: // constants.timelineChartTypes.indexOf(chart.type) > -1 && // chart.timeline !== common.CHART_DEFAULT_TIMELINE && // common.isDefined() // ? chart.timeline // : undefined, // range_fill_opacity: // constants.rangeFillOpacityChartTypes.indexOf(chart.type) > -1 && // chart.rangeFillOpacity !== common.CHART_DEFAULT_RANGE_FILL_OPACITY && // common.isDefined() // ? chart.rangeFillOpacity // : undefined, }, tile: { tile_width: chart.tileWidth !== common.CHART_DEFAULT_TILE_WIDTH && common.isDefined(chart.tileWidth) ? chart.tileWidth : undefined, tile_height: chart.tileHeight !== common.CHART_DEFAULT_TILE_HEIGHT && common.isDefined(chart.tileHeight) ? chart.tileHeight : undefined, view_size: chart.viewSize !== common.CHART_DEFAULT_VIEW_SIZE && common.isDefined(chart.viewSize) ? chart.viewSize : undefined, view_width: chart.viewWidth !== common.CHART_DEFAULT_VIEW_WIDTH && common.isDefined(chart.viewWidth) ? chart.viewWidth : undefined, view_height: chart.viewHeight !== common.CHART_DEFAULT_VIEW_HEIGHT && common.isDefined(chart.viewHeight) ? chart.viewHeight : undefined } }; let keepData = false; Object.keys(rep.data).forEach((x: any) => { if (common.isDefined((<any>rep.data)[x])) { keepData = true; } }); if (keepData === false) { delete rep.data; } let keepAxis = false; Object.keys(rep.axis).forEach((x: any) => { if (common.isDefined((<any>rep.axis)[x])) { keepAxis = true; } }); if (keepAxis === false) { delete rep.axis; } let keepOptions = false; Object.keys(rep.options).forEach((x: any) => { if (common.isDefined((<any>rep.options)[x])) { keepOptions = true; } }); if (keepOptions === false) { delete rep.options; } let keepTile = false; Object.keys(rep.tile).forEach((x: any) => { if (common.isDefined((<any>rep.tile)[x])) { keepTile = true; } }); if (keepTile === false) { delete rep.tile; } return rep; }
the_stack
import * as coreClient from "@azure/core-client"; /** Result of the request to list NotificationHubs operations. It contains a list of operations and a URL link to get the next set of results. */ export interface OperationListResult { /** * List of NotificationHubs operations supported by the Microsoft.NotificationHubs resource provider. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: Operation[]; /** * URL to get the next set of operation list results if there are any. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** A NotificationHubs REST API operation */ export interface Operation { /** * Operation name: {provider}/{resource}/{operation} * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** The object that represents the operation. */ display?: OperationDisplay; } /** The object that represents the operation. */ export interface OperationDisplay { /** * Service provider: Microsoft.NotificationHubs * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provider?: string; /** * Resource on which the operation is performed: Invoice, etc. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resource?: string; /** * Operation type: Read, write, delete, etc. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly operation?: string; } /** Error response indicates NotificationHubs service is not able to process the incoming request. The reason is provided in the error message. */ export interface ErrorResponse { /** Error code. */ code?: string; /** Error message indicating why the operation failed. */ message?: string; } /** Parameters supplied to the Check Name Availability for Namespace and NotificationHubs. */ export interface CheckAvailabilityParameters { /** * Resource Id * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** Resource name */ name: string; /** * Resource type * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** Resource location */ location?: string; /** Resource tags */ tags?: { [propertyName: string]: string }; /** The sku of the created namespace */ sku?: Sku; /** True if the name is available and can be used to create new Namespace/NotificationHub. Otherwise false. */ isAvailiable?: boolean; } /** The Sku description for a namespace */ export interface Sku { /** Name of the notification hub sku */ name: SkuName; /** The tier of particular sku */ tier?: string; /** The Sku size */ size?: string; /** The Sku Family */ family?: string; /** The capacity of the resource */ capacity?: number; } export interface Resource { /** * Resource Id * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * Resource name * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * Resource type * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** Resource location */ location?: string; /** Resource tags */ tags?: { [propertyName: string]: string }; /** The sku of the created namespace */ sku?: Sku; } /** Parameters supplied to the Patch Namespace operation. */ export interface NamespacePatchParameters { /** Resource tags */ tags?: { [propertyName: string]: string }; /** The sku of the created namespace */ sku?: Sku; } /** Parameters supplied to the CreateOrUpdate Namespace AuthorizationRules. */ export interface SharedAccessAuthorizationRuleCreateOrUpdateParameters { /** Properties of the Namespace AuthorizationRules. */ properties: SharedAccessAuthorizationRuleProperties; } /** SharedAccessAuthorizationRule properties. */ export interface SharedAccessAuthorizationRuleProperties { /** The rights associated with the rule. */ rights?: AccessRights[]; /** * A base64-encoded 256-bit primary key for signing and validating the SAS token. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly primaryKey?: string; /** * A base64-encoded 256-bit primary key for signing and validating the SAS token. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly secondaryKey?: string; /** * A string that describes the authorization rule. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly keyName?: string; /** * A string that describes the claim type * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly claimType?: string; /** * A string that describes the claim value * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly claimValue?: string; /** * The last modified time for this rule * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly modifiedTime?: string; /** * The created time for this rule * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdTime?: string; /** * The revision number for the rule * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly revision?: number; } /** The response of the List Namespace operation. */ export interface NamespaceListResult { /** Result of the List Namespace operation. */ value?: NamespaceResource[]; /** Link to the next set of results. Not empty if Value contains incomplete list of Namespaces */ nextLink?: string; } /** The response of the List Namespace operation. */ export interface SharedAccessAuthorizationRuleListResult { /** Result of the List AuthorizationRules operation. */ value?: SharedAccessAuthorizationRuleResource[]; /** Link to the next set of results. Not empty if Value contains incomplete list of AuthorizationRules */ nextLink?: string; } /** Namespace/NotificationHub Connection String */ export interface ResourceListKeys { /** PrimaryConnectionString of the AuthorizationRule. */ primaryConnectionString?: string; /** SecondaryConnectionString of the created AuthorizationRule */ secondaryConnectionString?: string; /** PrimaryKey of the created AuthorizationRule. */ primaryKey?: string; /** SecondaryKey of the created AuthorizationRule */ secondaryKey?: string; /** KeyName of the created AuthorizationRule */ keyName?: string; } /** Namespace/NotificationHub Regenerate Keys */ export interface PolicykeyResource { /** Name of the key that has to be regenerated for the Namespace/Notification Hub Authorization Rule. The value can be Primary Key/Secondary Key. */ policyKey?: string; } /** Description of a NotificationHub ApnsCredential. */ export interface ApnsCredential { /** The APNS certificate. Specify if using Certificate Authentication Mode. */ apnsCertificate?: string; /** The APNS certificate password if it exists. */ certificateKey?: string; /** The APNS endpoint of this credential. If using Certificate Authentication Mode and Sandbox specify 'gateway.sandbox.push.apple.com'. If using Certificate Authentication Mode and Production specify 'gateway.push.apple.com'. If using Token Authentication Mode and Sandbox specify 'https://api.development.push.apple.com:443/3/device'. If using Token Authentication Mode and Production specify 'https://api.push.apple.com:443/3/device'. */ endpoint?: string; /** The APNS certificate thumbprint. Specify if using Certificate Authentication Mode. */ thumbprint?: string; /** A 10-character key identifier (kid) key, obtained from your developer account. Specify if using Token Authentication Mode. */ keyId?: string; /** The name of the application or BundleId. Specify if using Token Authentication Mode. */ appName?: string; /** The issuer (iss) registered claim key. The value is a 10-character TeamId, obtained from your developer account. Specify if using Token Authentication Mode. */ appId?: string; /** Provider Authentication Token, obtained through your developer account. Specify if using Token Authentication Mode. */ token?: string; } /** Description of a NotificationHub WnsCredential. */ export interface WnsCredential { /** The package ID for this credential. */ packageSid?: string; /** The secret key. */ secretKey?: string; /** The Windows Live endpoint. */ windowsLiveEndpoint?: string; } /** Description of a NotificationHub GcmCredential. */ export interface GcmCredential { /** The FCM legacy endpoint. Default value is 'https://fcm.googleapis.com/fcm/send' */ gcmEndpoint?: string; /** The Google API key. */ googleApiKey?: string; } /** Description of a NotificationHub MpnsCredential. */ export interface MpnsCredential { /** The MPNS certificate. */ mpnsCertificate?: string; /** The certificate key for this credential. */ certificateKey?: string; /** The MPNS certificate Thumbprint */ thumbprint?: string; } /** Description of a NotificationHub AdmCredential. */ export interface AdmCredential { /** The client identifier. */ clientId?: string; /** The credential secret access key. */ clientSecret?: string; /** The URL of the authorization token. */ authTokenUrl?: string; } /** Description of a NotificationHub BaiduCredential. */ export interface BaiduCredential { /** Baidu Api Key. */ baiduApiKey?: string; /** Baidu Endpoint. */ baiduEndPoint?: string; /** Baidu Secret Key */ baiduSecretKey?: string; } /** The response of the List NotificationHub operation. */ export interface NotificationHubListResult { /** Result of the List NotificationHub operation. */ value?: NotificationHubResource[]; /** Link to the next set of results. Not empty if Value contains incomplete list of NotificationHub */ nextLink?: string; } export interface SubResource { /** Resource Id */ id?: string; } /** Description of a CheckAvailability resource. */ export type CheckAvailabilityResult = Resource & { /** True if the name is available and can be used to create new Namespace/NotificationHub. Otherwise false. */ isAvailiable?: boolean; }; /** Parameters supplied to the CreateOrUpdate Namespace operation. */ export type NamespaceCreateOrUpdateParameters = Resource & { /** The name of the namespace. */ namePropertiesName?: string; /** Provisioning state of the Namespace. */ provisioningState?: string; /** Specifies the targeted region in which the namespace should be created. It can be any of the following values: Australia East, Australia Southeast, Central US, East US, East US 2, West US, North Central US, South Central US, East Asia, Southeast Asia, Brazil South, Japan East, Japan West, North Europe, West Europe */ region?: string; /** * Identifier for Azure Insights metrics * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly metricId?: string; /** Status of the namespace. It can be any of these values:1 = Created/Active2 = Creating3 = Suspended4 = Deleting */ status?: string; /** The time the namespace was created. */ createdAt?: Date; /** The time the namespace was updated. */ updatedAt?: Date; /** Endpoint you can use to perform NotificationHub operations. */ serviceBusEndpoint?: string; /** The Id of the Azure subscription associated with the namespace. */ subscriptionId?: string; /** ScaleUnit where the namespace gets created */ scaleUnit?: string; /** Whether or not the namespace is currently enabled. */ enabled?: boolean; /** Whether or not the namespace is set as Critical. */ critical?: boolean; /** Data center for the namespace */ dataCenter?: string; /** The namespace type. */ namespaceType?: NamespaceType; }; /** Description of a Namespace resource. */ export type NamespaceResource = Resource & { /** The name of the namespace. */ namePropertiesName?: string; /** Provisioning state of the Namespace. */ provisioningState?: string; /** Specifies the targeted region in which the namespace should be created. It can be any of the following values: Australia East, Australia Southeast, Central US, East US, East US 2, West US, North Central US, South Central US, East Asia, Southeast Asia, Brazil South, Japan East, Japan West, North Europe, West Europe */ region?: string; /** * Identifier for Azure Insights metrics * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly metricId?: string; /** Status of the namespace. It can be any of these values:1 = Created/Active2 = Creating3 = Suspended4 = Deleting */ status?: string; /** The time the namespace was created. */ createdAt?: Date; /** The time the namespace was updated. */ updatedAt?: Date; /** Endpoint you can use to perform NotificationHub operations. */ serviceBusEndpoint?: string; /** The Id of the Azure subscription associated with the namespace. */ subscriptionId?: string; /** ScaleUnit where the namespace gets created */ scaleUnit?: string; /** Whether or not the namespace is currently enabled. */ enabled?: boolean; /** Whether or not the namespace is set as Critical. */ critical?: boolean; /** Data center for the namespace */ dataCenter?: string; /** The namespace type. */ namespaceType?: NamespaceType; }; /** Description of a Namespace AuthorizationRules. */ export type SharedAccessAuthorizationRuleResource = Resource & { /** The rights associated with the rule. */ rights?: AccessRights[]; /** * A base64-encoded 256-bit primary key for signing and validating the SAS token. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly primaryKey?: string; /** * A base64-encoded 256-bit primary key for signing and validating the SAS token. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly secondaryKey?: string; /** * A string that describes the authorization rule. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly keyName?: string; /** * A string that describes the claim type * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly claimType?: string; /** * A string that describes the claim value * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly claimValue?: string; /** * The last modified time for this rule * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly modifiedTime?: string; /** * The created time for this rule * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdTime?: string; /** * The revision number for the rule * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly revision?: number; }; /** Parameters supplied to the CreateOrUpdate NotificationHub operation. */ export type NotificationHubCreateOrUpdateParameters = Resource & { /** The NotificationHub name. */ namePropertiesName?: string; /** The RegistrationTtl of the created NotificationHub */ registrationTtl?: string; /** The AuthorizationRules of the created NotificationHub */ authorizationRules?: SharedAccessAuthorizationRuleProperties[]; /** The ApnsCredential of the created NotificationHub */ apnsCredential?: ApnsCredential; /** The WnsCredential of the created NotificationHub */ wnsCredential?: WnsCredential; /** The GcmCredential of the created NotificationHub */ gcmCredential?: GcmCredential; /** The MpnsCredential of the created NotificationHub */ mpnsCredential?: MpnsCredential; /** The AdmCredential of the created NotificationHub */ admCredential?: AdmCredential; /** The BaiduCredential of the created NotificationHub */ baiduCredential?: BaiduCredential; }; /** Description of a NotificationHub Resource. */ export type NotificationHubResource = Resource & { /** The NotificationHub name. */ namePropertiesName?: string; /** The RegistrationTtl of the created NotificationHub */ registrationTtl?: string; /** The AuthorizationRules of the created NotificationHub */ authorizationRules?: SharedAccessAuthorizationRuleProperties[]; /** The ApnsCredential of the created NotificationHub */ apnsCredential?: ApnsCredential; /** The WnsCredential of the created NotificationHub */ wnsCredential?: WnsCredential; /** The GcmCredential of the created NotificationHub */ gcmCredential?: GcmCredential; /** The MpnsCredential of the created NotificationHub */ mpnsCredential?: MpnsCredential; /** The AdmCredential of the created NotificationHub */ admCredential?: AdmCredential; /** The BaiduCredential of the created NotificationHub */ baiduCredential?: BaiduCredential; }; /** Parameters supplied to the patch NotificationHub operation. */ export type NotificationHubPatchParameters = Resource & { /** The NotificationHub name. */ namePropertiesName?: string; /** The RegistrationTtl of the created NotificationHub */ registrationTtl?: string; /** The AuthorizationRules of the created NotificationHub */ authorizationRules?: SharedAccessAuthorizationRuleProperties[]; /** The ApnsCredential of the created NotificationHub */ apnsCredential?: ApnsCredential; /** The WnsCredential of the created NotificationHub */ wnsCredential?: WnsCredential; /** The GcmCredential of the created NotificationHub */ gcmCredential?: GcmCredential; /** The MpnsCredential of the created NotificationHub */ mpnsCredential?: MpnsCredential; /** The AdmCredential of the created NotificationHub */ admCredential?: AdmCredential; /** The BaiduCredential of the created NotificationHub */ baiduCredential?: BaiduCredential; }; /** Description of a NotificationHub Resource. */ export type DebugSendResponse = Resource & { /** successful send */ success?: number; /** send failure */ failure?: number; /** actual failure description */ results?: Record<string, unknown>; }; /** Description of a NotificationHub PNS Credentials. */ export type PnsCredentialsResource = Resource & { /** The ApnsCredential of the created NotificationHub */ apnsCredential?: ApnsCredential; /** The WnsCredential of the created NotificationHub */ wnsCredential?: WnsCredential; /** The GcmCredential of the created NotificationHub */ gcmCredential?: GcmCredential; /** The MpnsCredential of the created NotificationHub */ mpnsCredential?: MpnsCredential; /** The AdmCredential of the created NotificationHub */ admCredential?: AdmCredential; /** The BaiduCredential of the created NotificationHub */ baiduCredential?: BaiduCredential; }; /** Known values of {@link SkuName} that the service accepts. */ export enum KnownSkuName { Free = "Free", Basic = "Basic", Standard = "Standard" } /** * Defines values for SkuName. \ * {@link KnownSkuName} can be used interchangeably with SkuName, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Free** \ * **Basic** \ * **Standard** */ export type SkuName = string; /** Defines values for NamespaceType. */ export type NamespaceType = "Messaging" | "NotificationHub"; /** Defines values for AccessRights. */ export type AccessRights = "Manage" | "Send" | "Listen"; /** Optional parameters. */ export interface OperationsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult; /** Optional parameters. */ export interface OperationsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationListResult; /** Optional parameters. */ export interface NamespacesCheckAvailabilityOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the checkAvailability operation. */ export type NamespacesCheckAvailabilityResponse = CheckAvailabilityResult; /** Optional parameters. */ export interface NamespacesCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type NamespacesCreateOrUpdateResponse = NamespaceResource; /** Optional parameters. */ export interface NamespacesPatchOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the patch operation. */ export type NamespacesPatchResponse = NamespaceResource; /** Optional parameters. */ export interface NamespacesDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface NamespacesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type NamespacesGetResponse = NamespaceResource; /** Optional parameters. */ export interface NamespacesCreateOrUpdateAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdateAuthorizationRule operation. */ export type NamespacesCreateOrUpdateAuthorizationRuleResponse = SharedAccessAuthorizationRuleResource; /** Optional parameters. */ export interface NamespacesDeleteAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface NamespacesGetAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getAuthorizationRule operation. */ export type NamespacesGetAuthorizationRuleResponse = SharedAccessAuthorizationRuleResource; /** Optional parameters. */ export interface NamespacesListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type NamespacesListResponse = NamespaceListResult; /** Optional parameters. */ export interface NamespacesListAllOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAll operation. */ export type NamespacesListAllResponse = NamespaceListResult; /** Optional parameters. */ export interface NamespacesListAuthorizationRulesOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAuthorizationRules operation. */ export type NamespacesListAuthorizationRulesResponse = SharedAccessAuthorizationRuleListResult; /** Optional parameters. */ export interface NamespacesListKeysOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listKeys operation. */ export type NamespacesListKeysResponse = ResourceListKeys; /** Optional parameters. */ export interface NamespacesRegenerateKeysOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the regenerateKeys operation. */ export type NamespacesRegenerateKeysResponse = ResourceListKeys; /** Optional parameters. */ export interface NamespacesListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type NamespacesListNextResponse = NamespaceListResult; /** Optional parameters. */ export interface NamespacesListAllNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAllNext operation. */ export type NamespacesListAllNextResponse = NamespaceListResult; /** Optional parameters. */ export interface NamespacesListAuthorizationRulesNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAuthorizationRulesNext operation. */ export type NamespacesListAuthorizationRulesNextResponse = SharedAccessAuthorizationRuleListResult; /** Optional parameters. */ export interface NotificationHubsCheckNotificationHubAvailabilityOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the checkNotificationHubAvailability operation. */ export type NotificationHubsCheckNotificationHubAvailabilityResponse = CheckAvailabilityResult; /** Optional parameters. */ export interface NotificationHubsCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type NotificationHubsCreateOrUpdateResponse = NotificationHubResource; /** Optional parameters. */ export interface NotificationHubsPatchOptionalParams extends coreClient.OperationOptions { /** Parameters supplied to patch a NotificationHub Resource. */ parameters?: NotificationHubPatchParameters; } /** Contains response data for the patch operation. */ export type NotificationHubsPatchResponse = NotificationHubResource; /** Optional parameters. */ export interface NotificationHubsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface NotificationHubsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type NotificationHubsGetResponse = NotificationHubResource; /** Optional parameters. */ export interface NotificationHubsDebugSendOptionalParams extends coreClient.OperationOptions { /** Debug send parameters */ parameters?: Record<string, unknown>; } /** Contains response data for the debugSend operation. */ export type NotificationHubsDebugSendResponse = DebugSendResponse; /** Optional parameters. */ export interface NotificationHubsCreateOrUpdateAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdateAuthorizationRule operation. */ export type NotificationHubsCreateOrUpdateAuthorizationRuleResponse = SharedAccessAuthorizationRuleResource; /** Optional parameters. */ export interface NotificationHubsDeleteAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface NotificationHubsGetAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getAuthorizationRule operation. */ export type NotificationHubsGetAuthorizationRuleResponse = SharedAccessAuthorizationRuleResource; /** Optional parameters. */ export interface NotificationHubsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type NotificationHubsListResponse = NotificationHubListResult; /** Optional parameters. */ export interface NotificationHubsListAuthorizationRulesOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAuthorizationRules operation. */ export type NotificationHubsListAuthorizationRulesResponse = SharedAccessAuthorizationRuleListResult; /** Optional parameters. */ export interface NotificationHubsListKeysOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listKeys operation. */ export type NotificationHubsListKeysResponse = ResourceListKeys; /** Optional parameters. */ export interface NotificationHubsRegenerateKeysOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the regenerateKeys operation. */ export type NotificationHubsRegenerateKeysResponse = ResourceListKeys; /** Optional parameters. */ export interface NotificationHubsGetPnsCredentialsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getPnsCredentials operation. */ export type NotificationHubsGetPnsCredentialsResponse = PnsCredentialsResource; /** Optional parameters. */ export interface NotificationHubsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type NotificationHubsListNextResponse = NotificationHubListResult; /** Optional parameters. */ export interface NotificationHubsListAuthorizationRulesNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAuthorizationRulesNext operation. */ export type NotificationHubsListAuthorizationRulesNextResponse = SharedAccessAuthorizationRuleListResult; /** Optional parameters. */ export interface NotificationHubsManagementClientOptionalParams extends coreClient.ServiceClientOptions { /** server parameter */ $host?: string; /** Api Version */ apiVersion?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import Dimensions = Utils.Measurements.Dimensions; import DisplayObject = etch.drawing.DisplayObject; import IDisplayContext = etch.drawing.IDisplayContext; import Point = etch.primitives.Point; import Size = minerva.Size; import {Device} from '../Device'; import {IApp} from '../IApp'; import {MenuCategory} from './MenuCategory'; import {ThemeSelector} from './Options/OptionColorTheme'; import {Version} from './../_Version'; import {Option} from './Options/Option'; import {Slider} from './Options/OptionSlider'; import {OptionMeter} from './Options/OptionMeter'; import {OptionActionButton} from './Options/OptionActionButton'; declare var App: IApp; export class SettingsPanel extends DisplayObject{ public Open: boolean; public OffsetY: number; //public TabOffset: number[]; private _RollOvers: boolean[]; private _Attribution: any; public MenuItems: MenuCategory[] = []; private _MenuCols: number[]; public MenuJson: any; public Height: number; private _OpenTab: number; private _VersionNumber: string; private _LinkWidth: number[]; private _LinksWidth: number; public Options: Option[]; private _OptionsRoll: boolean[]; public Range: number; public Margin: number; public SliderColours: string[]; private _CopyJson: any; Init(drawTo: IDisplayContext): void { super.Init(drawTo); this.Open = false; this.OffsetY = -this.DrawTo.Height; this._RollOvers = []; this.Height = 60; this.MenuItems = []; this._MenuCols = App.ThemeManager.MenuOrder; this._OpenTab = 0; this._VersionNumber = Version; //console.log(Version); // OPTIONS // this.Range = 0; this.Margin = 0; this.SliderColours = []; this.Options = []; this._OptionsRoll = []; this._Attribution = App.L10n.Attribution; this._Attribution.build = String.format(this._Attribution.build, this._VersionNumber); this.MenuJson = { categories: [ { name: "settings" }, { name: "connect" }, { name: "about" } ] }; this._CopyJson = { guideLine: "Visit the BlokDust companion guide for an in depth Wiki, tutorials, news & more:", guideURL: "BlokDust Guide", copyLine: "Spread the word about BlokDust:", connectLine: "Connect with BlokDust elsewhere:", generateLine: "Randomise Title", facebook: "share on facebook", twitter: "share on twitter", google: "share on google +", bookmark: "bookmark creation", tweetText: "Browser-based music making with @blokdust - ", links: [ "FACEBOOK", "TWITTER", "YOUTUBE", "GITHUB" ], urls: [ 'guide.blokdust.com', 'facebook.com/blokdust', 'twitter.com/blokdust', 'youtube.com/channel/UCukBbnIMiUZBbD4fJHrcHZQ', 'github.com/BlokDust/BlokDust' ] }; this.Populate(this.MenuJson); } //------------------------------------------------------------------------------------------- // POPULATE //------------------------------------------------------------------------------------------- Populate(json) { var units = App.Unit; var ctx = this.Ctx; var dataType = units*10; var gutter = 60; var menuCats = []; if (App.Metrics.Device !== Device.desktop) { gutter = 40; } // GET NUMBER OF CATEGORIES // var n = json.categories.length; // GET MENU & CATEGORY WIDTHS // ctx.font = "400 " + dataType + "px Dosis"; ctx.textAlign = "left"; var catWidth = []; if (App.Metrics.Device === Device.mobile) { var menuWidth = (this.DrawTo.Width/7)*5; } else { var menuWidth = (this.DrawTo.Width/7)*4; } // total text width // for (var i=0; i<n; i++) { catWidth[i] = ctx.measureText(json.categories[i].name.toUpperCase()).width + (gutter*units); } // start x for positioning // var catX = ((this.DrawTo.Width*0.5) - (menuWidth*0.5)); // POPULATE MENU // for (var i=0; i<n; i++) { var name = json.categories[i].name.toUpperCase(); var point = new Point(catX + (catWidth[i]*0.5),0); var size = new Size(catWidth[i],16); var offset = -this.DrawTo.Height; if (this._OpenTab===i) { offset = 0; } menuCats[i] = new MenuCategory(point,size,name,offset); catX += catWidth[i]; } this.MenuItems = menuCats; this.MenuItems[this._OpenTab].Selected = 1; // LINKS in CONNECT // this._LinkWidth = []; this._LinksWidth = 0; for (var i=0; i<this._CopyJson.links.length; i++) { this._LinkWidth[i] = ctx.measureText(this._CopyJson.links[i]).width; this._LinksWidth += this._LinkWidth[i]; } this.PopulateOptions(); } //------------------------------------------------------------------------------------------- // DRAW //------------------------------------------------------------------------------------------- Draw() { var ctx = this.Ctx; var midType = App.Metrics.TxtMid; var headType = App.Metrics.TxtHeader; var largeType = App.Metrics.TxtLarge; var urlType = App.Metrics.TxtUrl2; var italicType2 = App.Metrics.TxtItalic2; var units = App.Unit; var grid = App.GridSize; var centerY = this.OffsetY + (App.Height * 0.5); var tabY = this.OffsetY; if (App.Metrics.Device === Device.mobile) { var menuWidth = (this.DrawTo.Width/7)*5; } else { var menuWidth = (this.DrawTo.Width/7)*4; } var halfWidth = menuWidth * 0.5; var dx = (App.Width*0.5); var leftX = dx - halfWidth; var pageY = tabY + (120*units); var tab; //TODO: Draw function needs big tidy up if (this.Open) { // BG // App.FillColor(ctx,App.Palette[2]); ctx.globalAlpha = 0.95; if (this.Open) { ctx.fillRect(0,this.OffsetY,App.Width,App.Height); // solid } ctx.globalAlpha = 1; // CLOSE BUTTON // var closeY = tabY + (30*units); ctx.lineWidth = 2; App.FillColor(ctx,App.Palette[App.ThemeManager.Txt]); App.StrokeColor(ctx,App.Palette[App.ThemeManager.Txt]); ctx.beginPath(); ctx.moveTo(dx + halfWidth + (12.5*units), closeY - (7.5*units)); ctx.lineTo(dx + halfWidth + (27.5*units), closeY + (7.5*units)); ctx.moveTo(dx + halfWidth + (27.5*units), closeY - (7.5*units)); ctx.lineTo(dx + halfWidth + (12.5*units), closeY + (7.5*units)); ctx.stroke(); var gutter = (40*units); var thirdWidth = (menuWidth - (gutter*2))/3; var thirdY = pageY + (130 * units); var x1 = dx - halfWidth; var x2 = dx - halfWidth + thirdWidth + gutter; var x3 = dx - halfWidth + (thirdWidth*2) + (gutter*2); if (App.Metrics.Device == Device.desktop) { ctx.textAlign = "left"; ctx.font = headType; ctx.fillText(this._Attribution.title.toUpperCase(),20*units,this.OffsetY + (30*units) + (11*units)); } // CLIPPING BOX // ctx.save(); ctx.beginPath(); ctx.moveTo(dx - (App.Width*0.5),tabY + (60*units)); ctx.lineTo(dx + (App.Width*0.5),tabY + (60*units)); ctx.lineTo(dx + (App.Width*0.5),App.Height); ctx.lineTo(dx - (App.Width*0.5),App.Height); ctx.closePath(); ctx.clip(); // TAB 1 //------------------------------------------------------------------------------------------- tab = this.MenuItems[0].YOffset; this.Options[0].Draw(ctx,units,0,this,pageY + tab); this.Options[1].Draw(ctx,units,1,this,pageY + tab + (60*units)); this.Options[2].Draw(ctx,units,2,this,pageY + tab + (108*units)); this.Options[3].Draw(ctx,units,3,this,pageY + tab + (156*units)); // TAB 2 //------------------------------------------------------------------------------------------- tab = this.MenuItems[1].YOffset; // GUIDE BUTTON // App.FillColor(ctx,App.Palette[App.ThemeManager.MenuOrder[3]]); ctx.fillRect(dx - (210*units),pageY + tab + (10*units),420*units,40*units); if (this._RollOvers[7]) { ctx.beginPath(); ctx.moveTo(dx, pageY + tab + (59*units)); ctx.lineTo(dx + (10*units), pageY + tab + (49*units)); ctx.lineTo(dx - (10*units), pageY + tab + (49*units)); ctx.closePath(); ctx.fill(); } ctx.font = urlType; ctx.textAlign = "center"; App.FillColor(ctx,App.Palette[App.ThemeManager.Txt]); ctx.fillText(this._CopyJson.guideURL.toUpperCase(), dx, pageY + tab + (39*units)); var shareY = pageY + tab + (155*units); var elsewhereY = pageY + tab + (110*units); // SHARE BUTTONS // ctx.fillStyle = "#fc4742";// gp //TODO: Store these share colours somewhere ctx.fillRect(dx + (80*units),shareY,130*units,30*units); if (this._RollOvers[10]) { ctx.beginPath(); ctx.moveTo(dx + (145*units), shareY + (39*units)); ctx.lineTo(dx + (135*units), shareY + (29*units)); ctx.lineTo(dx + (155*units), shareY + (29*units)); ctx.closePath(); ctx.fill(); } ctx.fillStyle = "#2db0e7"; // tw ctx.fillRect(dx - (65*units),shareY,130*units,30*units); if (this._RollOvers[9]) { ctx.beginPath(); ctx.moveTo(dx, shareY + (39*units)); ctx.lineTo(dx - (10*units), shareY + (29*units)); ctx.lineTo(dx + (10*units), shareY + (29*units)); ctx.closePath(); ctx.fill(); } ctx.fillStyle = "#2152ad"; // fb ctx.fillRect(dx - (210*units),shareY,130*units,30*units); if (this._RollOvers[8]) { ctx.beginPath(); ctx.moveTo(dx - (145*units), shareY + (39*units)); ctx.lineTo(dx - (135*units), shareY + (29*units)); ctx.lineTo(dx - (155*units), shareY + (29*units)); ctx.closePath(); ctx.fill(); } // SHARE COPY // App.FillColor(ctx,App.Palette[App.ThemeManager.Txt]); App.StrokeColor(ctx,App.Palette[App.ThemeManager.Txt]); ctx.textAlign = "center"; ctx.font = italicType2; ctx.fillText(this._CopyJson.copyLine, dx, shareY - (10*units) ); ctx.fillText(this._CopyJson.connectLine, dx, elsewhereY - (25*units) ); ctx.fillText(this._CopyJson.guideLine, dx, pageY + tab ); // BUTTON TEXT // ctx.textAlign = "center"; ctx.font = midType; ctx.fillText(this._CopyJson.facebook.toUpperCase(), dx - (145*units), shareY + (18.5*units) ); ctx.fillText(this._CopyJson.twitter.toUpperCase(), dx, shareY + (18.5*units) ); ctx.fillText(this._CopyJson.google.toUpperCase(), dx + (145*units), shareY + (18.5*units) ); // TEXT LINKS // var spacer = 30*units; var linkWidth = this._LinkWidth; var linksWidth = this._LinksWidth + (spacer*3); ctx.textAlign = "left"; ctx.fillText(this._CopyJson.links[0], dx - (linksWidth*0.5), elsewhereY ); ctx.fillText(this._CopyJson.links[1], dx - (linksWidth*0.5) + linkWidth[0] + spacer, elsewhereY ); ctx.fillText(this._CopyJson.links[2], dx - (linksWidth*0.5) + linkWidth[0] + linkWidth[1] + (spacer*2), elsewhereY ); ctx.fillText(this._CopyJson.links[3], dx - (linksWidth*0.5) + linkWidth[0] + linkWidth[1] + linkWidth[2] + (spacer*3), elsewhereY ); App.StrokeColor(ctx,App.Palette[1]); ctx.beginPath(); ctx.moveTo(dx - (linksWidth*0.5) + linkWidth[0] + (spacer*0.5), elsewhereY - (15*units)); ctx.lineTo(dx - (linksWidth*0.5) + linkWidth[0] + (spacer*0.5), elsewhereY + (10*units)); ctx.moveTo(dx - (linksWidth*0.5) + linkWidth[0] + linkWidth[1] + (spacer*1.5), elsewhereY - (15*units)); ctx.lineTo(dx - (linksWidth*0.5) + linkWidth[0] + linkWidth[1] + (spacer*1.5), elsewhereY + (10*units)); ctx.moveTo(dx - (linksWidth*0.5) + linkWidth[0] + linkWidth[1] + linkWidth[2] + (spacer*2.5), elsewhereY - (15*units)); ctx.lineTo(dx - (linksWidth*0.5) + linkWidth[0] + linkWidth[1] + linkWidth[2] + (spacer*2.5), elsewhereY + (10*units)); ctx.stroke(); App.StrokeColor(ctx,App.Palette[App.ThemeManager.Txt]); ctx.lineWidth = 1; ctx.beginPath(); if (this._RollOvers[11]) { ctx.moveTo(dx - (linksWidth*0.5), elsewhereY + (2*units)); ctx.lineTo(dx - (linksWidth*0.5) + linkWidth[0],elsewhereY + (2*units)); } if (this._RollOvers[12]) { ctx.moveTo(dx - (linksWidth*0.5) + linkWidth[0] + spacer, elsewhereY + (2*units)); ctx.lineTo(dx - (linksWidth*0.5) + linkWidth[0] + linkWidth[1] + spacer,elsewhereY + (2*units)); } if (this._RollOvers[13]) { ctx.moveTo(dx - (linksWidth*0.5) + linkWidth[0] + linkWidth[1] + (spacer*2), elsewhereY + (2*units)); ctx.lineTo(dx - (linksWidth*0.5) + linkWidth[0] + linkWidth[1] + linkWidth[2] + (spacer*2),elsewhereY + (2*units)); } if (this._RollOvers[14]) { ctx.moveTo(dx - (linksWidth*0.5) + linkWidth[0] + linkWidth[1] + linkWidth[2] + (spacer*3), elsewhereY + (2*units)); ctx.lineTo(dx - (linksWidth*0.5) + linkWidth[0] + linkWidth[1] + linkWidth[2] + linkWidth[3] + (spacer*3),elsewhereY + (2*units)); } ctx.stroke(); // TAB 3 //------------------------------------------------------------------------------------------- tab = this.MenuItems[2].YOffset; App.FillColor(ctx,App.Palette[App.ThemeManager.Txt]); ctx.font = largeType; ctx.textAlign = "left"; this.WordWrap(ctx, this._Attribution.about, dx - halfWidth, pageY + tab, units*16, Math.ceil(menuWidth)); var xs = [x1,x2,x3]; var widths = []; var strings = [ this._Attribution.twyman.url,this._Attribution.phillips.url,this._Attribution.silverton.url, this._Attribution.twyman.twitter,this._Attribution.phillips.twitter,this._Attribution.silverton.twitter ]; ctx.font = italicType2; for (var i=1; i<=(strings.length); i++) { widths.push(ctx.measureText(strings[i-1]).width); } App.StrokeColor(ctx,App.Palette[App.ThemeManager.Txt]); ctx.lineWidth = 1; for (var i=1; i<4; i++) { if (this._RollOvers[i]) { ctx.beginPath(); ctx.moveTo(xs[i-1], thirdY + (44*units) + tab); ctx.lineTo(xs[i-1] + (widths[i-1]),thirdY + (44*units) + tab); ctx.stroke(); } if (this._RollOvers[i+3]) { ctx.beginPath(); ctx.moveTo(xs[i-1], thirdY + (58*units) + tab); ctx.lineTo(xs[i-1] + (widths[i+2]),thirdY + (58*units) + tab); ctx.stroke(); } } App.FillColor(ctx,App.Palette[App.ThemeManager.Txt]); // BLURBS // this.WordWrap(ctx, this._Attribution.twyman.blurb, x1, thirdY + tab, units*14, Math.ceil(thirdWidth)); this.WordWrap(ctx, this._Attribution.phillips.blurb, x2, thirdY + tab, units*14, Math.ceil(thirdWidth)); this.WordWrap(ctx, this._Attribution.silverton.blurb, x3, thirdY + tab, units*14, Math.ceil(thirdWidth)); // URLS // ctx.fillText(this._Attribution.twyman.url, x1, thirdY + (42 * units) + tab); ctx.fillText(this._Attribution.phillips.url, x2, thirdY + (42 * units) + tab); ctx.fillText(this._Attribution.silverton.url, x3, thirdY + (42 * units) + tab); // TWITTERS // ctx.fillText(this._Attribution.twyman.twitter, x1, thirdY + (56 * units) + tab); ctx.fillText(this._Attribution.phillips.twitter, x2, thirdY + (56 * units) + tab); ctx.fillText(this._Attribution.silverton.twitter, x3, thirdY + (56 * units) + tab); // BLOCKS // var blockY = thirdY - grid - (10*units) + tab; App.FillColor(ctx,App.Palette[4]); ctx.beginPath(); ctx.moveTo(x1,blockY - (grid*3)); ctx.lineTo(x1 + (grid),blockY - (grid*3)); ctx.lineTo(x1 + (grid*2),blockY - (grid*2)); ctx.lineTo(x1 + grid,blockY - grid); ctx.closePath(); ctx.fill(); ctx.beginPath(); ctx.moveTo(x1 + (grid),blockY); ctx.lineTo(x1 + (grid*2),blockY - grid); ctx.lineTo(x1 + (grid*2),blockY); ctx.closePath(); ctx.fill(); App.FillColor(ctx,App.Palette[5]); ctx.beginPath(); ctx.moveTo(x2,blockY); ctx.lineTo(x2,blockY - grid); ctx.lineTo(x2 + grid,blockY - (grid*2)); ctx.lineTo(x2 + (grid*3),blockY - (grid*2)); ctx.lineTo(x2 + grid,blockY); ctx.closePath(); ctx.fill(); App.FillColor(ctx,App.Palette[7]); ctx.beginPath(); ctx.moveTo(x3,blockY); ctx.lineTo(x3 + grid,blockY - (grid*3)); ctx.lineTo(x3 + (grid*2),blockY - (grid*3)); ctx.lineTo(x3 + (grid*2),blockY - grid); ctx.lineTo(x3 + grid,blockY); ctx.closePath(); ctx.fill(); App.FillColor(ctx,App.Palette[3]); ctx.beginPath(); ctx.moveTo(x1,blockY); ctx.lineTo(x1,blockY - (grid*3)); ctx.lineTo(x1 + grid,blockY - (grid*2)); ctx.lineTo(x1 + grid,blockY - grid); ctx.closePath(); ctx.fill(); App.FillColor(ctx,App.Palette[10]); ctx.beginPath(); ctx.moveTo(x2,blockY); ctx.lineTo(x2,blockY - grid); ctx.lineTo(x2 + grid,blockY - (grid*2)); ctx.lineTo(x2 + grid,blockY); ctx.closePath(); ctx.fill(); ctx.beginPath(); ctx.moveTo(x2, blockY - (grid*3)); ctx.lineTo(x2 + grid,blockY - (grid*3)); ctx.lineTo(x2,blockY - (grid*2)); ctx.closePath(); ctx.fill(); App.FillColor(ctx,App.Palette[9]); ctx.beginPath(); ctx.moveTo(x3,blockY); ctx.lineTo(x3,blockY - (grid*2)); ctx.lineTo(x3 + grid,blockY - (grid*3)); ctx.lineTo(x3 + grid,blockY - grid); ctx.closePath(); ctx.fill(); ctx.beginPath(); ctx.moveTo(x3 + (grid*2), blockY); ctx.lineTo(x3 + (grid*3),blockY); ctx.lineTo(x3 + (grid*3),blockY - grid); ctx.closePath(); ctx.fill(); // END TAB 3 // ctx.restore(); // CHROME RECOMMENDED // App.FillColor(ctx,App.Palette[App.ThemeManager.Txt]); App.StrokeColor(ctx,App.Palette[App.ThemeManager.Txt]); ctx.font = largeType; ctx.textAlign = "center"; ctx.fillText('Chrome Recommended', App.Width*0.5, this.OffsetY + this.DrawTo.Height - (20 * units)); ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo((App.Width*0.5) - (60*units), this.OffsetY + this.DrawTo.Height - (27 * units)); ctx.lineTo((App.Width*0.5) - (63.89*units), this.OffsetY + this.DrawTo.Height - (20 * units)); ctx.lineTo((App.Width*0.5) - (56.11*units), this.OffsetY + this.DrawTo.Height - (20 * units)); ctx.closePath(); ctx.stroke(); // BUILD VERSION // ctx.font = italicType2; ctx.textAlign = "right"; ctx.fillText(this._Attribution.build, this.DrawTo.Width - (20*units), this.OffsetY + this.DrawTo.Height - (20 * units)); // DIVIDERS // App.StrokeColor(ctx,App.Palette[1]); // Horizontal // ctx.beginPath(); ctx.moveTo(dx - halfWidth,tabY + (60*units)-1); ctx.lineTo(dx + halfWidth,tabY + (60*units)-1); //vertical // for (var i=0;i<this.MenuItems.length;i++) { var cat = this.MenuItems[i]; var menuX = cat.Position.x; if (i > 0) { ctx.moveTo(Math.round(menuX - (cat.Size.width*0.5)), tabY + (16*units)); ctx.lineTo(Math.round(menuX - (cat.Size.width*0.5)), tabY + (44*units)); } } ctx.stroke(); // CATEGORIES // ctx.textAlign = "center"; ctx.font = midType; for (var i=0;i<this.MenuItems.length;i++) { ctx.globalAlpha = 1; var cat = this.MenuItems[i]; // SELECTION COLOUR // var col = this._MenuCols[i - (Math.floor(i / this._MenuCols.length) * (this._MenuCols.length))]; App.FillColor(ctx,App.Palette[col]); // DRAW CAT HEADER // cat.Draw(ctx, units, this,tabY); } } } WordWrap( context , text, x, y, lineHeight, fitWidth) { fitWidth = fitWidth || 0; if (fitWidth <= 0) { context.fillText( text, x, y ); return; } var words = text.split(' '); var currentLine = 0; var idx = 1; while (words.length > 0 && idx <= words.length) { var str = words.slice(0,idx).join(' '); var w = context.measureText(str).width; if ( w > fitWidth ) { if (idx==1) { idx=2; } context.fillText( words.slice(0,idx-1).join(' '), x, y + (lineHeight*currentLine) ); currentLine++; words = words.splice(idx-1); idx = 1; } else {idx++;} } if (idx > 0) context.fillText( words.join(' '), x, y + (lineHeight*currentLine) ); } NumberWithCommas(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } //------------------------------------------------------------------------------------------- // TWEEN //------------------------------------------------------------------------------------------- DelayTo(panel,destination,t,delay,v){ var offsetTween = new window.TWEEN.Tween({x: panel[""+v]}); offsetTween.to({x: destination}, t); offsetTween.onUpdate(function () { panel[""+v] = this.x; }); offsetTween.onComplete(function() { if (v === "OffsetY") { if (destination!==0) { panel.Open = false; } } }); offsetTween.easing(window.TWEEN.Easing.Exponential.InOut); offsetTween.delay(delay); offsetTween.start(this.LastVisualTick); } //------------------------------------------------------------------------------------------- // INTERACTION //------------------------------------------------------------------------------------------- OpenPanel() { this.Open = true; this.OffsetY = -this.DrawTo.Height; this.DelayTo(this,0,500,0,"OffsetY"); this.MenuItems[this._OpenTab].YOffset = 0; //this.Populate(); } ClosePanel() { this.DelayTo(this,-this.DrawTo.Height,500,0,"OffsetY"); } PopulateOptions() { var optionList = []; var optionY = []; var optionNames = ["Color Theme","Master Volume","DB Meter","Tour"]; var units = App.Unit; var centerY = this.OffsetY + (this.DrawTo.Height * 0.5); var tabY = this.OffsetY; var pageY = tabY + (120*units); var dx = (this.DrawTo.Width*0.5); if (App.Metrics.Device === Device.mobile) { var menuWidth = (this.DrawTo.Width/7)*5; } else { var menuWidth = (this.DrawTo.Width/7)*4; } var halfWidth = menuWidth*0.5; // MARGIN WIDTH // var mw = 0; this.Ctx.font = App.Metrics.TxtMid; for (var i=0;i<optionNames.length;i++) { var nw = this.Ctx.measureText(optionNames[i].toUpperCase()).width; if (nw > mw) { mw = nw; } } var marginWidth = mw + (15*units); this.Margin = dx - halfWidth + marginWidth; this.Range = menuWidth - marginWidth; var order = App.ThemeManager.OptionsOrder; this.SliderColours = [App.Palette[order[0]],App.Palette[order[1]],App.Palette[order[2]],App.Palette[order[3]],App.Palette[order[4]]]; // COLOR THEME // optionList.push(new ThemeSelector(optionNames[0])); // VOLUME // var sliderValue = App.Audio.Master.volume.value + 70; var sliderSetting = "volume"; var sliderX = this.linPosition(0, this.Range, 0, 60, sliderValue); var sliderO = this.Margin; optionList.push(new Slider(new Point(sliderX,pageY + this.MenuItems[1].YOffset + (60*units)),new Size(1,48*App.Unit),sliderO,sliderValue,0,60,true,optionNames[1],sliderSetting,false)); // METER // optionList.push(new OptionMeter(optionNames[2])); // TUTORIAL // optionList.push(new OptionActionButton(new Point(0,pageY + this.MenuItems[1].YOffset + (156*units)),new Size(1,48*App.Unit),optionNames[3],"Launch Tutorial","tutorial")); this.Options = optionList; } MouseDown(point) { this.HitTests(point); if (this._RollOvers[0]) { this.ClosePanel(); return; } // OPTIONS // if (this._OpenTab===0) { for (var i=0;i<this.Options.length;i++) { if (this._OptionsRoll[i]) { this.Options[i].Selected = true; if (this.Options[i].Type=="themeSelector") { var option = this.Options[i]; if (option.HandleRoll[0]) { App.ThemeManager.CurrentThemeNo -= 1; if (App.ThemeManager.CurrentThemeNo < 0) { App.ThemeManager.CurrentThemeNo = App.ThemeManager.Themes.length-1; } App.ThemeManager.LoadTheme(App.ThemeManager.CurrentThemeNo,false); } if (option.HandleRoll[1]) { App.ThemeManager.CurrentThemeNo += 1; if (App.ThemeManager.CurrentThemeNo > (App.ThemeManager.Themes.length-1)) { App.ThemeManager.CurrentThemeNo = 0; } App.ThemeManager.LoadTheme(App.ThemeManager.CurrentThemeNo,false); } } if (this.Options[i].Type=="slider") { this.SliderSet(i, point.x); } if (this.Options[i].Type=="meter") { this.Options[i].MonitorReset(); } if (this.Options[i].Type == "actionbutton") { if (this.Options[i].HandleRoll[0]) { this.ActionButton(this.Options[i].Setting); } } } } } // SELECT CATEGORY // for (var i=0; i<this.MenuItems.length; i++) { if (this.MenuItems[i].Hover) { window.TWEEN.removeAll(); // TODO - swap for local tween pool var cat = this.MenuItems[i]; this.DelayTo(cat,1,400,0,"Selected"); this.DelayTo(cat,0,400,400,"YOffset"); this._OpenTab = i; // I'M THE SELECTED CATEGORY // RESET NON-SELECTED CATEGORIES // for (var j=0; j<this.MenuItems.length; j++) { if (j!==i) { var cat = this.MenuItems[j]; this.DelayTo(cat,0,250,0,"Selected"); this.DelayTo(cat,-this.DrawTo.Height,250,0,"YOffset"); } } return; } } // CONNECT // if (this._OpenTab===1) { var bdUrls = this._CopyJson.urls; if (this._RollOvers[7]) { // GUIDE // window.open("http://" + bdUrls[0], "_blank"); } if (this._RollOvers[8]) { // FB SHARE // this.ShareFacebook(); } if (this._RollOvers[9]) { // TW SHARE // this.ShareTwitter(); } if (this._RollOvers[10]) { // GP SHARE // this.ShareGoogle(); } if (this._RollOvers[11]) { // FB SHARE // window.open("http://" + bdUrls[1], "_blank"); } if (this._RollOvers[12]) { // TW SHARE // window.open("http://" + bdUrls[2], "_blank"); } if (this._RollOvers[13]) { // GP SHARE // window.open("http://" + bdUrls[3], "_blank"); } if (this._RollOvers[14]) { // GP SHARE // window.open("http://" + bdUrls[4], "_blank"); } } // EXTERNAL URLS // if (this._OpenTab===2) { var urls = [this._Attribution.twyman.url, this._Attribution.phillips.url, this._Attribution.silverton.url, this._Attribution.twyman.twitter, this._Attribution.phillips.twitter, this._Attribution.silverton.twitter]; for (var i = 1; i < 7; i++) { if (this._RollOvers[i]) { if (i > 3) { window.open("http://twitter.com/" + urls[i - 1], "_blank"); } else { window.open("http://" + urls[i - 1], "_blank"); } } } } } MouseMove(point) { this.HitTests(point); for (var i=0;i<this.Options.length;i++) { if (this.Options[i].Selected) { if (this.Options[i].Type=="slider") { this.SliderSet(i, point.x); } } } } HitTests(point) { var units = App.Unit; var centerY = this.OffsetY + (this.DrawTo.Height * 0.5); var tabY = this.OffsetY; var pageY = tabY + (120*units); var closeY = tabY + (30*units); var dx = (this.DrawTo.Width*0.5); if (App.Metrics.Device === Device.mobile) { var menuWidth = (this.DrawTo.Width/7)*5; } else { var menuWidth = (this.DrawTo.Width/7)*4; } var halfWidth = menuWidth*0.5; var gutter = (40*units); var thirdWidth = (menuWidth - (gutter*2))/3; var thirdY = pageY + (130 * units); var x1 = dx - halfWidth; var x2 = dx - halfWidth + thirdWidth + gutter; var x3 = dx - halfWidth + (thirdWidth*2) + (gutter*2); var xs = [x1,x2,x3]; var tab; this._RollOvers[0] = Dimensions.hitRect(dx + halfWidth, closeY - (20*units),40*units,40*units, point.x, point.y); // close for (var i=1; i<4; i++) { this._RollOvers[i] = Dimensions.hitRect(xs[i-1], thirdY + (25*units) + this.MenuItems[2].YOffset,thirdWidth,20*units, point.x, point.y); // url this._RollOvers[i+3] = Dimensions.hitRect(xs[i-1], thirdY + (45*units) + this.MenuItems[2].YOffset,thirdWidth,20*units, point.x, point.y); // twitter } tab = this.MenuItems[1].YOffset; this._RollOvers[7] = Dimensions.hitRect(dx - (210*units), pageY + tab + (10*units),420*units,40*units, point.x, point.y); // guide this._RollOvers[8] = Dimensions.hitRect(dx - (210*units),pageY + tab + (155*units),130*units,30*units, point.x, point.y); // fb this._RollOvers[9] = Dimensions.hitRect(dx - (65*units),pageY + tab + (155*units),130*units,30*units, point.x, point.y); // tw this._RollOvers[10] = Dimensions.hitRect(dx + (80*units),pageY + tab + (155*units),130*units,30*units, point.x, point.y); // gp var spacer = 30*units; var linkWidth = this._LinkWidth; var linksWidth = this._LinksWidth + (spacer*3); this._RollOvers[11] = Dimensions.hitRect(dx - (linksWidth*0.5) - (spacer * 0.5),pageY + tab + (90*units),linkWidth[0] + spacer,30*units, point.x, point.y); // fb this._RollOvers[12] = Dimensions.hitRect(dx - (linksWidth*0.5) + linkWidth[0] + (spacer * 0.5),pageY + tab + (90*units),linkWidth[1] + spacer,30*units, point.x, point.y); // tw this._RollOvers[13] = Dimensions.hitRect(dx - (linksWidth*0.5) + linkWidth[0] + linkWidth[1] + (spacer * 1.5),pageY + tab + (90*units),linkWidth[2] + spacer,30*units, point.x, point.y); // yt this._RollOvers[14] = Dimensions.hitRect(dx - (linksWidth*0.5) + linkWidth[0] + linkWidth[1] + linkWidth[2] + (spacer * 2.5),pageY + tab + (90*units),linkWidth[3] + spacer,30*units, point.x, point.y); // gh // CATEGORY HIT TEST // for (var i=0; i<this.MenuItems.length; i++) { var cat = this.MenuItems[i]; cat.Hover = Dimensions.hitRect(cat.Position.x - (cat.Size.width*0.5) + (2*units), tabY + (5*units), cat.Size.width - (4*units), (this.Height*units) - (10*units), point.x, point.y ); } // OPTIONS HIT TESTS // tab = this.MenuItems[0].YOffset; for (var i=0;i<this.Options.length;i++) { if (this.Options[i].Type == "slider") { this._OptionsRoll[i] = Dimensions.hitRect(this.Margin - (10*units), pageY + tab + (60*units), this.Range + (20*units), 48*App.Unit, point.x, point.y); } if (this.Options[i].Type == "meter") { this._OptionsRoll[i] = Dimensions.hitRect(this.Margin - (10*units), pageY + tab + (108*units), this.Range + (20*units), 48*App.Unit, point.x, point.y); } if (this.Options[i].Type == "themeSelector") { this._OptionsRoll[i] = Dimensions.hitRect(this.Margin - (10*units), pageY + tab, this.Range + (20*units), 60*App.Unit, point.x, point.y); this.Options[i].HandleRoll[0] = Dimensions.hitRect(this.Margin - (10*units), pageY + tab, 40*units, 60*units, point.x, point.y); this.Options[i].HandleRoll[1] = Dimensions.hitRect(this.Margin + this.Range - (30*units), pageY + tab, 40*units, 60*units, point.x, point.y); } if (this.Options[i].Type == "actionbutton") { this._OptionsRoll[i] = Dimensions.hitRect(this.Margin - (10*units), pageY + tab + (156*units), this.Range + (20*units), 48*App.Unit, point.x, point.y); this.Options[i].HandleRoll[0] = Dimensions.hitRect(this.Margin + (this.Range * 0.25), pageY + tab + (156*units), (this.Range * 0.5), this.Options[i].Size.height, point.x, point.y); } } } MouseUp(point) { for (var i=0;i<this.Options.length;i++) { this.Options[i].Selected = false; } } // DRAGGING A SLIDER // SliderSet(n,mx) { var units = App.Unit; var centerY = this.OffsetY + (this.DrawTo.Height * 0.5); var tabY = this.OffsetY; var pageY = tabY + (120*units); var dx = (this.DrawTo.Width*0.5); var menuWidth = (this.DrawTo.Width/7)*4; var halfWidth = menuWidth*0.5; this.Options[n].Position.x = mx - this.Margin; this.Options[n].Position.x = this.ValueInRange(this.Options[n].Position.x,0,this.Range); var log = false; this.UpdateValue(this.Options[n],"Value","Min","Max",0, this.Range,"Setting","x",log); } ActionButton(setting) { switch (setting) { case "tutorial" : this.ClosePanel(); App.MainScene.Tutorial.OpenSplash(); break; } } // UPDATE OPTIONS VALUE // UpdateValue(object,value,min,max,rangemin,rangemax,setting,axis,log) { // CALCULATE VALUE // object[""+value] = this.linValue(rangemin,rangemax,object[""+min],object[""+max],object.Position[""+axis]); // QUANTIZE // if (object.Quantised) { object[""+value] = Math.round(object[""+value]); object.Position["" + axis] = this.linPosition(rangemin, rangemax, object["" + min], object["" + max], object["" + value]); } // SET VALUE // var val = object[""+value]; // console.log("" + object[""+setting] +" | "+ val); switch (object[""+setting]) { case "volume": App.Audio.Master.volume.value = val - 70; if (val===0) { App.Audio.Master.volume.value = val - 200; } break; } } ShareFacebook() { var href = "http://www.facebook.com/sharer.php?"; href = "" + href + "u=http://blokdust.com"; window.open(href,'', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600'); } ShareTwitter() { var href = "https://twitter.com/intent/tweet?text="; href = "" + href + encodeURIComponent(this._CopyJson.tweetText); href = "" + href + "&url=http://blokdust.com"; window.open(href,'', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600'); } ShareGoogle() { var href = "https://plus.google.com/share?url="; href = "" + href + "http://blokdust.com"; window.open(href,'', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600'); } //------------------------------------------------------------------------------------------- // MATHS //------------------------------------------------------------------------------------------- ValueInRange(value,floor,ceiling) { if (value < floor) { value = floor; } if (value> ceiling) { value = ceiling; } return value; } linValue(minpos,maxpos,minval,maxval,position) { var scale = (maxval - minval) / (maxpos - minpos); //console.log("" +minval + " | " +maxval + " | " +position); return (position - minpos) * scale + minval; } linPosition(minpos,maxpos,minval,maxval,value) { var scale = (maxval - minval) / (maxpos - minpos); //console.log("" +minval + " | " +maxval + " | " +value); return minpos + (value - minval) / scale; } Resize() { } }
the_stack
export class Scalar { /** * Two pi constants convenient for computation. */ public static TwoPi: number = Math.PI * 2 /** * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45) * @param a - number * @param b - number * @param epsilon - (default = 1.401298E-45) * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45) */ public static WithinEpsilon(a: number, b: number, epsilon: number = 1.401298e-45): boolean { let num = a - b return -epsilon <= num && num <= epsilon } /** * Returns a string : the upper case translation of the number i to hexadecimal. * @param i - number * @returns the upper case translation of the number i to hexadecimal. */ public static ToHex(i: number): string { let str = i.toString(16) if (i <= 15) { return ('0' + str).toUpperCase() } return str.toUpperCase() } /** * Returns -1 if value is negative and +1 is value is positive. * @param _value - the value * @returns the value itself if it's equal to zero. */ public static Sign(value: number): number { const _value = +value // convert to a number if (_value === 0 || isNaN(_value)) { return _value } return _value > 0 ? 1 : -1 } /** * Returns the value itself if it's between min and max. * Returns min if the value is lower than min. * Returns max if the value is greater than max. * @param value - the value to clmap * @param min - the min value to clamp to (default: 0) * @param max - the max value to clamp to (default: 1) * @returns the clamped value */ public static Clamp(value: number, min = 0, max = 1): number { return Math.min(max, Math.max(min, value)) } /** * the log2 of value. * @param value - the value to compute log2 of * @returns the log2 of value. */ public static Log2(value: number): number { return Math.log(value) * Math.LOG2E } /** * Loops the value, so that it is never larger than length and never smaller than 0. * * This is similar to the modulo operator but it works with floating point numbers. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5. * With t = 5 and length = 2.5, the result would be 0.0. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator * @param value - the value * @param length - the length * @returns the looped value */ public static Repeat(value: number, length: number): number { return value - Math.floor(value / length) * length } /** * Normalize the value between 0.0 and 1.0 using min and max values * @param value - value to normalize * @param min - max to normalize between * @param max - min to normalize between * @returns the normalized value */ public static Normalize(value: number, min: number, max: number): number { return (value - min) / (max - min) } /** * Denormalize the value from 0.0 and 1.0 using min and max values * @param normalized - value to denormalize * @param min - max to denormalize between * @param max - min to denormalize between * @returns the denormalized value */ public static Denormalize(normalized: number, min: number, max: number): number { return normalized * (max - min) + min } /** * Calculates the shortest difference between two given angles given in degrees. * @param current - current angle in degrees * @param target - target angle in degrees * @returns the delta */ public static DeltaAngle(current: number, target: number): number { let num: number = Scalar.Repeat(target - current, 360.0) if (num > 180.0) { num -= 360.0 } return num } /** * PingPongs the value t, so that it is never larger than length and never smaller than 0. * @param tx - value * @param length - length * @returns The returned value will move back and forth between 0 and length */ public static PingPong(tx: number, length: number): number { let t: number = Scalar.Repeat(tx, length * 2.0) return length - Math.abs(t - length) } /** * Interpolates between min and max with smoothing at the limits. * * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions. * @param from - from * @param to - to * @param tx - value * @returns the smooth stepped value */ public static SmoothStep(from: number, to: number, tx: number): number { let t: number = Scalar.Clamp(tx) t = -2.0 * t * t * t + 3.0 * t * t return to * t + from * (1.0 - t) } /** * Moves a value current towards target. * * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta. * Negative values of maxDelta pushes the value away from target. * @param current - current value * @param target - target value * @param maxDelta - max distance to move * @returns resulting value */ public static MoveTowards(current: number, target: number, maxDelta: number): number { let result: number = 0 if (Math.abs(target - current) <= maxDelta) { result = target } else { result = current + Scalar.Sign(target - current) * maxDelta } return result } /** * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees. * * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead. * @param current - current value * @param target - target value * @param maxDelta - max distance to move * @returns resulting angle */ public static MoveTowardsAngle(current: number, target: number, maxDelta: number): number { let num: number = Scalar.DeltaAngle(current, target) let result: number = 0 if (-maxDelta < num && num < maxDelta) { result = target } else { result = Scalar.MoveTowards(current, current + num, maxDelta) } return result } /** * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar. * @param start - start value * @param end - target value * @param amount - amount to lerp between * @returns the lerped value */ public static Lerp(start: number, end: number, amount: number): number { return start + (end - start) * amount } /** * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees. * @param start - start value * @param end - target value * @param amount - amount to lerp between * @returns the lerped value */ public static LerpAngle(start: number, end: number, amount: number): number { let num: number = Scalar.Repeat(end - start, 360.0) if (num > 180.0) { num -= 360.0 } return start + num * Scalar.Clamp(amount) } /** * Calculates the linear parameter t that produces the interpolant value within the range [a, b]. * @param a - start value * @param b - target value * @param value - value between a and b * @returns the inverseLerp value */ public static InverseLerp(a: number, b: number, value: number): number { let result: number = 0 if (a !== b) { result = Scalar.Clamp((value - a) / (b - a)) } else { result = 0.0 } return result } /** * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2". * {@link http://mathworld.wolfram.com/HermitePolynomial.html} * @param value1 - spline value * @param tangent1 - spline value * @param value2 - spline value * @param tangent2 - spline value * @param amount - input value * @returns hermite result */ public static Hermite(value1: number, tangent1: number, value2: number, tangent2: number, amount: number): number { let squared = amount * amount let cubed = amount * squared let part1 = 2.0 * cubed - 3.0 * squared + 1.0 let part2 = -2.0 * cubed + 3.0 * squared let part3 = cubed - 2.0 * squared + amount let part4 = cubed - squared return value1 * part1 + value2 * part2 + tangent1 * part3 + tangent2 * part4 } /** * Returns a random float number between and min and max values * @param min - min value of random * @param max - max value of random * @returns random value */ public static RandomRange(min: number, max: number): number { if (min === max) { return min } return Math.random() * (max - min) + min } /** * This function returns percentage of a number in a given range. * * RangeToPercent(40,20,60) will return 0.5 (50%) * RangeToPercent(34,0,100) will return 0.34 (34%) * @param num - to convert to percentage * @param min - min range * @param max - max range * @returns the percentage */ public static RangeToPercent(num: number, min: number, max: number): number { return (num - min) / (max - min) } /** * This function returns number that corresponds to the percentage in a given range. * * PercentToRange(0.34,0,100) will return 34. * @param percent - to convert to number * @param min - min range * @param max - max range * @returns the number */ public static PercentToRange(percent: number, min: number, max: number): number { return (max - min) * percent + min } /** * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians. * @param angle - The angle to normalize in radian. * @returns The converted angle. */ public static NormalizeRadians(angle: number): number { // More precise but slower version kept for reference. // tslint:disable:no-commented-out-code /* // angle = angle % Tools.TwoPi; // angle = (angle + Tools.TwoPi) % Tools.TwoPi; //if (angle > Math.PI) { // angle -= Tools.TwoPi; //} */ return angle - Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi) } }
the_stack
import * as React from "react"; import { Popover } from "@blueprintjs/core"; import { PickingInfo, Vector3, Observable, Node, Scene } from "babylonjs"; import { Editor } from "../editor"; import { Nullable, Undefinable } from "../../../shared/types"; import { IFile } from "../project/files"; export interface IAssetsComponentProps { /** * The editor reference to be used in the assets component. */ editor: Editor; /** * The id of the component. */ id: string; /** * Optional callback called on the user double clicks an asset. */ onClick?: Undefinable<(item: IAssetComponentItem, img: HTMLImageElement) => void>; /** * Optional callback called on the user double clicks an asset. */ doubleClick?: Undefinable<(item: IAssetComponentItem, img: HTMLImageElement) => void>; /** * Optional style to apply. */ style?: Undefinable<React.CSSProperties>; } export interface IAssetComponentItem { /** * Defines the id of the texture. */ id: string; /** * Defines the preview of the texture in base64. */ base64: string; /** * The key string used by React. */ key: string; /** * Optional style that can be added to the item node. */ ref?: Nullable<HTMLDivElement>; /** * Optional style options for the div. */ style?: Undefinable<React.CSSProperties>; /** * Defines wether or not the item is selected. */ isSelected?: Undefinable<boolean>; /** * Defines wether or not popover is enabled. */ popoverEnabled?: Undefinable<boolean>; /** * Defines the extra data describing the asset item. */ extraData?: { [index: string]: number | string | boolean; } } export interface IDragAndDroppedAssetComponentItem extends IAssetComponentItem { /** * Defines the id of the component containing the asset being drag'n'dropped. */ assetComponentId: string; } export interface IAssetsComponentState { /** * Defines all the assets to draw in the panel. */ items: IAssetComponentItem[]; /** * Defines the height of the panel. */ height: number; } export interface IAbstractAssets { /** * Refreshes the component. * @param object the optional object reference that has been modified in the editor. */ refresh<T>(object: Undefinable<T>): Promise<void>; /** * Called on the user drops an asset in editor. (typically the preview canvas). * @param item the item being dropped. * @param pickInfo the pick info generated on the drop event. */ onDropAsset(item: IAssetComponentItem, pickInfo: PickingInfo): void; /** * Called on the user drops files in the assets component and returns true if the files have been computed. * @param files the list of files being dropped. */ onDropFiles?(files: IFile[]): boolean | Promise<boolean>; /** * Called on an asset item has been drag'n'dropped on graph component. * @param data defines the data of the asset component item being drag'n'dropped. * @param nodes defines the array of nodes having the given item being drag'n'dropped. */ onGraphDropAsset?(data: IAssetComponentItem, nodes: (Scene | Node)[]): boolean; } export class AbstractAssets extends React.Component<IAssetsComponentProps, IAssetsComponentState> implements IAbstractAssets { /** * Defines the list of all available assets. */ public items: IAssetComponentItem[] = []; /** * Defines the observable used to notify observers that an asset has been updated. */ public updateAssetObservable: Observable<void> = new Observable<void>(); /** * The editor reference. */ protected editor: Editor; /** * Defines the size of assets to be drawn in the panel. Default is 100x100 pixels. */ protected size: number = 100; /** * Defines the type of the data transfer data when drag'n'dropping asset. */ public readonly dragAndDropType: string = "text/plain"; /** * Stores the current list of nodes drawn in the panel.. * @warning should be used with care. */ protected _itemsNodes: React.ReactNode[] = []; private _filter: string = ""; private _dropListener: Nullable<(ev: DragEvent) => void> = null; private _itemBeingDragged: Nullable<IAssetComponentItem> = null; /** * Constructor. * @param props the component's props. */ public constructor(props: IAssetsComponentProps) { super(props); this.editor = props.editor; this.state = { items: this.items, height: 0 }; } /** * Refreshes the component. */ public async refresh(): Promise<void> { this.setState({ items: this.items }); } /** * Called once a project has been loaded, this function is used to clean up * unused assets files automatically. */ public async clean(): Promise<void> { // Empty for now... } /** * Called on the user drops an asset in editor. (typically the preview canvas). * @param item the item being dropped. * @param pickInfo the pick info generated on the drop event. */ public onDropAsset(_: IAssetComponentItem, __: PickingInfo): void { // Nothing to do by default. } /** * Called on the user double clicks an item. * @param item the item being double clicked. * @param img the double-clicked image element. */ public onDoubleClick(item: IAssetComponentItem, img: HTMLImageElement): void { if (this.props.doubleClick) { this.props.doubleClick(item, img); } } /** * Called on the user clicks on an item. * @param item the item being clicked. * @param img the clicked image element. */ public onClick(item: IAssetComponentItem, img: HTMLImageElement): void { if (this.props.onClick) { this.props.onClick(item, img); } } /** * Called on the user right-clicks on an item. * @param item the item being right-clicked. * @param event the original mouse event. */ public onContextMenu(_: IAssetComponentItem, event: React.MouseEvent<HTMLImageElement, MouseEvent>): void { event.stopPropagation(); } /** * Called on the user right-clicks on the component's main div. * @param event the original mouse event. */ public onComponentContextMenu(_: React.MouseEvent<HTMLDivElement, MouseEvent>): void { // Empty for now. } /** * Called on the user pressed the delete key on the asset. * @param item defines the item being deleted. */ public onDeleteAsset(_: IAssetComponentItem): void { // Empty for now... } /** * Called on an asset item has been drag'n'dropped on graph component. * @param data defines the data of the asset component item being drag'n'dropped. * @param nodes defines the array of nodes having the given item being drag'n'dropped. */ public onGraphDropAsset(_: IAssetComponentItem, __: (Scene | Node)[]): boolean { return false; } /** * Renders the component. */ public render(): React.ReactNode { // Filter const filter = this._filter.toLowerCase(); if (filter !== "") { this._itemsNodes = this.state.items.filter((i) => i.id.toLowerCase().indexOf(filter) !== -1) .map((i) => this._getItemNode(i)); } else { this._itemsNodes = this.state.items.map((i) => this._getItemNode(i)); } // Render! const size = this.editor.getPanelSize("assets"); if (!this._itemsNodes.length) { return ( <div style={{ width: "100%", height: "100%" }} onContextMenu={(e) => this.onComponentContextMenu(e)}> <h1 style={{ float: "left", left: "50%", top: "50%", transform: "translate(-50%, -50%)", overflow: "hidden", position: "relative", fontFamily: "Roboto,sans-serif !important", opacity: "0.5", color: "white", }}>Empty</h1> </div> ); } return ( <div style={{ width: "100%", height: size.height - 60, overflow: "auto", ...this.props.style }} children={this._itemsNodes} onContextMenu={(e) => this.onComponentContextMenu(e)} onClick={() => { this.state.items.forEach((i) => i.isSelected = false); this.setState({ items: this.state.items }); }} ></div> ); } /** * Called on the component did mount. */ public componentDidMount(): void { this.resize(); if (this.editor.scene) { this.refresh(); } } /** * Sets the new filter on the user wants to filter the assets. * @param filter the new filter to search assets. */ public setFilter(filter: string): void { this._filter = filter; this.setState({ items: this.items }); } /** * Resizes the element. */ public resize(): void { this.setState({ height: this.editor.getPanelSize("assets").height }); } /** * Updates the given item thumbnail. * @param key defines the key (identifier) or the item to update. * @param base64 defines the new base64 value of the thumbnail. */ public updateAssetThumbnail(key: string, base64: string): void { const items = this.state.items?.slice() ?? []; const item = items.find((i) => i.key === key); if (item) { item.base64 = base64; this.setState({ items }); } } /** * Returns the jsx element according to the given component item. */ private _getItemNode(item: IAssetComponentItem): JSX.Element { const popoverContent = ( <div style={{ padding: "15px" }}> {this.getItemTooltipContent(item) ?? item.id} </div> ); return ( <div key={item.key} ref={(ref) => item.ref = ref} style={{ float: "left", margin: "10px", borderRadius: "10px", position: "relative", width: `${this.size}px`, height: `${this.size + 15}px`, outlineStyle: item.isSelected ? "groove" : undefined, outlineColor: "#48aff0", outlineWidth: "3px", }} onMouseOver={() => item.ref && (item.ref.style.outlineStyle = "groove")} onMouseLeave={() => item.ref && !item.isSelected && (item.ref.style.outlineStyle = "unset")} > <Popover content={popoverContent} usePortal interactionKind="hover" isOpen={item.popoverEnabled ? undefined : item.popoverEnabled} hoverOpenDelay={1000} minimal autoFocus enforceFocus canEscapeKeyClose boundary="window"> <img src={item.base64} style={{ outlineWidth: "2px", borderRadius: "15px", objectFit: "contain", width: `${this.size}px`, outlineColor: "#48aff0", height: `${this.size}px`, ...item.style ?? {}, }} onClick={(e) => this._handleClick(item, e)} onDoubleClick={(e) => this.onDoubleClick(item, e.target as HTMLImageElement)} onContextMenu={(e) => this.onContextMenu(item, e)} onDragStart={(e) => this.dragStart(e, item)} onDragEnd={(e) => this.dragEnd(e)} onDrop={() => this._itemBeingDragged && this.dropOver(item, this.itemBeingDragged!)} onDragEnter={() => this._itemBeingDragged && this.dragEnter(item)} onDragLeave={() => this._itemBeingDragged && this.dragLeave(item)} onKeyDown={(ev) => ev.keyCode === 46 && this.onDeleteAsset(item)} ></img> </Popover> <small style={{ float: "left", width: `${this.size}px`, left: "50%", top: "8px", transform: "translate(-50%, -50%)", textOverflow: "ellipsis", whiteSpace: "nowrap", overflow: "hidden", position: "relative", }}>{item.id}</small> </div> ); } /** * Called on the user clicks on the asset. */ private _handleClick(item: IAssetComponentItem, ev: React.MouseEvent<HTMLImageElement, MouseEvent>): void { ev.stopPropagation(); this.items.forEach((i) => { i.isSelected = false; }); item.isSelected = true; this.setState({ items: this.state.items }); this.onClick(item, ev.target as HTMLImageElement); } /** * Returns the current item that is being dragged. */ protected get itemBeingDragged(): Nullable<IAssetComponentItem> { return this._itemBeingDragged; } /** * Returns the content of the item's tooltip on the pointer is over the given item. * @param item defines the reference to the item having the pointer over. */ protected getItemTooltipContent(_: IAssetComponentItem): Undefinable<JSX.Element> { return undefined; } /** * Called on the user starts dragging the asset. */ protected dragStart(e: React.DragEvent<HTMLImageElement>, item: IAssetComponentItem): void { this._dropListener = this._getDropListener(item); this._itemBeingDragged = item; e.dataTransfer.setData(this.dragAndDropType, JSON.stringify({ id: item.id, key: item.key, extraData: item.extraData, assetComponentId: this.props.id, } as IDragAndDroppedAssetComponentItem)); this.editor.engine!.getRenderingCanvas()?.addEventListener("drop", this._dropListener); this.items.forEach((i) => { i.isSelected = false; i.popoverEnabled = false; }); item.isSelected = true; this.setState({ items: this.state.items }); } /** * Called on the currently dragged item is over the given item. * @param item the item having the currently dragged item over. */ protected dragEnter(_: IAssetComponentItem): void { // Nothing to do now... } /** * Called on the currently dragged item is out the given item. * @param item the item having the currently dragged item out. */ protected dragLeave(_: IAssetComponentItem): void { // Nothing to do now... } /** * Called on the currently dragged item has been dropped. * @param item the item having the currently dragged item dropped over. * @param droppedItem the item that has been dropped. */ protected dropOver(_: IAssetComponentItem, __: IAssetComponentItem): void { // Nothing to do now... } /** * Called on the user ends dragging the asset. * @param e defines the reference to the drag'n'drop event. */ protected dragEnd(e: React.DragEvent<HTMLImageElement>): void { e.dataTransfer?.clearData(); this.editor.engine!.getRenderingCanvas()?.removeEventListener("drop", this._dropListener!); this._dropListener = null; this._itemBeingDragged = null; this.items.forEach((i) => i.popoverEnabled = true); this.setState({ items: this.state.items }); } /** * Called on an item has been dropped on the game's canvas. */ private _getDropListener(item: IAssetComponentItem): (ev: DragEvent) => void { return (ev: DragEvent) => { const pick = this.editor.scene!.pick( ev.offsetX, ev.offsetY, undefined, false, ); if (!pick) { return; } if (!pick.pickedMesh) { pick.pickedPoint = Vector3.Zero(); } this.onDropAsset(item, pick); }; } }
the_stack
import { createGetPluginByName } from "@/corePlugins" import * as extractColors from "@/extractColors" import { dlv } from "@/get_set" import { defaultLogger as console } from "@/logger" import { importFrom } from "@/module" import chroma from "chroma-js" import type { Postcss, Result, Rule } from "postcss" import type { Processor } from "postcss-selector-parser" import { URI } from "vscode-uri" const colorProps = [ "background-color", "color", "border-color", "border-top-color", "border-right-color", "border-bottom-color", "border-left-color", "text-decoration-color", "accent-color", "caret-color", "fill", "stroke", "outline-color", "stop-color", "column-rule-color", "--tw-ring-color", "--tw-ring-offset-color", "--tw-gradient-from", "--tw-gradient-to", "--tw-gradient-stops", ] export type ColorDesc = { color?: string backgroundColor?: string borderColor?: string } type Awaited<T> = T extends PromiseLike<infer U> ? U : T export type TwContext = Awaited<ReturnType<typeof createTwContext>> export async function createTwContext(config: Tailwind.ResolvedConfigJS, extensionUri: URI) { const parser = importFrom("postcss-selector-parser", { base: extensionUri.fsPath, }) const postcss: Postcss = importFrom("postcss", { base: extensionUri.fsPath, }) const tailwindcss: Tailwind.tailwindcss = importFrom("tailwindcss", { base: extensionUri.fsPath, }) const createContext: Tailwind.createContext = importFrom("tailwindcss/lib/jit/lib/setupContextUtils", { base: extensionUri.fsPath, }).createContext const generateRules: Tailwind.generateRules = importFrom("tailwindcss/lib/jit/lib/generateRules", { base: extensionUri.fsPath, }).generateRules const variables = new Set<string>() const classnames = new Set<string>() const _colors = new Map<string, Map<string, string[]>>() const colors = new Map<string, ColorDesc>() const __config = { ...config } __config.separator = "☕" const re = new RegExp(`^([\\w-]+${__config.separator})+`, "g") if (typeof __config.prefix === "function") { console.info("function prefix is not supported.") } if (typeof __config.prefix === "function") { const getPrefix = __config.prefix __config.prefix = function (classname: string) { const prefix = getPrefix(classname) fn(prefix, classname) return prefix function fn(prefix: string, classname: string) { // } } } else if (typeof __config.prefix !== "string") { __config.prefix = "" } __config.mode = "aot" const selectorProcessor: Processor = parser() let result = await postcss([tailwindcss(__config)]).process("@base;@tailwind components;@tailwind utilities;", { from: undefined, }) process(result) __config.mode = "jit" const extended = ["transform-cpu"].concat( Array.from(["border-t", "border-b", "border-l", "border-r"]) .map(b => getColorNames(config).map(c => `${config.prefix}${b}-${c}`)) .flat(), ) __config.purge = { content: [], safelist: extended } result = await postcss([tailwindcss(__config)]).process("@base;@tailwind components;@tailwind utilities;", { from: undefined, }) process(result) __config.mode = "jit" const context = createContext(__config) const _getPlugin = createGetPluginByName(__config) const screens = Object.keys(__config.theme.screens).sort(screenSorter) const restVariants = Array.from(context.variantMap.keys()).filter( key => screens.indexOf(key) === -1 && key !== "dark" && key !== "light" && key !== "placeholder", ) const variants: [string[], string[], string[], string[]] = [ screens, ["dark", "light"], ["placeholder"], restVariants, ] return { variants, classnames, variables, context, screens, colors, isVariant, renderVariant, renderClassname, renderCssProperty, renderDecls, escape, getPlugin(classname: string) { return _getPlugin(classname, trimPrefix) }, getColorDesc, getTheme, getConfig, trimPrefix, } function trimPrefix(classname: string): string { if (typeof __config.prefix === "function") { return classname } return classname.slice(__config.prefix.length) } function process(result: Result) { result.root.walkRules(rule => { const { nodes } = selectorProcessor.astSync(rule) for (let i = 0; i < nodes.length; i++) { for (let j = 0; j < nodes[i].nodes.length; j++) { const node = nodes[i].nodes[j] if (node.type === "class") { const classname = node.value.replace(re, "") classnames.add(classname) if (!colors.has(classname)) { const decls = _getDecls(rule) if (isColorDecls(decls)) { _colors.set(classname, decls) const desc = getColorDesc(classname) if (desc) colors.set(classname, desc) } } } } } }) } function indent(tabSize: number, value: string) { return value .split(/(\r\n|\n)/g) .map(line => line.replace(/^(\t| {4})+/g, match => "".padStart((match.length >> 2) * tabSize))) .join("") } function getColorNames(resloved: Tailwind.ResolvedConfigJS): string[] { const colors = resloved.theme.colors const names: string[] = [] // eslint-disable-next-line @typescript-eslint/no-explicit-any function pr(c: any, prefix = "") { for (const key in c) { if (key === "DEFAULT") { names.push(prefix.slice(0, -1)) continue } if (typeof c[key] === "string" || typeof c[key] === "number" || typeof c[key] === "function") { if (prefix) { names.push(`${prefix}${key}`) } else { names.push(key) } } else if (c[key] instanceof Array) { // } else if (typeof c[key] === "object") { pr(c[key], key + "-") } } } pr(colors) return names } function _getDecls(rule: Rule) { const decls = new Map<string, string[]>() rule.walkDecls(({ prop, value, variable, important }) => { const values = decls.get(prop) if (values) { values.push(value) } else { decls.set(prop, [value]) } if (variable) { variables.add(prop) } }) return decls } function getDecls(classname: string) { const items = generateRules([classname], context).sort(([a], [b]) => { if (a < b) { return -1 } else if (a > b) { return 1 } else { return 0 } }) const root = postcss.root({ nodes: items.map(([, rule]) => rule) }) const decls = new Map<string, string[]>() root.walkDecls(({ prop, value, variable, important }) => { const values = decls.get(prop) if (values) { values.push(value) } else { decls.set(prop, [value]) } }) return decls } function isColorDecls(decls: Map<string, string[]>) { for (const [prop] of decls) { if (colorProps.indexOf(prop) !== -1) { return true } } return false } function getColorDecls(classname: string) { const decls = _colors.get(classname) if (decls) return decls return getDecls(classname) } function getColorDesc(classname: string) { if (!classnames.has(classname)) { return undefined } const cached = colors.get(classname) if (cached) { colors.delete(classname) colors.set(classname, cached) return cached } function addCache(key: string, value: ColorDesc) { if (colors.size >= 16000) { const first = colors.keys().next().value colors.delete(first) colors.set(key, value) } } const decls = getColorDecls(classname) if (!decls) return undefined const desc: ColorDesc = {} const props = Array.from(decls.keys()) const isForeground = props.some(prop => prop === "color") const isBackground = props.some(prop => prop.startsWith("background")) const isBorder = props.some(prop => prop.startsWith("border") || prop === "text-decoration-color") const isOther = !isForeground && !isBackground && !isBorder if (classname.endsWith("-current")) { if (isForeground) { desc.color = "currentColor" } if (isBorder) { desc.borderColor = "currentColor" } if (isBackground || isOther) { desc.backgroundColor = "currentColor" } addCache(classname, desc) return desc } if (classname.endsWith("-inherit")) { if (isForeground) { desc.color = "inherit" } if (isBorder) { desc.borderColor = "inherit" } if (isBackground || isOther) { desc.backgroundColor = "inherit" } addCache(classname, desc) return desc } if (classname.endsWith("-transparent")) { if (isForeground) { desc.color = "transparent" } if (isBorder) { desc.borderColor = "transparent" } if (isBackground || isOther) { desc.backgroundColor = "transparent" } addCache(classname, desc) return desc } for (const values of decls.values()) { for (const value of values) { const colors = extractColors.default(value) if (colors.length <= 0) { continue } const firstColor = colors[0] let color: chroma.Color | undefined if (extractColors.isColorIdentifier(firstColor) || extractColors.isColorHexValue(firstColor)) { if (value.slice(firstColor.range[0], firstColor.range[1]) === "transparent") { if (isBorder) { desc.borderColor = "transparent" } if (isForeground) { desc.color = "transparent" } if (isBackground || isOther) { desc.backgroundColor = "transparent" } continue } try { color = chroma(value.slice(firstColor.range[0], firstColor.range[1])).alpha(1.0) } catch {} } else { try { if (firstColor.fnName.startsWith("rgb")) { color = chroma(+firstColor.args[0], +firstColor.args[1], +firstColor.args[2]) } else { color = chroma(`hsl(${firstColor.args.slice(0, 3).join()})`) } } catch {} } if (!color) continue const val = color.hex() if (isBorder) { desc.borderColor = val } if (isForeground) { desc.color = val } if (isBackground || isOther) { desc.backgroundColor = val } } } addCache(classname, desc) return desc } function screenSorter(a: string, b: string) { function getWidth(value: string) { const match = value.match(/@media\s+\(.*width:\s*(\d+)px/) if (match != null) { const [, px] = match return Number(px) } return 0 } return getWidth(renderVariant(a)) - getWidth(renderVariant(b)) } function escape(classname: string): string { const node = parser.attribute() node.value = classname return node.raws.value } function renderVariant(variant: string, tabSize = 4) { const data: string[] = [] const meta = context.variantMap.get(variant) if (!meta) { return "" } const fakeRoot = postcss.root({ nodes: [ postcss.rule({ selector: ".☕", }), ], }) const re = new RegExp( ("." + escape(variant + __config.separator + "☕")).replace(/[/\\^$+?.()|[\]{}]/g, "\\$&"), "g", ) for (const [, fn] of meta) { const container = fakeRoot.clone() fn({ container, separator: __config.separator }) container.walkDecls(decl => { decl.remove() }) container.walk(node => { switch (node.type) { case "atrule": data.push(`@${node.name} ${node.params}`) return false case "rule": data.push(node.selector.replace(re, "&")) } return }) } return indent(tabSize, data.join(", ") + " {\n /* ... */\n}") } function toPixelUnit(cssValue: string, rootFontSize: number) { if (rootFontSize <= 0) { return cssValue } const reg = /(-?\d[.\d+e]*)rem/ const match = reg.exec(cssValue) if (!match) { return cssValue } const [text, n] = match const val = parseFloat(n) if (Number.isNaN(val)) { return cssValue } return cssValue.replace(reg, text + `/** ${(rootFontSize * val).toFixed(0)}px */`) } function renderClassname({ classname, important = false, rootFontSize = 0, tabSize = 4, }: { classname: string important?: boolean rootFontSize?: number tabSize?: number }) { const items = generateRules([classname], context).sort(([a], [b]) => { if (a < b) { return -1 } else if (a > b) { return 1 } else { return 0 } }) const root = postcss.root({ nodes: items.map(([, rule]) => rule) }) root.walkAtRules("defaults", rule => { rule.remove() }) if (important || rootFontSize) { root.walkDecls(decl => { decl.important = important decl.value = toPixelUnit(decl.value, rootFontSize) }) } return indent(tabSize, root.toString()) } function renderCssProperty({ prop, value, important, rootFontSize, tabSize = 4, }: { prop: string value: string important?: boolean rootFontSize?: number tabSize?: number }) { const decl = postcss.decl() decl.prop = prop decl.value = value if (important) decl.important = important if (rootFontSize) decl.value = toPixelUnit(decl.value, rootFontSize) const rule = postcss.rule() rule.selector = "&" rule.append(decl) const root = postcss.root({ nodes: [rule] }) return indent(tabSize, root.toString()) } function renderDecls(classname: string) { const items = generateRules([classname], context).sort(([a], [b]) => { if (a < b) { return -1 } else if (a > b) { return 1 } else { return 0 } }) const root = postcss.root({ nodes: items.map(([, rule]) => rule) }) const decls: Map<string, string[]> = new Map() root.walkDecls(({ prop, value, variable, important }) => { const values = decls.get(prop) if (values) { values.push(value) } else { decls.set(prop, [value]) } if (variable) { variables.add(prop) } }) return decls } function isVariant(value: string) { return context.variantMap.has(value) } /** * get theme value. * * example: ```getTheme(["colors", "blue", "500"])``` * @param keys */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function getTheme(keys: string[], useDefault = false) { if (!config) { return undefined } let value = dlv(config.theme, keys) if (useDefault && value?.["DEFAULT"] != undefined) { value = value["DEFAULT"] } return value } function getConfig(keys: string[]) { if (!config) { return undefined } return dlv(config, keys) } }
the_stack
import path from 'path' import { workspace, window, WorkspaceEdit, RelativePattern } from 'vscode' import fg from 'fast-glob' import _, { uniq, throttle, set } from 'lodash' import fs from 'fs-extra' import { findBestMatch } from 'string-similarity' import { FILEWATCHER_TIMEOUT } from '../../meta' import { ParsedFile, PendingWrite, DirStructure, TargetPickingStrategy } from '../types' import { LocaleTree } from '../Nodes' import { AllyError, ErrorType } from '../Errors' import { Analyst, Global, Config } from '..' import { Telemetry, TelemetryKey } from '../Telemetry' import { Loader } from './Loader' import { ReplaceLocale, Log, applyPendingToObject, unflatten, NodeHelper, getCache, setCache } from '~/utils' import i18n from '~/i18n' const THROTTLE_DELAY = 1500 export class LocaleLoader extends Loader { private _files: Record<string, ParsedFile> = {} private _path_matchers: {regex: RegExp; matcher: string}[] = [] private _dir_structure: DirStructure = 'file' private _locale_dirs: string[] = [] constructor(public readonly rootpath: string) { super(`[LOCALE]${rootpath}`) } async init() { if (await this.findLocaleDirs()) { Log.info(`🚀 Initializing loader "${this.rootpath}"`) this._dir_structure = await this.guessDirStructure() Log.info(`📂 Directory structure: ${this._dir_structure}`) if (Config._pathMatcher) Log.info(`🗃 Custom Path Matcher: ${Config._pathMatcher}`) this._path_matchers = Global.getPathMatchers(this._dir_structure) Log.info(`🗃 Path Matcher Regex: ${this._path_matchers.map(i => i.regex)}`) await this.loadAll() } this.update() Log.divider() } get localesPaths() { return Global.localesPaths } get files() { return Object.values(this._files) } get locales() { // sort by source, display and others by alpha const source = Config.sourceLanguage const display = Config.displayLanguage const allLocales = _(this._files) .values() .map(f => f.locale) .uniq() .sort() .value() const locales = allLocales .filter(i => i !== source && i !== display) if (allLocales.includes(display)) locales.unshift(display) if (display !== source && allLocales.includes(source)) locales.unshift(source) return locales } // #region throttled functions private throttledFullReload = throttle(async() => { Log.info('🔄 Perfroming a full reload', 2) await this.loadAll(false) this.update() }, THROTTLE_DELAY, { leading: true }) private throttledUpdate = throttle(() => { this.update() }, THROTTLE_DELAY, { leading: true }) private throttledLoadFileWaitingList: [string, string][] = [] private throttledLoadFileExecutor = throttle(async() => { const list = this.throttledLoadFileWaitingList this.throttledLoadFileWaitingList = [] if (list.length) { let changed = false for (const [d, r] of list) changed = await this.loadFile(d, r) || changed if (changed) this.update() } }, THROTTLE_DELAY, { leading: true }) private throttledLoadFile = (d: string, r: string) => { if (!this.throttledLoadFileWaitingList.find(([a, b]) => a === d && b === r)) this.throttledLoadFileWaitingList.push([d, r]) this.throttledLoadFileExecutor() } // #endregion private getFilepathsOfLocale(locale: string) { // TODO: maybe shadow options return Object.values(this._files) .filter(f => f.locale === locale) .map(f => f.filepath) } async guessDirStructure(): Promise<DirStructure> { const POSITIVE_RATE = 0.6 const config = Global.dirStructure if (config !== 'auto') return config const dir = this._locale_dirs[0] const dirnames = await fg('*', { onlyDirectories: true, cwd: dir, deep: 1, ignore: Config.ignoreFiles, }) const total = dirnames.length if (total === 0) return 'file' const positives = dirnames .map(d => Config.tagSystem.lookup(d)) const positive = positives .filter(d => d) .length // if there are some dirs are named as locale code, guess it's dir mode return (positive / total) >= POSITIVE_RATE ? 'dir' : 'file' } async requestMissingFilepath(pending: PendingWrite) { const { locale, keypath } = pending // try to match namespaces if (Config.namespace) { const namespace = pending.namespace || this.getNodeByKey(keypath)?.meta?.namespace const filesSameLocale = this.files.find(f => f.namespace === namespace && f.locale === locale) if (filesSameLocale) return filesSameLocale.filepath const fileSource = this.files.find(f => f.namespace === namespace && f.locale === Config.sourceLanguage) if (fileSource && fileSource.matcher) { const relative = path.relative(fileSource.dirpath, fileSource.filepath) const newFilepath = ReplaceLocale(relative, fileSource.matcher, locale, Global.enabledParserExts) return path.join(fileSource.dirpath, newFilepath) } } const paths = this.getFilepathsOfLocale(locale) if (paths.length === 1) return paths[0] if (paths.length === 0) { return await window.showInputBox({ prompt: i18n.t('prompt.enter_file_path_to_store_key', keypath), placeHolder: `path/to/${locale}.json`, ignoreFocusOut: true, }) } if (Config.targetPickingStrategy === TargetPickingStrategy.MostSimilar && pending.textFromPath) return this.findBestMatchFile(pending.textFromPath, paths) if (Config.targetPickingStrategy === TargetPickingStrategy.FilePrevious && pending.textFromPath) return this.handleExtractToFilePrevious(pending.textFromPath, paths, keypath) if (Config.targetPickingStrategy === TargetPickingStrategy.GlobalPrevious) return this.handleExtractToGlobalPrevious(paths, keypath) return await this.promptPathToSave(paths, keypath) } async promptPathToSave(paths: string[], keypath: string) { const result = await window.showQuickPick( paths.map(i => ({ label: `$(file) ${path.basename(i)}`, description: path.relative(this.rootpath, i), path: i, })), { placeHolder: i18n.t('prompt.select_file_to_store_key', keypath), ignoreFocusOut: true, }) return result?.path } /** * Extract text to current file's previous selected locale file * @param fromPath: path of current extracting file * @param paths: paths of locale files * @param keypath */ async handleExtractToFilePrevious(fromPath: string, paths: string[], keypath: string): Promise<string | void> { const cacheKey = 'perFilePickingTargets' const pickingTargets: any = getCache(cacheKey, {}) const cachedPath = pickingTargets[fromPath] if (cachedPath) return cachedPath const newPath = await this.promptPathToSave(paths, keypath) pickingTargets[fromPath] = newPath setCache(cacheKey, pickingTargets) return newPath } /** * Extract text to previous selected locale file (includes selection made in other files) * @param paths: paths of locale files * @param keypath */ async handleExtractToGlobalPrevious(paths: any, keypath: string): Promise<string | void> { const cacheKey = 'globalPickingTargets' const pickingTarget = getCache<string>(cacheKey) if (pickingTarget) return pickingTarget const newPath = await this.promptPathToSave(paths, keypath) setCache(cacheKey, newPath) return newPath } findBestMatchFile(fromPath: string, paths: string[]): string { return findBestMatch(fromPath, paths).bestMatch.target } async write(pendings: PendingWrite|PendingWrite[]) { if (!Array.isArray(pendings)) pendings = [pendings] pendings = pendings.filter(i => i) const distributed: Record<string, PendingWrite[]> = {} // distribute pendings writes by files for (const pending of pendings) { const filepath = pending.filepath || await this.requestMissingFilepath(pending) if (!filepath) { Log.info(`💥 Unable to find path for writing ${JSON.stringify(pending)}`) continue } if (Config.namespace) pending.namespace = pending.namespace || this._files[filepath]?.namespace if (!distributed[filepath]) distributed[filepath] = [] distributed[filepath].push(pending) } try { for (const [filepath, pendings] of Object.entries(distributed)) { const ext = path.extname(filepath) const parser = Global.getMatchedParser(ext) if (!parser) throw new AllyError(ErrorType.unsupported_file_type, undefined, ext) if (parser.readonly || Config.readonly) throw new AllyError(ErrorType.write_in_readonly_mode) Log.info(`💾 Writing ${filepath}`) let original: any = {} if (fs.existsSync(filepath)) { original = await parser.load(filepath) original = this.preprocessData(original, { locale: pendings[0].locale, targetFile: filepath, }) } let modified = original for (const pending of pendings) { let keypath = pending.keypath if (Global.namespaceEnabled) { const node = this.getNodeByKey(keypath) keypath = NodeHelper.getPathWithoutNamespace(keypath, node, pending.namespace) } modified = applyPendingToObject( modified, keypath, pending.value, await Global.requestKeyStyle(), ) } const locale = pendings[0].locale const processingContext = { locale, targetFile: filepath } const processed = this.deprocessData(modified, processingContext) await parser.save(filepath, processed, Config.sortKeys) if (this._files[filepath]) { this._files[filepath].value = modified this._files[filepath].mtime = this.getMtime(filepath) } } } catch (e) { this.update() throw e } this.update() } canHandleWrites(pending: PendingWrite) { return !pending.features?.VueSfc && !pending.features?.FluentVueSfc } async renameKey(oldkey: string, newkey: string) { const edit = new WorkspaceEdit() oldkey = this.rewriteKeys(oldkey, 'source') newkey = this.rewriteKeys(newkey, 'reference') const locations = await Analyst.getAllOccurrenceLocations(oldkey) for (const location of locations) edit.replace(location.uri, location.range, newkey) this.renameKeyInLocales(oldkey, newkey) return edit } async renameKeyInLocales(oldkey: string, newkey: string) { const writes = _(this._files) .entries() .flatMap(([filepath, file]) => { const value = _.get(file.value, oldkey) if (value === undefined) return [] return [{ value: undefined, keypath: oldkey, filepath, locale: file.locale, }, { value: _.get(file.value, oldkey), keypath: newkey, filepath, locale: file.locale, }] }) .value() if (!writes.length) return await this.write(writes) } getNamespaceFromFilepath(filepath: string) { const file = this._files[filepath] if (file) return file.namespace } private getFileInfo(dirpath: string, relativePath: string) { const fullpath = path.resolve(dirpath, relativePath) const ext = path.extname(relativePath) let match: RegExpExecArray | null = null let matcher: string | undefined for (const r of this._path_matchers) { match = r.regex.exec(relativePath) if (match && match.length > 0) { matcher = r.matcher break } } if (!match || match.length < 1) return let namespace = match.groups?.namespace if (namespace) namespace = namespace.replace(/\//g, '.') let locale = match.groups?.locale if (locale) locale = Config.normalizeLocale(locale, '') else locale = Config.sourceLanguage if (!locale) return const parser = Global.getMatchedParser(ext) return { locale, parser, ext, namespace, fullpath, matcher, } } private async loadFile(dirpath: string, relativePath: string) { try { const result = this.getFileInfo(dirpath, relativePath) if (!result) return const { locale, parser, namespace, fullpath: filepath, matcher } = result if (!parser) return if (!locale) return const mtime = this.getMtime(filepath) Log.info(`📑 Loading (${locale}) ${relativePath} [${mtime}]`, 1) let data = await parser.load(filepath) data = this.preprocessData(data, { locale, targetFile: filepath }) const value = Config.disablePathParsing ? data : unflatten(data) this._files[filepath] = { filepath, dirpath, locale, value, mtime, namespace, readonly: parser.readonly || Config.readonly, matcher, } return true } catch (e) { this.unsetFile(relativePath) Log.info(`🐛 Failed to load ${e}`, 2) // eslint-disable-next-line no-console console.error(e) } } private unsetFile(filepath: string) { delete this._files[filepath] } private async loadDirectory(searchingPath: string) { const files = await fg('**/*.*', { cwd: searchingPath, onlyFiles: true, ignore: [ 'node_modules/**', 'vendors/**', ...Config.ignoreFiles, ], deep: Config.includeSubfolders ? undefined : 2, }) for (const relative of files) await this.loadFile(searchingPath, relative) } private getMtime(filepath: string) { try { return fs.statSync(filepath).mtimeMs } catch { return 0 } } private getRelativePath(filepath: string) { let dirpath = this._locale_dirs.find(dir => filepath.startsWith(dir)) if (!dirpath) return let relative = path.relative(dirpath, filepath) if (process.platform === 'win32') { relative = relative.replace(/\\/g, '/') dirpath = dirpath.replace(/\\/g, '/') } return { dirpath, relative } } private async onFileChanged(type: string, { fsPath: filepath }: { fsPath: string }) { filepath = path.resolve(filepath) // not tracking if (type !== 'create' && !this._files[filepath]) return // already up-to-date if (type !== 'change' && this._files[filepath]?.mtime === this.getMtime(filepath)) { Log.info(`🔄 Skipped on loading "${filepath}" (same mtime)`) return } const { dirpath, relative } = this.getRelativePath(filepath) || {} if (!dirpath || !relative) return Log.info(`🔄 File changed (${type}) ${relative}`) // full reload if configured if (Config.fullReloadOnChanged && ['delete', 'change', 'create'].includes(type)) { this.throttledFullReload() return } switch (type) { case 'delete': delete this._files[filepath] this.throttledUpdate() break case 'create': case 'change': this.throttledLoadFile(dirpath, relative) break } } private async watchOn(rootPath: string) { Log.info(`\n👀 Watching change on ${rootPath}`) const watcher = workspace.createFileSystemWatcher( new RelativePattern(rootPath, '**/*'), ) watcher.onDidChange((e: any) => setTimeout(() => this.onFileChanged('change', e), FILEWATCHER_TIMEOUT), this, this._disposables) watcher.onDidCreate((e: any) => setTimeout(() => this.onFileChanged('create', e), FILEWATCHER_TIMEOUT), this, this._disposables) watcher.onDidDelete((e: any) => setTimeout(() => this.onFileChanged('delete', e), FILEWATCHER_TIMEOUT), this, this._disposables) this._disposables.push(watcher) } private updateLocalesTree() { this._flattenLocaleTree = {} const root = new LocaleTree({ keypath: '' }) if (Global.namespaceEnabled) { const namespaces = uniq(this.files.map(f => f.namespace)) as string[] for (const ns of namespaces) { const files = this.files.filter(f => f.namespace === ns) for (const file of files) { const value = ns ? set({}, ns, file.value) : file.value this.updateTree(root, value, '', '', { ...file, meta: { namespace: file.namespace } }) } } } else { for (const file of Object.values(this._files)) this.updateTree(root, file.value, '', '', file) } this._localeTree = root } private update() { try { this.updateLocalesTree() this._onDidChange.fire(this.name) Log.info('✅ Loading finished\n') } catch (e) { Log.error(e) } } private async findLocaleDirs() { this._files = {} this._locale_dirs = [] const localesPaths = this.localesPaths if (localesPaths?.length) { try { const _locale_dirs = await fg(localesPaths, { cwd: this.rootpath, onlyDirectories: true, }) if (localesPaths.includes('.')) _locale_dirs.push('.') this._locale_dirs = uniq( _locale_dirs .map(p => path.resolve(this.rootpath, p)), ) } catch (e) { Log.error(e) } } if (this._locale_dirs.length === 0) { Log.info('\n⚠ No locales paths.') return false } return true } private async loadAll(watch = true) { for (const pathname of this._locale_dirs) { try { Log.info(`\n📂 Loading locales under ${pathname}`) await this.loadDirectory(pathname) if (watch) this.watchOn(pathname) if (!this.files.length) window.showWarningMessage(i18n.t('prompt.no_locale_loaded')) if (this.files.length && this.keys.length) Telemetry.track(TelemetryKey.Activated) } catch (e) { Log.error(e) } } } }
the_stack
import { Rule, Tree } from '@angular-devkit/schematics'; import { ASM_ACTIONS, ASM_ADAPTER, ASM_AUTH_HTTP_HEADER_SERVICE, ASM_AUTH_SERVICE, ASM_AUTH_STORAGE_SERVICE, ASM_CONFIG, ASM_CONNECTOR, ASM_FEATURE, ASM_OCC_MODULE, ASM_SELECTORS, ASM_SERVICE, ASM_STATE, ASM_STATE_PERSISTENCE_SERVICE, ASM_UI, BUDGET_ROUTING_CONFIG, CART_NOT_EMPTY_GUARD, CLOSE_ACCOUNT_COMPONENT, CLOSE_ACCOUNT_MODULE, COST_CENTER_ROUTING_CONFIG, CS_AGENT_AUTH_SERVICE, CUSTOMER_SEARCH_DATA, CUSTOMER_SEARCH_OPTIONS, CUSTOMER_SEARCH_PAGE, CUSTOMER_SEARCH_PAGE_NORMALIZER, DEFAULT_BUDGET_ROUTING_CONFIG, DEFAULT_COST_CENTER_ROUTING_CONFIG, DEFAULT_PERMISSION_ROUTING_CONFIG, DEFAULT_UNITS_ROUTING_CONFIG, DEFAULT_USER_GROUP_ROUTING_CONFIG, DEFAULT_USER_ROUTING_CONFIG, FORGOT_PASSWORD_MODULE, ITEM, LOGIN_FORM_MODULE, LOGIN_MODULE, LOGIN_REGISTER_COMPONENT, LOGIN_REGISTER_MODULE, OCC_ASM_ADAPTER, ORDER_ENTRY, PERMISSION_ROUTING_CONFIG, PERSONALIZATION_ACTION, PERSONALIZATION_CONFIG, PERSONALIZATION_CONTEXT, PERSONALIZATION_CONTEXT_SERVICE, PRODUCT_VARIANT_STYLE_ICONS_COMPONENT, PRODUCT_VARIANT_STYLE_ICONS_MODULE, QUALTRICS_COMPONENT, QUALTRICS_CONFIG, QUALTRICS_EVENT_NAME, QUALTRICS_LOADER_SERVICE, REGISTER_COMPONENT_MODULE, RESET_PASSWORD_MODULE, SMART_EDIT_SERVICE, STATE_WITH_ASM, SYNCED_ASM_STATE, TOKEN_TARGET, UNITS_ROUTING_CONFIG, UPDATE_EMAIL_MODULE, UPDATE_PASSWORD_MODULE, UPDATE_PROFILE_MODULE, USER_GROUP_ROUTING_CONFIG, USER_ROUTING_CONFIG, VARIANT_STYLE_ICONS_COMPONENT, VARIANT_STYLE_ICONS_MODULE, } from '../../../shared/constants'; import { ASM_MODULE } from '../../../shared/lib-configs/asm-schematics-config'; import { QUALTRICS_MODULE } from '../../../shared/lib-configs/qualtrics-schematics-config'; import { SPARTACUS_ASM, SPARTACUS_CHECKOUT_OLD_COMPONENTS, SPARTACUS_CHECKOUT_OLD_CORE, SPARTACUS_CHECKOUT_OLD_OCC, SPARTACUS_CHECKOUT_OLD_ROOT, SPARTACUS_CORE, SPARTACUS_ORGANIZATION_ADMINISTRATION_COMPONENTS, SPARTACUS_ORGANIZATION_ADMINISTRATION_ROOT, SPARTACUS_PRODUCT, SPARTACUS_QUALTRICS, SPARTACUS_SMARTEDIT, SPARTACUS_STOREFRONTLIB, SPARTACUS_TRACKING, SPARTACUS_USER_ACCOUNT_COMPONENTS, SPARTACUS_USER_PROFILE_COMPONENTS, } from '../../../shared/libs-constants'; import { RenamedSymbol } from '../../../shared/utils/file-utils'; import { migrateRenamedSymbols } from '../../mechanism/rename-symbol/rename-symbol'; export const RENAMED_SYMBOLS_DATA: RenamedSymbol[] = [ // feature-libs/organization/administration/root/config/default-budget-routing.config.ts { previousNode: BUDGET_ROUTING_CONFIG, previousImportPath: SPARTACUS_ORGANIZATION_ADMINISTRATION_COMPONENTS, newNode: DEFAULT_BUDGET_ROUTING_CONFIG, newImportPath: SPARTACUS_ORGANIZATION_ADMINISTRATION_ROOT, }, // feature-libs/organization/administration/root/config/default-cost-center-routing.config.ts { previousNode: COST_CENTER_ROUTING_CONFIG, previousImportPath: SPARTACUS_ORGANIZATION_ADMINISTRATION_COMPONENTS, newNode: DEFAULT_COST_CENTER_ROUTING_CONFIG, newImportPath: SPARTACUS_ORGANIZATION_ADMINISTRATION_ROOT, }, // feature-libs/organization/administration/root/config/default-permission-routing.config.ts { previousNode: PERMISSION_ROUTING_CONFIG, previousImportPath: SPARTACUS_ORGANIZATION_ADMINISTRATION_COMPONENTS, newNode: DEFAULT_PERMISSION_ROUTING_CONFIG, newImportPath: SPARTACUS_ORGANIZATION_ADMINISTRATION_ROOT, }, // feature-libs/organization/administration/root/config/default-units-routing.config.ts { previousNode: UNITS_ROUTING_CONFIG, previousImportPath: SPARTACUS_ORGANIZATION_ADMINISTRATION_COMPONENTS, newNode: DEFAULT_UNITS_ROUTING_CONFIG, newImportPath: SPARTACUS_ORGANIZATION_ADMINISTRATION_ROOT, }, // feature-libs/organization/administration/root/config/default-user-group-routing.config.ts { previousNode: USER_GROUP_ROUTING_CONFIG, previousImportPath: SPARTACUS_ORGANIZATION_ADMINISTRATION_COMPONENTS, newNode: DEFAULT_USER_GROUP_ROUTING_CONFIG, newImportPath: SPARTACUS_ORGANIZATION_ADMINISTRATION_ROOT, }, // feature-libs/organization/administration/root/config/default-user-routing.config.ts { previousNode: USER_ROUTING_CONFIG, previousImportPath: SPARTACUS_ORGANIZATION_ADMINISTRATION_COMPONENTS, newNode: DEFAULT_USER_ROUTING_CONFIG, newImportPath: SPARTACUS_ORGANIZATION_ADMINISTRATION_ROOT, }, // projects/storefrontlib/cms-components/product/config/default-view-config.ts { previousNode: 'defaultScrollConfig', previousImportPath: '@spartacus/storefront', newNode: 'defaultViewConfig', }, // projects/storefrontlib/cms-components/misc/qualtrics/qualtrics-loader.service.ts { previousNode: QUALTRICS_LOADER_SERVICE, previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: `${SPARTACUS_QUALTRICS}/components`, }, // projects/storefrontlib/cms-components/misc/qualtrics/config/qualtrics-config.ts { previousNode: QUALTRICS_CONFIG, previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: `${SPARTACUS_QUALTRICS}/components`, }, // projects/storefrontlib/cms-components/misc/qualtrics/qualtrics-loader.service.ts { previousNode: QUALTRICS_EVENT_NAME, previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: `${SPARTACUS_QUALTRICS}/components`, }, // projects/storefrontlib/cms-components/misc/qualtrics/qualtrics.component.ts { previousNode: QUALTRICS_COMPONENT, previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: `${SPARTACUS_QUALTRICS}/components`, }, // projects/storefrontlib/cms-components/misc/qualtrics/qualtrics.module.ts { previousNode: QUALTRICS_MODULE, previousImportPath: SPARTACUS_STOREFRONTLIB, newNode: 'QualtricsComponentsModule', newImportPath: `${SPARTACUS_QUALTRICS}/components`, }, // projects/storefrontlib/cms-components/asm/asm.module.ts { previousNode: ASM_MODULE, previousImportPath: SPARTACUS_STOREFRONTLIB, newNode: 'AsmComponentsModule', newImportPath: `${SPARTACUS_ASM}/components`, }, // projects/core/src/occ/adapters/asm/asm-occ.module.ts { previousNode: ASM_OCC_MODULE, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/occ`, }, // projects/core/src/occ/adapters/asm/occ-asm.adapter.ts { previousNode: OCC_ASM_ADAPTER, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/occ`, }, // projects/core/src/asm/config/asm-config.ts { previousNode: ASM_CONFIG, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/core`, }, // projects/core/src/asm/connectors/asm.adapter.ts { previousNode: ASM_ADAPTER, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/core`, }, // projects/core/src/asm/connectors/asm.connector.ts { previousNode: ASM_CONNECTOR, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/core`, }, // projects/core/src/asm/connectors/converters.ts { previousNode: CUSTOMER_SEARCH_PAGE_NORMALIZER, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/core`, }, // projects/core/src/asm/facade/asm.service.ts { previousNode: ASM_SERVICE, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/core`, }, // projects/core/src/asm/facade/csagent-auth.service.ts { previousNode: CS_AGENT_AUTH_SERVICE, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/root`, }, // projects/core/src/asm/models/asm.models.ts { previousNode: CUSTOMER_SEARCH_PAGE, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/core`, }, // projects/core/src/asm/models/asm.models.ts { previousNode: CUSTOMER_SEARCH_OPTIONS, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/core`, }, // projects/core/src/asm/models/asm.models.ts { previousNode: ASM_UI, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/core`, }, // projects/core/src/asm/services/asm-auth-http-header.service.ts { previousNode: ASM_AUTH_HTTP_HEADER_SERVICE, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/root`, }, // projects/core/src/asm/services/asm-auth.service.ts { previousNode: TOKEN_TARGET, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/root`, }, // projects/core/src/asm/services/asm-auth-storage.service.ts { previousNode: ASM_AUTH_STORAGE_SERVICE, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/root`, }, // projects/core/src/asm/services/asm-state-persistence.service.ts { previousNode: SYNCED_ASM_STATE, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/core`, }, // projects/core/src/asm/services/asm-state-persistence.service.ts { previousNode: ASM_STATE_PERSISTENCE_SERVICE, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/core`, }, // projects/core/src/asm/store/actions/asm-ui.action.ts // projects/core/src/asm/store/actions/customer.action.ts // projects/core/src/asm/store/actions/logout-agent.action.ts { previousNode: ASM_ACTIONS, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/core`, }, // projects/core/src/asm/store/asm-state.ts { previousNode: ASM_FEATURE, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/core`, }, // projects/core/src/asm/store/asm-state.ts { previousNode: CUSTOMER_SEARCH_DATA, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/core`, }, // projects/core/src/asm/store/asm-state.ts { previousNode: STATE_WITH_ASM, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/core`, }, // projects/core/src/asm/store/asm-state.ts { previousNode: ASM_STATE, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/core`, }, // projects/core/src/asm/store/selectors/asm-ui.selectors.ts // projects/core/src/asm/store/selectors/feature.selector.ts { previousNode: ASM_SELECTORS, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/core`, }, // projects/core/src/asm/services/asm-auth.service.ts { previousNode: ASM_AUTH_SERVICE, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_ASM}/root`, }, // projects/core/src/personalization/config/personalization-config.ts { previousNode: PERSONALIZATION_CONFIG, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_TRACKING}/personalization/root`, }, // projects/core/src/personalization/services/personalization-context.service.ts { previousNode: PERSONALIZATION_CONTEXT_SERVICE, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_TRACKING}/personalization/core`, }, // projects/core/src/personalization/model/personalization-context.model.ts { previousNode: PERSONALIZATION_ACTION, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_TRACKING}/personalization/core`, }, // projects/core/src/personalization/model/personalization-context.model.ts { previousNode: PERSONALIZATION_CONTEXT, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_TRACKING}/personalization/core`, }, // projects/core/src/smart-edit/services/smart-edit.service.ts { previousNode: SMART_EDIT_SERVICE, previousImportPath: SPARTACUS_CORE, newImportPath: `${SPARTACUS_SMARTEDIT}/core`, }, // projects/storefrontlib/cms-components/product/product-variants/variant-style-icons/variant-style-icons.component.ts { previousNode: VARIANT_STYLE_ICONS_COMPONENT, previousImportPath: SPARTACUS_STOREFRONTLIB, newNode: PRODUCT_VARIANT_STYLE_ICONS_COMPONENT, newImportPath: `${SPARTACUS_PRODUCT}/variants/root`, }, // projects/storefrontlib/cms-components/product/product-variants/variant-style-icons/variant-style-icons.module.ts { previousNode: VARIANT_STYLE_ICONS_MODULE, previousImportPath: SPARTACUS_STOREFRONTLIB, newNode: PRODUCT_VARIANT_STYLE_ICONS_MODULE, newImportPath: `${SPARTACUS_PRODUCT}/variants/root`, }, // projects/storefrontlib/cms-components/myaccount/close-account/close-account.module.ts { previousNode: CLOSE_ACCOUNT_MODULE, previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_USER_PROFILE_COMPONENTS, }, // projects/storefrontlib/cms-components/myaccount/forgot-password/forgot-password.module.ts { previousNode: FORGOT_PASSWORD_MODULE, previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_USER_PROFILE_COMPONENTS, }, // projects/storefrontlib/cms-components/user/register/register.module.ts { previousNode: REGISTER_COMPONENT_MODULE, previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_USER_PROFILE_COMPONENTS, }, // projects/storefrontlib/cms-components/myaccount/reset-password/reset-password.module.ts { previousNode: RESET_PASSWORD_MODULE, previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_USER_PROFILE_COMPONENTS, }, // projects/storefrontlib/cms-components/myaccount/update-email/update-email.module.ts { previousNode: UPDATE_EMAIL_MODULE, previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_USER_PROFILE_COMPONENTS, }, // projects/storefrontlib/cms-components/myaccount/update-password/update-password.module.ts { previousNode: UPDATE_PASSWORD_MODULE, previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_USER_PROFILE_COMPONENTS, }, // projects/storefrontlib/cms-components/myaccount/update-profile/update-profile.module.ts { previousNode: UPDATE_PROFILE_MODULE, previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_USER_PROFILE_COMPONENTS, }, // projects/storefrontlib/cms-components/user/login/login.module.ts { previousNode: LOGIN_MODULE, previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_USER_ACCOUNT_COMPONENTS, }, // projects/storefrontlib/cms-components/user/login-form/login-form.module.ts { previousNode: LOGIN_FORM_MODULE, previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_USER_ACCOUNT_COMPONENTS, }, // projects/storefrontlib/cms-components/user/login-register/login-register.module.ts { previousNode: LOGIN_REGISTER_MODULE, previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_USER_ACCOUNT_COMPONENTS, }, // projects/storefrontlib/cms-components/myaccount/close-account/components/close-account/close-account.component.ts { previousNode: CLOSE_ACCOUNT_COMPONENT, previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_USER_PROFILE_COMPONENTS, }, // projects/storefrontlib/cms-components/user/login-register/login-register.component.ts { previousNode: LOGIN_REGISTER_COMPONENT, previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_USER_ACCOUNT_COMPONENTS, }, // projects/storefrontlib/cms-components/cart/cart-shared/cart-item/cart-item.component.ts { previousNode: ITEM, previousImportPath: SPARTACUS_STOREFRONTLIB, newNode: ORDER_ENTRY, newImportPath: SPARTACUS_CORE, }, ]; export const CHECKOUT_LIB_MOVED_SYMBOLS_DATA: RenamedSymbol[] = [ // projects/storefrontlib/cms-components/user/checkout-login/* { previousNode: 'CheckoutLoginComponent', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'CheckoutLoginModule', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, // projects/storefrontlib/cms-components/order-confirmation/* { previousNode: 'OrderConfirmationModule', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'ReplenishmentOrderConfirmationModule', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'OrderConfirmationGuard', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'GuestRegisterFormComponent', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'OrderConfirmationItemsComponent', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'OrderConfirmationOverviewComponent', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'OrderConfirmationThankYouMessageComponent', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'OrderConfirmationTotalsComponent', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, // projects/storefrontlib/cms-components/checkout/* { previousNode: 'CheckoutComponentModule', newNode: 'CheckoutComponentsModule', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'CheckoutOrchestratorComponent', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'CheckoutOrchestratorModule', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'CheckoutOrderSummaryComponent', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'CheckoutOrderSummaryModule', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'CheckoutProgressComponent', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'CheckoutProgressModule', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'CheckoutProgressMobileBottomComponent', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'CheckoutProgressMobileBottomModule', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'CheckoutProgressMobileTopComponent', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'CheckoutProgressMobileTopModule', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'DeliveryModeComponent', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'DeliveryModeModule', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'PaymentMethodComponent', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'PaymentMethodModule', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'PaymentFormComponent', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'PaymentFormModule', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'PlaceOrderComponent', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'PlaceOrderModule', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'ReviewSubmitComponent', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'ReviewSubmitModule', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'ScheduleReplenishmentOrderComponent', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'ScheduleReplenishmentOrderModule', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'CardWithAddress', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'ShippingAddressComponent', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'ShippingAddressModule', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'DeliveryModePreferences', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_ROOT, }, { previousNode: 'CheckoutConfig', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_ROOT, }, { previousNode: 'CheckoutAuthGuard', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'CheckoutStepsSetGuard', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'CheckoutGuard', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'NotCheckoutAuthGuard', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'CheckoutStepType', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_ROOT, }, { previousNode: 'checkoutShippingSteps', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_ROOT, }, { previousNode: 'checkoutPaymentSteps', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_ROOT, }, { previousNode: 'CheckoutStep', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_ROOT, }, { previousNode: 'CheckoutConfigService', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'CheckoutDetailsService', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'CheckoutReplenishmentFormService', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'CheckoutStepService', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, { previousNode: 'ExpressCheckoutService', previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, // projects/core/src/occ/adapters/checkout/* { previousNode: 'CheckoutOccModule', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_OCC, }, { previousNode: 'OccCheckoutCostCenterAdapter', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_OCC, }, { previousNode: 'OccCheckoutDeliveryAdapter', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_OCC, }, { previousNode: 'OccCheckoutPaymentTypeAdapter', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_OCC, }, { previousNode: 'OccCheckoutPaymentAdapter', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_OCC, }, { previousNode: 'OccCheckoutReplenishmentOrderAdapter', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_OCC, }, { previousNode: 'OccCheckoutAdapter', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_OCC, }, { previousNode: 'OccReplenishmentOrderFormSerializer', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_OCC, }, // projects/core/src/checkout/* { previousNode: 'CheckoutModule', newNode: 'CheckoutCoreModule', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CheckoutAdapter', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CheckoutConnector', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CheckoutCostCenterAdapter', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CheckoutCostCenterConnector', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CheckoutDeliveryAdapter', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CheckoutDeliveryConnector', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'DELIVERY_MODE_NORMALIZER', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CheckoutPaymentAdapter', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CheckoutPaymentConnector', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'PAYMENT_DETAILS_SERIALIZER', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CARD_TYPE_NORMALIZER', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'PAYMENT_TYPE_NORMALIZER', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'PaymentTypeAdapter', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'PaymentTypeConnector', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'PaymentTypeConnector', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CheckoutReplenishmentOrderAdapter', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CheckoutReplenishmentOrderConnector', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'REPLENISHMENT_ORDER_FORM_SERIALIZER', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CheckoutEventBuilder', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CheckoutEventModule', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'OrderPlacedEvent', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_ROOT, }, { previousNode: 'CheckoutCostCenterService', newNode: 'CheckoutCostCenterFacade', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_ROOT, }, { previousNode: 'CheckoutDeliveryService', newNode: 'CheckoutDeliveryFacade', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_ROOT, }, { previousNode: 'CheckoutPaymentService', newNode: 'CheckoutPaymentFacade', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_ROOT, }, { previousNode: 'CheckoutService', newNode: 'CheckoutFacade', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_ROOT, }, { previousNode: 'PaymentTypeService', newNode: 'PaymentTypeFacade', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_ROOT, }, { previousNode: 'ClearCheckoutService', newNode: 'ClearCheckoutFacade', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_ROOT, }, { previousNode: 'CheckoutDetails', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CheckoutPageMetaResolver', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CHECKOUT_FEATURE', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CHECKOUT_DETAILS', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'SET_DELIVERY_ADDRESS_PROCESS_ID', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'SET_DELIVERY_MODE_PROCESS_ID', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'SET_SUPPORTED_DELIVERY_MODE_PROCESS_ID', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'SET_PAYMENT_DETAILS_PROCESS_ID', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'GET_PAYMENT_TYPES_PROCESS_ID', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'SET_COST_CENTER_PROCESS_ID', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'PLACED_ORDER_PROCESS_ID', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'StateWithCheckout', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CardTypesState', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CheckoutStepsState', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'PaymentTypesState', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'OrderTypesState', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'PaymentTypesState', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CheckoutState', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CheckoutActions', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, { previousNode: 'CheckoutSelectors', previousImportPath: SPARTACUS_CORE, newImportPath: SPARTACUS_CHECKOUT_OLD_CORE, }, // projects/storefrontlib/cms-components/cart/cart-not-empty.guard.ts { previousNode: CART_NOT_EMPTY_GUARD, previousImportPath: SPARTACUS_STOREFRONTLIB, newImportPath: SPARTACUS_CHECKOUT_OLD_COMPONENTS, }, ]; export function migrate(): Rule { return (tree: Tree) => { return migrateRenamedSymbols(tree, [ ...RENAMED_SYMBOLS_DATA, ...CHECKOUT_LIB_MOVED_SYMBOLS_DATA, ]); }; }
the_stack
import { AccountSetBaseSuper, MsgOpt, WalletStatus } from "./base"; import { AppCurrency, KeplrSignOptions } from "@keplr-wallet/types"; import { BroadcastMode, makeSignDoc, Msg, StdFee, StdSignDoc, } from "@cosmjs/launchpad"; import { DenomHelper } from "@keplr-wallet/common"; import { Dec, DecUtils, Int } from "@keplr-wallet/unit"; import { Any } from "@keplr-wallet/proto-types/google/protobuf/any"; import { AuthInfo, TxRaw, TxBody, Fee, } from "@keplr-wallet/proto-types/cosmos/tx/v1beta1/tx"; import { SignMode } from "@keplr-wallet/proto-types/cosmos/tx/signing/v1beta1/signing"; import { PubKey } from "@keplr-wallet/proto-types/cosmos/crypto/secp256k1/keys"; import { Coin } from "@keplr-wallet/proto-types/cosmos/base/v1beta1/coin"; import { MsgSend } from "@keplr-wallet/proto-types/cosmos/bank/v1beta1/tx"; import { MsgTransfer } from "@keplr-wallet/proto-types/ibc/applications/transfer/v1/tx"; import { MsgDelegate, MsgUndelegate, MsgBeginRedelegate, } from "@keplr-wallet/proto-types/cosmos/staking/v1beta1/tx"; import { MsgWithdrawDelegatorReward } from "@keplr-wallet/proto-types/cosmos/distribution/v1beta1/tx"; import { MsgVote } from "@keplr-wallet/proto-types/cosmos/gov/v1beta1/tx"; import { VoteOption } from "@keplr-wallet/proto-types/cosmos/gov/v1beta1/gov"; import { BaseAccount, Bech32Address, ChainIdHelper, TendermintTxTracer, } from "@keplr-wallet/cosmos"; import { BondStatus } from "../query/cosmos/staking/types"; import { QueriesSetBase, IQueriesStore, CosmosQueries } from "../query"; import { DeepPartial, DeepReadonly } from "utility-types"; import { ChainGetter } from "../common"; import Axios, { AxiosInstance } from "axios"; import deepmerge from "deepmerge"; import { isAddress } from "@ethersproject/address"; import { Buffer } from "buffer/"; export interface CosmosAccount { cosmos: CosmosAccountImpl; } export const CosmosAccount = { use(options: { msgOptsCreator?: ( chainId: string ) => DeepPartial<CosmosMsgOpts> | undefined; queriesStore: IQueriesStore<CosmosQueries>; wsObject?: new (url: string, protocols?: string | string[]) => WebSocket; preTxEvents?: { onBroadcastFailed?: (chainId: string, e?: Error) => void; onBroadcasted?: (chainId: string, txHash: Uint8Array) => void; onFulfill?: (chainId: string, tx: any) => void; }; }): ( base: AccountSetBaseSuper, chainGetter: ChainGetter, chainId: string ) => CosmosAccount { return (base, chainGetter, chainId) => { const msgOptsFromCreator = options.msgOptsCreator ? options.msgOptsCreator(chainId) : undefined; return { cosmos: new CosmosAccountImpl( base, chainGetter, chainId, options.queriesStore, deepmerge<CosmosMsgOpts, DeepPartial<CosmosMsgOpts>>( defaultCosmosMsgOpts, msgOptsFromCreator ? msgOptsFromCreator : {} ), options ), }; }; }, }; export interface CosmosMsgOpts { readonly send: { readonly native: MsgOpt; }; readonly ibcTransfer: MsgOpt; readonly delegate: MsgOpt; readonly undelegate: MsgOpt; readonly redelegate: MsgOpt; // The gas multiplication per rewards. readonly withdrawRewards: MsgOpt; readonly govVote: MsgOpt; } export const defaultCosmosMsgOpts: CosmosMsgOpts = { send: { native: { type: "cosmos-sdk/MsgSend", gas: 80000, }, }, ibcTransfer: { type: "cosmos-sdk/MsgTransfer", gas: 450000, }, delegate: { type: "cosmos-sdk/MsgDelegate", gas: 250000, }, undelegate: { type: "cosmos-sdk/MsgUndelegate", gas: 250000, }, redelegate: { type: "cosmos-sdk/MsgBeginRedelegate", gas: 250000, }, // The gas multiplication per rewards. withdrawRewards: { type: "cosmos-sdk/MsgWithdrawDelegationReward", gas: 140000, }, govVote: { type: "cosmos-sdk/MsgVote", gas: 250000, }, }; type ProtoMsgsOrWithAminoMsgs = { // TODO: Make `aminoMsgs` nullable // And, make proto sign doc if `aminoMsgs` is null aminoMsgs: Msg[]; protoMsgs: Any[]; }; export class CosmosAccountImpl { public broadcastMode: "sync" | "async" | "block" = "sync"; constructor( protected readonly base: AccountSetBaseSuper, protected readonly chainGetter: ChainGetter, protected readonly chainId: string, protected readonly queriesStore: IQueriesStore<CosmosQueries>, protected readonly _msgOpts: CosmosMsgOpts, protected readonly txOpts: { wsObject?: new (url: string, protocols?: string | string[]) => WebSocket; preTxEvents?: { onBroadcastFailed?: (chainId: string, e?: Error) => void; onBroadcasted?: (chainId: string, txHash: Uint8Array) => void; onFulfill?: (chainId: string, tx: any) => void; }; } ) { this.base.registerSendTokenFn(this.processSendToken.bind(this)); } get msgOpts(): CosmosMsgOpts { return this._msgOpts; } protected async processSendToken( amount: string, currency: AppCurrency, recipient: string, memo: string, stdFee: Partial<StdFee>, signOptions?: KeplrSignOptions, onTxEvents?: | ((tx: any) => void) | { onBroadcasted?: (txHash: Uint8Array) => void; onFulfill?: (tx: any) => void; } ): Promise<boolean> { const denomHelper = new DenomHelper(currency.coinMinimalDenom); const hexAdjustedRecipient = (recipient: string) => { const bech32prefix = this.chainGetter.getChain(this.chainId).bech32Config .bech32PrefixAccAddr; if (bech32prefix === "evmos" && recipient.startsWith("0x")) { // Validate hex address if (!isAddress(recipient)) { throw new Error("Invalid hex address"); } const buf = Buffer.from( recipient.replace("0x", "").toLowerCase(), "hex" ); return new Bech32Address(buf).toBech32(bech32prefix); } return recipient; }; switch (denomHelper.type) { case "native": const actualAmount = (() => { let dec = new Dec(amount); dec = dec.mul(DecUtils.getPrecisionDec(currency.coinDecimals)); return dec.truncate().toString(); })(); const msg = { type: this.msgOpts.send.native.type, value: { from_address: this.base.bech32Address, to_address: hexAdjustedRecipient(recipient), amount: [ { denom: currency.coinMinimalDenom, amount: actualAmount, }, ], }, }; await this.sendMsgs( "send", { aminoMsgs: [msg], protoMsgs: [ { typeUrl: "/cosmos.bank.v1beta1.MsgSend", value: MsgSend.encode({ fromAddress: msg.value.from_address, toAddress: msg.value.to_address, amount: msg.value.amount, }).finish(), }, ], }, memo, { amount: stdFee.amount ?? [], gas: stdFee.gas ?? this.msgOpts.send.native.gas.toString(), }, signOptions, this.txEventsWithPreOnFulfill(onTxEvents, (tx) => { if (tx.code == null || tx.code === 0) { // After succeeding to send token, refresh the balance. const queryBalance = this.queries.queryBalances .getQueryBech32Address(this.base.bech32Address) .balances.find((bal) => { return ( bal.currency.coinMinimalDenom === currency.coinMinimalDenom ); }); if (queryBalance) { queryBalance.fetch(); } } }) ); return true; } return false; } async sendMsgs( type: string | "unknown", msgs: | ProtoMsgsOrWithAminoMsgs | (() => Promise<ProtoMsgsOrWithAminoMsgs> | ProtoMsgsOrWithAminoMsgs), memo: string = "", fee: StdFee, signOptions?: KeplrSignOptions, onTxEvents?: | ((tx: any) => void) | { onBroadcastFailed?: (e?: Error) => void; onBroadcasted?: (txHash: Uint8Array) => void; onFulfill?: (tx: any) => void; } ) { this.base.setTxTypeInProgress(type); let txHash: Uint8Array; let signDoc: StdSignDoc; try { if (typeof msgs === "function") { msgs = await msgs(); } const result = await this.broadcastMsgs( msgs, fee, memo, signOptions, this.broadcastMode ); txHash = result.txHash; signDoc = result.signDoc; } catch (e) { this.base.setTxTypeInProgress(""); if (this.txOpts.preTxEvents?.onBroadcastFailed) { this.txOpts.preTxEvents.onBroadcastFailed(this.chainId, e); } if ( onTxEvents && "onBroadcastFailed" in onTxEvents && onTxEvents.onBroadcastFailed ) { onTxEvents.onBroadcastFailed(e); } throw e; } let onBroadcasted: ((txHash: Uint8Array) => void) | undefined; let onFulfill: ((tx: any) => void) | undefined; if (onTxEvents) { if (typeof onTxEvents === "function") { onFulfill = onTxEvents; } else { onBroadcasted = onTxEvents.onBroadcasted; onFulfill = onTxEvents.onFulfill; } } if (this.txOpts.preTxEvents?.onBroadcasted) { this.txOpts.preTxEvents.onBroadcasted(this.chainId, txHash); } if (onBroadcasted) { onBroadcasted(txHash); } const txTracer = new TendermintTxTracer( this.chainGetter.getChain(this.chainId).rpc, "/websocket", { wsObject: this.txOpts.wsObject, } ); txTracer.traceTx(txHash).then((tx) => { txTracer.close(); this.base.setTxTypeInProgress(""); // After sending tx, the balances is probably changed due to the fee. for (const feeAmount of signDoc.fee.amount) { const bal = this.queries.queryBalances .getQueryBech32Address(this.base.bech32Address) .balances.find( (bal) => bal.currency.coinMinimalDenom === feeAmount.denom ); if (bal) { bal.fetch(); } } // Always add the tx hash data. if (tx && !tx.hash) { tx.hash = Buffer.from(txHash).toString("hex"); } if (this.txOpts.preTxEvents?.onFulfill) { this.txOpts.preTxEvents.onFulfill(this.chainId, tx); } if (onFulfill) { onFulfill(tx); } }); } // Return the tx hash. protected async broadcastMsgs( msgs: ProtoMsgsOrWithAminoMsgs, fee: StdFee, memo: string = "", signOptions?: KeplrSignOptions, mode: "block" | "async" | "sync" = "async" ): Promise<{ txHash: Uint8Array; signDoc: StdSignDoc; }> { if (this.base.walletStatus !== WalletStatus.Loaded) { throw new Error(`Wallet is not loaded: ${this.base.walletStatus}`); } const aminoMsgs: Msg[] = msgs.aminoMsgs; const protoMsgs: Any[] = msgs.protoMsgs; // TODO: Make proto sign doc if `aminoMsgs` is empty or null if (aminoMsgs.length === 0 || protoMsgs.length === 0) { throw new Error("There is no msg to send"); } if (aminoMsgs.length !== protoMsgs.length) { throw new Error("The length of aminoMsgs and protoMsgs are different"); } const account = await BaseAccount.fetchFromRest( this.instance, this.base.bech32Address, true ); const coinType = this.chainGetter.getChain(this.chainId).bip44.coinType; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const keplr = (await this.base.getKeplr())!; const signDoc = makeSignDoc( aminoMsgs, fee, this.chainId, memo, account.getAccountNumber().toString(), account.getSequence().toString() ); const signResponse = await keplr.signAmino( this.chainId, this.base.bech32Address, signDoc, signOptions ); const signedTx = TxRaw.encode({ bodyBytes: TxBody.encode( TxBody.fromPartial({ messages: protoMsgs, memo: signResponse.signed.memo, }) ).finish(), authInfoBytes: AuthInfo.encode({ signerInfos: [ { publicKey: { typeUrl: coinType === 60 ? "/ethermint.crypto.v1.ethsecp256k1.PubKey" : "/cosmos.crypto.secp256k1.PubKey", value: PubKey.encode({ key: Buffer.from( signResponse.signature.pub_key.value, "base64" ), }).finish(), }, modeInfo: { single: { mode: SignMode.SIGN_MODE_LEGACY_AMINO_JSON, }, multi: undefined, }, sequence: signResponse.signed.sequence, }, ], fee: Fee.fromPartial({ amount: signResponse.signed.fee.amount as Coin[], gasLimit: signResponse.signed.fee.gas, }), }).finish(), signatures: [Buffer.from(signResponse.signature.signature, "base64")], }).finish(); return { txHash: await keplr.sendTx(this.chainId, signedTx, mode as BroadcastMode), signDoc: signResponse.signed, }; } get instance(): AxiosInstance { const chainInfo = this.chainGetter.getChain(this.chainId); return Axios.create({ ...{ baseURL: chainInfo.rest, }, ...chainInfo.restConfig, }); } async sendIBCTransferMsg( channel: { portId: string; channelId: string; counterpartyChainId: string; }, amount: string, currency: AppCurrency, recipient: string, memo: string = "", stdFee: Partial<StdFee> = {}, signOptions?: KeplrSignOptions, onTxEvents?: | ((tx: any) => void) | { onBroadcasted?: (txHash: Uint8Array) => void; onFulfill?: (tx: any) => void; } ) { if (new DenomHelper(currency.coinMinimalDenom).type !== "native") { throw new Error("Only native token can be sent via IBC"); } const actualAmount = (() => { let dec = new Dec(amount); dec = dec.mul(DecUtils.getPrecisionDec(currency.coinDecimals)); return dec.truncate().toString(); })(); const destinationInfo = this.queriesStore.get(channel.counterpartyChainId) .cosmos.queryRPCStatus; await this.sendMsgs( "ibcTransfer", async () => { // Wait until fetching complete. await destinationInfo.waitFreshResponse(); if (!destinationInfo.network) { throw new Error( `Failed to fetch the network chain id of ${channel.counterpartyChainId}` ); } if ( ChainIdHelper.parse(destinationInfo.network).identifier !== ChainIdHelper.parse(channel.counterpartyChainId).identifier ) { throw new Error( `Fetched the network chain id is different with counterparty chain id (${destinationInfo.network}, ${channel.counterpartyChainId})` ); } if ( !destinationInfo.latestBlockHeight || destinationInfo.latestBlockHeight.equals(new Int("0")) ) { throw new Error( `Failed to fetch the latest block of ${channel.counterpartyChainId}` ); } const msg = { type: this.msgOpts.ibcTransfer.type, value: { source_port: channel.portId, source_channel: channel.channelId, token: { denom: currency.coinMinimalDenom, amount: actualAmount, }, sender: this.base.bech32Address, receiver: recipient, timeout_height: { revision_number: ChainIdHelper.parse( destinationInfo.network ).version.toString() as string | undefined, // Set the timeout height as the current height + 150. revision_height: destinationInfo.latestBlockHeight .add(new Int("150")) .toString(), }, }, }; if (msg.value.timeout_height.revision_number === "0") { delete msg.value.timeout_height.revision_number; } return { aminoMsgs: [msg], protoMsgs: [ { typeUrl: "/ibc.applications.transfer.v1.MsgTransfer", value: MsgTransfer.encode( MsgTransfer.fromPartial({ sourcePort: msg.value.source_port, sourceChannel: msg.value.source_channel, token: msg.value.token, sender: msg.value.sender, receiver: msg.value.receiver, timeoutHeight: { revisionNumber: msg.value.timeout_height.revision_number ? msg.value.timeout_height.revision_number : "0", revisionHeight: msg.value.timeout_height.revision_height, }, }) ).finish(), }, ], }; }, memo, { amount: stdFee.amount ?? [], gas: stdFee.gas ?? this.msgOpts.ibcTransfer.gas.toString(), }, signOptions, this.txEventsWithPreOnFulfill(onTxEvents, (tx) => { if (tx.code == null || tx.code === 0) { // After succeeding to send token, refresh the balance. const queryBalance = this.queries.queryBalances .getQueryBech32Address(this.base.bech32Address) .balances.find((bal) => { return ( bal.currency.coinMinimalDenom === currency.coinMinimalDenom ); }); if (queryBalance) { queryBalance.fetch(); } } }) ); } /** * Send `MsgDelegate` msg to the chain. * @param amount Decimal number used by humans. * If amount is 0.1 and the stake currenct is uatom, actual amount will be changed to the 100000uatom. * @param validatorAddress * @param memo * @param onFulfill */ async sendDelegateMsg( amount: string, validatorAddress: string, memo: string = "", stdFee: Partial<StdFee> = {}, signOptions?: KeplrSignOptions, onTxEvents?: | ((tx: any) => void) | { onBroadcasted?: (txHash: Uint8Array) => void; onFulfill?: (tx: any) => void; } ) { const currency = this.chainGetter.getChain(this.chainId).stakeCurrency; let dec = new Dec(amount); dec = dec.mulTruncate(DecUtils.getPrecisionDec(currency.coinDecimals)); const msg = { type: this.msgOpts.delegate.type, value: { delegator_address: this.base.bech32Address, validator_address: validatorAddress, amount: { denom: currency.coinMinimalDenom, amount: dec.truncate().toString(), }, }, }; await this.sendMsgs( "delegate", { aminoMsgs: [msg], protoMsgs: [ { typeUrl: "/cosmos.staking.v1beta1.MsgDelegate", value: MsgDelegate.encode({ delegatorAddress: msg.value.delegator_address, validatorAddress: msg.value.validator_address, amount: msg.value.amount, }).finish(), }, ], }, memo, { amount: stdFee.amount ?? [], gas: stdFee.gas ?? this.msgOpts.delegate.gas.toString(), }, signOptions, this.txEventsWithPreOnFulfill(onTxEvents, (tx) => { if (tx.code == null || tx.code === 0) { // After succeeding to delegate, refresh the validators and delegations, rewards. this.queries.cosmos.queryValidators .getQueryStatus(BondStatus.Bonded) .fetch(); this.queries.cosmos.queryDelegations .getQueryBech32Address(this.base.bech32Address) .fetch(); this.queries.cosmos.queryRewards .getQueryBech32Address(this.base.bech32Address) .fetch(); } }) ); } /** * Send `MsgUndelegate` msg to the chain. * @param amount Decimal number used by humans. * If amount is 0.1 and the stake currenct is uatom, actual amount will be changed to the 100000uatom. * @param validatorAddress * @param memo * @param onFulfill */ async sendUndelegateMsg( amount: string, validatorAddress: string, memo: string = "", stdFee: Partial<StdFee> = {}, signOptions?: KeplrSignOptions, onTxEvents?: | ((tx: any) => void) | { onBroadcasted?: (txHash: Uint8Array) => void; onFulfill?: (tx: any) => void; } ) { const currency = this.chainGetter.getChain(this.chainId).stakeCurrency; let dec = new Dec(amount); dec = dec.mulTruncate(DecUtils.getPrecisionDec(currency.coinDecimals)); const msg = { type: this.msgOpts.undelegate.type, value: { delegator_address: this.base.bech32Address, validator_address: validatorAddress, amount: { denom: currency.coinMinimalDenom, amount: dec.truncate().toString(), }, }, }; await this.sendMsgs( "undelegate", { aminoMsgs: [msg], protoMsgs: [ { typeUrl: "/cosmos.staking.v1beta1.MsgUndelegate", value: MsgUndelegate.encode({ delegatorAddress: msg.value.delegator_address, validatorAddress: msg.value.validator_address, amount: msg.value.amount, }).finish(), }, ], }, memo, { amount: stdFee.amount ?? [], gas: stdFee.gas ?? this.msgOpts.undelegate.gas.toString(), }, signOptions, this.txEventsWithPreOnFulfill(onTxEvents, (tx) => { if (tx.code == null || tx.code === 0) { // After succeeding to unbond, refresh the validators and delegations, unbonding delegations, rewards. this.queries.cosmos.queryValidators .getQueryStatus(BondStatus.Bonded) .fetch(); this.queries.cosmos.queryDelegations .getQueryBech32Address(this.base.bech32Address) .fetch(); this.queries.cosmos.queryUnbondingDelegations .getQueryBech32Address(this.base.bech32Address) .fetch(); this.queries.cosmos.queryRewards .getQueryBech32Address(this.base.bech32Address) .fetch(); } }) ); } /** * Send `MsgBeginRedelegate` msg to the chain. * @param amount Decimal number used by humans. * If amount is 0.1 and the stake currenct is uatom, actual amount will be changed to the 100000uatom. * @param srcValidatorAddress * @param dstValidatorAddress * @param memo * @param onFulfill */ async sendBeginRedelegateMsg( amount: string, srcValidatorAddress: string, dstValidatorAddress: string, memo: string = "", stdFee: Partial<StdFee> = {}, signOptions?: KeplrSignOptions, onTxEvents?: | ((tx: any) => void) | { onBroadcasted?: (txHash: Uint8Array) => void; onFulfill?: (tx: any) => void; } ) { const currency = this.chainGetter.getChain(this.chainId).stakeCurrency; let dec = new Dec(amount); dec = dec.mulTruncate(DecUtils.getPrecisionDec(currency.coinDecimals)); const msg = { type: this.msgOpts.redelegate.type, value: { delegator_address: this.base.bech32Address, validator_src_address: srcValidatorAddress, validator_dst_address: dstValidatorAddress, amount: { denom: currency.coinMinimalDenom, amount: dec.truncate().toString(), }, }, }; await this.sendMsgs( "redelegate", { aminoMsgs: [msg], protoMsgs: [ { typeUrl: "/cosmos.staking.v1beta1.MsgBeginRedelegate", value: MsgBeginRedelegate.encode({ delegatorAddress: msg.value.delegator_address, validatorSrcAddress: msg.value.validator_src_address, validatorDstAddress: msg.value.validator_dst_address, amount: msg.value.amount, }).finish(), }, ], }, memo, { amount: stdFee.amount ?? [], gas: stdFee.gas ?? this.msgOpts.redelegate.gas.toString(), }, signOptions, this.txEventsWithPreOnFulfill(onTxEvents, (tx) => { if (tx.code == null || tx.code === 0) { // After succeeding to redelegate, refresh the validators and delegations, rewards. this.queries.cosmos.queryValidators .getQueryStatus(BondStatus.Bonded) .fetch(); this.queries.cosmos.queryDelegations .getQueryBech32Address(this.base.bech32Address) .fetch(); this.queries.cosmos.queryRewards .getQueryBech32Address(this.base.bech32Address) .fetch(); } }) ); } async sendWithdrawDelegationRewardMsgs( validatorAddresses: string[], memo: string = "", stdFee: Partial<StdFee> = {}, signOptions?: KeplrSignOptions, onTxEvents?: | ((tx: any) => void) | { onBroadcasted?: (txHash: Uint8Array) => void; onFulfill?: (tx: any) => void; } ) { const msgs = validatorAddresses.map((validatorAddress) => { return { type: this.msgOpts.withdrawRewards.type, value: { delegator_address: this.base.bech32Address, validator_address: validatorAddress, }, }; }); await this.sendMsgs( "withdrawRewards", { aminoMsgs: msgs, protoMsgs: msgs.map((msg) => { return { typeUrl: "/cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward", value: MsgWithdrawDelegatorReward.encode({ delegatorAddress: msg.value.delegator_address, validatorAddress: msg.value.validator_address, }).finish(), }; }), }, memo, { amount: stdFee.amount ?? [], gas: stdFee.gas ?? ( this.msgOpts.withdrawRewards.gas * validatorAddresses.length ).toString(), }, signOptions, this.txEventsWithPreOnFulfill(onTxEvents, (tx) => { if (tx.code == null || tx.code === 0) { // After succeeding to withdraw rewards, refresh rewards. this.queries.cosmos.queryRewards .getQueryBech32Address(this.base.bech32Address) .fetch(); } }) ); } async sendGovVoteMsg( proposalId: string, option: "Yes" | "No" | "Abstain" | "NoWithVeto", memo: string = "", stdFee: Partial<StdFee> = {}, signOptions?: KeplrSignOptions, onTxEvents?: | ((tx: any) => void) | { onBroadcasted?: (txHash: Uint8Array) => void; onFulfill?: (tx: any) => void; } ) { const voteOption = (() => { switch (option) { case "Yes": return 1; case "Abstain": return 2; case "No": return 3; case "NoWithVeto": return 4; } })(); const msg = { type: this.msgOpts.govVote.type, value: { option: voteOption, proposal_id: proposalId, voter: this.base.bech32Address, }, }; await this.sendMsgs( "govVote", { aminoMsgs: [msg], protoMsgs: [ { typeUrl: "/cosmos.gov.v1beta1.MsgVote", value: MsgVote.encode({ proposalId: msg.value.proposal_id, voter: msg.value.voter, option: (() => { switch (msg.value.option) { case 1: return VoteOption.VOTE_OPTION_YES; case 2: return VoteOption.VOTE_OPTION_ABSTAIN; case 3: return VoteOption.VOTE_OPTION_NO; case 4: return VoteOption.VOTE_OPTION_NO_WITH_VETO; default: return VoteOption.VOTE_OPTION_UNSPECIFIED; } })(), }).finish(), }, ], }, memo, { amount: stdFee.amount ?? [], gas: stdFee.gas ?? this.msgOpts.govVote.gas.toString(), }, signOptions, this.txEventsWithPreOnFulfill(onTxEvents, (tx) => { if (tx.code == null || tx.code === 0) { // After succeeding to vote, refresh the proposal. const proposal = this.queries.cosmos.queryGovernance.proposals.find( (proposal) => proposal.id === proposalId ); if (proposal) { proposal.fetch(); } const vote = this.queries.cosmos.queryProposalVote.getVote( proposalId, this.base.bech32Address ); vote.fetch(); } }) ); } protected txEventsWithPreOnFulfill( onTxEvents: | ((tx: any) => void) | { onBroadcasted?: (txHash: Uint8Array) => void; onFulfill?: (tx: any) => void; } | undefined, preOnFulfill?: (tx: any) => void ): | { onBroadcasted?: (txHash: Uint8Array) => void; onFulfill?: (tx: any) => void; } | undefined { if (!onTxEvents) { return; } const onBroadcasted = typeof onTxEvents === "function" ? undefined : onTxEvents.onBroadcasted; const onFulfill = typeof onTxEvents === "function" ? onTxEvents : onTxEvents.onFulfill; return { onBroadcasted, onFulfill: onFulfill || preOnFulfill ? (tx: any) => { if (preOnFulfill) { preOnFulfill(tx); } if (onFulfill) { onFulfill(tx); } } : undefined, }; } protected get queries(): DeepReadonly<QueriesSetBase & CosmosQueries> { return this.queriesStore.get(this.chainId); } }
the_stack
import {action} from '@storybook/addon-actions'; import {ActionButton} from '@react-spectrum/button'; import {ActionGroup} from '@react-spectrum/actiongroup'; import {chain, useId} from '@react-aria/utils'; import {classNames} from '@react-spectrum/utils'; import {Content} from '@react-spectrum/view'; import Copy from '@spectrum-icons/workflow/Copy'; import Cut from '@spectrum-icons/workflow/Cut'; import {Dialog, DialogTrigger} from '@react-spectrum/dialog'; import dndStyles from './dnd.css'; import {DroppableGridExample} from './DroppableGrid'; import {DroppableListBox, DroppableListBoxExample} from './DroppableListBox'; import dropzoneStyles from '@adobe/spectrum-css-temp/components/dropzone/vars.css'; import {Flex} from '@react-spectrum/layout'; import {FocusRing} from '@react-aria/focus'; import Folder from '@spectrum-icons/workflow/Folder'; import {GridCollection, useGridState} from '@react-stately/grid'; import {Heading} from '@react-spectrum/text'; import {Item} from '@react-stately/collections'; import {mergeProps} from '@react-aria/utils'; import Paste from '@spectrum-icons/workflow/Paste'; import {PressResponder} from '@react-aria/interactions'; import {Provider, useProvider} from '@react-spectrum/provider'; import React from 'react'; import {ReorderableGridExample} from './Reorderable'; import ShowMenu from '@spectrum-icons/workflow/ShowMenu'; import {storiesOf} from '@storybook/react'; import {unwrapDOMRef} from '@react-spectrum/utils'; import {useButton} from '@react-aria/button'; import {useClipboard, useDrag, useDraggableItem, useDrop} from '..'; import {useDraggableCollectionState} from '@react-stately/dnd'; import {useGrid, useGridCell, useGridRow} from '@react-aria/grid'; import {useListData} from '@react-stately/data'; import {useListState} from '@react-stately/list'; import {VirtualizedListBoxExample} from './VirtualizedListBox'; let manyItems = []; for (let i = 0; i < 20; i++) { manyItems.push({id: '' + i, type: 'item', text: 'Item ' + i}); } storiesOf('Drag and Drop', module) .add( 'Default', () => ( <Flex direction="column" gap="size-200" alignItems="center"> <Draggable /> <Droppable /> <input /> <Droppable type="text/html" /> <input /> <Droppable /> </Flex> ) ) .add( 'nested drop regions', () => ( <Flex direction="column" gap="size-200" alignItems="center"> <Draggable /> <Droppable actionId="Parent"> <Droppable actionId="Child" /> </Droppable> </Flex> ) ) .add( 'Droppable listbox', () => ( <Flex direction="row" gap="size-200" alignItems="center"> <Draggable /> <DroppableListBox> <Item key="1" textValue="One"> <Folder size="S" /> <span>One</span> </Item> <Item key="2">Two</Item> <Item key="3" textValue="Three"> <Folder size="S" /> <span>Three</span> </Item> </DroppableListBox> </Flex> ) ) .add( 'In dialog', () => ( <Flex direction="column" gap="size-200" alignItems="center"> <Draggable /> <DialogButton> <Dialog> <Heading>Dialog</Heading> <Content> <Flex direction="column" gap="size-200" alignItems="center"> <Draggable /> <Droppable /> <Droppable /> </Flex> </Content> </Dialog> </DialogButton> <Droppable /> </Flex> ) ) .add( 'Draggable grid, droppable listbox', () => ( <Flex direction="row" gap="size-200" alignItems="center" wrap> <DraggableCollectionExample /> <DroppableListBoxExample /> </Flex> ) ) .add( 'Droppable grid', () => ( <Flex direction="column" alignItems="start"> <ActionGroup onAction={action => { switch (action) { case 'copy': case 'cut': { let selected = document.querySelector('[aria-label="Draggable list"] [aria-selected="true"] [role="gridcell"]') as HTMLElement; selected?.focus(); document.execCommand(action); break; } case 'paste': { // This only works in Safari... let selected = document.querySelector('[aria-label="List"] [aria-selected="true"] [role="gridcell"]') as HTMLElement; selected?.focus(); document.execCommand('paste'); break; } } }}> <Item key="copy" aria-label="Copy"><Copy /></Item> <Item key="cut" aria-label="Cut"><Cut /></Item> <Item key="paste" aria-label="Paste"><Paste /></Item> </ActionGroup> <Flex direction="row" gap="size-200" alignItems="center" wrap> <DraggableCollectionExample /> <DroppableGridExample onDropEnter={action('onDropEnter')} onDropExit={action('onDropExit')} onDrop={action('onDrop')} /> </Flex> </Flex> ) ) .add( 'Droppable grid with many items', () => ( <Flex direction="row" gap="size-200" alignItems="center" wrap> <DraggableCollectionExample /> <DroppableGridExample items={manyItems} /> </Flex> ) ) .add( 'Virtualized listbox', () => ( <Flex direction="row" gap="size-200" alignItems="center" wrap> <DraggableCollectionExample /> <VirtualizedListBoxExample items={manyItems} /> </Flex> ) ) .add( 'Multiple collection drop targets', () => ( <Flex direction="row" gap="size-200" alignItems="center" wrap> <DraggableCollectionExample /> <VirtualizedListBoxExample items={manyItems.map(item => ({...item, type: 'folder'}))} accept="folder" /> <VirtualizedListBoxExample items={manyItems} accept="item" /> </Flex> ) ) .add( 'Reorderable', () => ( <ReorderableGridExample /> ) ); function Draggable() { let {dragProps, dragButtonProps, isDragging} = useDrag({ getItems() { return [{ 'text/plain': 'hello world' }]; }, getAllowedDropOperations() { return ['copy']; }, onDragStart: action('onDragStart'), // onDragMove: action('onDragMove'), onDragEnd: action('onDragEnd') }); let {clipboardProps} = useClipboard({ getItems() { return [{ 'text/plain': 'hello world' }]; } }); let ref = React.useRef(); let {buttonProps} = useButton({...dragButtonProps, elementType: 'div'}, ref); return ( <FocusRing focusRingClass={classNames(dndStyles, 'focus-ring')}> <div ref={ref} {...mergeProps(dragProps, buttonProps, clipboardProps)} className={classNames(dndStyles, 'draggable', {'is-dragging': isDragging})}> <ShowMenu size="XS" /> <span>Drag me</span> </div> </FocusRing> ); } function Droppable({type, children, actionId = ''}: any) { let ref = React.useRef(); let {dropProps, isDropTarget} = useDrop({ ref, onDropEnter: action(`onDropEnter${actionId}`), // onDropMove: action('onDropMove'), onDropExit: action(`onDropExit${actionId}`), onDropActivate: action(`onDropActivate${actionId}`), onDrop: action(`onDrop${actionId}`), getDropOperation(types, allowedOperations) { return !type || types.has(type) ? allowedOperations[0] : 'cancel'; } }); let {clipboardProps} = useClipboard({ onPaste: action(`onPaste${actionId}`) }); let {buttonProps} = useButton({elementType: 'div'}, ref); return ( <FocusRing focusRingClass={classNames(dropzoneStyles, 'focus-ring')}> <div {...mergeProps(dropProps, buttonProps, clipboardProps)} ref={ref} className={classNames(dropzoneStyles, 'spectrum-Dropzone', {'is-dragged': isDropTarget})}> Drop here {children} </div> </FocusRing> ); } function DialogButton({children}) { let [isOpen, setOpen] = React.useState(false); let ref = React.useRef(); let {dropProps, isDropTarget} = useDrop({ ref: unwrapDOMRef(ref), onDropActivate() { setOpen(true); } }); return ( <DialogTrigger isDismissable isOpen={isOpen} onOpenChange={setOpen}> <PressResponder {...dropProps} isPressed={isDropTarget}> <ActionButton ref={ref}>Open dialog</ActionButton> </PressResponder> {children} </DialogTrigger> ); } function DraggableCollectionExample() { let list = useListData({ initialItems: [ {id: 'foo', type: 'folder', text: 'Foo'}, {id: 'bar', type: 'folder', text: 'Bar'}, {id: 'baz', type: 'item', text: 'Baz'} ] }); let onDragEnd = (e) => { if (e.dropOperation === 'move') { list.remove(...e.keys); } }; let onCut = keys => { list.remove(...keys); }; return ( <DraggableCollection items={list.items} selectedKeys={list.selectedKeys} onSelectionChange={list.setSelectedKeys} onDragEnd={onDragEnd} onCut={onCut}> {item => ( <Item textValue={item.text}> {item.type === 'folder' && <Folder size="S" />} <span>{item.text}</span> </Item> )} </DraggableCollection> ); } function DraggableCollection(props) { let ref = React.useRef<HTMLDivElement>(null); let state = useListState(props); let gridState = useGridState({ ...props, selectionMode: 'multiple', collection: new GridCollection({ columnCount: 1, items: [...state.collection].map(item => ({ ...item, childNodes: [{ key: `cell-${item.key}`, type: 'cell', index: 0, value: null, level: 0, rendered: null, textValue: item.textValue, hasChildNodes: false, childNodes: [] }] })) }) }); let provider = useProvider(); let dragState = useDraggableCollectionState({ collection: gridState.collection, selectionManager: gridState.selectionManager, getItems(keys) { return [...keys].map(key => { let item = gridState.collection.getItem(key); return { // @ts-ignore [item.value.type]: item.textValue, 'text/plain': item.textValue }; }); }, renderPreview(selectedKeys, draggedKey) { let item = state.collection.getItem(draggedKey); return ( <Provider {...provider}> <div className={classNames(dndStyles, 'draggable', 'is-drag-preview', {'is-dragging-multiple': selectedKeys.size > 1})}> <div className={classNames(dndStyles, 'drag-handle')}> <ShowMenu size="XS" /> </div> <span>{item.rendered}</span> {selectedKeys.size > 1 && <div className={classNames(dndStyles, 'badge')}>{selectedKeys.size}</div> } </div> </Provider> ); }, onDragStart: action('onDragStart'), onDragEnd: chain(action('onDragEnd'), props.onDragEnd) }); let {gridProps} = useGrid({ ...props, 'aria-label': 'Draggable list', focusMode: 'cell' }, gridState, ref); return ( <div ref={ref} {...gridProps} style={{ display: 'flex', flexDirection: 'column' }}> {[...gridState.collection].map(item => ( <DraggableCollectionItem key={item.key} item={item} state={gridState} dragState={dragState} onCut={props.onCut} /> ))} </div> ); } function DraggableCollectionItem({item, state, dragState, onCut}) { let rowRef = React.useRef(); let cellRef = React.useRef(); let cellNode = [...item.childNodes][0]; let isSelected = state.selectionManager.isSelected(item.key); let {rowProps} = useGridRow({node: item}, state, rowRef); let {gridCellProps} = useGridCell({ node: cellNode, focusMode: 'cell', shouldSelectOnPressUp: true }, state, cellRef); let {dragProps, dragButtonProps} = useDraggableItem({key: item.key}, dragState); let {clipboardProps} = useClipboard({ getItems: () => dragState.getItems(item.key), onCut: () => onCut(dragState.getKeysForDrag(item.key)) }); let buttonRef = React.useRef(); let {buttonProps} = useButton({ ...dragButtonProps, elementType: 'div' }, buttonRef); let id = useId(); return ( <div {...rowProps} ref={rowRef} aria-labelledby={id}> <FocusRing focusRingClass={classNames(dndStyles, 'focus-ring')}> <div {...mergeProps(gridCellProps, dragProps, clipboardProps)} aria-labelledby={id} ref={cellRef} className={classNames(dndStyles, 'draggable', { 'is-dragging': dragState.isDragging(item.key), 'is-selected': isSelected })}> <FocusRing focusRingClass={classNames(dndStyles, 'focus-ring')}> <div {...buttonProps as React.HTMLAttributes<HTMLElement>} ref={buttonRef} className={classNames(dndStyles, 'drag-handle')}> <ShowMenu size="XS" /> </div> </FocusRing> <span id={id}>{item.rendered}</span> </div> </FocusRing> </div> ); }
the_stack
import * as should from "should"; import { Benchmarker } from "node-opcua-benchmarker"; import { resolveNodeId } from "node-opcua-nodeid"; import { constructEventFilter } from "node-opcua-service-filter"; import { StatusCodes } from "node-opcua-status-code"; import { AddressSpace, Namespace, checkSelectClause } from ".."; import { getMiniAddressSpace } from "../testHelpers"; // tslint:disable-next-line:no-var-requires const describe = require("node-opcua-leak-detector").describeWithLeakDetector; describe("AddressSpace : add event type ", () => { let addressSpace: AddressSpace; let namespace: Namespace; before(async () => { addressSpace = await getMiniAddressSpace(); namespace = addressSpace.getOwnNamespace(); const eventType = namespace.addEventType({ browseName: "MyCustomEvent", // isAbstract:false, subtypeOf: "BaseEventType" // should be implicit }); }); after(() => { addressSpace.dispose(); }); it("#generateEventId should generate event id sequentially", () => { const id1 = addressSpace.generateEventId(); const id2 = addressSpace.generateEventId(); const id3 = addressSpace.generateEventId(); // xx console.log(id1.value.toString("hex")); // xx console.log(id2.value.toString("hex")); // xx console.log(id3.value.toString("hex")); id1.value.toString("hex").should.not.eql(id2.value.toString("hex")); id1.value.toString("hex").should.not.eql(id3.value.toString("hex")); }); it("should find BaseEventType", () => { addressSpace.findEventType("BaseEventType")!.nodeId.toString().should.eql("ns=0;i=2041"); }); it("BaseEventType should be abstract ", () => { const baseEventType = addressSpace.findEventType("BaseEventType")!; baseEventType.nodeId.toString().should.eql("ns=0;i=2041"); baseEventType.isAbstract.should.eql(true); }); it("should find AuditEventType", () => { const auditEventType = addressSpace.findEventType("AuditEventType")!; auditEventType.nodeId.toString().should.eql("ns=0;i=2052"); auditEventType.isAbstract.should.eql(true); }); it("should verify that AuditEventType is a superType of BaseEventType", () => { const baseEventType = addressSpace.findObjectType("BaseEventType")!; const auditEventType = addressSpace.findObjectType("AuditEventType")!; auditEventType.isSupertypeOf(baseEventType).should.eql(true); baseEventType.isSupertypeOf(auditEventType).should.eql(false); }); it("should find a newly added EventType", () => { should(addressSpace.findEventType("__EventTypeForTest1")).eql(null); const eventType = namespace.addEventType({ browseName: "__EventTypeForTest1", subtypeOf: "BaseEventType" // should be implicit }); eventType.browseName.toString().should.eql("1:__EventTypeForTest1"); const privateNamespace = addressSpace.getOwnNamespace(); const reloaded = addressSpace.findEventType("__EventTypeForTest1", privateNamespace.index)!; should(reloaded).not.eql(null, "cannot findEventType " + "__EventTypeForTest1"); reloaded.nodeId.should.eql(eventType.nodeId); }); it("should retrieve EventType in several ways", () => { const namespaceIndex = addressSpace.getOwnNamespace().index; namespaceIndex.should.eql(1); const eventType1 = addressSpace.findEventType("MyCustomEvent", namespaceIndex)!; const eventType2 = addressSpace.getOwnNamespace().findObjectType("MyCustomEvent")!; const eventType3 = addressSpace.findEventType("1:MyCustomEvent")!; eventType1.should.eql(eventType2); eventType1.should.eql(eventType3); }); it("added EventType should be abstract by default", () => { const namespaceIndex = addressSpace.getOwnNamespace().index; const eventType = addressSpace.findEventType("MyCustomEvent", namespaceIndex)!; eventType.isAbstract.should.eql(true); eventType.browseName.toString().should.eql("1:MyCustomEvent"); }); it("should be possible to add a non-abstract event type", () => { const eventType = namespace.addEventType({ browseName: "MyConcreteCustomEvent", isAbstract: false }); eventType.browseName.toString().should.eql("1:MyConcreteCustomEvent"); eventType.isAbstract.should.eql(false); }); it("should select node in a EventType using a SelectClause on BaseEventType", () => { // browseNodeByTargetName const baseEventType = addressSpace.findEventType("BaseEventType")!; const eventFilter = constructEventFilter(["SourceName", "EventId", "ReceiveTime"]); eventFilter.selectClauses!.length.should.eql(3); let statusCode = checkSelectClause(baseEventType, eventFilter.selectClauses![0]); statusCode.should.eql(StatusCodes.Good); statusCode = checkSelectClause(baseEventType, eventFilter.selectClauses![1]); statusCode.should.eql(StatusCodes.Good); statusCode = checkSelectClause(baseEventType, eventFilter.selectClauses![2]); statusCode.should.eql(StatusCodes.Good); }); it("should select node in a EventType using a SelectClause n AuditEventType", () => { // browseNodeByTargetName const auditEventType = addressSpace.findEventType("AuditEventType")!; const eventFilter = constructEventFilter(["SourceName", "EventId", "ReceiveTime"]); eventFilter.selectClauses!.length.should.eql(3); let statusCode = checkSelectClause(auditEventType, eventFilter.selectClauses![0]); statusCode.should.eql(StatusCodes.Good); statusCode = checkSelectClause(auditEventType, eventFilter.selectClauses![1]); statusCode.should.eql(StatusCodes.Good); statusCode = checkSelectClause(auditEventType, eventFilter.selectClauses![2]); statusCode.should.eql(StatusCodes.Good); }); it("should instantiate a condition efficiently ( more than 1000 per second on a decent computer)", function (this: any, done: any) { const bench = new Benchmarker(); const eventType = namespace.addEventType({ browseName: "MyConditionType", isAbstract: false, subtypeOf: "ConditionType" }); let counter = 0; bench .add("test", () => { const condition = namespace.instantiateCondition(eventType, { browseName: "MyCondition" + counter, conditionSource: undefined, receiveTime: { dataType: "DateTime", value: new Date(1789, 6, 14) }, sourceName: { dataType: "String", value: "HelloWorld" } }); condition.browseName.toString().should.eql("1:MyCondition" + counter); counter++; }) .on("cycle", (message: string) => { // xx console.log(message); }) .on("complete", function (this: any) { console.log(" Fastest is ", this.fastest.name); // xx console.log(" count : ", this.fastest.count); done(); }) .run({ max_time: 0.1 }); }); it("#constructEventData ", () => { const auditEventType = addressSpace.findObjectType("AuditEventType")!; const data = { actionTimeStamp: { dataType: "Null" }, clientAuditEntryId: { dataType: "Null" }, clientUserId: { dataType: "Null" }, serverId: { dataType: "Null" }, sourceNode: { dataType: "NodeId", value: resolveNodeId("Server") }, status: { dataType: "Null" } }; const data1 = addressSpace.constructEventData(auditEventType, data); const expected_fields = [ "$eventDataSource", "__nodes", "actionTimeStamp", "clientAuditEntryId", "clientUserId", "eventId", "eventType", "localTime", "message", "receiveTime", "serverId", "severity", "sourceName", "sourceNode", "status", "time" ]; Object.keys(data1).sort().should.eql(expected_fields); // xx console.log(JSON.stringify(data,null," ")); }); // xit("#createEventData should add an basic event type", () => { // // const eventType = addressSpace.findEventType("MyCustomEvent")!; // eventType.browseName.toString().should.eql("MyCustomEvent"); // // namespace.addVariable({ // browseName: "MyCustomEventProperty", // dataType: "Double", // propertyOf: eventType, // value: { dataType: DataType.Double, value: 1.0 } // }); // // const event = addressSpace.createEventData("MyCustomEvent", { // receiveTime: { // dataType: "DateTime", // value: new Date(1789, 6, 14) // }, // sourceName: { // dataType: "String", // value: "HelloWorld" // }, // }); // // // event shall have property of BaseEventType // // see OPC Spec 1.02 : part 5 : page 19 : 6.4.2 BaseEventType // // // // EventId ByteString // // EventType NodeId // // SourceNode NodeId // // SourceName String // // Time UtcTime // // ReceiveTime UtcTime // // LocalTime TimeZoneDataType // optional // // Message LocalizedText // // Severity UInt16 // // event.should.have.property("eventId"); // event.should.have.property("eventType"); // event.should.have.property("sourceNode"); // event.should.have.property("sourceName"); // event.should.have.property("time"); // event.should.have.property("receiveTime"); // event.should.have.property("localTime"); // event.should.have.property("message"); // event.should.have.property("severity"); // // event.eventId.should.be.instanceof(Variant); // // event.eventId.dataType.should.eql(DataType.ByteString); // event.sourceName.value.should.eql("HelloWorld"); // event.receiveTime.value.should.eql(new Date(1789, 6, 14)); // // }); describe("test AddressSpace#generateEventId", () => { it("it should generate different eventId each time", () => { const eventType1 = addressSpace.generateEventId().value; const eventType2 = addressSpace.generateEventId().value; eventType1.toString("hex").should.not.eql(eventType2.toString("hex")); // xx console.log(eventType1.toString("hex"), eventType2.toString("hex")); }); }); });
the_stack
import { EventEmitter } from "events"; import * as timers from "timers"; import * as ByteBuffer from "bytebuffer"; import { BitStream } from "./ext/bitbuffer"; import * as assert from "assert"; import { MAX_EDICT_BITS, MAX_OSPATH } from "./consts"; import { ConVars } from "./convars"; import { Entities } from "./entities"; import { GameRules } from "./entities/gamerules"; import { Player } from "./entities/player"; import { Team } from "./entities/team"; import { GameEvents } from "./gameevents"; import { IceKey } from "./icekey"; import * as net from "./net"; import { NetMessageName } from "./net"; import { CNETMsgDisconnect, CNETMsgFile, CNETMsgNOP, CNETMsgPlayerAvatarData, CNETMsgSetConVar, CNETMsgSignonState, CNETMsgSplitScreenUser, CNETMsgStringCmd, CNETMsgTick, CSVCMsgBroadcastCommand, CSVCMsgBSPDecal, CSVCMsgClassInfo, CSVCMsgCmdKeyValues, CSVCMsgCreateStringTable, CSVCMsgCrosshairAngle, CSVCMsgEncryptedData, CSVCMsgEntityMsg, CSVCMsgFixAngle, CSVCMsgGameEvent, CSVCMsgGameEventList, CSVCMsgGetCvarValue, CSVCMsgHltvReplay, CSVCMsgMenu, CSVCMsgPacketEntities, CSVCMsgPaintmapData, CSVCMsgPrefetch, CSVCMsgPrint, CSVCMsgSendTable, CSVCMsgServerInfo, CSVCMsgSetPause, CSVCMsgSetView, CSVCMsgSounds, CSVCMsgSplitScreen, CSVCMsgTempEntities, CSVCMsgUpdateStringTable, CSVCMsgUserMessage, CSVCMsgVoiceData, CSVCMsgVoiceInit } from "./protobufs/netmessages"; import { Vector } from "./sendtabletypes"; import { StringTables } from "./stringtables"; import { UserMessages } from "./usermessages"; interface IDemoHeader { /** * Header magic (HL2DEMO) */ magic: string; /** * Demo protocol version */ protocol: number; /** * Network protocol version */ networkProtocol: number; /** * Server hostname */ serverName: string; /** * Recording player name */ clientName: string; /** * Level name */ mapName: string; /** * Game directory */ gameDirectory: string; /** * Total playback time (seconds) */ playbackTime: number; /** * Total playback ticks */ playbackTicks: number; /** * Total playback frames */ playbackFrames: number; /** * Length of signon (bytes) */ signonLength: number; } const enum DemoCommands { Signon = 1, Packet = 2, /** * Sync client clock to demo tick */ SyncTick = 3, ConsoleCmd = 4, UserCmd = 5, DataTables = 6, Stop = 7, /** * A blob of binary data understood by a callback function */ CustomData = 8, StringTables = 9 } /** * Parses a demo file header from the buffer. * @param {ArrayBuffer} buffer - Buffer of the demo header * @returns {IDemoHeader} Header object */ export function parseHeader(buffer: Buffer): IDemoHeader { const bytebuf = ByteBuffer.wrap(buffer, true); return { magic: bytebuf.readString(8, ByteBuffer.METRICS_BYTES).split("\0", 2)[0]!, protocol: bytebuf.readInt32(), networkProtocol: bytebuf.readInt32(), serverName: bytebuf .readString(MAX_OSPATH, ByteBuffer.METRICS_BYTES) .split("\0", 2)[0]!, clientName: bytebuf .readString(MAX_OSPATH, ByteBuffer.METRICS_BYTES) .split("\0", 2)[0]!, mapName: bytebuf .readString(MAX_OSPATH, ByteBuffer.METRICS_BYTES) .split("\0", 2)[0]!, gameDirectory: bytebuf .readString(MAX_OSPATH, ByteBuffer.METRICS_BYTES) .split("\0", 2)[0]!, playbackTime: bytebuf.readFloat(), playbackTicks: bytebuf.readInt32(), playbackFrames: bytebuf.readInt32(), signonLength: bytebuf.readInt32() }; } function readIBytes(bytebuf: ByteBuffer) { const length = bytebuf.readInt32(); return bytebuf.readBytes(length); } export interface IDemoStartEvent { /** * Cancel parsing the demo. */ cancel: () => void; } export interface IDemoEndEvent { /** * Error that caused the premature end of parsing. */ error?: Error; /** * Did parsing finish prematurely because the demo was incomplete? */ incomplete: boolean; } export declare interface DemoFile { /** * Fired when parsing begins. */ on(event: "start", listener: (event: IDemoStartEvent) => void): this; emit(name: "start", event: IDemoStartEvent): boolean; /** * Fired when parsing failed. */ on(event: "error", listener: (error: Error) => void): this; emit(name: "error", error: Error): boolean; /** * Fired when parsing has finished, successfully or otherwise. */ on(event: "end", listener: (event: IDemoEndEvent) => void): this; emit(name: "end", event: IDemoEndEvent): boolean; /** * Fired when a tick starts, before any tick command processing. */ on(event: "tickstart", listener: (tick: number) => void): this; emit(name: "tickstart", tick: number): boolean; /** * Fired per command. Parameter is a value in range [0,1] that indicates * the percentage of the demo file has been parsed so far. */ on(event: "progress", listener: (progressFraction: number) => void): this; emit(name: "progress", progressFraction: number): boolean; /** * Fired each frame indicating all inputs of the recording player. * Note this is only fired for in-eye/perspective demos. */ on(event: "usercmd", listener: (userCmd: IUserCmd) => void): this; emit(name: "usercmd", userCmd: IUserCmd): boolean; /** * Fired after all commands are processed for a tick. */ on(event: "tickend", listener: (tick: number) => void): this; emit(name: "tickend", tick: number): boolean; emit(name: NetMessageName, msg: any): boolean; on(message: "net_NOP", listener: (msg: CNETMsgNOP) => void): this; on( message: "net_Disconnect", listener: (msg: CNETMsgDisconnect) => void ): this; on(message: "net_File", listener: (msg: CNETMsgFile) => void): this; on( message: "net_SplitScreenUser", listener: (msg: CNETMsgSplitScreenUser) => void ): this; on(message: "net_Tick", listener: (msg: CNETMsgTick) => void): this; on(message: "net_StringCmd", listener: (msg: CNETMsgStringCmd) => void): this; on(message: "net_SetConVar", listener: (msg: CNETMsgSetConVar) => void): this; on( message: "net_SignonState", listener: (msg: CNETMsgSignonState) => void ): this; on( message: "net_PlayerAvatarData", listener: (msg: CNETMsgPlayerAvatarData) => void ): this; on( message: "svc_ServerInfo", listener: (msg: CSVCMsgServerInfo) => void ): this; on(message: "svc_SendTable", listener: (msg: CSVCMsgSendTable) => void): this; on(message: "svc_ClassInfo", listener: (msg: CSVCMsgClassInfo) => void): this; on(message: "svc_SetPause", listener: (msg: CSVCMsgSetPause) => void): this; on( message: "svc_CreateStringTable", listener: (msg: CSVCMsgCreateStringTable) => void ): this; on( message: "svc_UpdateStringTable", listener: (msg: CSVCMsgUpdateStringTable) => void ): this; on(message: "svc_VoiceInit", listener: (msg: CSVCMsgVoiceInit) => void): this; on(message: "svc_VoiceData", listener: (msg: CSVCMsgVoiceData) => void): this; on(message: "svc_Print", listener: (msg: CSVCMsgPrint) => void): this; on(message: "svc_Sounds", listener: (msg: CSVCMsgSounds) => void): this; on(message: "svc_SetView", listener: (msg: CSVCMsgSetView) => void): this; on(message: "svc_FixAngle", listener: (msg: CSVCMsgFixAngle) => void): this; on( message: "svc_CrosshairAngle", listener: (msg: CSVCMsgCrosshairAngle) => void ): this; on(message: "svc_BSPDecal", listener: (msg: CSVCMsgBSPDecal) => void): this; on( message: "svc_SplitScreen", listener: (msg: CSVCMsgSplitScreen) => void ): this; on( message: "svc_UserMessage", listener: (msg: CSVCMsgUserMessage) => void ): this; on( message: "svc_EntityMessage", listener: (msg: CSVCMsgEntityMsg) => void ): this; on(message: "svc_GameEvent", listener: (msg: CSVCMsgGameEvent) => void): this; on( message: "svc_PacketEntities", listener: (msg: CSVCMsgPacketEntities) => void ): this; on( message: "svc_TempEntities", listener: (msg: CSVCMsgTempEntities) => void ): this; on(message: "svc_Prefetch", listener: (msg: CSVCMsgPrefetch) => void): this; on(message: "svc_Menu", listener: (msg: CSVCMsgMenu) => void): this; on( message: "svc_GameEventList", listener: (msg: CSVCMsgGameEventList) => void ): this; on( message: "svc_GetCvarValue", listener: (msg: CSVCMsgGetCvarValue) => void ): this; on( message: "svc_PaintmapData", listener: (msg: CSVCMsgPaintmapData) => void ): this; on( message: "svc_CmdKeyValues", listener: (msg: CSVCMsgCmdKeyValues) => void ): this; on( message: "svc_EncryptedData", listener: (msg: CSVCMsgEncryptedData) => void ): this; on( message: "svc_HltvReplay", listener: (msg: CSVCMsgHltvReplay) => void ): this; on( message: "svc_Broadcast_Command", listener: (msg: CSVCMsgBroadcastCommand) => void ): this; } export type InputButton = | "attack" // = 1 << 0, | "jump" // = 1 << 1, | "duck" // = 1 << 2, | "forward" // = 1 << 3, | "back" // = 1 << 4, | "use" // = 1 << 5, | "cancel" // = 1 << 6, | "left" // = 1 << 7, | "right" // = 1 << 8, | "moveleft" // = 1 << 9, | "moveright" // = 1 << 10, | "attack2" // = 1 << 11, | "run" // = 1 << 12, | "reload" // = 1 << 13, | "alt1" // = 1 << 14, | "alt2" // = 1 << 15, | "score" // = 1 << 16, // Used by client.dll for when scoreboard is held down | "speed" // = 1 << 17, // Player is holding the speed key | "walk" // = 1 << 18, // Player holding walk key | "zoom" // = 1 << 19, // Zoom key for HUD zoom | "weapon1" // = 1 << 20, // weapon defines these bits | "weapon2" // = 1 << 21, // weapon defines these bits | "bullrush" // = 1 << 22, | "grenade1" // = 1 << 23, // grenade 1 | "grenade2" // = 1 << 24, // grenade 2 | "lookspin"; // = 1 << 25 export interface IUserCmd { commandNumber: number; tickCount: number; viewAngles: Vector; aimDirection: Vector; forwardMove: number; sideMove: number; upMove: number; buttons: ReadonlyArray<InputButton>; impulse: number; weaponSelect: number; weaponSubType: number; randomSeed: number; mouseDeltaX: number; mouseDeltaY: number; } /** * Represents a demo file for parsing. */ export class DemoFile extends EventEmitter { /** * @returns Number of ticks per second */ get tickRate(): number { return 1.0 / this.tickInterval; } /** * @returns Number of seconds elapsed */ get currentTime(): number { return this.currentTick * this.tickInterval; } /** * Shortcut for `this.entities.players` * @returns All connected player entities */ get players(): ReadonlyArray<Player> { return this.entities.players; } /** * Shortcut for `this.entities.teams` * @returns All team entities */ get teams(): ReadonlyArray<Team> { return this.entities.teams; } /** * Shortcut for `this.entities.gameRules` * @returns GameRules entity */ get gameRules(): GameRules { return this.entities.gameRules; } /** * When parsing, set to current tick. */ public currentTick: number = 0; /** * Number of seconds per tick */ public tickInterval: number = NaN; public header!: IDemoHeader; /** * When parsing, set to player slot for current command. */ public playerSlot: number = 0; public readonly entities: Entities; public readonly gameEvents: GameEvents; public readonly stringTables: StringTables; public readonly userMessages: UserMessages; public readonly conVars: ConVars; private _bytebuf!: ByteBuffer; private _lastThreadYieldTime = 0; private _immediateTimerToken: NodeJS.Immediate | null = null; private _timeoutTimerToken: NodeJS.Timer | null = null; private _encryptionKey: Uint8Array | null = null; /** * Starts parsing buffer as a demo file. * * @fires DemoFile#tickstart * @fires DemoFile#tickend * @fires DemoFile#end * * @param {ArrayBuffer} buffer - Buffer pointing to start of demo header */ constructor() { super(); this.entities = new Entities(); this.gameEvents = new GameEvents(); this.stringTables = new StringTables(); this.userMessages = new UserMessages(); this.conVars = new ConVars(); this.gameEvents.listen(this); // It is important that entities listens after game events, as they both listen on // tickend. this.entities.listen(this); this.stringTables.listen(this); this.userMessages.listen(this); this.conVars.listen(this); // #65: Some demos are missing playbackTicks from the header // Pull the tick interval from ServerInfo this.on("svc_ServerInfo", msg => { this.tickInterval = msg.tickInterval; }); this.on("svc_EncryptedData", this._handleEncryptedData.bind(this)); } public parse(buffer: Buffer): void { this.header = parseHeader(buffer); // #65: Some demos are missing playbackTicks from the header if (this.header.playbackTicks > 0) { this.tickInterval = this.header.playbackTime / this.header.playbackTicks; } this._bytebuf = ByteBuffer.wrap(buffer.slice(1072), true); let cancelled = false; this.emit("start", { cancel: () => { cancelled = true; } }); // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!cancelled) timers.setTimeout(this._parseRecurse.bind(this), 0); } /** * Cancel the current parse operation. */ public cancel(): void { if (this._immediateTimerToken) { timers.clearImmediate(this._immediateTimerToken); this._immediateTimerToken = null; } if (this._timeoutTimerToken) { timers.clearTimeout(this._timeoutTimerToken); this._timeoutTimerToken = null; } } /** * Set encryption key for decrypting `svc_EncryptedData` packets. * This allows decryption of messages from public matchmaking, like * chat messages and caster voice data. * * The key can be extracted from `match730_*.dem.info` files with `extractPublicEncryptionKey`. * * @param publicKey Public encryption key. */ public setEncryptionKey(publicKey: Uint8Array | null): void { if (publicKey != null && publicKey.length !== 16) { throw new Error( `Public key must be 16 bytes long, got ${publicKey.length} bytes instead` ); } this._encryptionKey = publicKey; } private _handleEncryptedData(msg: CSVCMsgEncryptedData) { if (msg.keyType !== 2 || this._encryptionKey == null) return; const key = new IceKey(2); key.set(this._encryptionKey); assert(msg.encrypted.length % key.blockSize() === 0); const plainText = new Uint8Array(msg.encrypted.length); key.decryptUint8Array(msg.encrypted, plainText); // Create a ByteBuffer skipped past the padding const buf = ByteBuffer.wrap(plainText, true); const paddingBytes = buf.readUint8(); buf.skip(paddingBytes); // Read size of netmessage. For some reason, it's encoded // redundantly encoded several times. buf.BE(); const bytesWritten = buf.readInt32(); buf.LE(); assert(buf.remaining() === bytesWritten); const cmd = buf.readVarint32(); const size = buf.readVarint32(); assert(buf.remaining() === size); const message = net.findByType(cmd); assert(message != null, `No message handler for ${cmd}`); if (message != null && this.listenerCount(message.name)) { const msgInst = message.class.decode(new Uint8Array(buf.toBuffer())); this.emit(message.name, msgInst); } } /** * Fired when a packet of this type is hit. `svc_MessageName` events are also fired. * @public * @event DemoFile#net_MessageName */ private _handleDemoPacket() { // skip cmd info this._bytebuf.skip(152); // skip over sequence info this._bytebuf.readInt32(); this._bytebuf.readInt32(); const chunk = readIBytes(this._bytebuf); while (chunk.remaining()) { const cmd = chunk.readVarint32(); const size = chunk.readVarint32(); const message = net.findByType(cmd); assert(message != null, `No message handler for ${cmd}`); if (message == null) { chunk.skip(size); continue; } if (this.listenerCount(message.name)) { const messageBuffer = chunk.readBytes(size); const msgInst = message.class.decode( new Uint8Array(messageBuffer.toBuffer()) ); this.emit(message.name, msgInst); } else { chunk.skip(size); } } } private _handleDataChunk() { readIBytes(this._bytebuf); } private _handleDataTables() { const chunk = readIBytes(this._bytebuf); this.entities.handleDataTables(chunk); } private _handleUserCmd() { this._bytebuf.readInt32(); // outgoing sequence const chunk = readIBytes(this._bytebuf); // If nobody's listening, don't waste cycles decoding it if (!this.listenerCount("usercmd")) return; const bitbuf = BitStream.from( chunk.buffer.slice(chunk.offset, chunk.limit) ); const move = { commandNumber: 0, tickCount: 0, viewAngles: { x: 0, y: 0, z: 0 }, aimDirection: { x: 0, y: 0, z: 0 }, forwardMove: 0, sideMove: 0, upMove: 0, buttons: new Array<InputButton>(), impulse: 0, weaponSelect: 0, weaponSubType: 0, randomSeed: 0, mouseDeltaX: 0, mouseDeltaY: 0 }; if (bitbuf.readOneBit()) { move.commandNumber = bitbuf.readUInt32(); } else { move.commandNumber = 1; } if (bitbuf.readOneBit()) { move.tickCount = bitbuf.readUInt32(); } else { move.tickCount = 1; } // Read direction if (bitbuf.readOneBit()) move.viewAngles.x = bitbuf.readFloat32(); if (bitbuf.readOneBit()) move.viewAngles.y = bitbuf.readFloat32(); if (bitbuf.readOneBit()) move.viewAngles.z = bitbuf.readFloat32(); // Read aim direction if (bitbuf.readOneBit()) move.aimDirection.x = bitbuf.readFloat32(); if (bitbuf.readOneBit()) move.aimDirection.y = bitbuf.readFloat32(); if (bitbuf.readOneBit()) move.aimDirection.z = bitbuf.readFloat32(); // Read movement if (bitbuf.readOneBit()) move.forwardMove = bitbuf.readFloat32(); if (bitbuf.readOneBit()) move.sideMove = bitbuf.readFloat32(); if (bitbuf.readOneBit()) move.upMove = bitbuf.readFloat32(); if (bitbuf.readOneBit()) { const buttons = bitbuf.readUInt32(); if (buttons & (1 << 0)) move.buttons.push("attack"); if (buttons & (1 << 1)) move.buttons.push("jump"); if (buttons & (1 << 2)) move.buttons.push("duck"); if (buttons & (1 << 3)) move.buttons.push("forward"); if (buttons & (1 << 4)) move.buttons.push("back"); if (buttons & (1 << 5)) move.buttons.push("use"); if (buttons & (1 << 6)) move.buttons.push("cancel"); if (buttons & (1 << 7)) move.buttons.push("left"); if (buttons & (1 << 8)) move.buttons.push("right"); if (buttons & (1 << 9)) move.buttons.push("moveleft"); if (buttons & (1 << 10)) move.buttons.push("moveright"); if (buttons & (1 << 11)) move.buttons.push("attack2"); if (buttons & (1 << 12)) move.buttons.push("run"); if (buttons & (1 << 13)) move.buttons.push("reload"); if (buttons & (1 << 14)) move.buttons.push("alt1"); if (buttons & (1 << 15)) move.buttons.push("alt2"); if (buttons & (1 << 16)) move.buttons.push("score"); if (buttons & (1 << 17)) move.buttons.push("speed"); if (buttons & (1 << 18)) move.buttons.push("walk"); if (buttons & (1 << 19)) move.buttons.push("zoom"); if (buttons & (1 << 20)) move.buttons.push("weapon1"); if (buttons & (1 << 21)) move.buttons.push("weapon2"); if (buttons & (1 << 22)) move.buttons.push("bullrush"); if (buttons & (1 << 23)) move.buttons.push("grenade1"); if (buttons & (1 << 24)) move.buttons.push("grenade2"); if (buttons & (1 << 25)) move.buttons.push("lookspin"); } if (bitbuf.readOneBit()) move.impulse = bitbuf.readUInt8(); if (bitbuf.readOneBit()) { move.weaponSelect = bitbuf.readUBits(MAX_EDICT_BITS); if (bitbuf.readOneBit()) move.weaponSubType = bitbuf.readUBits(6); } if (bitbuf.readOneBit()) move.mouseDeltaX = bitbuf.readInt16(); if (bitbuf.readOneBit()) move.mouseDeltaY = bitbuf.readInt16(); this.emit("usercmd", move); } private _handleStringTables() { const chunk = readIBytes(this._bytebuf); const bitbuf = BitStream.from( chunk.buffer.slice(chunk.offset, chunk.limit) ); this.stringTables.handleStringTables(bitbuf); } private _recurse() { const now = Date.now(); if (now - this._lastThreadYieldTime < 32) { this._immediateTimerToken = timers.setImmediate( this._parseRecurse.bind(this) ); } else { this._lastThreadYieldTime = now; this._timeoutTimerToken = timers.setTimeout( this._parseRecurse.bind(this), 0 ); } } private _parseRecurse() { this._recurse(); try { this.emit("progress", this._bytebuf.offset / this._bytebuf.limit); const command = this._bytebuf.readUint8(); const tick = this._bytebuf.readInt32(); this.playerSlot = this._bytebuf.readUint8(); if (tick !== this.currentTick) { this.emit("tickend", this.currentTick); this.currentTick = tick; this.emit("tickstart", this.currentTick); } switch (command) { case DemoCommands.Packet: case DemoCommands.Signon: this._handleDemoPacket(); break; case DemoCommands.DataTables: this._handleDataTables(); break; case DemoCommands.StringTables: this._handleStringTables(); break; case DemoCommands.ConsoleCmd: // TODO this._handleDataChunk(); break; case DemoCommands.UserCmd: this._handleUserCmd(); break; case DemoCommands.Stop: this.cancel(); this.emit("tickend", this.currentTick); this.emit("end", { incomplete: false }); return; case DemoCommands.CustomData: throw new Error("Custom data not supported"); case DemoCommands.SyncTick: break; default: throw new Error("Unrecognised command"); } } catch (e) { // Always cancel if we have an error - we've already scheduled the next tick this.cancel(); // #11, #172: Some demos have been written incompletely. // Don't throw an error when we run out of bytes to read. if ( e instanceof RangeError && this.header.playbackTicks === 0 && this.header.playbackTime === 0 && this.header.playbackFrames === 0 ) { this.emit("end", { incomplete: true }); } else { const error = e instanceof Error ? e : new Error(`Exception during parsing: ${e}`); this.emit("error", error); this.emit("end", { error, incomplete: false }); } } } }
the_stack
import { TreeDataProvider, TreeItem, Event, EventEmitter, TreeView, window, Uri, TreeItemCollapsibleState, commands, } from 'vscode'; import * as path from 'path'; import { CliExitData } from './cli'; import { getInstance, Odo, OdoImpl } from './odo'; import { Command } from './odo/command'; import { ComponentTypeDescription, ComponentTypesJson, DevfileComponentType, isDevfileComponent, isRegistry, Registry, } from './odo/componentType'; import { isStarterProject, StarterProject } from './odo/componentTypeDescription'; import { vsCommand, VsCommandError } from './vscommand'; import { Platform } from './util/platform'; import validator from 'validator'; type ComponentType = DevfileComponentType | StarterProject | Registry; export enum ContextType { DEVFILE_COMPONENT_TYPE = 'devfileComponentType', DEVFILE_STARTER_PROJECT = 'devfileStarterProject', DEVFILE_REGISTRY = 'devfileRegistry', } export class ComponentTypesView implements TreeDataProvider<ComponentType> { private static viewInstance: ComponentTypesView; private treeView: TreeView<ComponentType>; private onDidChangeTreeDataEmitter: EventEmitter<ComponentType> = new EventEmitter< ComponentType | undefined >(); readonly onDidChangeTreeData: Event<ComponentType | undefined> = this.onDidChangeTreeDataEmitter.event; readonly odo: Odo = getInstance(); private registries: Registry[]; createTreeView(id: string): TreeView<ComponentType> { if (!this.treeView) { this.treeView = window.createTreeView(id, { treeDataProvider: this, }); } return this.treeView; } static get instance(): ComponentTypesView { if (!ComponentTypesView.viewInstance) { ComponentTypesView.viewInstance = new ComponentTypesView(); } return ComponentTypesView.viewInstance; } // eslint-disable-next-line class-methods-use-this getTreeItem(element: ComponentType): TreeItem | Thenable<TreeItem> { if (isRegistry(element)) { return { label: element.Name, contextValue: ContextType.DEVFILE_REGISTRY, tooltip: `Devfile Registry\nName: ${element.Name}\nURL: ${element.URL}`, collapsibleState: TreeItemCollapsibleState.Collapsed, }; } if (isStarterProject(element)) { return { label: element.name, contextValue: ContextType.DEVFILE_STARTER_PROJECT, tooltip: `Starter Project\nName: ${element.name}\nDescription: ${ element.description ? element.description : 'n/a' }`, description: element.description, iconPath: { dark: Uri.file( path.join( __dirname, '..', '..', 'images', 'component', 'start-project-dark.png', ), ), light: Uri.file( path.join( __dirname, '..', '..', 'images', 'component', 'start-project-light.png', ), ), }, }; } return { label: `${element.DisplayName}`, contextValue: ContextType.DEVFILE_COMPONENT_TYPE, iconPath: { dark: Uri.file( path.join( __dirname, '..', '..', 'images', 'component', 'component-type-dark.png', ), ), light: Uri.file( path.join( __dirname, '..', '..', 'images', 'component', 'component-type-light.png', ), ), }, tooltip: `Component Type\nName: ${element.Name}\nKind: devfile\nDescription: ${ element.Description ? element.Description : 'n/a' }`, description: element.Description, collapsibleState: TreeItemCollapsibleState.Collapsed, }; } public loadItems<I, O>(result: CliExitData, fetch: (data: I) => O[]): O[] { let data: O[] = []; try { const items = fetch(JSON.parse(result.stdout)); if (items) data = items; } catch (ignore) { // ignore parse errors and return empty array } return data; } addRegistry(newRegistry: Registry): void { this.registries.push(newRegistry); this.refresh(false); this.reveal(newRegistry); } removeRegistry(targetRegistry: Registry): void { this.registries.splice( this.registries.findIndex((registry) => registry.Name === targetRegistry.Name), 1, ); this.refresh(false); } private async getRegistries(): Promise<Registry[]> { if (!this.registries) { this.registries = await this.odo.getRegistries(); } return this.registries; } // eslint-disable-next-line class-methods-use-this async getChildren(parent: ComponentType): Promise<ComponentType[]> { let children: ComponentType[]; const addEnv = this.odo.getKubeconfigEnv(); if (!parent) { this.registries = await this.getRegistries(); children = this.registries; } else if (isRegistry(parent)) { const result = await this.odo.execute( Command.listCatalogComponentsJson(), Platform.getUserHomePath(), true, addEnv, ); children = this.loadItems<ComponentTypesJson, DevfileComponentType>( result, (data) => data.items, ); children = children.filter( (element: DevfileComponentType) => element.Registry.Name === parent.Name, ); } else if (isDevfileComponent(parent)) { const result: CliExitData = await this.odo.execute( Command.describeCatalogComponent(parent.Name), Platform.getUserHomePath(), true, addEnv, ); const descriptions = this.loadItems< ComponentTypeDescription[], ComponentTypeDescription >(result, (data) => data); const description = descriptions.find( (element) => element.RegistryName === parent.Registry.Name && element.Devfile.metadata.name === parent.Name, ); children = description?.Devfile?.starterProjects.map((starter: StarterProject) => { starter.typeName = parent.Name; return starter; }); } return children; } // eslint-disable-next-line class-methods-use-this getParent?(): ComponentType { return undefined; } reveal(item: Registry): void { this.treeView.reveal(item); } refresh(cleanCache = true): void { if (cleanCache) { this.registries = undefined; } this.onDidChangeTreeDataEmitter.fire(undefined); } @vsCommand('openshift.componentTypesView.refresh') public static refresh(): void { ComponentTypesView.instance.refresh(); } public static getSampleRepositoryUrl(element: StarterProject): string { const url = Object.values(element.git.remotes).find((prop) => typeof prop === 'string'); return url; } @vsCommand('openshift.componentType.openStarterProjectRepository') public static async openRepositoryURL(element: StarterProject): Promise<void | string> { const url: string = ComponentTypesView.getSampleRepositoryUrl(element); if (url) { try { await commands.executeCommand('vscode.open', Uri.parse(url, true)); } catch (err) { // TODO: report actual url only for default odo repository throw new VsCommandError( err.toString(), 'Unable to open s`ample project repository', ); } } else { return 'Cannot find sample project repository url'; } } @vsCommand('openshift.componentType.cloneStarterProjectRepository') public static async cloneRepository(element: StarterProject): Promise<void | string> { const url: string = ComponentTypesView.getSampleRepositoryUrl(element); if (url) { try { Uri.parse(url); await commands.executeCommand('git.clone', url); } catch (err) { // TODO: report actual url only for default odo repository throw new VsCommandError( err.toString(), 'Unable to clone sample project repository', ); } } else { return 'Cannot find sample project repository url'; } } @vsCommand('openshift.componentTypesView.registry.add') public static async addRegistryCmd(): Promise<void> { // ask for registry const regName = await window.showInputBox({ prompt: 'Provide registry name to display in the view', placeHolder: 'Registry Name', validateInput: async (value) => { const trimmedValue = value.trim(); if (trimmedValue.length === 0) { return 'Registry name cannot be empty'; } if (!validator.matches(trimmedValue, '^[a-zA-Z0-9]+$')) { return 'Registry name can have only alphabet characters and numbers'; } const registries = await ComponentTypesView.instance.getRegistries(); if (registries.find((registry) => registry.Name === value)) { return `Registry name '${value}' is already used`; } }, }); if (!regName) return null; const regURL = await window.showInputBox({ ignoreFocusOut: true, prompt: 'Provide registry URL to display in the view', placeHolder: 'Registry URL', validateInput: async (value) => { const trimmedValue = value.trim(); if (!validator.isURL(trimmedValue)) { return 'Entered URL is invalid'; } const registries = await ComponentTypesView.instance.getRegistries(); if (registries.find((registry) => registry.URL === value)) { return `Registry with entered URL '${value}' already exists`; } }, }); if (!regURL) return null; const secure = await window.showQuickPick(['Yes', 'No'], { placeHolder: 'Is it a secure registry?', }); if (!secure) return null; let token: string; if (secure === 'Yes') { token = await window.showInputBox({ placeHolder: 'Token to access the registry' }); if (!token) return null; } const newRegistry = await OdoImpl.Instance.addRegistry(regName, regURL, token); ComponentTypesView.instance.addRegistry(newRegistry); } @vsCommand('openshift.componentTypesView.registry.remove') public static async removeRegistry(registry: Registry): Promise<void> { const yesNo = await window.showInformationMessage( `Remove registry '${registry.Name}'?`, 'Yes', 'No', ); if (yesNo === 'Yes') { await OdoImpl.Instance.removeRegistry(registry.Name); ComponentTypesView.instance.removeRegistry(registry); } } }
the_stack
import { isOSX } from '@malagu/core'; export type KeySequence = KeyCode[]; export namespace KeySequence { export function equals(a: KeySequence, b: KeySequence): boolean { if (a.length !== b.length) { return false; } for (let i = 0; i < a.length; i++) { if (!a[i].equals(b[i])) { return false; } } return true; } export enum CompareResult { NONE = 0, PARTIAL, SHADOW, FULL } /* Compares two KeySequences, returns: * FULL if the KeySequences are the same. * PARTIAL if the KeySequence a part of b. * SHADOW if the KeySequence b part of a. * NONE if the KeySequences are not the same at all. */ export function compare(a: KeySequence, b: KeySequence): CompareResult { let first = a; let second = b; let shadow = false; if (b.length < a.length) { first = b; second = a; shadow = true; } for (let i = 0; i < first.length; i++) { if (first[i].equals(second[i]) === false) { return KeySequence.CompareResult.NONE; } } if (first.length < second.length) { if (shadow === false) { return KeySequence.CompareResult.PARTIAL; } else { return KeySequence.CompareResult.SHADOW; } } return KeySequence.CompareResult.FULL; } export function parse(keybinding: string): KeySequence { const keyCodes = []; const rawKeyCodes = keybinding.trim().split(/\s+/g); for (const rawKeyCode of rawKeyCodes) { const keyCode = KeyCode.parse(rawKeyCode); if (keyCode !== undefined) { keyCodes.push(keyCode); } } return keyCodes; } } /** * The key sequence for this binding. This key sequence should consist of one or more key strokes. Key strokes * consist of one or more keys held down at the same time. This should be zero or more modifier keys, and zero or one other key. * Since `M2+M3+<Key>` (Alt+Shift+<Key>) is reserved on MacOS X for writing special characters, such bindings are commonly * undefined for platform MacOS X and redefined as `M1+M3+<Key>`. The rule applies on the `M3+M2+<Key>` sequence. */ export interface Keystroke { readonly first?: Key; readonly modifiers?: KeyModifier[]; } export interface KeyCodeSchema { key?: Partial<Key>; ctrl?: boolean; shift?: boolean; alt?: boolean; meta?: boolean; character?: string; } /** * Representation of a pressed key combined with key modifiers. */ export class KeyCode { public readonly key: Key | undefined; public readonly ctrl: boolean; public readonly shift: boolean; public readonly alt: boolean; public readonly meta: boolean; public readonly character: string | undefined; public constructor(schema: KeyCodeSchema) { const key = schema.key; if (key) { if (key.code && key.keyCode && key.easyString) { this.key = key as Key; } else if (key.code) { this.key = Key.getKey(key.code); } else if (key.keyCode) { this.key = Key.getKey(key.keyCode); } } this.ctrl = !!schema.ctrl; this.shift = !!schema.shift; this.alt = !!schema.alt; this.meta = !!schema.meta; this.character = schema.character; } /** * Return true if this KeyCode only contains modifiers. */ public isModifierOnly(): boolean { return this.key === undefined; } /** * Return true if the given KeyCode is equal to this one. */ equals(other: KeyCode): boolean { if (this.key && (!other.key || this.key.code !== other.key.code) || !this.key && other.key) { return false; } return this.ctrl === other.ctrl && this.alt === other.alt && this.shift === other.shift && this.meta === other.meta; } /* * Return a keybinding string compatible with the `Keybinding.keybinding` property. */ toString(): string { const result = []; if (this.meta) { result.push(SpecialCases.META); } if (this.shift) { result.push(Key.SHIFT_LEFT.easyString); } if (this.alt) { result.push(Key.ALT_LEFT.easyString); } if (this.ctrl) { result.push(Key.CONTROL_LEFT.easyString); } if (this.key) { result.push(this.key.easyString); } return result.join('+'); } /** * Create a KeyCode from one of several input types. */ public static createKeyCode(input: KeyboardEvent | Keystroke | KeyCodeSchema | string, eventDispatch: 'code' | 'keyCode' = 'code'): KeyCode { if (typeof input === 'string') { const parts = input.split('+'); if (!KeyCode.isModifierString(parts[0])) { return KeyCode.createKeyCode({ first: Key.getKey(parts[0]), modifiers: parts.slice(1) as KeyModifier[] }); } return KeyCode.createKeyCode({ modifiers: parts as KeyModifier[] }); } else if (KeyCode.isKeyboardEvent(input)) { const key = KeyCode.toKey(input, eventDispatch); return new KeyCode({ key: Key.isModifier(key.code) ? undefined : key, meta: isOSX && input.metaKey, shift: input.shiftKey, alt: input.altKey, ctrl: input.ctrlKey, character: KeyCode.toCharacter(input) }); } else if ((input as Keystroke).first || (input as Keystroke).modifiers) { const keystroke = input as Keystroke; const schema: KeyCodeSchema = { key: keystroke.first }; if (keystroke.modifiers) { if (isOSX) { schema.meta = keystroke.modifiers.some(mod => mod === KeyModifier.CtrlCmd); schema.ctrl = keystroke.modifiers.some(mod => mod === KeyModifier.MacCtrl); } else { schema.meta = false; schema.ctrl = keystroke.modifiers.some(mod => mod === KeyModifier.CtrlCmd); } schema.shift = keystroke.modifiers.some(mod => mod === KeyModifier.Shift); schema.alt = keystroke.modifiers.some(mod => mod === KeyModifier.Alt); } return new KeyCode(schema); } else { return new KeyCode(input as KeyCodeSchema); } } private static keybindings: { [key: string]: KeyCode } = {}; /* Reset the key hashmap, this is for testing purposes. */ public static resetKeyBindings(): void { KeyCode.keybindings = {}; } /** * Parses a string and returns a KeyCode object. * @param keybinding String representation of a keybinding */ public static parse(keybinding: string): KeyCode { if (KeyCode.keybindings[keybinding]) { return KeyCode.keybindings[keybinding]; } const schema: KeyCodeSchema = {}; const keys = []; let currentKey = ''; for (const character of keybinding.trim().toLowerCase()) { if (currentKey && (character === '-' || character === '+')) { keys.push(currentKey); currentKey = ''; } else if (character !== '+') { currentKey += character; } } if (currentKey) { keys.push(currentKey); } /* If duplicates i.e ctrl+ctrl+a or alt+alt+b or b+alt+b it is invalid */ if (keys.length !== new Set(keys).size) { throw new Error(`Can't parse keybinding ${keybinding} Duplicate modifiers`); } for (let keyString of keys) { if (SPECIAL_ALIASES[keyString] !== undefined) { keyString = SPECIAL_ALIASES[keyString]; } const key = EASY_TO_KEY[keyString]; /* meta only works on macOS */ if (keyString === SpecialCases.META) { if (isOSX) { schema.meta = true; } else { throw new Error(`Can't parse keybinding ${keybinding} meta is for OSX only`); } /* ctrlcmd for M1 keybindings that work on both macOS and other platforms */ } else if (keyString === SpecialCases.CTRLCMD) { if (isOSX) { schema.meta = true; } else { schema.ctrl = true; } } else if (Key.isKey(key)) { if (Key.isModifier(key.code)) { if (key.code === Key.CONTROL_LEFT.code || key.code === Key.CONTROL_RIGHT.code) { schema.ctrl = true; } else if (key.code === Key.SHIFT_LEFT.code || key.code === Key.SHIFT_RIGHT.code) { schema.shift = true; } else if (key.code === Key.ALT_LEFT.code || key.code === Key.ALT_RIGHT.code) { schema.alt = true; } } else { schema.key = key; } } else { throw new Error(`Unrecognized key '${keyString}' in '${keybinding}'`); } } KeyCode.keybindings[keybinding] = new KeyCode(schema); return KeyCode.keybindings[keybinding]; } } export namespace KeyCode { /** * Determines a `true` of `false` value for the key code argument. */ export type Predicate = (keyCode: KeyCode) => boolean; /* * Return true if the string is a modifier M1 to M4. */ export function isModifierString(key: string): boolean { return key === KeyModifier.CtrlCmd || key === KeyModifier.Shift || key === KeyModifier.Alt || key === KeyModifier.MacCtrl; } /** * Different scopes have different execution environments. This means that they have different built-ins * (different global object, different constructors, etc.). This may result in unexpected results. For instance, * `[] instanceof window.frames[0].Array` will return `false`, because `Array.prototype !== window.frames[0].Array` * and arrays inherit from the former. * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof * * Note: just add another check if the current `event.type` checking is insufficient. */ export function isKeyboardEvent(event: object & { readonly type?: string }): event is KeyboardEvent { if (typeof KeyboardEvent === 'undefined') { // This can happen in tests return false; } if (event instanceof KeyboardEvent) { return true; } const { type } = event; if (type) { return type === 'keypress' || type === 'keydown' || type === 'keyup'; } return false; } /** * Determine the pressed key of a keyboard event. This key should correspond to the physical key according * to a standard US keyboard layout. International keyboard layouts are handled by `KeyboardLayoutService`. * * `keyIdentifier` is used to access this deprecated field: * https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyIdentifier */ export function toKey(event: KeyboardEvent, dispatch: 'code' | 'keyCode' = 'code'): Key { const code = event.code; if (code && dispatch === 'code') { if (isOSX) { // https://github.com/eclipse-theia/theia/issues/4986 const char = event.key; if (code === 'IntlBackslash' && (char === '`' || char === '~')) { return Key.BACKQUOTE; } else if (code === 'Backquote' && (char === '§' || char === '±')) { return Key.INTL_BACKSLASH; } } // https://github.com/eclipse-theia/theia/issues/7315 if (code.startsWith('Numpad') && event.key && event.key.length > 1) { const k = Key.getKey(event.key); if (k) { return k; } } const key = Key.getKey(code); if (key) { return key; } } // eslint-disable-next-line deprecation/deprecation const keyCode = event.keyCode; if (keyCode) { const key = Key.getKey(keyCode); if (key) { return key; } } const keyIdentifier = (event as KeyboardEvent & { keyIdentifier?: string }).keyIdentifier; if (keyIdentifier) { const key = Key.getKey(keyIdentifier); if (key) { return key; } } throw new Error(`Cannot get key code from the keyboard event: ${event}.`); } /** * Determine the actual printable character that is generated from a pressed key. * If the key does not correspond to a printable character, `undefined` is returned. * The result may be altered by modifier keys. */ export function toCharacter(event: KeyboardEvent): string | undefined { const key = event.key; // Use the key property if it contains exactly one unicode character if (key && Array.from(key).length === 1) { return key; } // eslint-disable-next-line deprecation/deprecation const charCode = event.charCode; // Use the charCode property if it does not correspond to a unicode control character if (charCode && charCode > 0x1f && !(charCode >= 0x80 && charCode <= 0x9f)) { return String.fromCharCode(charCode); } return undefined; } } export enum KeyModifier { /** * M1 is the COMMAND key on MacOS X, and the CTRL key on most other platforms. */ CtrlCmd = 'M1', /** * M2 is the SHIFT key. */ Shift = 'M2', /** * M3 is the Option key on MacOS X, and the ALT key on most other platforms. */ Alt = 'M3', /** * M4 is the CTRL key on MacOS X, and is undefined on other platforms. */ MacCtrl = 'M4' } export namespace KeyModifier { /** * The CTRL key, independently of the platform. * _Note:_ In general `KeyModifier.CtrlCmd` should be preferred over this constant. */ export const CTRL: KeyModifier.MacCtrl | KeyModifier.CtrlCmd = isOSX ? KeyModifier.MacCtrl : KeyModifier.CtrlCmd; /** * An alias for the SHIFT key (`KeyModifier.Shift`). */ export const SHIFT: KeyModifier.Shift = KeyModifier.Shift; /** * `true` if the argument represents a modifier. Otherwise, `false`. */ export function isModifier(key: string | undefined): boolean { if (key) { switch (key) { case 'M1': // Fall through. case 'M2': // Fall through. case 'M3': // Fall through. case 'M4': return true; default: return false; } } return false; } } export interface Key { readonly code: string; readonly keyCode: number; readonly easyString: string; } const CODE_TO_KEY: { [code: string]: Key } = {}; const KEY_CODE_TO_KEY: { [keyCode: number]: Key } = {}; const EASY_TO_KEY: { [code: string]: Key } = {}; // From 'ctrl' to Key structure const MODIFIERS: Key[] = []; const SPECIAL_ALIASES: { [index: string]: string } = { 'option': 'alt', 'command': 'meta', 'cmd': 'meta', 'return': 'enter', 'esc': 'escape', 'mod': 'ctrl', 'ins': 'insert', 'del': 'delete', 'control': 'ctrl', }; export namespace SpecialCases { export const META = 'meta'; export const CTRLCMD = 'ctrlcmd'; } export namespace Key { // eslint-disable-next-line @typescript-eslint/no-explicit-any export function isKey(arg: any): arg is Key { return typeof arg === 'object' && ('code' in arg) && ('keyCode' in arg); } export function getKey(arg: string | number): Key | undefined { if (typeof arg === 'number') { return KEY_CODE_TO_KEY[arg]; } else { return CODE_TO_KEY[arg]; } } export function isModifier(arg: string | number): boolean { if (typeof arg === 'number') { return MODIFIERS.find(key => key.keyCode === arg) !== undefined; } return MODIFIERS.find(key => key.code === arg) !== undefined; } export function equals(key: Key, keyCode: KeyCode): boolean { return !!keyCode.key && key.keyCode === keyCode.key.keyCode; } export const BACKSPACE: Key = { code: 'Backspace', keyCode: 8, easyString: 'backspace' }; export const TAB: Key = { code: 'Tab', keyCode: 9, easyString: 'tab' }; export const ENTER: Key = { code: 'Enter', keyCode: 13, easyString: 'enter' }; export const ESCAPE: Key = { code: 'Escape', keyCode: 27, easyString: 'escape' }; export const SPACE: Key = { code: 'Space', keyCode: 32, easyString: 'space' }; export const PAGE_UP: Key = { code: 'PageUp', keyCode: 33, easyString: 'pageup' }; export const PAGE_DOWN: Key = { code: 'PageDown', keyCode: 34, easyString: 'pagedown' }; export const END: Key = { code: 'End', keyCode: 35, easyString: 'end' }; export const HOME: Key = { code: 'Home', keyCode: 36, easyString: 'home' }; export const ARROW_LEFT: Key = { code: 'ArrowLeft', keyCode: 37, easyString: 'left' }; export const ARROW_UP: Key = { code: 'ArrowUp', keyCode: 38, easyString: 'up' }; export const ARROW_RIGHT: Key = { code: 'ArrowRight', keyCode: 39, easyString: 'right' }; export const ARROW_DOWN: Key = { code: 'ArrowDown', keyCode: 40, easyString: 'down' }; export const INSERT: Key = { code: 'Insert', keyCode: 45, easyString: 'insert' }; export const DELETE: Key = { code: 'Delete', keyCode: 46, easyString: 'delete' }; export const SHIFT_LEFT: Key = { code: 'ShiftLeft', keyCode: 16, easyString: 'shift' }; export const SHIFT_RIGHT: Key = { code: 'ShiftRight', keyCode: 16, easyString: 'shift' }; export const CONTROL_LEFT: Key = { code: 'ControlLeft', keyCode: 17, easyString: 'ctrl' }; export const CONTROL_RIGHT: Key = { code: 'ControlRight', keyCode: 17, easyString: 'ctrl' }; export const ALT_LEFT: Key = { code: 'AltLeft', keyCode: 18, easyString: 'alt' }; export const ALT_RIGHT: Key = { code: 'AltRight', keyCode: 18, easyString: 'alt' }; export const CAPS_LOCK: Key = { code: 'CapsLock', keyCode: 20, easyString: 'capslock' }; export const OS_LEFT: Key = { code: 'OSLeft', keyCode: 91, easyString: 'super' }; export const OS_RIGHT: Key = { code: 'OSRight', keyCode: 92, easyString: 'super' }; export const DIGIT0: Key = { code: 'Digit0', keyCode: 48, easyString: '0' }; export const DIGIT1: Key = { code: 'Digit1', keyCode: 49, easyString: '1' }; export const DIGIT2: Key = { code: 'Digit2', keyCode: 50, easyString: '2' }; export const DIGIT3: Key = { code: 'Digit3', keyCode: 51, easyString: '3' }; export const DIGIT4: Key = { code: 'Digit4', keyCode: 52, easyString: '4' }; export const DIGIT5: Key = { code: 'Digit5', keyCode: 53, easyString: '5' }; export const DIGIT6: Key = { code: 'Digit6', keyCode: 54, easyString: '6' }; export const DIGIT7: Key = { code: 'Digit7', keyCode: 55, easyString: '7' }; export const DIGIT8: Key = { code: 'Digit8', keyCode: 56, easyString: '8' }; export const DIGIT9: Key = { code: 'Digit9', keyCode: 57, easyString: '9' }; export const KEY_A: Key = { code: 'KeyA', keyCode: 65, easyString: 'a' }; export const KEY_B: Key = { code: 'KeyB', keyCode: 66, easyString: 'b' }; export const KEY_C: Key = { code: 'KeyC', keyCode: 67, easyString: 'c' }; export const KEY_D: Key = { code: 'KeyD', keyCode: 68, easyString: 'd' }; export const KEY_E: Key = { code: 'KeyE', keyCode: 69, easyString: 'e' }; export const KEY_F: Key = { code: 'KeyF', keyCode: 70, easyString: 'f' }; export const KEY_G: Key = { code: 'KeyG', keyCode: 71, easyString: 'g' }; export const KEY_H: Key = { code: 'KeyH', keyCode: 72, easyString: 'h' }; export const KEY_I: Key = { code: 'KeyI', keyCode: 73, easyString: 'i' }; export const KEY_J: Key = { code: 'KeyJ', keyCode: 74, easyString: 'j' }; export const KEY_K: Key = { code: 'KeyK', keyCode: 75, easyString: 'k' }; export const KEY_L: Key = { code: 'KeyL', keyCode: 76, easyString: 'l' }; export const KEY_M: Key = { code: 'KeyM', keyCode: 77, easyString: 'm' }; export const KEY_N: Key = { code: 'KeyN', keyCode: 78, easyString: 'n' }; export const KEY_O: Key = { code: 'KeyO', keyCode: 79, easyString: 'o' }; export const KEY_P: Key = { code: 'KeyP', keyCode: 80, easyString: 'p' }; export const KEY_Q: Key = { code: 'KeyQ', keyCode: 81, easyString: 'q' }; export const KEY_R: Key = { code: 'KeyR', keyCode: 82, easyString: 'r' }; export const KEY_S: Key = { code: 'KeyS', keyCode: 83, easyString: 's' }; export const KEY_T: Key = { code: 'KeyT', keyCode: 84, easyString: 't' }; export const KEY_U: Key = { code: 'KeyU', keyCode: 85, easyString: 'u' }; export const KEY_V: Key = { code: 'KeyV', keyCode: 86, easyString: 'v' }; export const KEY_W: Key = { code: 'KeyW', keyCode: 87, easyString: 'w' }; export const KEY_X: Key = { code: 'KeyX', keyCode: 88, easyString: 'x' }; export const KEY_Y: Key = { code: 'KeyY', keyCode: 89, easyString: 'y' }; export const KEY_Z: Key = { code: 'KeyZ', keyCode: 90, easyString: 'z' }; export const MULTIPLY: Key = { code: 'NumpadMultiply', keyCode: 106, easyString: 'multiply' }; export const ADD: Key = { code: 'NumpadAdd', keyCode: 107, easyString: 'add' }; export const DECIMAL: Key = { code: 'NumpadDecimal', keyCode: 108, easyString: 'decimal' }; export const SUBTRACT: Key = { code: 'NumpadSubtract', keyCode: 109, easyString: 'subtract' }; export const DIVIDE: Key = { code: 'NumpadDivide', keyCode: 111, easyString: 'divide' }; export const F1: Key = { code: 'F1', keyCode: 112, easyString: 'f1' }; export const F2: Key = { code: 'F2', keyCode: 113, easyString: 'f2' }; export const F3: Key = { code: 'F3', keyCode: 114, easyString: 'f3' }; export const F4: Key = { code: 'F4', keyCode: 115, easyString: 'f4' }; export const F5: Key = { code: 'F5', keyCode: 116, easyString: 'f5' }; export const F6: Key = { code: 'F6', keyCode: 117, easyString: 'f6' }; export const F7: Key = { code: 'F7', keyCode: 118, easyString: 'f7' }; export const F8: Key = { code: 'F8', keyCode: 119, easyString: 'f8' }; export const F9: Key = { code: 'F9', keyCode: 120, easyString: 'f9' }; export const F10: Key = { code: 'F10', keyCode: 121, easyString: 'f10' }; export const F11: Key = { code: 'F11', keyCode: 122, easyString: 'f11' }; export const F12: Key = { code: 'F12', keyCode: 123, easyString: 'f12' }; export const F13: Key = { code: 'F13', keyCode: 124, easyString: 'f13' }; export const F14: Key = { code: 'F14', keyCode: 125, easyString: 'f14' }; export const F15: Key = { code: 'F15', keyCode: 126, easyString: 'f15' }; export const F16: Key = { code: 'F16', keyCode: 127, easyString: 'f16' }; export const F17: Key = { code: 'F17', keyCode: 128, easyString: 'f17' }; export const F18: Key = { code: 'F18', keyCode: 129, easyString: 'f18' }; export const F19: Key = { code: 'F19', keyCode: 130, easyString: 'f19' }; export const F20: Key = { code: 'F20', keyCode: 131, easyString: 'f20' }; export const F21: Key = { code: 'F21', keyCode: 132, easyString: 'f21' }; export const F22: Key = { code: 'F22', keyCode: 133, easyString: 'f22' }; export const F23: Key = { code: 'F23', keyCode: 134, easyString: 'f23' }; export const F24: Key = { code: 'F24', keyCode: 135, easyString: 'f24' }; export const NUM_LOCK: Key = { code: 'NumLock', keyCode: 144, easyString: 'numlock' }; export const SEMICOLON: Key = { code: 'Semicolon', keyCode: 186, easyString: ';' }; export const EQUAL: Key = { code: 'Equal', keyCode: 187, easyString: '=' }; export const COMMA: Key = { code: 'Comma', keyCode: 188, easyString: ',' }; export const MINUS: Key = { code: 'Minus', keyCode: 189, easyString: '-' }; export const PERIOD: Key = { code: 'Period', keyCode: 190, easyString: '.' }; export const SLASH: Key = { code: 'Slash', keyCode: 191, easyString: '/' }; export const BACKQUOTE: Key = { code: 'Backquote', keyCode: 192, easyString: '`' }; export const INTL_RO: Key = { code: 'IntlRo', keyCode: 193, easyString: 'intlro' }; export const BRACKET_LEFT: Key = { code: 'BracketLeft', keyCode: 219, easyString: '[' }; export const BACKSLASH: Key = { code: 'Backslash', keyCode: 220, easyString: '\\' }; export const BRACKET_RIGHT: Key = { code: 'BracketRight', keyCode: 221, easyString: ']' }; export const QUOTE: Key = { code: 'Quote', keyCode: 222, easyString: '\'' }; export const INTL_BACKSLASH: Key = { code: 'IntlBackslash', keyCode: 229, easyString: 'intlbackslash' }; export const INTL_YEN: Key = { code: 'IntlYen', keyCode: 255, easyString: 'intlyen' }; export const MAX_KEY_CODE = INTL_YEN.keyCode; } /* -------------------- Initialize the static key mappings -------------------- */ (() => { // Set the default key mappings from the constants in the Key namespace Object.keys(Key).map(prop => Reflect.get(Key, prop)).filter(key => Key.isKey(key)).forEach(key => { CODE_TO_KEY[key.code] = key; KEY_CODE_TO_KEY[key.keyCode] = key; EASY_TO_KEY[key.easyString] = key; }); // Set additional key mappings CODE_TO_KEY['Numpad0'] = Key.DIGIT0; KEY_CODE_TO_KEY[96] = Key.DIGIT0; CODE_TO_KEY['Numpad1'] = Key.DIGIT1; KEY_CODE_TO_KEY[97] = Key.DIGIT1; CODE_TO_KEY['Numpad2'] = Key.DIGIT2; KEY_CODE_TO_KEY[98] = Key.DIGIT2; CODE_TO_KEY['Numpad3'] = Key.DIGIT3; KEY_CODE_TO_KEY[99] = Key.DIGIT3; CODE_TO_KEY['Numpad4'] = Key.DIGIT4; KEY_CODE_TO_KEY[100] = Key.DIGIT4; CODE_TO_KEY['Numpad5'] = Key.DIGIT5; KEY_CODE_TO_KEY[101] = Key.DIGIT5; CODE_TO_KEY['Numpad6'] = Key.DIGIT6; KEY_CODE_TO_KEY[102] = Key.DIGIT6; CODE_TO_KEY['Numpad7'] = Key.DIGIT7; KEY_CODE_TO_KEY[103] = Key.DIGIT7; CODE_TO_KEY['Numpad8'] = Key.DIGIT8; KEY_CODE_TO_KEY[104] = Key.DIGIT8; CODE_TO_KEY['Numpad9'] = Key.DIGIT9; KEY_CODE_TO_KEY[105] = Key.DIGIT9; CODE_TO_KEY['NumpadEnter'] = Key.ENTER; CODE_TO_KEY['NumpadEqual'] = Key.EQUAL; CODE_TO_KEY['MetaLeft'] = Key.OS_LEFT; // Chrome, Safari KEY_CODE_TO_KEY[224] = Key.OS_LEFT; // Firefox on Mac CODE_TO_KEY['MetaRight'] = Key.OS_RIGHT; // Chrome, Safari KEY_CODE_TO_KEY[93] = Key.OS_RIGHT; // Chrome, Safari, Edge KEY_CODE_TO_KEY[225] = Key.ALT_RIGHT; // Linux KEY_CODE_TO_KEY[110] = Key.DECIMAL; // Mac, Windows KEY_CODE_TO_KEY[59] = Key.SEMICOLON; // Firefox KEY_CODE_TO_KEY[61] = Key.EQUAL; // Firefox KEY_CODE_TO_KEY[173] = Key.MINUS; // Firefox KEY_CODE_TO_KEY[226] = Key.BACKSLASH; // Chrome, Edge on Windows KEY_CODE_TO_KEY[60] = Key.BACKSLASH; // Firefox on Linux // Set the modifier keys MODIFIERS.push(...[Key.ALT_LEFT, Key.ALT_RIGHT, Key.CONTROL_LEFT, Key.CONTROL_RIGHT, Key.OS_LEFT, Key.OS_RIGHT, Key.SHIFT_LEFT, Key.SHIFT_RIGHT]); })(); export type KeysOrKeyCodes = Key | KeyCode | (Key | KeyCode)[]; export namespace KeysOrKeyCodes { export const toKeyCode = (keyOrKeyCode: Key | KeyCode) => keyOrKeyCode instanceof KeyCode ? keyOrKeyCode : KeyCode.createKeyCode({ first: keyOrKeyCode }); export const toKeyCodes = (keysOrKeyCodes: KeysOrKeyCodes) => { if (keysOrKeyCodes instanceof KeyCode) { return [keysOrKeyCodes]; } else if (Array.isArray(keysOrKeyCodes)) { return keysOrKeyCodes.slice().map(toKeyCode); } return [toKeyCode(keysOrKeyCodes)]; }; }
the_stack
* @module Popup */ import "./Popup.scss"; import classnames from "classnames"; import * as React from "react"; import * as ReactDOM from "react-dom"; import { RelativePosition, SpecialKey } from "@itwin/appui-abstract"; import { FocusTrap } from "../focustrap/FocusTrap"; import { CommonProps } from "../utils/Props"; // cSpell:ignore focustrap focusable alertdialog /** @internal */ interface PopupPoint { x: number; y: number; } /** Properties for the [[Popup]] component * @public */ export interface PopupProps extends CommonProps { /** Show or hide the box shadow (defaults to true) */ showShadow: boolean; /** Show or hide the arrow (defaults to false) */ showArrow: boolean; /** Indicates whether the popup is shown or not (defaults to false) */ isOpen: boolean; /** Direction (relative to the target) to which the popup is expanded (defaults to Bottom) */ position: RelativePosition; /** Top position (absolute positioning - defaults to 0) */ top: number; /** Left position (absolute positioning - defaults to 0) */ left: number; /** Function called when the popup is opened */ onOpen?: () => void; /** Function called when user clicks outside the popup */ onOutsideClick?: (e: MouseEvent) => void; /** Function called when the popup is closed */ onClose?: () => void; /** Function called when the popup is closed on Enter */ onEnter?: () => void; /** Function called when the wheel is used */ onWheel?: (e: WheelEvent) => void; /** Function called when the right mouse button is pressed */ onContextMenu?: (e: MouseEvent) => void; /** Offset from the parent (defaults to 4) */ offset: number; /** Target element to position popup */ target?: HTMLElement | null; /** Role - if not specified "dialog" is used */ role?: "dialog" | "alert" | "alertdialog"; /** accessibility label */ ariaLabel?: string; /** set focus to popup - default to not set focus */ moveFocus?: boolean; /** Element to receive focus, specified by React.RefObject or CSS selector string. If undefined and moveFocus is true then focus is moved to first focusable element. */ focusTarget?: React.RefObject<HTMLElement> | string; /** Indicates whether the popup is pinned. */ isPinned?: boolean; /** Indicates whether to use animation for open/close (defaults to true) */ animate?: boolean; /** Indicates whether to close the popup when Enter is pressed (defaults to true) */ closeOnEnter?: boolean; /** Indicates whether to close the popup when the wheel is used (defaults to true) */ closeOnWheel?: boolean; /** Indicates whether to close the popup when the right mouse button is pressed (defaults to true) */ closeOnContextMenu?: boolean; /** If false outside click processing and closing are skipped if click occurs in another Popup component, default to false. */ closeOnNestedPopupOutsideClick?: boolean; /** If true the children are mounted once and unmounted when this component is unmounted. If false the * children are unmounted each time the popup is closed. */ keepContentsMounted?: boolean; } /** @internal */ interface PopupState { isOpen: boolean; top: number; left: number; position: RelativePosition; parentDocument: Document; animationEnded: boolean; } /** Popup React component displays a popup relative to an optional target element. * @public */ export class Popup extends React.Component<PopupProps, PopupState> { private _popup: HTMLElement | null = null; constructor(props: PopupProps) { super(props); const parentDocument = this.props.target?.ownerDocument ?? document; this.state = { animationEnded: false, isOpen: this.props.isOpen, top: 0, left: 0, position: this.props.position, parentDocument, }; } public static defaultProps: Partial<PopupProps> = { position: RelativePosition.Bottom, showShadow: true, showArrow: false, isOpen: false, offset: 4, top: -1, left: -1, }; public override componentDidMount() { if (this.props.isOpen) { this._onShow(); } } private getParentWindow() { // istanbul ignore next return this.state.parentDocument.defaultView ?? window; } public override componentDidUpdate(previousProps: PopupProps, prevState: PopupState) { if (this.state.position !== prevState.position) { this.setState( { animationEnded: false }); } if (this.props.target !== previousProps.target) { // istanbul ignore next { const parentDocument = this.props.target?.ownerDocument ?? document; if (parentDocument !== this.state.parentDocument) { this._unBindWindowEvents(); this.setState({ parentDocument }); } } } if (this.props.isOpen === previousProps.isOpen) { if (this.props.isOpen) { const position = this._toggleRelativePosition(); const point = this._fitPopup(this._getPosition(position)); if ((Math.abs(this.state.left - point.x) < 3) && (Math.abs(this.state.top - point.y) < 3) && this.state.position === position) return; this.setState({ left: point.x, top: point.y, position, }); } return; } if (this.props.isOpen) { this._onShow(); } else { this._onClose(); } } public override componentWillUnmount() { this._unBindWindowEvents(); } private _bindWindowEvents = () => { const activeWindow = this.getParentWindow(); activeWindow.addEventListener("pointerdown", this._handleOutsideClick); activeWindow.addEventListener("resize", this._hide); activeWindow.addEventListener("contextmenu", this._handleContextMenu); activeWindow.addEventListener("scroll", this._hide); activeWindow.addEventListener("wheel", this._handleWheel); activeWindow.addEventListener("keydown", this._handleKeyboard); }; private _unBindWindowEvents = () => { const activeWindow = this.getParentWindow(); activeWindow.removeEventListener("pointerdown", this._handleOutsideClick); activeWindow.removeEventListener("resize", this._hide); activeWindow.removeEventListener("contextmenu", this._handleContextMenu); activeWindow.removeEventListener("scroll", this._hide); activeWindow.removeEventListener("wheel", this._handleWheel); activeWindow.removeEventListener("keydown", this._handleKeyboard); }; private _handleWheel = (event: WheelEvent) => { if (this._popup && this._popup.contains(event.target as Node)) return; if (this.props.onWheel) return this.props.onWheel(event); const closeOnWheel = this.props.closeOnWheel !== undefined ? this.props.closeOnWheel : true; if (closeOnWheel) this._hide(); }; private isInCorePopup(element: HTMLElement): boolean { if (element.nodeName === "DIV") { if (element.classList && element.classList.contains("core-popup")) return true; if (element.parentElement && this.isInCorePopup(element.parentElement)) return true; } else { // istanbul ignore else if (element.parentElement && this.isInCorePopup(element.parentElement)) return true; } return false; } private _handleOutsideClick = (event: MouseEvent): void => { if (this._popup && this._popup.contains(event.target as Node)) return; if (this.props.isPinned) return; if (!this.props.closeOnNestedPopupOutsideClick && this.isInCorePopup(event.target as HTMLElement)) return; if (this.props.onOutsideClick) return this.props.onOutsideClick(event); if (this.props.target && this.props.target.contains(event.target as Node)) return; this._onClose(); }; private _handleContextMenu = (event: MouseEvent) => { if (this._popup && this._popup.contains(event.target as Node)) return; if (this.props.onContextMenu) return this.props.onContextMenu(event); const closeOnContextMenu = this.props.closeOnContextMenu !== undefined ? this.props.closeOnContextMenu : true; if (closeOnContextMenu) this._hide(); }; private _handleKeyboard = (event: KeyboardEvent): void => { if (this.props.isPinned) return; if (event.key === SpecialKey.Escape || event.key === SpecialKey.Enter) { const closeOnEnter = this.props.closeOnEnter !== undefined ? this.props.closeOnEnter : true; if (event.key === SpecialKey.Enter) { if (closeOnEnter) this._onClose(true); else this.props.onEnter && this.props.onEnter(); } else { this._onClose(false); } } }; private _hide = () => { if (this.props.isPinned) return; this._onClose(); }; private _onShow() { this._bindWindowEvents(); const position = this._toggleRelativePosition(); const point = this._fitPopup(this._getPosition(position)); this.setState({ left: point.x, top: point.y, isOpen: true, position }, () => { if (this.props.onOpen) this.props.onOpen(); }); } private _onClose(enterKey?: boolean) { if (!this.state.isOpen) return; this._unBindWindowEvents(); this.setState({ isOpen: false }, () => { if (enterKey && this.props.onEnter) this.props.onEnter(); if (this.props.onClose) this.props.onClose(); }); } private _isPositionAbsolute(): boolean { return (this.props.top !== -1 && this.props.left !== -1); } private _getClassNameByPosition(position: RelativePosition): string { if (!this._isPositionAbsolute()) { switch (position) { case RelativePosition.TopLeft: return "core-popup-top-left"; case RelativePosition.TopRight: return "core-popup-top-right"; case RelativePosition.BottomLeft: return "core-popup-bottom-left"; case RelativePosition.BottomRight: return "core-popup-bottom-right"; case RelativePosition.Top: return "core-popup-top"; case RelativePosition.Left: return "core-popup-left"; case RelativePosition.Right: return "core-popup-right"; case RelativePosition.Bottom: return "core-popup-bottom"; case RelativePosition.LeftTop: return "core-popup-left-top"; case RelativePosition.RightTop: return "core-popup-right-top"; } } return ""; } private _getPopupDimensions(): { popupWidth: number, popupHeight: number } { let popupWidth = 0; let popupHeight = 0; // istanbul ignore else if (this._popup) { const activeWindow = this.getParentWindow(); const style = activeWindow.getComputedStyle(this._popup); const borderLeftWidth = parsePxString(style.borderLeftWidth); const borderRightWidth = parsePxString(style.borderRightWidth); const borderTopWidth = parsePxString(style.borderTopWidth); const borderBottomWidth = parsePxString(style.borderBottomWidth); popupWidth = this._popup.clientWidth + borderLeftWidth + borderRightWidth; popupHeight = this._popup.clientHeight + borderTopWidth + borderBottomWidth; } return { popupWidth, popupHeight }; } private _getPosition = (position: RelativePosition) => { const activeWindow = this.getParentWindow(); const { target, offset, top, left } = this.props; const offsetArrow = (this.props.showArrow) ? 6 : 0; // absolute position if (this._isPositionAbsolute()) return { x: left, y: top }; // sanity check const point = { x: 0, y: 0 }; if (!this._popup || !target) return point; // relative position const scrollY = activeWindow.scrollY; const scrollX = activeWindow.scrollX; const targetRect = target.getBoundingClientRect(); const { popupWidth, popupHeight } = this._getPopupDimensions(); switch (position) { case RelativePosition.Top: point.y = scrollY + targetRect.top - popupHeight - offset - offsetArrow; point.x = scrollX + targetRect.left + (targetRect.width / 2) - (popupWidth / 2); break; case RelativePosition.TopLeft: point.y = scrollY + targetRect.top - popupHeight - offset - offsetArrow; point.x = scrollX + targetRect.left; break; case RelativePosition.TopRight: point.y = scrollY + targetRect.top - popupHeight - offset - offsetArrow; point.x = scrollX + targetRect.right - popupWidth; break; case RelativePosition.Bottom: point.y = scrollY + targetRect.bottom + offset + offsetArrow; point.x = scrollX + targetRect.left + (targetRect.width / 2) - (popupWidth / 2); break; case RelativePosition.BottomLeft: point.y = scrollY + targetRect.bottom + offset + offsetArrow; point.x = scrollX + targetRect.left; break; case RelativePosition.BottomRight: point.y = scrollY + targetRect.bottom + offset + offsetArrow; point.x = scrollX + targetRect.right - popupWidth; break; case RelativePosition.Left: point.y = scrollY + targetRect.top + (targetRect.height / 2) - (popupHeight / 2); point.x = scrollX + targetRect.left - popupWidth - offset - offsetArrow; break; case RelativePosition.LeftTop: point.y = scrollY + targetRect.top; point.x = scrollX + targetRect.left - popupWidth - offset - offsetArrow; break; case RelativePosition.Right: point.y = scrollY + targetRect.top + (targetRect.height / 2) - (popupHeight / 2); point.x = scrollX + targetRect.right + offset + offsetArrow; break; case RelativePosition.RightTop: point.y = scrollY + targetRect.top; point.x = scrollX + targetRect.right + offset + offsetArrow; break; } return point; }; private _toggleRelativePosition(): RelativePosition { const { target, position, offset } = this.props; if (!this._popup || !target) return position; // istanbul ignore if if (this._isPositionAbsolute()) return position; let newPosition = position; interface Rect { left: number; top: number; right: number; bottom: number; } const activeWindow = this.getParentWindow(); // Note: Cannot use DOMRect yet since it's experimental and not available in all browsers (Nov. 2018) const viewportRect: Rect = { left: activeWindow.scrollX, top: activeWindow.scrollY, right: activeWindow.scrollX + activeWindow.innerWidth, bottom: activeWindow.scrollY + activeWindow.innerHeight }; const targetRect = target.getBoundingClientRect(); const { popupWidth, popupHeight } = this._getPopupDimensions(); const containerStyle = activeWindow.getComputedStyle(target); const offsetArrow = this.props.showArrow ? /* istanbul ignore next */ 10 : 2; const bottomMargin = parseMargin(containerStyle.marginBottom); if ((targetRect.bottom + popupHeight + bottomMargin + offsetArrow + offset) > viewportRect.bottom) { if (newPosition === RelativePosition.Bottom) newPosition = RelativePosition.Top; else if (newPosition === RelativePosition.BottomLeft) newPosition = RelativePosition.TopLeft; else if (newPosition === RelativePosition.BottomRight) newPosition = RelativePosition.TopRight; } const topMargin = parseMargin(containerStyle.marginTop); if ((targetRect.top - popupHeight - topMargin - offsetArrow - offset) < viewportRect.top) { if (newPosition === RelativePosition.Top) newPosition = RelativePosition.Bottom; else if (newPosition === RelativePosition.TopLeft) newPosition = RelativePosition.BottomLeft; else if (newPosition === RelativePosition.TopRight) newPosition = RelativePosition.BottomRight; } const leftMargin = parseMargin(containerStyle.marginLeft); if ((targetRect.left - popupWidth - leftMargin - offsetArrow - offset) < viewportRect.left) { if (newPosition === RelativePosition.Left) newPosition = RelativePosition.Right; else if (newPosition === RelativePosition.LeftTop) newPosition = RelativePosition.RightTop; } const rightMargin = parseMargin(containerStyle.marginRight); if ((targetRect.right + popupWidth + rightMargin + offsetArrow + offset) > viewportRect.right) { if (newPosition === RelativePosition.Right) newPosition = RelativePosition.Left; else if (newPosition === RelativePosition.RightTop) newPosition = RelativePosition.LeftTop; } return newPosition; } // fit the popup within the extents of the view port private _fitPopup = (point: PopupPoint) => { const fittedPoint = point; // istanbul ignore if if (!this._popup) { return fittedPoint; } // const popupRect = this._popup.getBoundingClientRect(); const { popupWidth, popupHeight } = this._getPopupDimensions(); const { innerWidth, innerHeight } = window; // istanbul ignore if if (fittedPoint.y + popupHeight > innerHeight) { fittedPoint.y = innerHeight - popupHeight; } // istanbul ignore if if (fittedPoint.x + popupWidth > innerWidth) { fittedPoint.x = innerWidth - popupWidth; } // istanbul ignore if if (fittedPoint.y < 0) { fittedPoint.y = 0; } if (fittedPoint.x < 0) { fittedPoint.x = 0; } return fittedPoint; }; private _handleAnimationEnd = (event: React.AnimationEvent<HTMLDivElement>) => { if (event.target === this._popup) { this.setState({ animationEnded: true }); } }; public override render() { const animate = this.props.animate !== undefined ? this.props.animate : true; const className = classnames( "core-popup", this._getClassNameByPosition(this.state.position), this.props.showShadow && "core-popup-shadow", this.props.showArrow && "arrow", !animate && "core-popup-animation-none", this.props.className, this.state.animationEnded && "core-animation-ended", (!this.props.isOpen && this.props.keepContentsMounted) && "core-popup-hidden" ); const style: React.CSSProperties = { top: this.state.top, left: this.state.left, ...this.props.style, }; const role = this.props.role ? this.props.role : "dialog"; // accessibility property if (!this.props.isOpen && !this.props.keepContentsMounted) { return null; } return ReactDOM.createPortal( ( <div className={className} data-testid="core-popup" ref={(element) => { this._popup = element; }} style={style} role={role} aria-modal={true} tabIndex={-1} aria-label={this.props.ariaLabel} onAnimationEnd={this._handleAnimationEnd} > <FocusTrap active={!!this.props.moveFocus} initialFocusElement={this.props.focusTarget} returnFocusOnDeactivate={true}> {this.props.children} </FocusTrap> </div> ), this.state.parentDocument.body); } } function parsePxString(pxStr: string): number { const parsed = parseInt(pxStr, 10); return parsed || 0; } function parseMargin(value: string) { return value ? /* istanbul ignore next */ parseFloat(value) : 0; }
the_stack
declare namespace wx { // import startPullDownRefresh = swan.startPullDownRefresh; type NoneParamCallback = () => void; type OneParamCallback = (data: any) => void; type ResponseCallback = (res: any) => void; type DataResponseCallback = (res: DataResponse) => void; type TempFileResponseCallback = (res: TempFileResponse) => void; type ErrorCallback = (error: any) => void; type EventCallback = (event: any) => void; interface DataResponse { /** 回调函数返回的内容 */ data: any; } interface TempFileResponse { /** 文件的临时路径 */ tempFilePath: string; } interface PageOptions { /** 页面的初始数据 */ data?: any; /** 生命周期函数--监听页面加载 */ onLoad?: ((options: any) => void) | undefined; /** 生命周期函数--监听页面渲染完成 */ onReady?: NoneParamCallback | undefined; /** 生命周期函数--监听页面显示 */ onShow?: NoneParamCallback | undefined; /** 生命周期函数--监听页面隐藏 */ onHide?: NoneParamCallback | undefined; /** 生命周期函数--监听页面卸载 */ onUnload?: NoneParamCallback | undefined; [key: string]: any; } interface referrerInfo { /** 来源小程序、公众号或 App 的 appId */ appId: string, /** 来源小程序传过来的数据,scene=1037或1038时支持 */ extraData: Object } interface onLaunchOptions { /** 启动小程序的路径 */ path: string, /** 启动小程序的场景值 */ scene: number, /** 启动小程序的query参数 */ query: Object, shareTicket: string, /** 来源信息。从另一个小程序、公众号或App进入小程序时返回。范泽返回{} */ referrerInfo: referrerInfo } type onLaunchCallback = (options: onLaunchOptions) => void; type onShowOptions = onLaunchOptions; interface AppOptions { /** * 生命周期函数--监听小程序初始化 * 当小程序初始化完成时,会触发 onLaunch(全局只触发一次) */ onLaunch?: onLaunchCallback | undefined; /** * 生命周期函数--监听小程序显示 * 当小程序启动,或从后台进入前台显示,会触发 onShow */ onShow?: ((options: onShowOptions) => void) | undefined; /** * 生命周期函数--监听小程序隐藏 * 当小程序从前台进入后台,会触发 onHide */ onHide?: NoneParamCallback | undefined; /** 小程序发生脚本错误或 API 调用报错时触发。也可以使用 wx.onError 绑定监听。*/ onError?: ErrorCallback | undefined; /** * 小程序要打开的页面不存在时触发 * 1. 开发者可以在回调中进行页面重定向,但必须在回调中同步处理,异步处理(例如 setTimeout 异步执行)无效。 * 2. 若开发者没有调用 wx.onPageNotFound 绑定监听,也没有声明 App.onPageNotFound,当跳转页面不存在时,将推入微信客户端原生的页面不存在提示页面。 * 3. 如果回调中又重定向到另一个不存在的页面,将推入微信客户端原生的页面不存在提示页面,并且不再第二次回调。 */ onPageNotFound?: NoneParamCallback | undefined; [key: string]: any } // 网络 // 发起请求 interface RequestHeader { [key: string]: string; } interface RequestOptions { /** 开发者服务器接口地址 */ url: string; /** 请求的参数 */ data?: string | any | undefined; /** 设置请求的 header , header 中不能设置 Referer */ header?: RequestHeader | undefined; /** 默认为 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ method?: string | undefined; /** 收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'} */ success?: DataResponseCallback | undefined; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * wx.request发起的是https请求。一个微信小程序,同时只能有5个网络请求连接。 */ function request(options: RequestOptions): RequestTask; /** * 网络请求任务对象 */ interface RequestTask { // 中断请求任务 abort(): void; // 监听 HTTP Response Header 事件。会比请求完成事件更早 onHeadersReceived(callback: DataResponseCallback): void; // 取消监听 HTTP Response Header 事件 offHeadersReceived(callback: DataResponseCallback): void; } // 下载 interface OnProgressCallbackOptions { // 下载进度百分比 progress: number; // 已经下载的数据长度,单位 Bytes totalBytesWritten: number; // 预期需要下载的数据总长度,单位 Bytes totalBytesExpectedToWrite: number; } /** * 一个可以监听下载进度变化事件,以及取消下载任务的对象 */ interface DownloadTask { // 中断下载任务 abort(): void; // 下载进度变化事件的回调函数 onProgressUpdate(callback: (res: OnProgressCallbackOptions) => {}): void; // 取消监听下载进度变化事件 offProgressUpdate(callback: (res: OnProgressCallbackOptions) => {}): void; // 监听 HTTP Response Header 事件。会比请求完成事件更早 onHeadersReceived(callback: DataResponseCallback): void; // 取消监听 HTTP Response Header 事件 offHeadersReceived(callback: DataResponseCallback): void; } interface DownloadFileOptions { /** 下载资源的 url */ url: string; /** 下载资源的类型,用于客户端识别处理,有效值:image/audio/video */ type?: string | undefined; /** HTTP 请求 Header */ header?: RequestHeader | undefined; /** 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'} */ success?: TempFileResponseCallback | undefined; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 下载文件资源到本地。客户端直接发起一个 HTTP GET 请求, * 把下载到的资源根据 type 进行处理,并返回文件的本地临时路径。 */ function downloadFile(options: DownloadFileOptions): DownloadTask; // 上传 /** * 一个可以监听上传进度变化事件,以及取消上传任务的对象 */ interface UploadTask { // 中断上传任务 abort(): void; // 上传进度变化事件的回调函数 onProgressUpdate(callback: (res: OnProgressCallbackOptions) => {}): void; // 取消监听上传进度变化事件 offProgressUpdate(callback: (res: OnProgressCallbackOptions) => {}): void; // 监听 HTTP Response Header 事件。会比请求完成事件更早 onHeadersReceived(callback: DataResponseCallback): void; // 取消监听 HTTP Response Header 事件 offHeadersReceived(callback: DataResponseCallback): void; } interface UploadFileOptions { /** 开发者服务器 url */ url: string; /** 要上传文件资源的路径 */ filePath: string; /** 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 */ name: string; /** HTTP 请求 Header , header 中不能设置 Referer */ header?: RequestHeader | undefined; /** HTTP 请求中其他额外的 form data */ formData?: any; /** 接口调用成功的回调函数 */ success?: ResponseCallback | undefined; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 将本地资源上传到开发者服务器。 * 如页面通过 wx.chooseImage 等接口获取到一个本地资源的临时文件路径后, * 可通过此接口将本地资源上传到指定服务器。 * 客户端发起一个 HTTPS POST 请求, * 其中 Content-Type 为 multipart/form-data 。 */ function uploadFile(options: UploadFileOptions): UploadTask; // WebSocket interface ConnectSocketOptions { /** 开发者服务器接口地址,必须是 HTTPS 协议,且域名必须是后台配置的合法域名 */ url: string; /** 请求的数据 */ data?: any; /** HTTP Header , header 中不能设置 Referer */ header?: RequestHeader | undefined; /** 默认是GET,有效值为: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ method?: string | undefined; /** 接口调用成功的回调函数 */ success?: ResponseCallback | undefined; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 创建一个 WebSocket 连接; * 一个微信小程序同时只能有一个 WebSocket 连接, * 如果当前已存在一个 WebSocket 连接, * 会自动关闭该连接,并重新创建一个 WebSocket 连接。 */ function connectSocket(options: ConnectSocketOptions): void; /** 监听WebSocket连接打开事件。 */ function onSocketOpen(callback: OneParamCallback): void; /** 监听WebSocket错误。 */ function onSocketError(callback: ErrorCallback): void; interface SendSocketMessageOptions { /** 需要发送的内容 */ data: string; /** 接口调用成功的回调函数 */ success?: ResponseCallback | undefined; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 通过 WebSocket 连接发送数据,需要先 wx.connectSocket, * 并在 wx.onSocketOpen 回调之后才能发送。 */ function sendSocketMessage(options: SendSocketMessageOptions): void; /** * 监听WebSocket接受到服务器的消息事件。 */ function onSocketMessage(callback: DataResponseCallback): void; /** * 关闭WebSocket连接。 */ function closeSocket(): void; /** 监听WebSocket关闭。 */ function onSocketClose(callback: ResponseCallback): void; type ImageSizeType = 'original' | 'compressed'; type ImageSourceType = 'album' | 'camera'; type VideoSourceType = 'album' | 'camera'; type CameraDevice = 'front' | 'back'; interface TempFilesData { /** 文件的临时路径 */ tempFilePaths: string; } interface ChooseImageOptions { /** 最多可以选择的图片张数,默认9 */ count?: number | undefined; /** original 原图,compressed 压缩图,默认二者都有 */ sizeType?: Array<ImageSizeType> | undefined; /** album 从相册选图,camera 使用相机,默认二者都有 */ sourceType?: Array<ImageSourceType> | undefined; /** 成功则返回图片的本地文件路径列表 tempFilePaths */ success: (res: TempFilesData) => void; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 从本地相册选择图片或使用相机拍照。 */ function chooseImage(options: ChooseImageOptions): void; interface PreviewImageOptions { /** 当前显示图片的链接,不填则默认为 urls 的第一张 */ current?: string | undefined; /** 需要预览的图片链接列表 */ urls: Array<string>; /** 接口调用成功的回调函数 */ success?: ResponseCallback | undefined; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 预览图片。 */ function previewImage(options: PreviewImageOptions): void; interface StartRecordOptions { /** 录音成功后调用,返回录音文件的临时文件路径,res = {tempFilePath: '录音文件的临时路径'} */ success?: TempFileResponseCallback | undefined; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 开始录音。当主动调用wx.stopRecord, * 或者录音超过1分钟时自动结束录音,返回录音文件的临时文件路径。 * 注:文件的临时路径,在小程序本次启动期间可以正常使用, * 如需持久保存,需在主动调用wx.saveFile,在小程序下次启动时才能访问得到。 */ function startRecord(options: StartRecordOptions): void; /** * ​ 主动调用停止录音。 */ function stopRecord(): void; interface PlayVoiceOptions { /** 需要播放的语音文件的文件路径 */ filePath: string; /** 接口调用成功的回调函数 */ success?: ResponseCallback | undefined; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 开始播放语音,同时只允许一个语音文件正在播放, * 如果前一个语音文件还没播放完,将中断前一个语音播放。 */ function playVoice(options: PlayVoiceOptions): void; /** * 暂停正在播放的语音。 * 再次调用wx.playVoice播放同一个文件时,会从暂停处开始播放。 * 如果想从头开始播放,需要先调用 wx.stopVoice。 */ function pauseVoice(): void; /** * 结束播放语音。 */ function stopVoice(): void; interface BackgroundAudioPlayerState { /** 选定音频的长度(单位:s),只有在当前有音乐播放时返回 */ duration?: number | undefined; /** 选定音频的播放位置(单位:s),只有在当前有音乐播放时返回 */ currentPosition?: number | undefined; /** 播放状态(2:没有音乐在播放,1:播放中,0:暂停中) */ status: number; /** 音频的下载进度(整数,80 代表 80%),只有在当前有音乐播放时返回 */ downloadPercent?: number | undefined; /** 歌曲数据链接,只有在当前有音乐播放时返回 */ dataUrl?: string | undefined; } type GetBackgroundAudioPlayerStateSuccessCallback = (state: BackgroundAudioPlayerState) => void; interface GetBackgroundAudioPlayerStateOptions { /** 接口调用成功的回调函数 */ success?: GetBackgroundAudioPlayerStateSuccessCallback | undefined; /** 接口调用失败的回调函数 */ fail?: NoneParamCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: NoneParamCallback | undefined; } /** 获取音乐播放状态。 */ function getBackgroundAudioPlayerState(options: GetBackgroundAudioPlayerStateOptions): void; interface PlayBackgroundAudioOptions { /** 音乐链接 */ dataUrl: string; /** 音乐标题 */ title?: string | undefined; /** 封面URL */ coverImgUrl?: string | undefined; /** 接口调用成功的回调函数 */ success?: ResponseCallback | undefined; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** 播放音乐,同时只能有一首音乐正在播放。 */ function playBackgroundAudio(options: PlayBackgroundAudioOptions): void; /** 暂停播放音乐。 */ function pauseBackgroundAudio(): void; interface SeekBackgroundAudioOptions { /** 音乐位置,单位:秒 */ position: number; /** 接口调用成功的回调函数 */ success?: ResponseCallback | undefined; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 控制音乐播放进度。 */ function seekBackgroundAudio(options: SeekBackgroundAudioOptions): void; /** * 停止播放音乐。 */ function stopBackgroundAudio(): void; /** 监听音乐播放。 */ function onBackgroundAudioPlay(callback: NoneParamCallback): void; /** 监听音乐暂停。 */ function onBackgroundAudioPause(callback: NoneParamCallback): void; /** 监听音乐停止。 */ function onBackgroundAudioStop(callback: NoneParamCallback): void; interface SavedFileData { /** 文件的保存路径 */ savedFilePath: string; } interface SaveFileOptions { /** 需要保存的文件的临时路径 */ tempFilePath: string; /** 返回文件的保存路径,res = {savedFilePath: '文件的保存路径'} */ success?: ((res: SavedFileData) => void) | undefined; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 保存文件到本地。 */ function saveFile(options: SaveFileOptions): void; interface VideoData { /** 选定视频的临时文件路径 */ tempFilePath: string; /** 选定视频的时间长度 */ duration: number; /** 选定视频的数据量大小 */ size: number; /** 返回选定视频的长 */ height: number; /** 返回选定视频的宽 */ width: number; } interface ChooseVideoOptions { /** album 从相册选视频,camera 使用相机拍摄,默认为:['album', 'camera'] */ sourceType?: Array<VideoSourceType> | undefined; /** 拍摄视频最长拍摄时间,单位秒。最长支持60秒 */ maxDuration?: number | undefined; /** 前置或者后置摄像头,默认为前后都有,即:['front', 'back'] */ camera?: Array<CameraDevice> | undefined; /** 接口调用成功,返回视频文件的临时文件路径,详见返回参数说明 */ success?: ((res: VideoData) => void) | undefined; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 拍摄视频或从手机相册中选视频,返回视频的临时文件路径。 */ function chooseVideo(options: ChooseVideoOptions): void; // 数据缓存 interface StorageInfo { // 当前 storage 中所有的 key keys: Array<string>; // 当前占用的空间大小, 单位 KB currentSize: number; // 限制的空间大小,单位 KB limitSize: number; } type StorageInfoCallback = (res: StorageInfoOptions) => void; interface StorageInfoOptions extends CommonCallbackOptions{ success?: StorageInfoCallback | undefined; } /** * getStorageInfo的同步版本 */ function getStorageInfoSync(): StorageInfo; /** * 异步获取当前storage的相关信息 * @param options */ function getStorageInfo(options: StorageInfoOptions): void; interface SetStorageOptions { /** 本地缓存中的指定的 key */ key: string; /** 需要存储的内容 */ data: any | string; /** 接口调用成功的回调函数 */ success?: ResponseCallback | undefined; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 将数据存储在本地缓存中指定的 key 中, * 会覆盖掉原来该 key 对应的内容,这是一个异步接口。 */ function setStorage(options: SetStorageOptions): void; /** * 将 data 存储在本地缓存中指定的 key 中, * 会覆盖掉原来该 key 对应的内容,这是一个同步接口。 * * @param {string} key 本地缓存中的指定的 key * @param {(Object | string)} data 需要存储的内容 */ function setStorageSync(key: string, data: any | string): void; interface GetStorageOptions { /** 本地缓存中的指定的 key */ key: string; /** 接口调用的回调函数,res = {data: key对应的内容} */ success: DataResponseCallback; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 从本地缓存中异步获取指定 key 对应的内容。 */ function getStorage(options: GetStorageOptions): void; /** * 从本地缓存中同步获取指定 key 对应的内容。 * * @param {string} key * @returns {(Object | string)} */ function getStorageSync(key: string): any | string; /** * 清理本地数据缓存。 */ function clearStorage(): void; /** * 同步清理本地数据缓存 */ function clearStorageSync(): void; // 媒体 // 地图 interface LocationBaseOptions { // 纬度,浮点数,范围为-90~90,负数表示南纬 latitude: number; // 经度,浮点数,范围为-180~180,负数表示西经 longitude: number; } interface GetCenterLocationSuccCbOptions extends CommonCallbackOptions{ success(res: LocationBaseOptions): void; } interface translateMarkerOptions extends CommonCallbackOptions{ // 指定 marker markerId: number; // 指定 marker 移动到的目标点 destination: LocationBaseOptions; // 移动过程中是否自动旋转 marker autoRotate: boolean; // marker 的旋转角度 rotate: number; // 动画持续时长,平移与旋转分别计算 duration?: number | undefined; // 动画结束回调函数 animationEnd?(): void; } interface zoomPointsOptions extends CommonCallbackOptions { // 要显示在可视区域内的坐标点列表 points: Array<LocationBaseOptions>; // 坐标点形成的矩形边缘到地图边缘的距离,单位像素。格式为[上,右,下,左],安卓上只能识别数组第一项,上下左右的padding一致。开发者工具暂不支持padding参数。 padding?: Array<number> | undefined; } interface GetReginSuccessCallbackOptions { // 西南角经纬度 southwest: number, // 东北角经纬度 northeast: number; } interface GetReginOptions extends CommonCallbackOptions{ success?(callback: (res: GetReginSuccessCallbackOptions) => void): void; } interface GetScaleOptions extends CommonCallbackOptions{ success?(callback: (res: {scale: number}) => void): void; } interface MapContext { // 获取当前地图中心的经纬度。返回的是 gcj02 坐标系,可以用于 wx.openLocation() getCenterLocation(options: GetCenterLocationSuccCbOptions): void; // 将地图中心移动到当前定位点。需要配合map组件的show-location使用 moveToLocation(): void; // 平移marker,带动画 translateMarker(options: translateMarkerOptions): void; // 缩放视野展示所有经纬度 includePoints(options: zoomPointsOptions): void; // 获取当前地图的视野范围 getRegion(options: GetReginOptions): void; // 获取当前地图的缩放级别 getScale(options: GetScaleOptions): void; } interface LocationData { /** 纬度,浮点数,范围为-90~90,负数表示南纬 */ latitude: number; /** 经度,浮点数,范围为-180~180,负数表示西经 */ longitude: number; /** 速度,浮点数,单位m/s */ speed: number; /** 位置的精确度 */ accuracy: number; } interface GetLocationOptions { /** 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于wx.openLocation的坐标 */ type?: 'wgs84' | 'gcj02' | undefined; /** 接口调用成功的回调函数,返回内容详见返回参数说明。 */ success: (res: LocationData) => void; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 获取当前的地理位置、速度。 */ function getLocation(options: GetLocationOptions): void; interface OpenLocationOptions { /** 纬度,范围为-90~90,负数表示南纬 */ latitude: number; /** 经度,范围为-180~180,负数表示西经 */ longitude: number; /** 缩放比例,范围1~28,默认为28 */ scale?: number | undefined; /** 位置名 */ name?: string | undefined; /** 地址的详细说明 */ address?: string | undefined; /** 接口调用成功的回调函数 */ success?: ResponseCallback | undefined; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 使用微信内置地图查看位置 */ function openLocation(options: OpenLocationOptions): void; interface NetworkTypeData { /** 返回网络类型2g,3g,4g,wifi */ networkType: '2g' | '3g' | '4g' | 'wifi'; } interface GetNetworkTypeOptions { /** 接口调用成功,返回网络类型 networkType */ success: (res: NetworkTypeData) => void; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 获取网络类型。 */ function getNetworkType(options: GetNetworkTypeOptions): void; interface SystemInfo { /** 手机型号 */ model: string; /** 设备像素比 */ pixelRatio: number; /** 窗口宽度 */ windowWidth: number; /** 窗口高度 */ windowHeight: number; /** 微信设置的语言 */ language: string; /** 微信版本号 */ version: string; } interface GetSystemInfoOptions { /** 成功获取系统信息的回调 */ success: (res: SystemInfo) => void; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 获取系统信息。 */ function getSystemInfo(options: GetSystemInfoOptions): void; interface UpdateManager { /** * 强制小程序重启并使用新版本。在小程序新版本下载完成后(即收到 onUpdateReady 回调)调用。 */ applyUpdate(callback: DataResponseCallback): void; /** * 监听向微信后台请求检查更新结果事件。微信在小程序冷启动时自动检查更新,不需由开发者主动触发。 */ onCheckForUpdate(): void; /** * 监听小程序有版本更新事件。客户端主动触发下载(无需开发者触发),下载成功后回调 */ onUpdateReady(callback: NoneParamCallback): void; /** * 监听小程序更新失败事件。小程序有新版本,客户端主动触发下载(无需开发者触发),下载失败(可能是网络原因等)后回调 */ onUpdateFailed(callback: NoneParamCallback): void; } /** * 获取全局唯一的版本更新管理器,用于管理小程序更新。关于小程序的更新机制,可以查看运行机制文档。 */ function getUpdateManager(): UpdateManager; /** * 获取小程序启动时的参数。与 App.onLaunch 的回调参数一致。 */ function getLaunchOptionsSync(): onLaunchCallback; // 应用级事件 /** * 取消监听小程序要打开的页面不存在事件 */ function offPageNotFound(): NoneParamCallback; /** * 监听小程序要打开的页面不存在事件。该事件与 App.onPageNotFound 的回调时机一致。 */ function onPageNotFound(): NoneParamCallback; /** * 取消监听小程序错误事件。 */ function offError(): NoneParamCallback; /** * 监听小程序错误事件。如脚本错误或 API 调用报错等。该事件与 App.onError 的回调时机与参数一致。 */ function onError(): ErrorCallback; /** * 取消监听小程序切前台事件 */ function offAppShow(): NoneParamCallback; /** * 监听小程序切前台事件。该事件与 App.onShow 的回调参数一致。 * @param callback */ function onAppShow(callback: onShowOptions): void; /** * 取消监听小程序切后台事件 */ function offAppHide(): NoneParamCallback; /** * 监听小程序切后台事件。该事件与 App.onHide 的回调时机一致。 */ function onAppHide(): NoneParamCallback; // 调试 TODO // 路由 interface routerOptions extends CommonCallbackOptions{ // 需要跳转的应用内非 tabBar 的页面的路径, 路径后可以带参数。参数与路径之间使用 ? 分隔,参数键与参数值用 = 相连,不同参数用 & 分隔;如 'path?key=value&key2=value2' url: string; } interface NavigateBackOptions extends CommonCallbackOptions { // 返回的页面数,如果 delta 大于现有页面数,则返回到首页。 delta: number; } /** * 关闭当前页面,返回上一页面或多级页面。可通过 getCurrentPages() 获取当前的页面栈,决定需要返回几层。 */ function navigateBack(options: NavigateBackOptions): void; /** * 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面 * @param options */ function switchTab(options: routerOptions): void; /** * 保留当前页面,跳转到应用内的某个页面。但是不能跳到 tabbar 页面。使用 wx.navigateBack 可以返回到原页面。 * @param options */ function navigateTo(options: routerOptions): void; /** * 关闭所有页面,打开到应用内的某个页面 */ function reLaunch(options: routerOptions): void; /** * 关闭当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面。 */ function redirectTo(options: routerOptions): void; // 界面 // 交互 // tapIndex为用户点击的按钮序号,从上到下的顺序,从0开始 type ActionSheetSuccessCallback = (res: {tapIndex: number}) => void; interface ActionSheetOptions { // 必填,按钮的文字数组,数组长度最大为 6 itemList: Array<string>; // 按钮的文字颜色 itemColor?: string | undefined; success?: ActionSheetSuccessCallback | undefined; fail?: ResponseCallback | undefined; complete?: ResponseCallback | undefined; } /** * 公共回调函数 */ interface CommonCallbackOptions { // 接口调用成功回调函数 success?: ResponseCallback | undefined; // 接口调用失败回调函数 fail?: ResponseCallback | undefined; // 接口调用结束的回调函数 complete?: ResponseCallback | undefined; } interface LoadingOptions extends CommonCallbackOptions{ // must,提示的内容 title: string; // 默认false。是否显示透明蒙层,防止触摸穿透 mask: boolean; } type icon = 'success' | 'loading' | 'none'; interface ToastOptions extends CommonCallbackOptions{ // 提示的内容 title: string; // 图标,默认值'success' icon?: icon | undefined; // 自定义图标的本地路径,image 的优先级高于 icon imgage?: string | undefined; // 提示的延迟时间,默认值1500ms duration?: number | undefined; // 是否显示透明蒙层,防止触摸穿透,默认值false mask: boolean; } interface ModalOptions extends CommonCallbackOptions{ // 提示的内容 title: string; // 提示的内容 content: string; // 是否显示取消按钮,默认值true showCancel?: boolean | undefined; // 取消按钮的文字,最多 4 个字符,默认值'取消' cancelText?: string | undefined; // 取消按钮的文字颜色,必须是 16 进制格式的颜色字符串,默认值'#000000' cancelColor?: string | undefined; // 确认按钮的文字,最多 4 个字符 confirmText?: string | undefined; // 确认按钮的文字颜色,必须是 16 进制格式的颜色字符串,默认值'#3cc51f' confirmColor?: boolean | undefined; } /** * 显示操作菜单 */ function showActionSheet(options: ActionSheetOptions): void; /** * 隐藏 loading 提示框 * @param options */ function hideLoading(options?: CommonCallbackOptions): void; /** * 显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框 * @param options */ function showLoading(options: LoadingOptions): void; /** * 隐藏消息提示框 * @param options */ function hideToast(options?: CommonCallbackOptions): void; /** * 显示消息提示框 * @param options */ function showToast(options: ToastOptions): void; /** * 显示模态对话框 * @param options */ function showModal(options: ModalOptions): void; interface NavigationBarColorAnimationOptions { // 动画变化时间,单位 ms,默认0 animation?: number | undefined; // 动画变化方式.动画从头到尾的速度是相同的,动画以低速开始,动画以低速结束,动画以低速开始和结束 timingFunc?: 'linear' | 'easeIn' | 'easeOut' | 'easeInOut' | undefined } interface NavigationBarColorOptions extends CommonCallbackOptions{ // 前景颜色值,包括按钮、标题、状态栏的颜色,仅支持 #ffffff 和 #000000 frontColor: string; // 背景颜色值,有效值为十六进制颜色 backgroundColor: string; // 动画效果 animation: NavigationBarColorAnimationOptions; } interface NavigationBarTitleOptions extends CommonCallbackOptions{ // 动态设置当前页面的标题 title: string; } // 导航栏 function setNavigationBarColor(): void; /** * 在当前页面隐藏导航条加载动画 */ function hideNavigationBarLoading(options?: CommonCallbackOptions): void; /** * 在当前页面显示导航条加载动画 */ function showNavigationBarLoading(options: CommonCallbackOptions): void; /** * 动态设置当前页面的标题 * @param options */ function setNavigationBarTitle(options: NavigationBarTitleOptions): void; // 背景 function setBackgroundTextStyle(): void; interface BackgroundColorOptions extends CommonCallbackOptions{ // 窗口的背景色,必须为十六进制颜色值 backgroundColor?: string | undefined; // 顶部窗口的背景色,必须为十六进制颜色值,仅 iOS 支持 backgroundColorTop?: string | undefined; // 底部窗口的背景色,必须为十六进制颜色值,仅 iOS 支持 backgroundColorBottom?: string | undefined; } function setBackgroundColor(): void; // Tab Bar interface TabBarItemOptions extends CommonCallbackOptions{ // tabBar 的哪一项,从左边算起 index: number; // tab 上的按钮文字 text?: string | undefined; // 图片路径,icon 大小限制为 40kb,建议尺寸为 81px * 81px,当 postion 为 top 时,此参数无效,不支持网络图片 iconPath?: string | undefined; // 选中时的图片路径,icon 大小限制为 40kb,建议尺寸为 81px * 81px ,当 postion 为 top 时,此参数无效 selectedIconPath?: string | undefined; } /** * 动态设置 tabBar 某一项的内容 * @param options */ function setTabBarItem(options: TabBarItemOptions): void; interface TabBarStyleOptions extends CommonCallbackOptions{ // tab 上的文字默认颜色,HexColor color: string; // tab 上的文字选中时的颜色,HexColor selectedColor: string; // tab 的背景色,HexColor backgroundColor: string; // tabBar上边框的颜色, 仅支持 black/white borderStyle: string; } /** * 动态设置tabBar的整体样式 */ function setTabBarStyle(options: TabBarItemOptions): void; interface TabBarAnimationOptions extends CommonCallbackOptions{ // 是否需要动画效果 animation: boolean; } /** * 隐藏tabBar */ function hideTabBar(options: TabBarAnimationOptions): void; /** * 显示tabBar */ function showTabBar(options: TabBarAnimationOptions): void; interface TabBarRedDotOptions extends CommonCallbackOptions{ // tabBar 的哪一项,从左边算起 index: number; } /** * 隐藏 tabBar 某一项的右上角的红点 * @param options */ function hideTabBarRedDot(options: TabBarBadgeOptions): void; /** * 显示 tabBar 某一项的右上角的红点 * @param options */ function showTabBarRedDot(options: TabBarRedDotOptions): void; interface TabBarBadgeOptions extends CommonCallbackOptions{ // tabBar 的哪一项,从左边算起 index: number; // 显示的文本,超过 4 个字符则显示成 ... text: string; } /** * 移除 tabBar 某一项右上角的文本 * @param options */ function removeTabBarBadge(options: TabBarRedDotOptions): void; /** * 为 tabBar 某一项的右上角添加文本 * @param options */ function setTabBarBadge(options: TabBarBadgeOptions): void; interface FontDescOptions { // 字体样式,可选值为 normal / italic / oblique style?: string | undefined; // 字体粗细,可选值为 normal / bold / 100 / 200../ 900 weight?: string | undefined; // 设置小型大写字母的字体显示文本,可选值为 normal / small-caps / inherit variant?: string | undefined; } // 字体 interface FontFaceOptions extends CommonCallbackOptions{ // 定义的字体名称 family: string; // 字体资源的地址。建议格式为 TTF 和 WOFF,WOFF2 在低版本的iOS上会不兼容。 source: string; // 可选的字体描述符 desc?: FontDescOptions | undefined; } function loadFontFace(options: FontFaceOptions): void; // 下拉刷新 /** * 停止当前页面下拉刷新。 */ function stopPullDownRefresh(options?: CommonCallbackOptions): void; /** * 开始下拉刷新。调用后触发下拉刷新动画,效果与用户手动下拉刷新一致。 */ function startPullDownRefresh(options?: CommonCallbackOptions): void; // 滚动 interface PageScrollToOptions extends CommonCallbackOptions{ // 滚动到页面的目标位置,单位 px scrollTop: number; // 滚动动画的时长,单位 ms。默认300 duration: number; } /** * 将页面滚动到 */ function pageScrollTo(): void; interface AccelerometerData { /** X 轴 */ x: number; /** Y 轴 */ y: number; /** Z 轴 */ z: number; } type AccelerometerChangeCallback = (res: AccelerometerData) => void; /** * 监听重力感应数据,频率:5次/秒 */ function onAccelerometerChange(callback: AccelerometerChangeCallback): void; interface CompassData { /** 面对的方向度数 */ direction: number; } type CompassChangeCallback = (res: CompassData) => void; function onCompassChange(callback: CompassChangeCallback): void; interface SetNavigationBarTitleOptions { /** 页面标题 */ title?: string | undefined; /** 成功获取系统信息的回调 */ success?: ResponseCallback | undefined; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 动态设置当前页面的标题。 */ function setNavigationBarTitle(options: SetNavigationBarTitleOptions): void; /** * 在当前页面显示导航条加载动画。 */ function showNavigationBarLoading(): void; /** * 隐藏导航条加载动画。 */ function hideNavigationBarLoading(): void; type TimingFunction = 'linear' | 'ease' | 'ease-in' | 'ease-in-out' | 'ease-out' | 'step-start' | 'step-end'; // 动画 interface CreateAnimationOptions { /** 动画持续时间,单位ms,默认值 400 */ duration?: number | undefined; /** 定义动画的效果,默认值"linear",有效值:"linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end" */ timingFunction?: TimingFunction | undefined; /** 动画持续时间,单位 ms,默认值 0 */ delay?: number | undefined; /** 设置transform-origin,默认为"50% 50% 0" */ transformOrigin?: string | undefined; } interface Animator { actions: Array<AnimationAction>; } interface AnimationAction { animates: Array<Animate>; option: AnimationActionOption; } interface AnimationActionOption { transformOrigin: string; transition: AnimationTransition; } interface AnimationTransition { delay: number; duration: number; timingFunction: TimingFunction; } interface Animate { type: string; args: Array<any>; } /** * 创建一个动画实例animation。调用实例的方法来描述动画。 * 最后通过动画实例的export方法导出动画数据传递给组件的animation属性。 * * 注意: export 方法每次调用后会清掉之前的动画操作 */ function createAnimation(options?: CreateAnimationOptions): Animation; /** 动画实例可以调用以下方法来描述动画,调用结束后会返回自身,支持链式调用的写法。 */ interface Animation { /** * 调用动画操作方法后要调用 step() 来表示一组动画完成, * 可以在一组动画中调用任意多个动画方法, * 一组动画中的所有动画会同时开始, * 一组动画完成后才会进行下一组动画。 * @param {CreateAnimationOptions} options 指定当前组动画的配置 */ step(options?: CreateAnimationOptions): void; /** * 导出动画操作 * * 注意: export 方法每次调用后会清掉之前的动画操作 */ export(): Animator; /** 透明度,参数范围 0~1 */ opacity(value: number): Animation; /** 颜色值 */ backgroundColor(color: string): Animation; /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ width(length: number): Animation; /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ height(length: number): Animation; /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ top(length: number): Animation; /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ left(length: number): Animation; /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ bottom(length: number): Animation; /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ right(length: number): Animation; /** deg的范围-180~180,从原点顺时针旋转一个deg角度 */ rotate(deg: number): Animation; /** deg的范围-180~180,在X轴旋转一个deg角度 */ rotateX(deg: number): Animation; /** deg的范围-180~180,在Y轴旋转一个deg角度 */ rotateY(deg: number): Animation; /** deg的范围-180~180,在Z轴旋转一个deg角度 */ rotateZ(deg: number): Animation; /** 同transform-function rotate3d */ rotate3d(x: number, y: number, z: number, deg: number): Animation; /** * 一个参数时,表示在X轴、Y轴同时缩放sx倍数; * 两个参数时表示在X轴缩放sx倍数,在Y轴缩放sy倍数 */ scale(sx: number, sy?: number): Animation; /** 在X轴缩放sx倍数 */ scaleX(sx: number): Animation; /** 在Y轴缩放sy倍数 */ scaleY(sy: number): Animation; /** 在Z轴缩放sy倍数 */ scaleZ(sz: number): Animation; /** 在X轴缩放sx倍数,在Y轴缩放sy倍数,在Z轴缩放sz倍数 */ scale3d(sx: number, sy: number, sz: number): Animation; /** * 一个参数时,表示在X轴偏移tx,单位px; * 两个参数时,表示在X轴偏移tx,在Y轴偏移ty,单位px。 */ translate(tx: number, ty?: number): Animation; /** * 在X轴偏移tx,单位px */ translateX(tx: number): Animation; /** * 在Y轴偏移tx,单位px */ translateY(ty: number): Animation; /** * 在Z轴偏移tx,单位px */ translateZ(tz: number): Animation; /** * 在X轴偏移tx,在Y轴偏移ty,在Z轴偏移tz,单位px */ translate3d(tx: number, ty: number, tz: number): Animation; /** * 参数范围-180~180; * 一个参数时,Y轴坐标不变,X轴坐标延顺时针倾斜ax度; * 两个参数时,分别在X轴倾斜ax度,在Y轴倾斜ay度 */ skew(ax: number, ay?: number): Animation; /** 参数范围-180~180;Y轴坐标不变,X轴坐标延顺时针倾斜ax度 */ skewX(ax: number): Animation; /** 参数范围-180~180;X轴坐标不变,Y轴坐标延顺时针倾斜ay度 */ skewY(ay: number): Animation; /** * 同transform-function matrix */ matrix(a: number, b: number, c: number, d: number, tx: number, ty: number): Animation; /** 同transform-function matrix3d */ matrix3d(a1: number, b1: number, c1: number, d1: number, a2: number, b2: number, c2: number, d2: number, a3: number, b3: number, c3: number, d3: number, a4: number, b4: number, c4: number, d4: number): Animation; } interface CanvasAction { method: string; data: Array<CanvasAction> | Array<number | string> } type LineCapType = 'butt' | 'round' | 'square'; type LineJoinType = 'bevel' | 'round' | 'miter'; /** * context只是一个记录方法调用的容器,用于生成记录绘制行为的actions数组。context跟<canvas/>不存在对应关系,一个context生成画布的绘制动作数组可以应用于多个<canvas/>。 */ interface CanvasContext { /** 获取当前context上存储的绘图动作 */ getActions(): Array<CanvasAction> /** 清空当前的存储绘图动作 */ clearActions(): void; /** * 对横纵坐标进行缩放 * 在调用scale方法后,之后创建的路径其横纵坐标会被缩放。 * 多次调用scale,倍数会相乘。 * * @param {number} scaleWidth 横坐标缩放的倍数 * @param {number} scaleHeight 纵坐标轴缩放的倍数 */ scale(scaleWidth: number, scaleHeight?: number): void; /** * 对坐标轴进行顺时针旋转 * 以原点为中心,原点可以用 translate方法修改。 * 顺时针旋转当前坐标轴。多次调用rotate,旋转的角度会叠加。 * * @param {number} rotate 旋转角度,以弧度计。 */ rotate(rotate: number): void; /** * 对坐标原点进行缩放 * 对当前坐标系的原点(0, 0)进行变换,默认的坐标系原点为页面左上角。 * * @param {number} x 水平坐标平移量 * @param {number} y 竖直坐标平移量 */ translate(x: number, y: number): void; /** * 保存当前坐标轴的缩放、旋转、平移信息 */ save(): void; /** * 恢复之前保存过的坐标轴的缩放、旋转、平移信息 */ restore(): void; /** * 在给定的矩形区域内,清除画布上的像素 * 清除画布上在该矩形区域内的内容。 * * @param {number} x 矩形区域左上角的x坐标 * @param {number} y 矩形区域左上角的y坐标 * @param {number} width 矩形区域的宽度 * @param {number} height 矩形区域的高度 */ clearRect(x: number, y: number, width: number, height: number): void; /** * 在画布上绘制被填充的文本 * * @param {string} text 在画布上输出的文本 * @param {number} x 绘制文本的左上角x坐标位置 * @param {number} y 绘制文本的左上角y坐标位置 */ fillText(text: string, x: number, y: number): void; /** * 在画布上绘制图像 * 绘制图像,图像保持原始尺寸。 * * @param {string} imageResource 所要绘制的图片资源。 通过chooseImage得到一个文件路径或者一个项目目录内的图片 * @param {number} x 图像左上角的x坐标 * @param {number} y 图像左上角的y坐标 */ drawImage(imageResource: string, x: number, y: number): void; /** * 对当前路径进行填充 */ fill(): void; /** * 对当前路径进行描边 */ stroke(): void; /** * 开始一个路径 * 开始创建一个路径,需要调用fill或者stroke才会使用路径进行填充或描边。 * 同一个路径内的多次setFillStyle、setStrokeStyle、setLineWidth等设置, * 以最后一次设置为准。 */ beginPath(): void; /** * 关闭一个路径 */ closePath(): void; /** * 把路径移动到画布中的指定点,但不创建线条。 * * @param {number} x 目标位置的x坐标 * @param {number} y 目标位置的y坐标 */ moveTo(x: number, y: number): void; /** * 在当前位置添加一个新点,然后在画布中创建从该点到最后指定点的路径。 * * @param {number} x 目标位置的x坐标 * @param {number} y 目标位置的y坐标 */ lineTo(x: number, y: number): void; /** * 添加一个矩形路径到当前路径。 * * @param {number} x 矩形路径左上角的x坐标 * @param {number} y 矩形路径左上角的y坐标 * @param {number} width 矩形路径的宽度 * @param {number} height 矩形路径的高度 */ rect(x: number, y: number, width: number, height: number): void; /** * 添加一个弧形路径到当前路径,顺时针绘制。 * * @param {number} x 矩形路径左上角的x坐标 * @param {number} y 矩形路径左上角的y坐标 * @param {number} radius 矩形路径左上角的y坐标 * @param {number} startAngle 起始弧度 * @param {number} endAngle 结束弧度 * @param {boolean} sweepAngle 从起始弧度开始,扫过的弧度 */ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, sweepAngle: boolean): void; /** * 创建二次方贝塞尔曲线 * * @param {number} cpx 贝塞尔控制点的x坐标 * @param {number} cpy 贝塞尔控制点的y坐标 * @param {number} x 结束点的x坐标 * @param {number} y 结束点的y坐标 */ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; /** * 创建三次方贝塞尔曲线 * * @param {number} cp1x 第一个贝塞尔控制点的 x 坐标 * @param {number} cp1y 第一个贝塞尔控制点的 y 坐标 * @param {number} cp2x 第二个贝塞尔控制点的 x 坐标 * @param {number} cp2y 第二个贝塞尔控制点的 y 坐标 * @param {number} x 结束点的x坐标 * @param {number} y 结束点的y坐标 */ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; /** * 设置填充样式 * * @param {string} color 设置为填充样式的颜色。'rgb(255, 0, 0)'或'rgba(255, 0, 0, 0.6)'或'#ff0000'格式的颜色字符串 */ setFillStyle(color: string): void; /** * 设置线条样式 * * @param {string} color 设置为填充样式的颜色。'rgb(255, 0, 0)'或'rgba(255, 0, 0, 0.6)'或'#ff0000'格式的颜色字符串 */ setStrokeStyle(color: string): void; /** * 设置阴影 * * @param {number} offsetX 阴影相对于形状在水平方向的偏移 * @param {number} offsetY 阴影相对于形状在竖直方向的偏移 * @param {number} blur 阴影的模糊级别,数值越大越模糊 0~100 * @param {string} color 阴影的颜色。 'rgb(255, 0, 0)'或'rgba(255, 0, 0, 0.6)'或'#ff0000'格式的颜色字符串 */ setShadow(offsetX: number, offsetY: number, blur: number, color: string): void; /** * 设置字体大小 * * @param {number} fontSize 字体的字号 */ setFontSize(fontSize: number): void; /** * 设置线条端点的样式 * * @param {LineCapType} lineCap 线条的结束端点样式。 'butt'、'round'、'square' */ setLineCap(lineCap: LineCapType): void; /** * 设置两线相交处的样式 * @param {LineJoinType} lineJoin 两条线相交时,所创建的拐角类型 */ setLineJoin(lineJoin: LineJoinType): void; /** * 设置线条宽度 * * @param {number} lineWidth 线条的宽度 */ setLineWidth(lineWidth: number): void; /** 设置最大斜接长度,斜接长度指的是在两条线交汇处内角和外角之间的距离。 * 当 setLineJoin为 miter 时才有效。 * 超过最大倾斜长度的,连接处将以 lineJoin 为 bevel 来显示 * * @param {number} miterLimit 最大斜接长度 */ setMiterLimit(miterLimit: number): void; } /** * 创建并返回绘图上下文context对象。 * context只是一个记录方法调用的容器, * 用于生成记录绘制行为的actions数组。c * ontext跟<canvas/>不存在对应关系, * 一个context生成画布的绘制动作数组可以应用于多个<canvas/>。 */ function createContext(): CanvasContext; interface DrawCanvasOptions { /** 画布标识,传入 <canvas/> 的 cavas-id */ canvasId: number | string; /** * 绘图动作数组,由 wx.createContext 创建的 context, * 调用 getActions 方法导出绘图动作数组。 */ actions: Array<CanvasAction>; } /** * 绘制画布 */ function drawCanvas(options: DrawCanvasOptions): void; /** * 收起键盘。 */ function hideKeyboard(): void; // 开放接口 // 登录 interface LoginResponse { /** 调用结果 */ errMsg: string; /** 用户允许登录后,回调内容会带上 code(有效期五分钟), * 开发者需要将 code 发送到开发者服务器后台, * 使用code 换取 session_key api, * 将 code 换成 openid 和 session_key */ code: string; } interface LoginOptions { /** 接口调用成功的回调函数 */ success?: ((res: LoginResponse) => void) | undefined; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 检查登录态是否过期。 */ function checkSession(options: CommonCallbackOptions): void; /** * 调用接口获取登录凭证(code)进而换取用户登录态信息, * 包括用户的唯一标识(openid) 及本次登录的 会话密钥(session_key)。 * 用户数据的加解密通讯需要依赖会话密钥完成。 */ function login(option: LoginOptions): void; type envVersion = 'develop' | 'trial' | 'release'; interface NavigateToMiniProgramOptions extends CommonCallbackOptions { // 要打开的小程序 appId appId: string; // 打开的页面路径,如果为空则打开首页 path?: string | undefined; // 需要传递给目标小程序的数据,目标小程序可在 App.onLaunch,App.onShow 中获取到这份数据。 extraData?: object | undefined; // 要打开的小程序版本。仅在当前小程序为开发版或体验版时此参数有效。如果当前小程序是正式版,则打开的小程序必定是正式版。 envVersion?: envVersion | undefined; } /** * 打开另一个小程序 */ function navigateToMiniProgram(options: NavigateToMiniProgramOptions): void; interface NavigateBackMiniProgramOptions extends CommonCallbackOptions { // 需要返回给上一个小程序的数据,上一个小程序可在 App.onShow 中获取到这份数据。 extraData: object; } /** * 返回到上一个小程序。只有在当前小程序是被其他小程序打开时可以调用成功 */ function navigateBackMiniProgram(options: NavigateBackMiniProgramOptions): void; // 帐号信息 interface AccountInfo { // 小程序帐号信息 miniProgram: { // 小程序appId appId: string; }; // 插件帐号信息(仅在插件中调用时包含这一项) Plugin: { // 插件appId appId: string; // 插件版本号 vetsion: string }; } /** * 获取当前账号信息 */ function getAccountInfoSync(): AccountInfo; // 帐号信息 interface UserInfo { nickName: string; avatarUrl: string; gender: number; province: string; city: string; country: string; } interface UserInfoResponse { /** 用户信息对象,不包含 openid 等敏感信息 */ userInfo: UserInfo; /** 不包括敏感信息的原始数据字符串,用于计算签名。 */ rawData: string; /** 使用 sha1( rawData + sessionkey ) 得到字符串,用于校验用户信息。 */ signature: string; /** 包括敏感数据在内的完整用户信息的加密数据,详细见加密数据解密算法 */ encryptData: string; } interface GetUserInfoOptions { /** 接口调用成功的回调函数 */ success?: ((res: UserInfoResponse) => void) | undefined; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } /** * 获取用户信息,需要先调用 wx.login 接口。 */ function getUserInfo(options: GetUserInfoOptions): void; type PaymentSignType = 'MD5'; interface RequestPaymentOptions { /** 时间戳从1970年1月1日00:00:00至今的秒数,即当前的时间 */ timeStamp: string|number; /** 随机字符串,长度为32个字符以下。 */ nonceStr: string; /** 统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=* */ package: string; /** 签名算法,暂支持 MD5 */ signType: PaymentSignType; /** 签名,具体签名方案参见微信公众号支付帮助文档; */ paySign: string; /** 接口调用成功的回调函数 */ success?: ResponseCallback | undefined; /** 接口调用失败的回调函数 */ fail?: ResponseCallback | undefined; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?: ResponseCallback | undefined; } // 支付 /** * 发起微信支付。 */ function requestPayment(options: RequestPaymentOptions): void; // 授权 /** * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/authorize.html * 用户信息 wx.getUserInfo、 * 地理位置 wx.getLocation,wx.chooseLocation、 * 通讯地址 wx.chooseAddress、 * 发票抬头 wx.chooseInvoiceTitle、 * 获取发票 wx.chooseInvoice、 * 微信运动步数 wx.getWeRunData、 * 录音功能 wx.startRecord、 * 保存到相册 wx.saveImageToPhotosAlbum, wx.saveVideoToPhotosAlbum、 * 摄像头 <camera />组件 */ type Scope = 'userInfo' | 'userLocation' | 'address' | 'invoiceTitle' | 'invoice' | 'werun' | 'record' | 'writePhotosAlbum' | 'camera'; interface AuthorizeOptions extends CommonCallbackOptions { // 需要获取权限的 scope,详见 scope 列表 scope: Scope; } /** * 提前向用户发起授权请求。调用后会立刻弹窗询问用户是否同意授权小程序使用某项功能或获取用户的某些数据,但不会实际调用对应接口。如果用户之前已经同意授权,则不会出现弹窗,直接返回成功。 */ function authorize(options: AuthorizeOptions): void; // 设置 interface SettingOptions extends CommonCallbackOptions{ success?(res: AuthSetting): void; } /** * 调起客户端小程序设置界面,返回用户设置的操作结果。设置界面只会出现小程序已经向用户请求过的权限。 */ function openSetting(options: SettingOptions): void; /** * 获取用户的当前设置。返回值中只会出现小程序已经向用户请求过的权限。 */ function getSetting(options: SettingOptions): void; /** * 用户授权结果,参考 type Scope */ interface AuthSetting { 'scope.userInfo': boolean; 'scope.userLocation': boolean; 'scope.address': boolean; 'scope.invoiceTitle': boolean; 'scope.invoice': boolean; 'scope.werun': boolean; 'scope.record': boolean; 'scope.writePhotosAlbum': boolean; 'scope.camera': boolean; } } // end of wx namespace interface Page { /** * setData 函数用于将数据从逻辑层发送到视图层, * 同时改变对应的 this.data 的值。 * 注意: * 1. 直接修改 this.data 无效,无法改变页面的状态,还会造成数据不一致。 * 2. 单次设置的数据不能超过1024kB,请尽量避免一次设置过多的数据。 */ setData(data: any): void; } interface PageConstructor { /** * Page() 函数用来注册一个页面。 * 接受一个 object 参数,其指定页面的初始数据、生命周期函数、事件处理函数等。 */ (options: wx.PageOptions): void; } declare var Page: PageConstructor; interface App { /** * getCurrentPage() 函数用户获取当前页面的实例。 */ getCurrentPage(): Page; } interface AppConstructor { /** * App() 函数用来注册一个小程序。 * 接受一个 object 参数,其指定小程序的生命周期函数等。 */ (options: wx.AppOptions): void; } declare var App: AppConstructor; /** * 我们提供了全局的 getApp() 函数,可以获取到小程序实例。 */ declare function getApp(): App; // 定时器 /** * 设定一个定时器。在定时到期以后执行注册的回调函数 * @param callback * @param delay 延迟的时间,函数的调用会在该延迟之后发生,单位 ms。 * @param rest param1, param2, ..., paramN 等附加参数,它们会作为参数传递给回调函数。 */ declare function setTimeout(callback: any, delay: number, rest?: any): number; /** * 取消由 setTimeout 设置的定时器。 * @param timeoutID 要取消的定时器的ID */ declare function clearTimeout(timeoutID: number): number; /** * 设定一个定时器。按照指定的周期(以毫秒计)来执行注册的回调函数 * @param callback * @param delay 延迟的时间,函数的调用会在该延迟之后发生,单位 ms。 * @param rest param1, param2, ..., paramN 等附加参数,它们会作为参数传递给回调函数。 */ declare function setInterval(callback: any, delay: number, rest: any): number; /** * 取消由 setInterval 设置的定时器。 * @param timeoutID 要取消的定时器的ID */ declare function clearInterval(timeoutID: number): number; export { wx, App, Page, getApp, setTimeout, clearTimeout, setInterval, clearInterval }
the_stack
namespace ergometer.csafe.defs { /* Frame contents */ export const EXT_FRAME_START_BYTE =0xF0; export const FRAME_START_BYTE =0xF1; export const FRAME_END_BYTE =0xF2; export const FRAME_STUFF_BYTE =0xF3; export const FRAME_MAX_STUFF_OFFSET_BYTE =0x03; export const FRAME_FLG_LEN =2; export const EXT_FRAME_ADDR_LEN =2; export const FRAME_CHKSUM_LEN =1; export const SHORT_CMD_TYPE_MSK =0x80; export const LONG_CMD_HDR_LENGTH =2; export const LONG_CMD_BYTE_CNT_OFFSET =1; export const RSP_HDR_LENGTH =2; export const FRAME_STD_TYPE =0; export const FRAME_EXT_TYPE =1; export const DESTINATION_ADDR_HOST =0x00; export const DESTINATION_ADDR_ERG_MASTER =0x01; export const DESTINATION_ADDR_BROADCAST =0xFF; export const DESTINATION_ADDR_ERG_DEFAULT =0xFD; export const FRAME_MAXSIZE =96; export const INTERFRAMEGAP_MIN =50; // msec export const CMDUPLIST_MAXSIZE =10; export const MEMORY_BLOCKSIZE =64; export const FORCEPLOT_BLOCKSIZE =32; export const HEARTBEAT_BLOCKSIZE =32; /* Manufacturer Info */ export const MANUFACTURE_ID =22; // assigned by Fitlinxx for Concept2 export const CLASS_ID =2; // standard CSAFE equipment export const MODEL_NUM =5; // PM4 export const UNITS_TYPE =0; // Metric export const SERIALNUM_DIGITS =9; export const HMS_FORMAT_CNT =3; export const YMD_FORMAT_CNT =3; export const ERRORCODE_FORMAT_CNT =3; /* Command space partitioning for standard commands */ export const CTRL_CMD_LONG_MIN =0x01; export const CFG_CMD_LONG_MIN =0x10; export const DATA_CMD_LONG_MIN =0x20; export const AUDIO_CMD_LONG_MIN =0x40; export const TEXTCFG_CMD_LONG_MIN =0x60; export const TEXTSTATUS_CMD_LONG_MIN =0x65; export const CAP_CMD_LONG_MIN =0x70; export const PMPROPRIETARY_CMD_LONG_MIN =0x76; export const CTRL_CMD_SHORT_MIN =0x80; export const STATUS_CMD_SHORT_MIN =0x91; export const DATA_CMD_SHORT_MIN =0xA0; export const AUDIO_CMD_SHORT_MIN =0xC0; export const TEXTCFG_CMD_SHORT_MIN =0xE0; export const TEXTSTATUS_CMD_SHORT_MIN =0xE5; /* Standard Short Control Commands */ export const enum SHORT_CTRL_CMDS { GETSTATUS_CMD = 0x80 , //CTRL_CMD_SHORT_MIN RESET_CMD, // 0x81 GOIDLE_CMD, // 0x82 GOHAVEID_CMD, // 0x83 GOINUSE_CMD = 0x85, // 0x85 GOFINISHED_CMD, // 0x86 GOREADY_CMD, // 0x87 BADID_CMD, // 0x88 CTRL_CMD_SHORT_MAX } /* Standard Short Status Commands */ export const enum SHORT_STATUS_CMDS { GETVERSION_CMD = 0x91, // STATUS_CMD_SHORT_MIN GETID_CMD, // 0x92 GETUNITS_CMD, // 0x93 GETSERIAL_CMD, // 0x94 GETLIST_CMD = 0x98, // 0x98 GETUTILIZATION_CMD, // 0x99 GETMOTORCURRENT_CMD, // 0x9A GETODOMETER_CMD, // 0x9B GETERRORCODE_CMD, // 0x9C GETSERVICECODE_CMD, // 0x9D GETUSERCFG1_CMD, // 0x9E GETUSERCFG2_CMD, // 0x9F STATUS_CMD_SHORT_MAX } /* Standard Short Data Commands */ export const enum SHORT_DATA_CMDS { GETTWORK_CMD = 0xA0, // DATA_CMD_SHORT_MIN GETHORIZONTAL_CMD, // 0xA1 GETVERTICAL_CMD, // 0xA2 GETCALORIES_CMD, // 0xA3 GETPROGRAM_CMD, // 0xA4 GETSPEED_CMD, // 0xA5 GETPACE_CMD, // 0xA6 GETCADENCE_CMD, // 0xA7 GETGRADE_CMD, // 0xA8 GETGEAR_CMD, // 0xA9 GETUPLIST_CMD, // 0xAA GETUSERINFO_CMD, // 0xAB GETTORQUE_CMD, // 0xAC GETHRCUR_CMD = 0xB0, // 0xB0 GETHRTZONE_CMD = 0xB2, // 0xB2 GETMETS_CMD, // 0xB3 GETPOWER_CMD, // 0xB4 GETHRAVG_CMD, // 0xB5 GETHRMAX_CMD, // 0xB6 GETUSERDATA1_CMD= 0xBE, // 0xBE GETUSERDATA2_CMD, // 0xBF DATA_CMD_SHORT_MAX } /* Standard Short Audio Commands */ export const enum SHORT_AUDIO_CMDS { GETAUDIOCHANNEL_CMD = 0xC0, //AUDIO_CMD_SHORT_MIN GETAUDIOVOLUME_CMD, // 0xC1 GETAUDIOMUTE_CMD, // 0xC2 AUDIO_CMD_SHORT_MAX } /* Standard Short Text Configuration Commands */ export const enum SHORT_TEXTCFG_CMDS { ENDTEXT_CMD = 0xE0, //TEXTCFG_CMD_SHORT_MIN DISPLAYPOPUP_CMD, // 0xE1 TEXTCFG_CMD_SHORT_MAX } /* Standard Short Text Status Commands */ export const enum SHORT_TEXTSTATUS_CMDS { GETPOPUPSTATUS_CMD=0xE5 , // TEXTSTATUS_CMD_SHORT_MIN TEXTSTATUS_CMD_SHORT_MAX } /* Standard Long commands */ /* Standard Long Control Commands */ export const enum LONG_CTRL_CMDS { AUTOUPLOAD_CMD = 0x01, // CTRL_CMD_LONG_MIN UPLIST_CMD, // 0x02 UPSTATUSSEC_CMD = 0x04, // 0x04 UPLISTSEC_CMD, // 0x05 CTRL_CMD_LONG_MAX } /* Standard Long Configuration Commands */ export const enum LONG_CFG_CMDS { IDDIGITS_CMD = 0x10, // CFG_CMD_LONG_MIN SETTIME_CMD, // 0x11 SETDATE_CMD, // 0x12 SETTIMEOUT_CMD, // 0x13 SETUSERCFG1_CMD = 0x1A, // 0x1A SETUSERCFG2_CMD, // 0x1B CFG_CMD_LONG_MAX } /* Standard Long Data Commands */ export const enum LONG_DATA_CMDS { SETTWORK_CMD= 0x20, //DATA_CMD_LONG_MIN SETHORIZONTAL_CMD, // 0x21 SETVERTICAL_CMD, // 0x22 SETCALORIES_CMD, // 0x23 SETPROGRAM_CMD, // 0x24 SETSPEED_CMD, // 0x25 SETGRADE_CMD = 0x28, // 0x28 SETGEAR_CMD, // 0x29 SETUSERINFO_CMD = 0x2B, // 0x2B SETTORQUE_CMD, // 0x2C SETLEVEL_CMD, // 0x2D SETTARGETHR_CMD = 0x30, // 0x30 SETGOAL_CMD = 0x32, // 0x32 SETMETS_CMD, // 0x33 SETPOWER_CMD, // 0x34 SETHRZONE_CMD, // 0x35 SETHRMAX_CMD, // 0x36 DATA_CMD_LONG_MAX } /* Standard Long Audio Commands */ export const enum LONG_AUDIO_CMDS { SETCHANNELRANGE_CMD = 0x40, // AUDIO_CMD_LONG_MIN SETVOLUMERANGE_CMD, // 0x41 SETAUDIOMUTE_CMD, // 0x42 SETAUDIOCHANNEL_CMD, // 0x43 SETAUDIOVOLUME_CMD, // 0x44 AUDIO_CMD_LONG_MAX } /* Standard Long Text Configuration Commands */ export const enum LONG_TEXTCFG_CMDS { STARTTEXT_CMD = 0x60 , // TEXTCFG_CMD_LONG_MIN APPENDTEXT_CMD, // 0x61 TEXTCFG_CMD_LONG_MAX } /* Standard Long Text Status Commands */ export const enum LONG_TEXTSTATUS_CMDS { GETTEXTSTATUS_CMD =0x65, // TEXTSTATUS_CMD_LONG_MIN, TEXTSTATUS_CMD_LONG_MAX } /* Standard Long Capabilities Commands */ export const enum LONG_CAP_CMDS { GETCAPS_CMD = 0x70, // CAP_CMD_LONG_MIN GETUSERCAPS1_CMD = 0x7E, // 0x7E GETUSERCAPS2_CMD = 0x7F, // 0x7F CAP_CMD_LONG_MAX } /* The currently defined CSAFE command space is augmented by adding 4 command wrappers to allow pushing and pulling of configuration/data from the host to the PM SETPMCFG_CMD Push configuration from host to PM SETPMDATA_CMD Push data from host to PM GETPMCFG_CMD Pull configuration to host from PM GETPMDATA_CMD PUll data to host from PM Note: These commands have been added for Concept 2 and do not comply with the existing CSAFE command set */ export const enum LONG_PMPROPRIETARY_CMDS { SETPMCFG_CMD =0x76 , // PMPROPRIETARY_CMD_LONG_MIN SETPMDATA_CMD, // 0x77 GETPMCFG_CMD = 0x7E, // 0x7E GETPMDATA_CMD, // 0x7F PMPROPRIETARY_CMD_LONG_MAX } /* Command space partitioning for PM proprietary commands */ export const GETPMCFG_CMD_SHORT_MIN =0x80; export const GETPMCFG_CMD_LONG_MIN =0x50; export const SETPMCFG_CMD_SHORT_MIN =0xE0; export const SETPMCFG_CMD_LONG_MIN =0x00; export const GETPMDATA_CMD_SHORT_MIN =0xA0; export const GETPMDATA_CMD_LONG_MIN =0x68; export const SETPMDATA_CMD_SHORT_MIN =0xD0; export const SETPMDATA_CMD_LONG_MIN =0x30; /* Custom Short PULL Configuration Commands for PM */ export const enum PM_SHORT_PULL_CFG_CMDS { PM_GET_FW_VERSION = 0x80, // GETPMCFG_CMD_SHORT_MIN PM_GET_HW_VERSION, // 0x81 PM_GET_HW_ADDRESS, // 0x82 PM_GET_TICK_TIMEBASE, // 0x83 PM_GET_HRM, // 0x84 // Unused, // 0x85 PM_GET_SCREENSTATESTATUS = 0x86, // 0x86 PM_GET_RACE_LANE_REQUEST, // 0x87 PM_GET_ERG_LOGICALADDR_REQUEST, // 0x88 PM_GET_WORKOUTTYPE, // 0x89 PM_GET_DISPLAYTYPE, // 0x8A PM_GET_DISPLAYUNITS, // 0x8B PM_GET_LANGUAGETYPE, // 0x8C PM_GET_WORKOUTSTATE, // 0x8D PM_GET_INTERVALTYPE, // 0x8E PM_GET_OPERATIONALSTATE, // 0x8F PM_GET_LOGCARDSTATE, // 0x90 PM_GET_LOGCARDSTATUS, // 0x91 PM_GET_POWERUPSTATE, // 0x92 PM_GET_ROWINGSTATE, // 0x93 PM_GET_SCREENCONTENT_VERSION, // 0x94 PM_GET_COMMUNICATIONSTATE, // 0x95 PM_GET_RACEPARTICIPANTCOUNT, // 0x96 PM_GET_BATTERYLEVELPERCENT, // 0x97 PM_GET_RACEMODESTATUS, // 0x98 PM_GET_INTERNALLOGPARAMS, // 0x99 PM_GET_PRODUCTCONFIGURATION, // 0x9A PM_GET_ERGSLAVEDISCOVERREQUESTSTATUS, // 0x9B PM_GET_WIFICONFIG, // 0x9C PM_GET_CPUTICKRATE, // 0x9D PM_GET_LOGCARDCENSUS, // 0x9E PM_GET_WORKOUTINTERVALCOUNT, // 0x9F GETPMCFG_CMD_SHORT_MAX } /* Custom Short PULL Data Commands for PM */ export const enum PM_SHORT_PULL_DATA_CMDS { PM_GET_WORKTIME = 0xA0 , // GETPMDATA_CMD_SHORT_MIN PM_GET_PROJECTED_WORKTIME, // 0xA1 PM_GET_TOTAL_RESTTIME, // 0xA2 PM_GET_WORKDISTANCE, // 0xA3 PM_GET_TOTAL_WORKDISTANCE, // 0xA4 PM_GET_PROJECTED_WORKDISTANCE, // 0xA5 PM_GET_RESTDISTANCE, // 0xA6 PM_GET_TOTAL_RESTDISTANCE, // 0xA7 PM_GET_STROKE_500MPACE, // 0xA8 PM_GET_STROKE_POWER, // 0xA9 PM_GET_STROKE_CALORICBURNRATE, // 0xAA PM_GET_SPLIT_AVG_500MPACE, // 0xAB PM_GET_SPLIT_AVG_POWER, // 0xAC PM_GET_SPLIT_AVG_CALORICBURNRATE, // 0xAD PM_GET_SPLIT_AVG_CALORIES, // 0xAE PM_GET_TOTAL_AVG_500MPACE, // 0xAF PM_GET_TOTAL_AVG_POWER, // 0xB0 PM_GET_TOTAL_AVG_CALORICBURNRATE, // 0xB1 PM_GET_TOTAL_AVG_CALORIES, // 0xB2 PM_GET_STROKERATE, // 0xB3 PM_GET_SPLIT_AVG_STROKERATE, // 0xB4 PM_GET_TOTAL_AVG_STROKERATE, // 0xB5 PM_GET_AVG_HEARTRATE, // 0xB6 PM_GET_ENDING_AVG_HEARTRATE, // 0xB7 PM_GET_REST_AVG_HEARTRATE, // 0xB8 PM_GET_SPLITTIME, // 0xB9 PM_GET_LASTSPLITTIME, // 0xBA PM_GET_SPLITDISTANCE, // 0xBB PM_GET_LASTSPLITDISTANCE, // 0xBC PM_GET_LASTRESTDISTANCE, // 0xBD PM_GET_TARGETPACETIME, // 0xBE PM_GET_STROKESTATE, // 0xBF PM_GET_STROKERATESTATE, // 0xC0 PM_GET_DRAGFACTOR, // 0xC1 PM_GET_ENCODERPERIOD, // 0xC2 PM_GET_HEARTRATESTATE, // 0xC3 PM_GET_SYNCDATA, // 0xC4 PM_GET_SYNCDATAALL, // 0xC5 PM_GET_RACEDATA, // 0xC6 PM_GET_TICKTIME, // 0xC7 PM_GET_ERRORTYPE, // 0xC8 PM_GET_ERRORVALUE, // 0xC9 PM_GET_STATUSTYPE, // 0xCA PM_GET_STATUSVALUE, // 0xCB PM_GET_EPMSTATUS, // 0xCC PM_GET_DISPLAYUPDATETIME, // 0xCD PM_GET_SYNCFRACTIONALTIME, // 0xCE PM_GET_RESTTIME, // 0xCF GETPMDATA_CMD_SHORT_MAX } /* Custom Short PUSH Data Commands for PM */ export const enum PM_SHORT_PUSH_DATA_CMDS { PM_SET_SYNC_DISTANCE =0xD0, // SETPMDATA_CMD_SHORT_MIN PM_SET_SYNC_STROKEPACE, // 0xD1 PM_SET_SYNC_AVG_HEARTRATE, // 0xD2 PM_SET_SYNC_TIME, // 0xD3 PM_SET_SYNC_SPLIT_DATA, // 0xD4 PM_SET_SYNC_ENCODER_PERIOD, // 0xD5 PM_SET_SYNC_VERSION_INFO, // 0xD6 PM_SET_SYNC_RACETICKTIME, // 0xD7 PM_SET_SYNC_DATAALL, // 0xD8 // Unused, // 0xD9 // Unused, // 0xDA // Unused, // 0xDB // Unused, // 0xDC // Unused, // 0xDD // Unused, // 0xDE // Unused, // 0xDF SETPMDATA_CMD_SHORT_MAX } /* Custom Short PUSH Configuration Commands for PM */ export const enum PM_SHORT_PUSH_CFG_CMDS { PM_SET_RESET_ALL = 0xE0, // SETPMCFG_CMD_SHORT_MIN PM_SET_RESET_ERGNUMBER, // 0xE1 // Unused, // 0xE2 // Unused, // 0xE3 // Unused, // 0xE4 // Unused, // 0xE5 // Unused, // 0xE6 // Unused, // 0xE7 // Unused, // 0xE8 // Unused, // 0xE9 // Unused, // 0xEA // Unused, // 0xEB // Unused, // 0xEC // Unused, // 0xED // Unused, // 0xEE // Unused, // 0xEF SETPMCFG_CMD_SHORT_MAX } /* Custom Long PUSH Configuration Commands for PM */ export const enum PM_LONG_PUSH_CFG_CMDS { PM_SET_BAUDRATE =0x00, // SETPMCFG_CMD_LONG_MIN PM_SET_WORKOUTTYPE, // 0x01 PM_SET_STARTTYPE, // 0x02 PM_SET_WORKOUTDURATION, // 0x03 PM_SET_RESTDURATION, // 0x04 PM_SET_SPLITDURATION, // 0x05 PM_SET_TARGETPACETIME, // 0x06 PM_SET_INTERVALIDENTIFIER, // 0x07 PM_SET_OPERATIONALSTATE, // 0x08 PM_SET_RACETYPE, // 0x09 PM_SET_WARMUPDURATION, // 0x0A PM_SET_RACELANESETUP, // 0x0B PM_SET_RACELANEVERIFY, // 0x0C PM_SET_RACESTARTPARAMS, // 0x0D PM_SET_ERGSLAVEDISCOVERYREQUEST, // 0x0E PM_SET_BOATNUMBER, // 0x0F PM_SET_ERGNUMBER, // 0x10 PM_SET_COMMUNICATIONSTATE, // 0x11 PM_SET_CMDUPLIST, // 0x12 PM_SET_SCREENSTATE, // 0x13 PM_CONFIGURE_WORKOUT, // 0x14 PM_SET_TARGETAVGWATTS, // 0x15 PM_SET_TARGETCALSPERHR, // 0x16 PM_SET_INTERVALTYPE, // 0x17 PM_SET_WORKOUTINTERVALCOUNT, // 0x18 PM_SET_DISPLAYUPDATERATE, // 0x19 PM_SET_AUTHENPASSWORD, // 0x1A PM_SET_TICKTIME, // 0x1B PM_SET_TICKTIMEOFFSET, // 0x1C PM_SET_RACEDATASAMPLETICKS, // 0x1D PM_SET_RACEOPERATIONTYPE, // 0x1E PM_SET_RACESTATUSDISPLAYTICKS, // 0x1F PM_SET_RACESTATUSWARNINGTICKS, // 0x20 PM_SET_RACEIDLEMODEPARAMS, // 0x21 PM_SET_DATETIME, // 0x22 PM_SET_LANGUAGETYPE, // 0x23 PM_SET_WIFICONFIG, // 0x24 PM_SET_CPUTICKRATE, // 0x25 PM_SET_LOGCARDUSER, // 0x26 PM_SET_SCREENERRORMODE, // 0x27 PM_SET_CABLETEST, // 0x28 PM_SET_USER_ID, // 0x29 PM_SET_USER_PROFILE, // 0x2A PM_SET_HRM, // 0x2B // Unused, // 0x2C // Unused, // 0x2D // Unused, // 0x2E PM_SET_SENSOR_CHANNEL = 0x2F, // 0x2F sensor channel SETPMCFG_CMD_LONG_MAX } /* Custom Long PUSH Data Commands for PM */ export const enum PM_LONG_PUSH_DATA_CMDS { PM_SET_TEAM_DISTANCE =0x30, // SETPMDATA_CMD_LONG_MIN PM_SET_TEAM_FINISH_TIME, // 0x31 PM_SET_RACEPARTICIPANT, // 0x32 PM_SET_RACESTATUS, // 0x33 PM_SET_LOGCARDMEMORY, // 0x34 PM_SET_DISPLAYSTRING, // 0x35 PM_SET_DISPLAYBITMAP, // 0x36 PM_SET_LOCALRACEPARTICIPANT, // 0x37 // Unused, // 0x38 // Unused, // 0x39 // Unused, // 0x3A // Unused, // 0x3B // Unused, // 0x3C // Unused, // 0x3D // Unused, // 0x3E // Unused, // 0x3F // Unused, // 0x40 // Unused, // 0x41 // Unused, // 0x42 // Unused, // 0x43 // Unused, // 0x44 // Unused, // 0x45 // Unused, // 0x46 // Unused, // 0x47 // Unused, // 0x48 // Unused, // 0x49 // Unused, // 0x4A // Unused, // 0x4B // Unused, // 0x4C // Unused, // 0x4D PM_SET_ANTRFMODE = 0x4E, // 0x4E mfg support only PM_SET_MEMORY = 0x4F, // 0x4F debug only SETPMDATA_CMD_LONG_MAX } /* Custom Long PULL Configuration Commands for PM */ export const enum PM_LONG_PULL_CFG_CMDS { PM_GET_ERGNUMBER = 0x50, // GETPMCFG_CMD_LONG_MIN PM_GET_ERGNUMBERREQUEST, // 0x51 PM_GET_USERIDSTRING, // 0x52 PM_GET_LOCALRACEPARTICIPANT, // 0x53 PM_GET_USER_ID = 0x54, // 0x54 PM_GET_USER_PROFILE, // 0x55 // PM_GET_WORKOUTPARAMETERS, // 0x56 // Unused, // 0x57 // Unused, // 0x58 // Unused, // 0x59 // Unused, // 0x5A // Unused, // 0x5B // Unused, // 0x5C // Unused, // 0x5D // Unused, // 0x5E // Unused, // 0x5F // Unused, // 0x60 // Unused, // 0x61 // Unused, // 0x62 // Unused, // 0x63 // Unused, // 0x64 // Unused, // 0x65 // Unused, // 0x66 // Unused, // 0x67 GETPMCFG_CMD_LONG_MAX }; /* Custom Long PULL Data Commands for PM */ export const enum PM_LONG_PULL_DATA_CMDS { PM_GET_MEMORY = 0x68, // GETPMDATA_CMD_LONG_MIN PM_GET_LOGCARDMEMORY, // 0x69 PM_GET_INTERNALLOGMEMORY, // 0x6A PM_GET_FORCEPLOTDATA, // 0x6B PM_GET_HEARTBEATDATA, // 0x6C PM_GET_UI_EVENTS, // 0x6D CSAFE_PM_GET_STROKESTATS, // 0x6E // Unused, // 0x6F CSAFE_PM_GET_DIAGLOG_RECORD_NUM =0x70, // 0x70 CSAFE_PM_GET_DIAGLOG_RECORD, // 0x71 // Unused, // 0x72 // Unused, // 0x73 // Unused, // 0x74 // Unused, // 0x75 // Command Wrapper, // 0x76 // Command Wrapper, // 0x77 // Unused, // 0x78 // Unused, // 0x79 // Unused, // 0x7A // Unused, // 0x7B // Unused, // 0x7C // Unused, // 0x7D // Command Wrapper, // 0x7E // Command Wrapper, // 0x7F GETPMDATA_CMD_LONG_MAX } /* Status byte flag and mask definitions */ export const PREVOK_FLG =0x00; export const PREVREJECT_FLG =0x10; export const PREVBAD_FLG =0x20; export const PREVNOTRDY_FLG =0x30; export const PREVFRAMESTATUS_MSK =0x30; export const SLAVESTATE_ERR_FLG =0x00; export const SLAVESTATE_RDY_FLG =0x01; export const SLAVESTATE_IDLE_FLG =0x02; export const SLAVESTATE_HAVEID_FLG =0x03; export const SLAVESTATE_INUSE_FLG =0x05; export const SLAVESTATE_PAUSE_FLG =0x06; export const SLAVESTATE_FINISH_FLG =0x07; export const SLAVESTATE_MANUAL_FLG =0x08; export const SLAVESTATE_OFFLINE_FLG =0x09; export const FRAMECNT_FLG =0x80; export const SLAVESTATE_MSK =0x0F; /* AUTOUPLOAD_CMD flag definitions */ export const AUTOSTATUS_FLG =0x01; export const UPSTATUS_FLG =0x02; export const UPLIST_FLG =0x04; export const ACK_FLG =0x10; export const EXTERNCONTROL_FLG =0x40; /* CSAFE Slave Capabilities Codes */ export const CAPCODE_PROTOCOL =0x00; export const CAPCODE_POWER =0x01; export const CAPCODE_TEXT =0x02; /* CSAFE units format definitions: <type>_<unit>_<tens>_<decimals> */ export const DISTANCE_MILE_0_0 =0x01; export const DISTANCE_MILE_0_1 =0x02; export const DISTANCE_MILE_0_2 =0x03; export const DISTANCE_MILE_0_3 =0x04; export const DISTANCE_FEET_0_0 =0x05; export const DISTANCE_INCH_0_0 =0x06; export const WEIGHT_LBS_0_0 =0x07; export const WEIGHT_LBS_0_1 =0x08; export const DISTANCE_FEET_1_0 =0x0A; export const SPEED_MILEPERHOUR_0_0 =0x10; export const SPEED_MILEPERHOUR_0_1 =0x11; export const SPEED_MILEPERHOUR_0_2 =0x12; export const SPEED_FEETPERMINUTE_0_0 =0x13; export const DISTANCE_KM_0_0 =0x21; export const DISTANCE_KM_0_1 =0x22; export const DISTANCE_KM_0_2 =0x23; export const DISTANCE_METER_0_0 =0x24; export const DISTANCE_METER_0_1 =0x25; export const DISTANCE_CM_0_0 =0x26; export const WEIGHT_KG_0_0 =0x27; export const WEIGHT_KG_0_1 =0x28; export const SPEED_KMPERHOUR_0_0 =0x30; export const SPEED_KMPERHOUR_0_1 =0x31; export const SPEED_KMPERHOUR_0_2 =0x32; export const SPEED_METERPERMINUTE_0_0 =0x33; export const PACE_MINUTEPERMILE_0_0 =0x37; export const PACE_MINUTEPERKM_0_0 =0x38; export const PACE_SECONDSPERKM_0_0 =0x39; export const PACE_SECONDSPERMILE_0_0 =0x3A; export const DISTANCE_FLOORS_0_0 =0x41; export const DISTANCE_FLOORS_0_1 =0x42; export const DISTANCE_STEPS_0_0 =0x43; export const DISTANCE_REVS_0_0 =0x44; export const DISTANCE_STRIDES_0_0 =0x45; export const DISTANCE_STROKES_0_0 =0x46; export const MISC_BEATS_0_0 =0x47; export const ENERGY_CALORIES_0_0 =0x48; export const GRADE_PERCENT_0_0 =0x4A; export const GRADE_PERCENT_0_2 =0x4B; export const GRADE_PERCENT_0_1 =0x4C; export const CADENCE_FLOORSPERMINUTE_0_1 =0x4F; export const CADENCE_FLOORSPERMINUTE_0_0 =0x50; export const CADENCE_STEPSPERMINUTE_0_0 =0x51; export const CADENCE_REVSPERMINUTE_0_0 =0x52; export const CADENCE_STRIDESPERMINUTE_0_0 =0x53; export const CADENCE_STROKESPERMINUTE_0_0 =0x54; export const MISC_BEATSPERMINUTE_0_0 =0x55; export const BURN_CALORIESPERMINUTE_0_0 =0x56; export const BURN_CALORIESPERHOUR_0_0 =0x57; export const POWER_WATTS_0_0 =0x58; export const ENERGY_INCHLB_0_0 =0x5A; export const ENERGY_FOOTLB_0_0 =0x5B; export const ENERGY_NM_0_0 =0x5C; /* Conversion constants */ export const KG_TO_LBS =2.2046; export const LBS_TO_KG =(1./KG_TO_LBS); /* ID Digits */ export const IDDIGITS_MIN =2; export const IDDIGITS_MAX =5; export const DEFAULT_IDDIGITS =5; export const DEFAULT_ID =0; export const MANUAL_ID =999999999; /* Slave State Tiimeout Parameters */ export const DEFAULT_SLAVESTATE_TIMEOUT =20; // seconds export const PAUSED_SLAVESTATE_TIMEOUT =220; // seconds export const INUSE_SLAVESTATE_TIMEOUT =6; // seconds export const IDLE_SLAVESTATE_TIMEOUT =30; // seconds /* Base Year */ export const BASE_YEAR =1900; /* Default time intervals */ export const DEFAULT_STATUSUPDATE_INTERVAL =256; // seconds export const DEFAULT_CMDUPLIST_INTERVAL =256; // seconds }
the_stack
import 'rxjs/add/observable/bindCallback'; import 'rxjs/add/observable/bindNodeCallback'; import 'rxjs/add/observable/defer'; import 'rxjs/add/observable/forkJoin'; import 'rxjs/add/observable/fromEventPattern'; import 'rxjs/add/operator/multicast'; import {Observable} from 'rxjs/Observable'; import {asap} from 'rxjs/scheduler/asap'; import {Subscriber} from 'rxjs/Subscriber'; import {Subscription} from 'rxjs/Subscription'; import {rxSubscriber} from 'rxjs/symbol/rxSubscriber'; (Zone as any).__load_patch('rxjs', (global: any, Zone: ZoneType, api: any) => { const symbol: (symbolString: string) => string = (Zone as any).__symbol__; const subscribeSource = 'rxjs.subscribe'; const nextSource = 'rxjs.Subscriber.next'; const errorSource = 'rxjs.Subscriber.error'; const completeSource = 'rxjs.Subscriber.complete'; const unsubscribeSource = 'rxjs.Subscriber.unsubscribe'; const teardownSource = 'rxjs.Subscriber.teardownLogic'; const empty = { closed: true, next(value: any): void{}, error(err: any): void{throw err;}, complete(): void{} }; function toSubscriber<T>( nextOrObserver?: any, error?: (error: any) => void, complete?: () => void): Subscriber<T> { if (nextOrObserver) { if (nextOrObserver instanceof Subscriber) { return (<Subscriber<T>>nextOrObserver); } if (nextOrObserver[rxSubscriber]) { return nextOrObserver[rxSubscriber](); } } if (!nextOrObserver && !error && !complete) { return new Subscriber(empty); } return new Subscriber(nextOrObserver, error, complete); } const patchObservable = function() { const ObservablePrototype: any = Observable.prototype; const symbolSubscribe = symbol('subscribe'); const _symbolSubscribe = symbol('_subscribe'); const _subscribe = ObservablePrototype[_symbolSubscribe] = ObservablePrototype._subscribe; const subscribe = ObservablePrototype[symbolSubscribe] = ObservablePrototype.subscribe; Object.defineProperties(Observable.prototype, { _zone: {value: null, writable: true, configurable: true}, _zoneSource: {value: null, writable: true, configurable: true}, _zoneSubscribe: {value: null, writable: true, configurable: true}, source: { configurable: true, get: function(this: Observable<any>) { return (this as any)._zoneSource; }, set: function(this: Observable<any>, source: any) { (this as any)._zone = Zone.current; (this as any)._zoneSource = source; } }, _subscribe: { configurable: true, get: function(this: Observable<any>) { if ((this as any)._zoneSubscribe) { return (this as any)._zoneSubscribe; } else if (this.constructor === Observable) { return _subscribe; } const proto = Object.getPrototypeOf(this); return proto && proto._subscribe; }, set: function(this: Observable<any>, subscribe: any) { (this as any)._zone = Zone.current; (this as any)._zoneSubscribe = subscribe; } }, subscribe: { writable: true, configurable: true, value: function(this: Observable<any>, observerOrNext: any, error: any, complete: any) { // Only grab a zone if we Zone exists and it is different from the current zone. const _zone = (this as any)._zone; if (_zone && _zone !== Zone.current) { // Current Zone is different from the intended zone. // Restore the zone before invoking the subscribe callback. return _zone.run(subscribe, this, [toSubscriber(observerOrNext, error, complete)]); } return subscribe.call(this, observerOrNext, error, complete); } } }); }; const patchSubscription = function() { const unsubscribeSymbol = symbol('unsubscribe'); const unsubscribe = (Subscription.prototype as any)[unsubscribeSymbol] = Subscription.prototype.unsubscribe; Object.defineProperties(Subscription.prototype, { _zone: {value: null, writable: true, configurable: true}, _zoneUnsubscribe: {value: null, writable: true, configurable: true}, _unsubscribe: { get: function(this: Subscription) { if ((this as any)._zoneUnsubscribe) { return (this as any)._zoneUnsubscribe; } const proto = Object.getPrototypeOf(this); return proto && proto._unsubscribe; }, set: function(this: Subscription, unsubscribe: any) { (this as any)._zone = Zone.current; (this as any)._zoneUnsubscribe = unsubscribe; } }, unsubscribe: { writable: true, configurable: true, value: function(this: Subscription) { // Only grab a zone if we Zone exists and it is different from the current zone. const _zone: Zone = (this as any)._zone; if (_zone && _zone !== Zone.current) { // Current Zone is different from the intended zone. // Restore the zone before invoking the subscribe callback. _zone.run(unsubscribe, this); } else { unsubscribe.apply(this); } } } }); }; const patchSubscriber = function() { const next = Subscriber.prototype.next; const error = Subscriber.prototype.error; const complete = Subscriber.prototype.complete; Object.defineProperty(Subscriber.prototype, 'destination', { configurable: true, get: function(this: Subscriber<any>) { return (this as any)._zoneDestination; }, set: function(this: Subscriber<any>, destination: any) { (this as any)._zone = Zone.current; (this as any)._zoneDestination = destination; } }); // patch Subscriber.next to make sure it run // into SubscriptionZone Subscriber.prototype.next = function() { const currentZone = Zone.current; const subscriptionZone = this._zone; // for performance concern, check Zone.current // equal with this._zone(SubscriptionZone) or not if (subscriptionZone && subscriptionZone !== currentZone) { return subscriptionZone.run(next, this, arguments, nextSource); } else { return next.apply(this, arguments); } }; Subscriber.prototype.error = function() { const currentZone = Zone.current; const subscriptionZone = this._zone; // for performance concern, check Zone.current // equal with this._zone(SubscriptionZone) or not if (subscriptionZone && subscriptionZone !== currentZone) { return subscriptionZone.run(error, this, arguments, errorSource); } else { return error.apply(this, arguments); } }; Subscriber.prototype.complete = function() { const currentZone = Zone.current; const subscriptionZone = this._zone; // for performance concern, check Zone.current // equal with this._zone(SubscriptionZone) or not if (subscriptionZone && subscriptionZone !== currentZone) { return subscriptionZone.run(complete, this, arguments, completeSource); } else { return complete.apply(this, arguments); } }; }; const patchObservableInstance = function(observable: any) { observable._zone = Zone.current; }; const patchObservableFactoryCreator = function(obj: any, factoryName: string) { const symbolFactory: string = symbol(factoryName); if (obj[symbolFactory]) { return; } const factoryCreator: any = obj[symbolFactory] = obj[factoryName]; if (!factoryCreator) { return; } obj[factoryName] = function() { const factory: any = factoryCreator.apply(this, arguments); return function() { const observable = factory.apply(this, arguments); patchObservableInstance(observable); return observable; }; }; }; const patchObservableFactory = function(obj: any, factoryName: string) { const symbolFactory: string = symbol(factoryName); if (obj[symbolFactory]) { return; } const factory: any = obj[symbolFactory] = obj[factoryName]; if (!factory) { return; } obj[factoryName] = function() { const observable = factory.apply(this, arguments); patchObservableInstance(observable); return observable; }; }; const patchObservableFactoryArgs = function(obj: any, factoryName: string) { const symbolFactory: string = symbol(factoryName); if (obj[symbolFactory]) { return; } const factory: any = obj[symbolFactory] = obj[factoryName]; if (!factory) { return; } obj[factoryName] = function() { const initZone = Zone.current; const args = Array.prototype.slice.call(arguments); for (let i = 0; i < args.length; i++) { const arg = args[i]; if (typeof arg === 'function') { args[i] = function() { const argArgs = Array.prototype.slice.call(arguments); const runningZone = Zone.current; if (initZone && runningZone && initZone !== runningZone) { return initZone.run(arg, this, argArgs); } else { return arg.apply(this, argArgs); } }; } } const observable = factory.apply(this, args); patchObservableInstance(observable); return observable; }; }; const patchMulticast = function() { const obj: any = Observable.prototype; const factoryName: string = 'multicast'; const symbolFactory: string = symbol(factoryName); if (obj[symbolFactory]) { return; } const factory: any = obj[symbolFactory] = obj[factoryName]; if (!factory) { return; } obj[factoryName] = function() { const _zone: any = Zone.current; const args = Array.prototype.slice.call(arguments); let subjectOrSubjectFactory: any = args.length > 0 ? args[0] : undefined; if (typeof subjectOrSubjectFactory !== 'function') { const originalFactory: any = subjectOrSubjectFactory; subjectOrSubjectFactory = function() { return originalFactory; }; } args[0] = function() { let subject: any; if (_zone && _zone !== Zone.current) { subject = _zone.run(subjectOrSubjectFactory, this, arguments); } else { subject = subjectOrSubjectFactory.apply(this, arguments); } if (subject && _zone) { subject._zone = _zone; } return subject; }; const observable = factory.apply(this, args); patchObservableInstance(observable); return observable; }; }; const patchImmediate = function(asap: any) { if (!asap) { return; } const scheduleSymbol = symbol('scheduleSymbol'); const flushSymbol = symbol('flushSymbol'); const zoneSymbol = symbol('zone'); if (asap[scheduleSymbol]) { return; } const schedule = asap[scheduleSymbol] = asap.schedule; asap.schedule = function() { const args = Array.prototype.slice.call(arguments); const work = args.length > 0 ? args[0] : undefined; const delay = args.length > 1 ? args[1] : 0; const state = (args.length > 2 ? args[2] : undefined) || {}; state[zoneSymbol] = Zone.current; const patchedWork = function() { const workArgs = Array.prototype.slice.call(arguments); const action = workArgs.length > 0 ? workArgs[0] : undefined; const scheduleZone = action && action[zoneSymbol]; if (scheduleZone && scheduleZone !== Zone.current) { return scheduleZone.runGuarded(work, this, arguments); } else { return work.apply(this, arguments); } }; return schedule.apply(this, [patchedWork, delay, state]); }; }; patchObservable(); patchSubscription(); patchSubscriber(); patchObservableFactoryCreator(Observable, 'bindCallback'); patchObservableFactoryCreator(Observable, 'bindNodeCallback'); patchObservableFactory(Observable, 'defer'); patchObservableFactory(Observable, 'forkJoin'); patchObservableFactoryArgs(Observable, 'fromEventPattern'); patchMulticast(); patchImmediate(asap); });
the_stack
import { ActionResult } from "@atomist/automation-client/lib/action/ActionResult"; import { GitHubRepoRef } from "@atomist/automation-client/lib/operations/common/GitHubRepoRef"; import { RemoteRepoRef } from "@atomist/automation-client/lib/operations/common/RepoId"; import { PullRequest } from "@atomist/automation-client/lib/operations/edit/editModes"; import { GitProject } from "@atomist/automation-client/lib/project/git/GitProject"; import { InMemoryFile } from "@atomist/automation-client/lib/project/mem/InMemoryFile"; import { InMemoryProject } from "@atomist/automation-client/lib/project/mem/InMemoryProject"; import { fileExists } from "@atomist/automation-client/lib/project/util/projectUtils"; import * as assert from "power-assert"; import { executeAutofixes, filterImmediateAutofixes, generateCommitMessageForAutofix, GoalInvocationParameters, } from "../../../lib/api-helper/listener/executeAutofixes"; import { fakeGoalInvocation } from "../../../lib/api-helper/testsupport/fakeGoalInvocation"; import { SingleProjectLoader } from "../../../lib/api-helper/testsupport/SingleProjectLoader"; import { ExecuteGoalResult } from "../../../lib/api/goal/ExecuteGoalResult"; import { GoalInvocation } from "../../../lib/api/goal/GoalInvocation"; import { SdmGoalEvent } from "../../../lib/api/goal/SdmGoalEvent"; import { PushListenerInvocation } from "../../../lib/api/listener/PushListener"; import { pushTest } from "../../../lib/api/mapping/PushTest"; import { AutofixRegistration } from "../../../lib/api/registration/AutofixRegistration"; import { TransformPresentation } from "../../../lib/api/registration/CodeTransformRegistration"; import { RepoRefResolver } from "../../../lib/spi/repo-ref/RepoRefResolver"; import { CoreRepoFieldsAndChannels, OnPushToAnyBranch, ScmProvider, SdmGoalState } from "../../../lib/typings/types"; export const AddThingAutofix: AutofixRegistration = { name: "AddThing", pushTest: pushTest("Is TypeScript", async (pi: PushListenerInvocation) => fileExists(pi.project, "**/*.ts", () => true), ), transform: async (project, ci) => { await project.addFile("thing", "1"); assert(!!ci.context.workspaceId); assert(project === ci.push.project); assert(!!ci.credentials); assert(!ci.parameters); return { edited: true, success: true, target: project }; }, }; interface BirdParams { bird: string; } export const AddThingWithParamAutofix: AutofixRegistration<BirdParams> = { name: "AddThing", pushTest: pushTest("Is TypeScript", async (pi: PushListenerInvocation) => fileExists(pi.project, "**/*.ts", () => true), ), transform: async (project, ci) => { await project.addFile("bird", ci.parameters.bird); assert(!!ci.context.workspaceId); assert(!!ci.parameters); return { edited: true, success: true, target: project }; }, parametersInstance: { bird: "ibis", }, }; const FakeRepoRefResolver: RepoRefResolver = { repoRefFromPush(push: OnPushToAnyBranch.Push): RemoteRepoRef { throw new Error("Not implemented"); }, providerIdFromPush(push: OnPushToAnyBranch.Push): string | null { throw new Error("Not implemented"); }, repoRefFromSdmGoal(sdmGoal: SdmGoalEvent, provider: ScmProvider.ScmProvider): RemoteRepoRef { throw new Error("Not implemented"); }, toRemoteRepoRef(repo: CoreRepoFieldsAndChannels.Fragment, opts: { sha?: string; branch?: string }): RemoteRepoRef { return { remoteBase: "unreal", providerType: 0, url: "not-here", cloneUrl(): string { return "nope"; }, createRemote(): Promise<ActionResult<any>> { throw new Error("Not implemented"); }, setUserConfig(): Promise<ActionResult<any>> { throw new Error("Not implemented"); }, raisePullRequest(): Promise<ActionResult<any>> { throw new Error("Not implemented"); }, deleteRemote(): Promise<ActionResult<any>> { throw new Error("Not implemented"); }, owner: repo.owner, repo: repo.name, sha: opts.sha, branch: opts.branch, }; }, }; describe("executeAutofixes", () => { it("should execute none", async () => { const id = new GitHubRepoRef("a", "b"); const pl = new SingleProjectLoader({ id } as any); const r = (await executeAutofixes([])( fakeGoalInvocation(id, { projectLoader: pl, repoRefResolver: FakeRepoRefResolver, } as any), )) as ExecuteGoalResult; assert.equal(r.code, 0); }); it("should execute header adder and find no match", async () => { const id = new GitHubRepoRef("a", "b"); const initialContent = "public class Thing {}"; const f = new InMemoryFile("src/main/java/Thing.java", initialContent); const p = InMemoryProject.from(id, f); ((p as any) as GitProject).revert = async () => undefined; ((p as any) as GitProject).gitStatus = async () => ({ isClean: false, sha: "ec7fe33f7ee33eee84b3953def258d4e7ccb6783", } as any); const pl = new SingleProjectLoader(p); const r = (await executeAutofixes([AddThingAutofix])( fakeGoalInvocation(id, { projectLoader: pl, repoRefResolver: FakeRepoRefResolver, } as any), )) as ExecuteGoalResult; assert.equal(r.code, 0); assert.equal(p.findFileSync(f.path).getContentSync(), initialContent); }); it("should execute header adder and find a match and add a header", async () => { const id = GitHubRepoRef.from({ owner: "a", repo: "b", sha: "ec7fe33f7ee33eee84b3953def258d4e7ccb6783" }); const initialContent = "public class Thing {}"; const f = new InMemoryFile("src/Thing.ts", initialContent); const p = InMemoryProject.from(id, f, { path: "LICENSE", content: "Apache License" }); ((p as any) as GitProject).revert = async () => undefined; ((p as any) as GitProject).commit = async () => undefined; ((p as any) as GitProject).push = async () => undefined; ((p as any) as GitProject).gitStatus = async () => ({ isClean: false, sha: "ec7fe33f7ee33eee84b3953def258d4e7ccb6783", } as any); const pl = new SingleProjectLoader(p); const gi = fakeGoalInvocation(id, { projectLoader: pl, repoRefResolver: FakeRepoRefResolver, } as any); assert(!!gi.credentials); const r = (await executeAutofixes([AddThingAutofix])(gi)) as ExecuteGoalResult; assert.equal(r.code, 0); assert(!!p); const foundFile = p.findFileSync("thing"); assert(!!foundFile); assert.equal(foundFile.getContentSync(), "1"); }).timeout(10000); it("should execute with parameter and find a match and add a header", async () => { const id = GitHubRepoRef.from({ owner: "a", repo: "b", sha: "ec7fe33f7ee33eee84b3953def258d4e7ccb6783" }); const initialContent = "public class Thing {}"; const f = new InMemoryFile("src/Thing.ts", initialContent); const p = InMemoryProject.from(id, f, { path: "LICENSE", content: "Apache License" }); ((p as any) as GitProject).revert = async () => undefined; ((p as any) as GitProject).commit = async () => undefined; ((p as any) as GitProject).push = async () => undefined; ((p as any) as GitProject).gitStatus = async () => ({ isClean: false, sha: "ec7fe33f7ee33eee84b3953def258d4e7ccb6783", } as any); const pl = new SingleProjectLoader(p); const r = (await executeAutofixes([AddThingWithParamAutofix])( fakeGoalInvocation(id, { projectLoader: pl, repoRefResolver: FakeRepoRefResolver, } as any), )) as ExecuteGoalResult; assert.equal(r.code, 0, "Did not return 0"); assert.equal(r.state, SdmGoalState.stopped); assert(!!p, r.description); const foundFile = p.findFileSync("bird"); assert(!!foundFile, r.description); assert.equal(foundFile.getContentSync(), "ibis"); }).timeout(10000); it("should execute with parameter and find push", async () => { const id = GitHubRepoRef.from({ owner: "a", repo: "b", sha: "ec7fe33f7ee33eee84b3953def258d4e7ccb6783" }); const initialContent = "public class Thing {}"; const f = new InMemoryFile("src/Thing.ts", initialContent); const p = InMemoryProject.from(id, f, { path: "LICENSE", content: "Apache License" }); ((p as any) as GitProject).revert = async () => undefined; ((p as any) as GitProject).commit = async () => undefined; ((p as any) as GitProject).push = async () => undefined; ((p as any) as GitProject).gitStatus = async () => ({ isClean: false, sha: "ec7fe33f7ee33eee84b3953def258d4e7ccb6783", } as any); const pl = new SingleProjectLoader(p); const gi = fakeGoalInvocation(id, { projectLoader: pl, repoRefResolver: FakeRepoRefResolver, } as any); const errors: string[] = []; const testFix: AutofixRegistration = { name: "test", transform: async (project, ci) => { if (project !== p) { errors.push("Project not the same"); } if (!ci.push || ci.push.push !== gi.goalEvent.push) { errors.push("push should be set"); } }, }; await executeAutofixes([testFix])(gi); assert.deepEqual(errors, []); }).timeout(10000); it("should fix with transformPresentation set", async () => { const id = GitHubRepoRef.from({ owner: "a", repo: "b", sha: "ec7fe33f7ee33eee84b3953def258d4e7ccb6783", branch: "master", }); const initialContent = "public class Thing {}"; const f = new InMemoryFile("src/Thing.ts", initialContent); const p = InMemoryProject.from(id, f, { path: "LICENSE", content: "Apache License" }); ((p as any) as GitProject).revert = async () => undefined; ((p as any) as GitProject).hasBranch = async name => { if (name === "test-branch") { return false; } assert.fail(); return undefined; }; ((p as any) as GitProject).commit = async () => undefined; ((p as any) as GitProject).push = async () => undefined; ((p as any) as GitProject).gitStatus = async () => ({ isClean: false, sha: "ec7fe33f7ee33eee84b3953def258d4e7ccb6783", } as any); let createdBranch = false; let createdPr = false; ((p as any) as GitProject).createBranch = async name => { if (name === "test-branch") { createdBranch = true; } return p as any; }; ((p as any) as GitProject).raisePullRequest = async (title, body, targetBranch) => { if (targetBranch === "master") { createdPr = true; } assert(body.startsWith("body")); assert(body.includes("AddThing")); return p as any; }; const pl = new SingleProjectLoader(p); const gi = fakeGoalInvocation(id, { projectLoader: pl, repoRefResolver: FakeRepoRefResolver, } as any); let invokedTp = false; const tp: TransformPresentation<GoalInvocationParameters> = (ci, p1) => { if (invokedTp) { assert.fail(); } invokedTp = true; return new PullRequest("test-branch", "title", "body"); }; assert(!!gi.credentials); const r = (await executeAutofixes([AddThingAutofix], tp)(gi)) as ExecuteGoalResult; assert.deepStrictEqual(r.code, 0); assert.deepStrictEqual(r.state, SdmGoalState.success); assert(!!p); const foundFile = p.findFileSync("thing"); assert(!!foundFile); assert.deepStrictEqual(foundFile.getContentSync(), "1"); assert(!!invokedTp); assert(!!createdBranch); assert(!!createdPr); }).timeout(10000); describe("filterImmediateAutofixes", () => { it("should correctly filter applied autofix", () => { const autofix = ({ name: "test-autofix", } as any) as AutofixRegistration; const push = { commits: [ { message: "foo", }, { message: generateCommitMessageForAutofix(autofix), }, { message: "bar", }, ], }; const filterAutofixes = filterImmediateAutofixes([autofix], ({ goalEvent: { push, }, } as any) as GoalInvocation); assert.strictEqual(filterAutofixes.length, 0); }); it("should correctly filter applied autofix but leave other", () => { const autofix1 = ({ name: "test-autofix1", } as any) as AutofixRegistration; const autofix2 = ({ name: "test-autofix2", } as any) as AutofixRegistration; const push = { commits: [ { message: "foo", }, { message: generateCommitMessageForAutofix(autofix1), }, { message: "bar", }, ], }; const filterAutofixes = filterImmediateAutofixes([autofix1, autofix2], ({ goalEvent: { push, }, } as any) as GoalInvocation); assert.strictEqual(filterAutofixes.length, 1); assert.strictEqual(filterAutofixes[0].name, autofix2.name); }); }); });
the_stack
/// <reference path="..\..\lib\lib.core.d.ts"/> /// <reference path="analyzerEnv.ts"/> /// <reference path="..\compiler\types.ts"/> /// <reference path="..\compiler\core.ts"/> /// <reference path="..\compiler\sys.ts"/> /// <reference path="..\compiler\commandLineParser.ts"/> /// <reference path="services.ts"/> /// <reference path="utilities.ts"/> /// <reference path="shims.ts"/> interface AnalyzisError { message: string; stack: string; } interface Hyperlink { sourceFile: string; start: number; symbolId: string; } interface ClassifiedRange { classification: string; start: number; length: number; hyperlinks: Hyperlink[]; definitionSymbolId?: string; definitionKind?: string; searchString?: string; fullName?: string; } interface AnalyzedFile { fileName: string; syntacticClassifications: ClassifiedRange[]; semanticClassifications: ClassifiedRange[]; fileSymbolId: string; } interface ProcessedFile { index: number; fileName: string; } function log<T>(text: string, f: () => T): T { let start = new Date().getTime(); let result = f(); let end = new Date().getTime(); ts.sys.write(text + ": " + (end - start) + " ms" + ts.sys.newLine) return result; } function analyze(libFileName: string, files: string[], outputFolder: string): ProcessedFile[]{ let sourceFileVersion = "1"; let sourceFileIsOpen = false; let program = log("createProgram", () => createProgram(files)); let fileNames = ts.map(program.getSourceFiles(), f => f.fileName); let scriptSnapshots: ts.Map<ts.IScriptSnapshot> = {}; let checker = log("getTypeChecker", () => program.getTypeChecker()); ts.forEach(program.getSourceFiles(), f => { scriptSnapshots[f.fileName] = ts.ScriptSnapshot.fromString(f.text); }); const hostCancellationToken: ts.HostCancellationToken = { isCancellationRequested: () => false } let host: ts.LanguageServiceHost = { getCancellationToken: () => hostCancellationToken, getCompilationSettings: () => { return {}; }, getDefaultLibFileName: () => libFileName, getCurrentDirectory: () => ".", getLocalizedDiagnosticMessages: () => undefined, getScriptFileNames: () => fileNames, getScriptVersion: _ => sourceFileVersion, getScriptSnapshot: name => scriptSnapshots[name], log: (s) => { }, trace: (s) => { }, error: (s) => { } }; let documentRegistry: ts.DocumentRegistry = { acquireDocument: (fileName, settings, snapshot, version) => program.getSourceFile(fileName), releaseDocument: (fileName, settings) => { }, updateDocument: (fileName, settings, snapshot, version) => program.getSourceFile(fileName), reportStats: () => "" }; let ls = ts.createLanguageService(host, documentRegistry); let sourceFiles = program.getSourceFiles(); let processedFiles: ProcessedFile[] = []; for (let i = 0, len = sourceFiles.length; i < len; ++i) { var f = sourceFiles[i]; var fileSpan = ts.createTextSpan(0, f.text.length); let result = log("getClassifications '" + f.fileName + "'", () => { let syntacticClassifications = ls.getSyntacticClassifications(f.fileName, fileSpan); let convertedSyntactic = convertClassifications(syntacticClassifications, f, /*addHyperlinks*/ true); let semanticClassifications = ls.getSemanticClassifications(f.fileName, fileSpan); let convertedSemantic = convertClassifications(semanticClassifications, f, /*addHyperlinks*/ false); return { fileName: f.fileName, syntacticClassifications: convertedSyntactic, semanticClassifications: convertedSemantic, fileSymbolId: makeSymbolId(f.fileName, 0) }; }); let json = JSON.stringify(result); let path = ts.combinePaths(outputFolder, i + ".json"); ts.sys.writeFile(path, json, /*writeByteOrderMark*/ false); processedFiles.push({ fileName: f.fileName, index: i }); } return processedFiles; // local functions function skipClassification(c: string) { switch (c) { case ts.ClassificationTypeNames.whiteSpace: case ts.ClassificationTypeNames.punctuation: case ts.ClassificationTypeNames.operator: return true; default: return false; } } function getDeclarationForName(n: ts.Node): ts.Declaration { switch (n.kind) { case ts.SyntaxKind.ConstructorKeyword: return <ts.Declaration>n.parent; case ts.SyntaxKind.Identifier: case ts.SyntaxKind.NumericLiteral: case ts.SyntaxKind.StringLiteral: if (n.parent && ts.isDeclaration(n.parent) && (<ts.Declaration>n.parent).name === n) { return <ts.Declaration>n.parent; } } return undefined; } function getDeclarationName(decl: ts.Node): string { switch (decl.kind) { case ts.SyntaxKind.TypeAliasDeclaration: return "type alias"; case ts.SyntaxKind.Constructor: return "constructor"; case ts.SyntaxKind.TypeParameter: return "type parameter"; case ts.SyntaxKind.Parameter: return "parameter"; case ts.SyntaxKind.VariableDeclaration: return "variable"; case ts.SyntaxKind.PropertySignature: case ts.SyntaxKind.PropertyDeclaration: case ts.SyntaxKind.PropertyAssignment: return "property"; case ts.SyntaxKind.EnumMember: return "enum member" case ts.SyntaxKind.MethodSignature: case ts.SyntaxKind.MethodDeclaration: return "method"; case ts.SyntaxKind.FunctionDeclaration: return "function"; case ts.SyntaxKind.GetAccessor: return "get accessor"; case ts.SyntaxKind.SetAccessor: return "set accessor"; case ts.SyntaxKind.ClassDeclaration: return "class"; case ts.SyntaxKind.InterfaceDeclaration: return "interface"; case ts.SyntaxKind.EnumDeclaration: return "enum"; case ts.SyntaxKind.ModuleDeclaration: return "module"; case ts.SyntaxKind.ImportDeclaration: return "import"; } } function getQualifiedName(decl: ts.Declaration): string { // TODO: should be revised when TS have local types let curr: ts.Node = decl; let name = ""; while (curr) { switch (curr.kind) { case ts.SyntaxKind.Constructor: if (curr !== decl) { return "constructor" } else { name = "constructor"; } curr = curr.parent; break; case ts.SyntaxKind.Parameter: case ts.SyntaxKind.TypeParameter: case ts.SyntaxKind.VariableDeclaration: case ts.SyntaxKind.FunctionDeclaration: return ts.declarationNameToString((<ts.Declaration>decl).name); // take a shortcut case ts.SyntaxKind.GetAccessor: case ts.SyntaxKind.SetAccessor: case ts.SyntaxKind.PropertyDeclaration: case ts.SyntaxKind.PropertySignature: case ts.SyntaxKind.PropertyAssignment: if (curr.parent && curr.parent.kind === ts.SyntaxKind.TypeLiteral) { return ts.declarationNameToString((<ts.Declaration>decl).name); // take a shortcut } case ts.SyntaxKind.EnumMember: case ts.SyntaxKind.ClassDeclaration: case ts.SyntaxKind.InterfaceDeclaration: case ts.SyntaxKind.EnumDeclaration: case ts.SyntaxKind.ModuleDeclaration: case ts.SyntaxKind.ImportDeclaration: let currName = ts.declarationNameToString((<ts.Declaration>curr).name); name = name.length ? currName + "." + name : currName; default: curr = curr.parent; } } return name; } function convertClassifications(classifications: ts.ClassifiedSpan[], f: ts.SourceFile, addHyperlinks: boolean): ClassifiedRange[]{ let ranges: ClassifiedRange[] = []; if (addHyperlinks) { ts.forEach(f.referencedFiles, r => { let hyperlinks = addHyperlinksForDefinition(r.pos, /*hyperlinks*/ undefined); // push hyperlinks for tripleslash refs if (hyperlinks) { let range: ClassifiedRange = { start: r.pos, length: r.end - r.pos, hyperlinks: hyperlinks, classification: ts.ClassificationTypeNames.stringLiteral, } ranges.push(range); } }); } ts.forEach(classifications, c => { if (skipClassification(c.classificationType)) { return; } let classification = c.classificationType; let start = c.textSpan.start; let length = c.textSpan.length; let hyperlinks: Hyperlink[]; let definitionSymbolId: string; let definitionKind: string; let fullName: string; let searchString: string; if (addHyperlinks) { switch (c.classificationType) { case ts.ClassificationTypeNames.comment: case ts.ClassificationTypeNames.operator: case ts.ClassificationTypeNames.punctuation: case ts.ClassificationTypeNames.whiteSpace: break; default: let token = ts.getTokenAtPosition(f, start); // yield definition info only for constructors if (c.classificationType === ts.ClassificationTypeNames.keyword && token && token.kind !== ts.SyntaxKind.ConstructorKeyword) { break; } let declaration = token && getDeclarationForName(token); if (declaration) { searchString = declaration.name && ts.declarationNameToString(declaration.name); definitionKind = getDeclarationName(declaration); fullName = getQualifiedName(declaration); if (declaration.name) { definitionSymbolId = makeSymbolId(f.fileName, declaration.name.getStart()); } else { definitionSymbolId = makeSymbolId(f.fileName, declaration.getStart()); } } else if (token.kind === ts.SyntaxKind.Identifier && token.parent && token.parent.kind === ts.SyntaxKind.LabeledStatement) { // label definitionKind = "label"; fullName = ts.declarationNameToString(<ts.Identifier>token); definitionSymbolId = makeSymbolId(f.fileName, token.getStart()); } else { hyperlinks = addHyperlinksForDefinition(start, hyperlinks); } } } let converted: ClassifiedRange = { classification: classification, start: start, length: length, hyperlinks: hyperlinks, definitionSymbolId: definitionSymbolId, searchString: searchString, fullName: fullName, definitionKind: definitionKind }; ranges.push(converted); }); return ranges; } function addHyperlinksForDefinition(start: number, hyperlinks: Hyperlink[]): Hyperlink[] { let defs = ls.getDefinitionAtPosition(f.fileName, start); if (defs) { ts.forEach(defs, d => { if (!hyperlinks) { hyperlinks = []; } let defStart = d.textSpan.start; let defFile = program.getSourceFile(d.fileName); let token = ts.getTouchingToken(defFile, defStart, /*includeItemAtEndPosition*/ undefined); if (token && token.kind !== ts.SyntaxKind.SourceFile) { // point definition to name if possible let target = ts.isDeclaration(token) ? (<ts.Declaration>token).name : token.parent && ts.isDeclaration(token.parent) ? (<ts.Declaration>token.parent).name : token; if (target) { defStart = target.getStart(); } } let link: Hyperlink = { sourceFile: d.fileName, start: d.textSpan.start, symbolId: makeSymbolId(d.fileName, defStart) }; hyperlinks.push(link); }); } return hyperlinks; } function makeSymbolId(fileName: string, start: number): string { return fileName + "|" + start; } const cancellationToken: ts.CancellationToken = { isCancellationRequested: () => false, throwIfCancellationRequested: () => {} } function createProgram(files: string[]): ts.Program { let host: ts.CompilerHost = { getSourceFile: (filename, languageVersion) => { if (ts.sys.fileExists(filename)) { let text = ts.sys.readFile(filename); let sourceFile = ts.createSourceFile(filename, text, languageVersion); sourceFile.version = sourceFileVersion; return sourceFile; } }, getCancellationToken: () => cancellationToken, getCanonicalFileName: (filename) => ts.sys.useCaseSensitiveFileNames ? filename : filename.toLowerCase(), useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames, getNewLine: () => "\r\n", getDefaultLibFileName: (): string => { return libFileName; }, writeFile: (filename, data, writeByteOrderMark) => { throw new Error("NYI"); }, getCurrentDirectory: (): string => { return ts.sys.getCurrentDirectory(); }, fileExists: fileName => ts.sys.fileExists(fileName), readFile: fileName => ts.sys.readFile(fileName) }; return ts.createProgram(files, { target: ts.ScriptTarget.ES5 }, host) } } function analyzeShim(json: string): boolean { let args = <{ fileNames: string[]; libFile: string; outputFolder?: string }>JSON.parse(json); let outputFolder = args.outputFolder || "output"; if (!ts.sys.directoryExists(outputFolder)) { ts.sys.createDirectory(outputFolder); } try { let results = analyze(args.libFile, args.fileNames, outputFolder); ts.sys.writeFile(ts.combinePaths(outputFolder, "ok.json"), JSON.stringify(results)); return true; } catch (e) { ts.sys.writeFile(ts.combinePaths(outputFolder, "error.json"), JSON.stringify({ message: e.message, stack: e.stack })); return false; } } declare let module: any; declare let process: any; if (typeof module !== "undefined" && module.exports && process.argv.length === 3) { analyzeShim(ts.sys.readFile(process.argv[2])); } analyzeShim
the_stack
'use strict'; import _ = require('lodash'); import assert = require('assert'); import BluePromise = require('bluebird'); import debug = require('debug'); import fs = require('fs'); import Immutable = require('immutable'); import ParamContext = require('./paramcontext'); import TsJavaOptions = require('./TsJavaOptions'); import Work = require('./work'); import zip = require('zip'); import reflection = require('./reflection'); import Java = reflection.Java; var openAsync = BluePromise.promisify(fs.open); var dlog = debug('ts-java:classes-map'); var requiredCoreClasses: string[] = [ 'java.lang.Object', 'java.lang.String', ]; interface Dictionary<T> { [index: string]: T; } type StringDictionary = Dictionary<string>; // One method's variants, grouped by method signature. type VariantsBySignature = Dictionary<MethodDefinition>; // All of one class's methods in a doubly-indexed map, by method name then by method signature. type MethodsByNameBySignature = Dictionary<VariantsBySignature>; var reservedShortNames: StringDictionary = { 'Number': null }; import ClassDefinition = ClassesMap.ClassDefinition; import ClassDefinitionMap = ClassesMap.ClassDefinitionMap; import FieldDefinition = ClassesMap.FieldDefinition; import MethodDefinition = ClassesMap.MethodDefinition; import VariantsArray = ClassesMap.VariantsArray; // ## ClassesMap // ClassesMap is a map of a set of java classes/interfaces, containing information extracted via Java Reflection. // For each such class/interface, we extract the set of interfaces inherited/implemented by the class, // and information about all methods implemented by the class (directly or indirectly via inheritance). class ClassesMap { // *unhandledTypes* is the set of all types that are not included by the configured classes/packages lists // yet are referenced by methods of classes that are included in the output java.d.ts file. public unhandledTypes: Immutable.Set<string>; // *unhandledInterfaces* are any excluded types that are interfaces of included types. public unhandledInterfaces: Immutable.Set<string>; // *unhandledSuperClasses* are any excluded that are superclasses of included types. public unhandledSuperClasses: Immutable.Set<string>; private classCache: Immutable.Map<string, Java.Class>; private options: TsJavaOptions; private classes: ClassDefinitionMap; private includedPatterns: Immutable.Set<RegExp>; // shortToLongNameMap is used to detect whether a class name unambiguously identifies one class path. private shortToLongNameMap: StringDictionary; // allClasses is the list of all classes that should appear in the output java.d.ts file. // The list is created via two steps: // 1) Scan the jars in the class path for all classes matching the inWhiteList filter. // 2) Remove any non-public classes from the list. private allClasses: Immutable.Set<string>; private interfaceDepthCache: Immutable.Map<string, number>; constructor(options: TsJavaOptions) { this.options = options; this.classCache = Immutable.Map<string, Java.Class>(); this.classes = {}; this.unhandledTypes = Immutable.Set<string>(); this.unhandledInterfaces = Immutable.Set<string>(); this.unhandledSuperClasses = Immutable.Set<string>(); this.allClasses = Immutable.Set<string>(); // We create this after the first pass. this.shortToLongNameMap = null; this.interfaceDepthCache = Immutable.Map<string, number>(); // TODO: remove these two lines when the deprecated `seedClasses` and `whiteList` are no longer needed. options.classes = options.classes || options.seedClasses; options.packages = options.packages || options.whiteList; this.includedPatterns = Immutable.Set(_.map(this.options.packages, (expr: string) => { var pattern: RegExp = this.packageExpressionToRegExp(expr); dlog('package pattern:', pattern); return pattern; })); var seeds = Immutable.Set(requiredCoreClasses).merge(options.classes); seeds.forEach((className: string) => { if (!this.inWhiteList(className)) { var pattern = new RegExp('^' + className.replace(/([\.\$])/g, '\\$1') + '$'); this.includedPatterns = this.includedPatterns.add(pattern); } }); } // *initialize()*: fully initialize from configured packages & classes. public initialize(): BluePromise<void> { return BluePromise.resolve() .then(() => this.preScanAllClasses()) .then(() => this.loadClassCache()) .then(() => this.createShortNameMap()) .then(() => this.analyzeIncludedClasses()); } // *getSortedClasses()*: return a sorted array of classes. public getSortedClasses(): Array<ClassDefinition> { return this.flattenDictionary(this.classes); } // *getClasses()*: return the map of all classes. Keys are classnames, values are classMaps. public getClasses(): ClassDefinitionMap { return this.classes; } // *getAllClasses()*: Return the set of all classes selected by the configuration, i.e. appearing in output java.d.ts. public getAllClasses(): Immutable.Set<string> { return this.allClasses; } // *getOptions()*: Return the TsJavaOptions used to configure this ClassesMap. public getOptions(): TsJavaOptions { return this.options; } // *packageExpressionToRegExp()*: Return a RegExp equivalent to the given package expression. public packageExpressionToRegExp(expr: string): RegExp { if (/\.\*$/.test(expr)) { // package string ends with .* expr = expr.slice(0, -1); // remove the * expr = expr + '[\\w\\$]+$'; // and replace it with expression designed to match exactly one classname string } else if (/\.\*\*$/.test(expr)) { // package string ends with .** expr = expr.slice(0, -2); // remove the ** } expr = '^' + expr.replace(/\./g, '\\.'); return new RegExp(expr); } // #### **tsTypeName()**: given a java type name, return a typescript type name // declared public only for unit tests public tsTypeName(javaTypeName: string, context: ParamContext = ParamContext.eInput): string { var typeName = javaTypeName; var ext = ''; while (typeName[0] === '[') { typeName = typeName.slice(1); ext += '[]'; } var m = typeName.match(/^L(.*);$/); if (m) { typeName = m[1]; } // First convert the 1-letter JNI abbreviated type names to their human readble types var jniAbbreviations: StringDictionary = { // see http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/types.html B: 'byte', C: 'char', D: 'double', F: 'float', I: 'int', J: 'long', S: 'short', Z: 'boolean' }; if (typeName in jniAbbreviations) { typeName = jniAbbreviations[typeName]; } // Next, promote primitive types to their corresponding Object types, to avoid redundancy below. var primitiveToObjectMap: StringDictionary = { 'byte': 'java.lang.Object', 'char': 'java.lang.Object', 'boolean': 'java.lang.Boolean', 'short': 'java.lang.Short', 'long' : 'java.lang.Long', 'int': 'java.lang.Integer', 'float': 'java.lang.Float', 'double': 'java.lang.Double' }; if (typeName in primitiveToObjectMap) { typeName = primitiveToObjectMap[typeName]; } if (!this.isIncludedClass(typeName) && typeName !== 'void') { // Since the type is not in our included classes, we might want to use the Typescript 'any' type. // However, array_t<any> doesn't really make sense. Rather, we want array_t<Object>, // or possibly instead of Object a superclass that is in our whitelist. this.unhandledTypes = this.unhandledTypes.add(typeName); typeName = 'java.lang.Object'; } // Finally, convert Java primitive types to Typescript primitive types. // node-java does type translation for a set of common/primitive types. // Translation is done both for function input parameters, and function return values. // In general, it's not a 1-1 mapping between types. // For function input parameters, we generaly need union types, so that methods can accept // either javascript values, or java values (object pointers of a given Java type). // Function return results are always a single type, but several java types may map to // one javascript type (e.g. number). // string_t is a union type [string|java.lang.String] defined in the handlebars template. // Likewise object_t is the union type [string|java.lang.Object], a special case because it // is common to pass a string to methods that are declared to take Object. // (This may change when we implement generics). // java.lang.Long type requires special handling, since javascript does not have 64-bit integers. // For return values, node-java returns a Number that has an additional key 'longValue' holding a string // representation of the full long integer. The value of the Number itself is the best floating point // approximation (53 bits of the mantissa plus an exponent). // We define an interface longValue_t (in package.txt) that that extends Number and adds a string member longValue. // We also define long_t, which is the union [number|longValue_t|java.lang.Long]. var javaTypeToTypescriptType: StringDictionary = { void: 'void', 'java.lang.Boolean': context === ParamContext.eInput ? 'boolean_t' : 'boolean', 'java.lang.Double': context === ParamContext.eInput ? 'double_t' : 'number', 'java.lang.Float': context === ParamContext.eInput ? 'float_t' : 'number', 'java.lang.Integer': context === ParamContext.eInput ? 'integer_t' : 'number', 'java.lang.Long': context === ParamContext.eInput ? 'long_t' : 'longValue_t', 'java.lang.Number': context === ParamContext.eInput ? 'number_t' : 'number', 'java.lang.Object': context === ParamContext.eInput ? 'object_t' : 'object_t', // special case 'java.lang.Short': context === ParamContext.eInput ? 'short_t' : 'number', 'java.lang.String': context === ParamContext.eInput ? 'string_t' : 'string' }; if (typeName in javaTypeToTypescriptType) { typeName = javaTypeToTypescriptType[typeName]; } else if (this.isIncludedClass(typeName)) { // Use the short class name if it doesn't cause name conflicts. // This can only be done correctly after running prescanAllClasses, // when this.shortToLongNameMap has been populated. // However, conflicts are very rare, and unit tests currently don't run prescanAllClasses, // so it is convenient to always map to the short name if shortToLongNameMap doesn't exist. var shortName = this.shortClassName(typeName); if (!this.shortToLongNameMap || this.shortToLongNameMap[shortName] === typeName) { typeName = shortName; } // Add the 'Java.' namespace typeName = 'Java.' + typeName; } else { dlog('Unhandled type:', typeName); this.unhandledTypes = this.unhandledTypes.add(typeName); typeName = 'any'; } // Handle arrays assert.ok(ext.length % 2 === 0); // ext must be sequence of zero or more '[]'. if (ext === '') { // A scalar type, nothing to do here } else if (context === ParamContext.eReturn) { // Functions that return a Java array are thunked by node-java to return a // javascript array of the corresponding type. // This seems to work even for multidimensional arrays. typeName = typeName + ext; } else if (ext === '[]') { // Node-java has support for 1d arrays via newArray. We need the special opaque type array_t<T> to // model the type of these array objects. typeName = 'array_t<' + typeName + '>'; } else { // This final else block handles two cases for multidimensial arrays: // 1) When used as a function input. // 2) When returned as a function result, and the element type is not a primitive. // Node-java currently doesn't handle these cases. We use the 'void' type here so that // such uses will be flagged with an error at compile time. this.unhandledTypes = this.unhandledTypes.add(typeName + ext); typeName = 'void'; } return typeName; } // *mapMethod()*: return a map of useful properties of a method or constructor. // For our purposes, we can treat constructors as methods except for the handling of return type. // declared public only for unit tests public mapMethod(method: Java.Executable): MethodDefinition { var signature = this.methodSignature(method); var Modifier: Java.Modifier.Static = Java.importClass('java.lang.reflect.Modifier'); var isStatic: boolean = Modifier.isStatic(method.getModifiers()); var returnType: string = 'void'; if ('getReturnType' in method) { returnType = (<Java.Method>method).getReturnType().getName(); } else { // It is convenient to declare the return type for a constructor to be the type of the class, // possibly transformed by tsTypeName. This is because node-java will always convert boxed primitive // types to the corresponding javascript primitives, e.g. java.lang.String -> string, and // java.lang.Integer -> number. returnType = method.getDeclaringClass().getName(); } var methodMap: MethodDefinition = { name: method.getName(), declared: method.getDeclaringClass().getName(), returns: returnType, tsReturns: this.tsTypeName(returnType, ParamContext.eReturn), paramNames: _.map(method.getParameters(), (p: Java.Parameter) => { return p.getName(); }), paramTypes: _.map(method.getParameterTypes(), (p: Java.Class) => { return p.getName(); }), tsParamTypes: _.map(method.getParameterTypes(), (p: Java.Class) => { return this.tsTypeName(p.getName()); }), isStatic: isStatic, isVarArgs: method.isVarArgs(), generic_proto: method.toGenericString(), plain_proto: method.toString(), signature: signature }; return methodMap; } // *mapClassMethods()*: return a methodMap array for the methods of a class // declared public only for unit tests public mapClassMethods(className: string, clazz: Java.Class): Array<MethodDefinition> { return _.map(clazz.getMethods(), function (m: Java.Method) { return this.mapMethod(m); }, this); } // *mapClass()*: return a map of all useful properties of a class. // declared public only for unit tests public mapClass(className: string, work: Work): ClassDefinition { var clazz: Java.Class = this.getClass(className); assert.strictEqual(className, clazz.getName()); // Get the superclass of the class, if it exists, and is an included class. // If the immediate type is not an included class, we ascend up the ancestry // until we find an included superclass. If none exists, we declare the // class to not have a superclass, even though it does. // We report all such skipped superclasses in the summary diagnostics. // The developer can then choose to add any of these classes to the seed classes list. var superclass: Java.Class = clazz.getSuperclass(); while (superclass && !this.isIncludedClass(superclass.getName())) { this.unhandledSuperClasses = this.unhandledSuperClasses.add(superclass.getName()); superclass = superclass.getSuperclass(); } var interfaces = this.mapClassInterfaces(className, clazz).sort(); if (superclass) { interfaces.unshift(superclass.getName()); } interfaces.forEach((intfName: string) => { if (!work.alreadyDone(intfName)) { work.addTodo(intfName); // needed only to simplify a unit test. Normally a no-op. dlog('Recursing in mapClass to do inherited interface:', intfName); this.classes[intfName] = this.mapClass(intfName, work); work.setDone(intfName); } }); var methods: Array<MethodDefinition> = this.mapClassMethods(className, clazz).sort(bySignature); var fields: Array<FieldDefinition> = this.mapClassFields(className, clazz); var constructors: Array<MethodDefinition> = this.mapClassConstructors(className, clazz); var shortName: string = this.shortClassName(className); var alias: string = shortName; var useAlias: boolean = true; if (this.shortToLongNameMap === null) { // First pass, don't do this work yet } else if (this.shortToLongNameMap[shortName] !== className) { alias = className; useAlias = false; } var isInterface = clazz.isInterface(); var isPrimitive = clazz.isPrimitive(); var isEnum = clazz.isEnum(); function bySignature(a: MethodDefinition, b: MethodDefinition) { return a.signature.localeCompare(b.signature); } var tsInterfaces = _.map(interfaces, (intf: string) => { return this.fixClassPath(intf); }); // tsInterfaces is used in the extends clause of an interface declaration. // Each intf is an interface name is a fully scoped java path, but in typescript // these paths are all relative paths under the output module Java. // In most cases it is not necessary to include the 'Java.' module in the interface // name, but in few cases leaving it out causes naming conflicts, most notably // between java.lang and groovy.lang. tsInterfaces = _.map(tsInterfaces, (intf: string) => { return 'Java.' + intf; }); var variantsDict: MethodsByNameBySignature = this.groupMethods(methods); this.mergeOverloadedVariants(variantsDict, interfaces); var variants: VariantsArray = _.map(variantsDict, (bySig: VariantsBySignature) => this.flattenDictionary(bySig).sort(this.compareVariants)); var classMap: ClassDefinition = { quotedPkgName: this.packageName(this.fixClassPath(className)), packageName: this.packageName(className), fullName: className, shortName: shortName, alias: alias, useAlias: useAlias, tsType: this.tsTypeName(className), isInterface: isInterface, isPrimitive: isPrimitive, superclass: superclass === null ? null : superclass.getName(), interfaces: interfaces, tsInterfaces: tsInterfaces, methods: methods, constructors: constructors.sort(this.compareVariants), variantsDict: variantsDict, variants: variants, isEnum: isEnum, fields: fields }; return classMap; } // *inWhiteList()*: Return true for classes of interest. // declared public only for unit tests public inWhiteList(className: string): boolean { var allowed: boolean = this.includedPatterns.find((ns: RegExp) => { return className.match(ns) !== null; }) !== undefined; if (allowed) { var isAnon: boolean = /\$\d+$/.test(className); if (isAnon) { dlog('Filtering out anon class:', className); allowed = false; } } return allowed; } // *shortClassName()*: Return the short class name given the full className (class path). // declared public only for unit tests public shortClassName(className: string): string { return _.last(className.split('.')); } // *getClass()*: get the Class object for the given full class name. // declared public only for unit tests public getClass(className: string): Java.Class { var clazz = this.classCache.get(className); if (!clazz) { // For historical reasons, we simulate the exception thrown when the Java classloader doesn't find class throw new Error('java.lang.ClassNotFoundException:' + className); } return clazz; } // *mapClassInterfaces()*: Find the direct interfaces of className. // declared public only for unit tests public mapClassInterfaces(className: string, clazz: Java.Class) : Array<string> { assert.strictEqual(clazz.getName(), className); var interfaces: Array<string> = this.resolveInterfaces(clazz).toArray(); // Methods of Object must always be available on any instance variable, even variables whose static // type is a Java interface. Java does this implicitly. We have to do it explicitly. var javaLangObject = 'java.lang.Object'; if (interfaces.length === 0 && className !== javaLangObject && clazz.getSuperclass() === null) { interfaces.push(javaLangObject); } return interfaces; } // *fixClassPath()*: given a full class path name, rename any path components that are reserved words. // declared public only for unit tests public fixClassPath(fullName: string): string { var reservedWords = [ // TODO: include full list of reserved words 'function', 'package' ]; var parts = fullName.split('.'); parts = _.map(parts, (part: string) => { if (_.indexOf(reservedWords, part) === -1) { return part; } else { return part + '_'; } }); return parts.join('.'); } // *isIncludedClass()*: Return true if the class will appear in the output java.d.ts file. // All such classes 1) match the classes or package expressions in the tsjava section of the package.json, // and 2) are public. private isIncludedClass(className: string): boolean { return this.allClasses.has(className); } // *resolveInterfaces()*: Find the set of non-excluded interfaces for the given class `clazz`. // If an interface of a class is excluded by the configuration, we check the ancestors of that class. private resolveInterfaces(clazz: Java.Class): Immutable.Set<string> { var result = Immutable.Set<string>(); _.forEach(clazz.getInterfaces(), (intf: Java.Class): void => { var intfName: string = intf.getName(); if (this.isIncludedClass(intfName)) { result = result.add(intfName); } else { // Remember the excluded interface this.unhandledInterfaces = this.unhandledInterfaces.add(intfName); // recurse and merge results. result = result.merge(this.resolveInterfaces(intf)); } }); return result; } // *typeEncoding()*: return the JNI encoding string for a java class private typeEncoding(clazz: Java.Class): string { var name = clazz.getName(); var primitives: StringDictionary = { boolean: 'Z', byte: 'B', char: 'C', double: 'D', float: 'F', int: 'I', long: 'J', short: 'S', void: 'V' }; var encoding: string; if (clazz.isPrimitive()) { encoding = primitives[name]; } else if (clazz.isArray()) { encoding = name; } else { encoding = clazz.getCanonicalName(); assert.ok(encoding, 'typeEncoding cannot handle type'); encoding = 'L' + encoding + ';'; } return encoding.replace(/\./g, '/'); } // #### **methodSignature()**: return the signature of a method, i.e. a string unique to any method variant, // encoding the method name, types of parameters, and the return type. // This string may be passed as the method name to java.callMethod() in order to execute a specific variant. private methodSignature(method: Java.Executable): string { var name = method.getName(); var paramTypes = method.getParameterTypes(); var sigs = paramTypes.map((p: Java.Class) => { return this.typeEncoding(p); }); var signature = name + '(' + sigs.join('') + ')'; if ('getReturnType' in method) { // methodSignature can be called on either a constructor or regular method. // constructors don't have return types. signature += this.typeEncoding((<Java.Method>method).getReturnType()); } return signature; } // *mapField()*: return a map of useful properties of a field. private mapField(field: Java.Field): FieldDefinition { var name: string = field.getName(); var fieldType: Java.Class = field.getType(); var fieldTypeName: string = fieldType.getName(); var declaredIn: string = field.getDeclaringClass().getName(); var tsType: string = this.tsTypeName(fieldTypeName, ParamContext.eReturn); var Modifier: Java.Modifier.Static = Java.importClass('java.lang.reflect.Modifier'); var isStatic: boolean = Modifier.isStatic(field.getModifiers()); var isSynthetic: boolean = field.isSynthetic(); var fieldDefinition: FieldDefinition = { name: name, tsType: tsType, isStatic: isStatic, isSynthetic: isSynthetic, declaredIn: declaredIn }; return fieldDefinition; } // *mapClassFields()*: return a FieldDefinition array for the fields of a class private mapClassFields(className: string, clazz: Java.Class): Array<FieldDefinition> { var allFields: Array<Java.Field> = clazz.getFields(); var allFieldDefs: Array<FieldDefinition> = _.map(allFields, (f: Java.Field) => this.mapField(f)); // For instance fields, we should keep only the fields declared in this class. // We'll have access to inherited fields through normal inheritance. // If we kept the inherited fields, it would result in duplicate definitions in the derived classes. var instanceFieldDefs: Array<FieldDefinition> = _.filter(allFieldDefs, (f: FieldDefinition) => { return !f.isStatic && f.declaredIn === clazz.getName(); }); // For static fields we should keep all inherited fields, since the .Static interface of a class // does not extend the .Static interface of its parent(s). // But we can't simply keep all static fields, because (apparently) a class can redefine a static // field with the same name as an inherited field. var staticFieldDefs: Array<FieldDefinition> = _.filter(allFieldDefs, (f: FieldDefinition) => f.isStatic); staticFieldDefs = _.uniq(staticFieldDefs, false, 'name'); return instanceFieldDefs.concat(staticFieldDefs); } // *mapClassConstructors()*: return a methodMap array for the constructors of a class private mapClassConstructors(className: string, clazz: Java.Class): Array<MethodDefinition> { return _.map(clazz.getConstructors(), function (m: Java.Constructor) { return this.mapMethod(m); }, this); } // *compareVariants()*: Compare two method definitions, which should be two variants with the same method name. // We arrange to sort methods from most specific to most generic, as expected by Typescript. private compareVariants(a: MethodDefinition, b: MethodDefinition): number { function countArgsOfTypeAny(a: MethodDefinition): number { return _.filter(a.tsParamTypes, (t: string) => t === 'any').length; } // We want variants with more parameters to come first. if (a.paramTypes.length > b.paramTypes.length) { return -1; } else if (a.paramTypes.length < b.paramTypes.length) { return 1; } // For the same number of parameters, order methods with fewer 'any' arguments first if (countArgsOfTypeAny(a) < countArgsOfTypeAny(b)) { return -1; } else if (countArgsOfTypeAny(a) > countArgsOfTypeAny(b)) { return 1; } // For the same number of parameters, order the longer (presumably more complex) signature to be first if (a.signature.length > b.signature.length) { return -1; } else if (a.signature.length < b.signature.length) { return 1; } // As a penultimate catch-all, sort lexically by signature. var result: number = b.signature.localeCompare(a.signature); if (result !== 0) { return result; } // As a final catch-all, sort lexically by the generic proto signature. return a.generic_proto.localeCompare(b.generic_proto); } // *flattenDictionary()*: return an array of the dictionary's values, sorted by the dictionary's keys. private flattenDictionary<T>(dict: Dictionary<T>): T[] { function caseInsensitiveOrder(a: string, b: string): number { var A = a.toLowerCase(); var B = b.toLowerCase(); if (A < B) { return -1; } else if (A > B) { return 1; } else { return 0; } } var keys = _.keys(dict).sort(caseInsensitiveOrder); return _.map(keys, (key: string): T => dict[key]); } // *groupMethods()*: group methods first by name, and then by signature. private groupMethods(flatList: Array<MethodDefinition>): MethodsByNameBySignature { var result: MethodsByNameBySignature = {}; _.forEach(flatList, (method: MethodDefinition) => { if (!_.has(result, method.name)) { result[method.name] = {}; } result[method.name][method.signature] = method; }); return result; } // *interfacesTransitiveClosure()*: return the transitive closure of all inherited interfaces given // a set of directly inherited interfaces. private interfacesTransitiveClosure(directInterfaces: string[]): string[] { var work: Work = new Work(); directInterfaces.forEach((intf: string) => work.addTodo(intf)); work.forEach((intf: string) => { this.classes[intf].interfaces.forEach((parent: string) => work.addTodo(parent)); }); return work.getDone().toArray(); } // *interfaceDepth()*: return the 'depth' of a class in the class graph. // A class with no inherited interfaces has depth 0. We arrange so that java.lang.Object is the only such class. // Every other interface has a depth 1 greater than the maximum depth of any of its direct parent interfaces. private interfaceDepth(intf: string): number { if (this.interfaceDepthCache.has(intf)) { return this.interfaceDepthCache.get(intf); } var parents: string[] = this.classes[intf].interfaces; var intfDepth: number = 0; if (parents.length > 0) { var depths: number[] = _.map(parents, (parent: string) => this.interfaceDepth(parent)); intfDepth = _.max(depths) + 1; } this.interfaceDepthCache = this.interfaceDepthCache.set(intf, intfDepth); return intfDepth; } // *mergeOverloadedVariants()*: Merge into a class's variants dictionary all inherited overloaded variants. // The algorithm intentionally overwrites any method definition with the definition from the inherited // interface that first declared it. The only sigificant difference between the original declaration and a later override // is the generic_proto field, which we render into the output .d.ts file as a comment before the method. private mergeOverloadedVariants(variantsDict: MethodsByNameBySignature, directInterfaces: string[]): void { var self = this; // Get the list of all inherited interfaces, ordered in descending order by interface depth. var interfaces: string[] = this.interfacesTransitiveClosure(directInterfaces) .sort((intf1: string, intf2: string): number => { return self.interfaceDepth(intf2) - self.interfaceDepth(intf1); }); // for each method name of the class _.forEach(variantsDict, (methodVariants: VariantsBySignature, methodName: string) => { // for all inherited interfaces _.forEach(interfaces, (intfName: string) => { var intfVariantsDict: MethodsByNameBySignature = this.classes[intfName].variantsDict; // if the inherited interface declares any of the variants of the method if (_.has(intfVariantsDict, methodName)) { // merge all of the variants into the class's variants dictionary. _.assign(variantsDict[methodName], intfVariantsDict[methodName]); } }); }); } // *packageName()*: given a full class path name, return the package name. private packageName(className: string): string { var parts = className.split('.'); parts.pop(); return parts.join('.'); } // *getWhitedListedClassesInJar()*: For the given jar, read the index, and return an array of all classes // from the jar that are selected by the configuration. private getWhitedListedClassesInJar(jarpath: string): BluePromise<Array<string>> { dlog('getWhitedListedClassesInJar started for:', jarpath); var result: Array<string> = []; return openAsync(jarpath, 'r') .then((fd: number) => { var reader = zip.Reader(fd); reader.forEach((entry: zip.Entry) => { if (entry) { var entryPath: string = entry.getName(); if (/\.class$/.test(entryPath)) { var className: string = entryPath.slice(0, -'.class'.length).replace(/\//g, '.'); if (this.inWhiteList(className)) { result.push(className); } } } }); }) .then(() => result); } // *createShortNameMap()*: Find all classes with unique class names, and create a map from name to full class name. // E.g. if `java.lang.String` is the only class named `String`, the map will contain {'String': 'java.lang.String'}. // For non-unique class names, the name is added to the map with a null value. private createShortNameMap(): BluePromise<void> { dlog('createShortNameMap started'); // We assume this.allClasses now contains a complete list of all classes // that we will process. We scan it now to create the shortToLongNameMap, // which allows us to discover class names conflicts. // Conflicts are recorded by using null for the longName. this.shortToLongNameMap = {}; this.allClasses.forEach((longName: string): any => { var shortName = this.shortClassName(longName); if (shortName in reservedShortNames || shortName in this.shortToLongNameMap) { // We have a conflict this.shortToLongNameMap[shortName] = null; } else { // No conflict yet this.shortToLongNameMap[shortName] = longName; } }); dlog('createShortNameMap completed'); return; } // *analyzeIncludedClasses()*: Analyze all of the classes included by the configuration, creating a ClassDefinition // for each class. private analyzeIncludedClasses(): BluePromise<void> { dlog('analyzeIncludedClasses started'); var work: Work = new Work(); this.allClasses.forEach((className: string): void => work.addTodo(className)); work.forEach((className: string): void => { this.classes[className] = this.mapClass(className, work); }); dlog('analyzeIncludedClasses completed'); return; } // *loadClassCache()*: Load all classes seen in prescan, pruning any non-public classes. private loadClassCache(): BluePromise<void> { var Modifier: Java.Modifier.Static = Java.importClass('java.lang.reflect.Modifier'); var nonPublic = Immutable.Set<string>(); var classLoader = Java.getClassLoader(); this.allClasses.forEach((className: string): void => { var clazz: Java.Class = classLoader.loadClass(className); var modifiers: number = clazz.getModifiers(); var isPublic: boolean = Modifier.isPublic(modifiers); var isPrivate: boolean = Modifier.isPrivate(modifiers); var isProtected: boolean = Modifier.isProtected(modifiers); if (isPublic) { this.classCache = this.classCache.set(className, clazz); } else { nonPublic = nonPublic.add(className); if (isPrivate) { dlog('Pruning private class:', className); } else if (isProtected) { dlog('Pruning protected class:', className); } else { dlog('Pruning package-private class:', className); } } }); this.allClasses = this.allClasses.subtract(nonPublic); return; } // *preScanAllClasses()*: scan all jars in the class path and find all classes matching our filter. // The result is stored in the member variable this.allClasses and returned as the function result private preScanAllClasses(): BluePromise<void> { dlog('preScanAllClasses started'); var options = this.options; var result = Immutable.Set<string>(); var promises: BluePromise<Array<string>>[] = _.map(options.classpath, (jarpath: string) => this.getWhitedListedClassesInJar(jarpath)); return BluePromise.all(promises) .each((classes: Array<string>) => { result = result.merge(classes); }) .then(() => { this.allClasses = result; dlog('preScanAllClasses completed'); }); } } module ClassesMap { 'use strict'; // ### MethodDefinition // All of the properties on interest for a method. export interface MethodDefinition { name: string; // name of method, e.g. 'forEachRemaining' declared: string; // interface where first declared: 'java.util.Iterator' returns: string; // return type, e.g. 'void', 'int', of class name tsReturns: string; // return type, e.g. 'void', 'number', of class name paramNames: Array<string>; // [ 'arg0' ], paramTypes: Array<string>; // [ 'java.util.function.Consumer', '[S' ], tsParamTypes: Array<string>; // [ 'java.util.function_.Consumer', 'number' ], isStatic: boolean; // true if this is a static method isVarArgs: boolean; // true if this method's last parameter is varargs ...type generic_proto: string; // The method prototype including generic type information plain_proto: string; // The java method prototype without generic type information signature: string; // A method signature related to the plain_proto prototype above // This signature does not include return type info, as java does not // use return type to distinguish among overloaded methods. } // ### VariantsArray export type VariantsArray = Array<Array<MethodDefinition>>; export interface FieldDefinition { name: string; tsType: string; isStatic: boolean; isSynthetic: boolean; declaredIn: string; } // ### ClassDefinition // All of the properties on interest for a class. export interface ClassDefinition { quotedPkgName: string; // 'java.util.function_' packageName: string; // 'java.util.function' fullName: string; // 'java.util.Iterator' shortName: string; // 'Iterator' alias: string; // This will be shortName, unless two classes have the same short name, // of if the short name conflicts with a Javascript type (e.g. Number). useAlias: boolean; // true if alias is the shortName. tsType: string; // For primitive wrappers, the ts type, e.g. 'java.lang.String' -> 'string' isInterface: boolean; // true if this is an interface, false for class or primitive type. isPrimitive: boolean; // true for a primitive type, false otherwise. superclass: string; // null if no superclass, otherwise class name interfaces: Array<string>; // [ 'java.util.function.Function' ] tsInterfaces: Array<string>; // [ 'java.util.function_.Function' ] methods: Array<MethodDefinition>; // definitions of all methods implemented by this class constructors: Array<MethodDefinition>; // definitions of all constructors for this class, may be empty. variantsDict: MethodsByNameBySignature; variants: VariantsArray; // definitions of all methods, grouped by method name isEnum: boolean; // true for an Enum, false otherwise. fields: Array<FieldDefinition>; // array of FieldDefinitions for public fields. } export interface ClassDefinitionMap { [index: string]: ClassDefinition; } } export = ClassesMap;
the_stack
import 'reflect-metadata'; import { ObjectDefinitionOptions, ObjectIdentifier, ReflectResult, TagClsMetadata, TagPropsMetadata, } from '../interface'; import { CLASS_KEY_CONSTRUCTOR, INJECT_TAG, MAIN_MODULE_KEY, OBJ_DEF_CLS, PRIVATE_META_DATA_KEY, TAGGED, TAGGED_CLS, TAGGED_PROP, } from '../constant'; import { DUPLICATED_INJECTABLE_DECORATOR, DUPLICATED_METADATA, INVALID_DECORATOR_OPERATION, } from './errMsg'; import { Metadata } from './metadata'; import { getParamNames, classNamed, isNullOrUndefined, isClass, generateRandomId, } from '../util'; const debug = require('util').debuglog('decorator:manager'); export type DecoratorKey = string | symbol; export const PRELOAD_MODULE_KEY = 'INJECTION_PRELOAD_MODULE_KEY'; export const INJECT_CLASS_KEY_PREFIX = 'INJECTION_CLASS_META_DATA'; export class DecoratorManager extends Map { /** * the key for meta data store in class */ injectClassKeyPrefix = INJECT_CLASS_KEY_PREFIX; /** * the key for method meta data store in class */ injectClassMethodKeyPrefix = 'INJECTION_CLASS_METHOD_META_DATA'; /** * the key for method meta data store in method */ injectMethodKeyPrefix = 'INJECTION_METHOD_META_DATA'; saveModule(key, module) { if (!this.has(key)) { this.set(key, new Set()); } this.get(key).add(module); } resetModule(key) { this.set(key, new Set()); } static getDecoratorClassKey(decoratorNameKey: DecoratorKey) { return decoratorNameKey.toString() + '_CLS'; } static removeDecoratorClassKeySuffix(decoratorNameKey: DecoratorKey) { return decoratorNameKey.toString().replace('_CLS', ''); } static getDecoratorMethodKey(decoratorNameKey: DecoratorKey) { return decoratorNameKey.toString() + '_METHOD'; } static getDecoratorClsExtendedKey(decoratorNameKey: DecoratorKey) { return decoratorNameKey.toString() + '_EXT'; } static getDecoratorClsMethodPrefix(decoratorNameKey: DecoratorKey) { return decoratorNameKey.toString() + '_CLS_METHOD'; } static getDecoratorClsMethodKey( decoratorNameKey: DecoratorKey, methodKey: DecoratorKey ) { return ( DecoratorManager.getDecoratorClsMethodPrefix(decoratorNameKey) + ':' + methodKey.toString() ); } static getDecoratorMethod( decoratorNameKey: DecoratorKey, methodKey: DecoratorKey ) { return ( DecoratorManager.getDecoratorMethodKey(decoratorNameKey) + '_' + methodKey.toString() ); } listModule(key) { return Array.from(this.get(key) || {}); } static saveMetadata( metaKey: string, target: any, dataKey: string, data: any ) { debug( 'saveMetadata %s on target %o with dataKey = %s.', metaKey, target, dataKey ); // filter Object.create(null) if (typeof target === 'object' && target.constructor) { target = target.constructor; } let m: Map<string, any>; if (Reflect.hasOwnMetadata(metaKey, target)) { m = Reflect.getMetadata(metaKey, target); } else { m = new Map<string, any>(); } m.set(dataKey, data); Reflect.defineMetadata(metaKey, m, target); } static attachMetadata( metaKey: string, target: any, dataKey: string, data: any, groupBy?: string ) { debug( 'attachMetadata %s on target %o with dataKey = %s.', metaKey, target, dataKey ); // filter Object.create(null) if (typeof target === 'object' && target.constructor) { target = target.constructor; } let m: Map<string, any>; if (Reflect.hasOwnMetadata(metaKey, target)) { m = Reflect.getMetadata(metaKey, target); } else { m = new Map<string, any>(); } if (!m.has(dataKey)) { if (groupBy) { m.set(dataKey, {}); } else { m.set(dataKey, []); } } if (groupBy) { m.get(dataKey)[groupBy] = data; } else { m.get(dataKey).push(data); } Reflect.defineMetadata(metaKey, m, target); } static getMetadata(metaKey: string, target: any, dataKey?: string) { debug( 'getMetadata %s on target %o with dataKey = %s.', metaKey, target, dataKey ); // filter Object.create(null) if (typeof target === 'object' && target.constructor) { target = target.constructor; } let m: Map<string, any>; if (!Reflect.hasOwnMetadata(metaKey, target)) { m = new Map<string, any>(); Reflect.defineMetadata(metaKey, m, target); } else { m = Reflect.getMetadata(metaKey, target); } if (!dataKey) { return m; } return m.get(dataKey); } /** * save meta data to class or property * @param decoratorNameKey the alias name for decorator * @param data the data you want to store * @param target target class * @param propertyName */ saveMetadata(decoratorNameKey: DecoratorKey, data, target, propertyName?) { if (propertyName) { const dataKey = DecoratorManager.getDecoratorMethod( decoratorNameKey, propertyName ); DecoratorManager.saveMetadata( this.injectMethodKeyPrefix, target, dataKey, data ); } else { const dataKey = DecoratorManager.getDecoratorClassKey(decoratorNameKey); DecoratorManager.saveMetadata( this.injectClassKeyPrefix, target, dataKey, data ); } } /** * attach data to class or property * @param decoratorNameKey * @param data * @param target * @param propertyName */ attachMetadata( decoratorNameKey: DecoratorKey, data, target, propertyName?: string, groupBy?: string ) { if (propertyName) { const dataKey = DecoratorManager.getDecoratorMethod( decoratorNameKey, propertyName ); DecoratorManager.attachMetadata( this.injectMethodKeyPrefix, target, dataKey, data, groupBy ); } else { const dataKey = DecoratorManager.getDecoratorClassKey(decoratorNameKey); DecoratorManager.attachMetadata( this.injectClassKeyPrefix, target, dataKey, data, groupBy ); } } /** * get single data from class or property * @param decoratorNameKey * @param target * @param propertyName */ getMetadata(decoratorNameKey: DecoratorKey, target, propertyName?) { if (propertyName) { const dataKey = DecoratorManager.getDecoratorMethod( decoratorNameKey, propertyName ); return DecoratorManager.getMetadata( this.injectMethodKeyPrefix, target, dataKey ); } else { const dataKey = `${DecoratorManager.getDecoratorClassKey( decoratorNameKey )}`; return DecoratorManager.getMetadata( this.injectClassKeyPrefix, target, dataKey ); } } /** * save property data to class * @param decoratorNameKey * @param data * @param target * @param propertyName */ savePropertyDataToClass( decoratorNameKey: DecoratorKey, data, target, propertyName ) { const dataKey = DecoratorManager.getDecoratorClsMethodKey( decoratorNameKey, propertyName ); DecoratorManager.saveMetadata( this.injectClassMethodKeyPrefix, target, dataKey, data ); } /** * attach property data to class * @param decoratorNameKey * @param data * @param target * @param propertyName * @param groupBy */ attachPropertyDataToClass( decoratorNameKey: DecoratorKey, data, target, propertyName, groupBy?: string ) { const dataKey = DecoratorManager.getDecoratorClsMethodKey( decoratorNameKey, propertyName ); DecoratorManager.attachMetadata( this.injectClassMethodKeyPrefix, target, dataKey, data, groupBy ); } /** * get property data from class * @param decoratorNameKey * @param target * @param propertyName */ getPropertyDataFromClass( decoratorNameKey: DecoratorKey, target, propertyName ) { const dataKey = DecoratorManager.getDecoratorClsMethodKey( decoratorNameKey, propertyName ); return DecoratorManager.getMetadata( this.injectClassMethodKeyPrefix, target, dataKey ); } /** * list property data from class * @param decoratorNameKey * @param target */ listPropertyDataFromClass(decoratorNameKey: DecoratorKey, target) { const originMap = DecoratorManager.getMetadata( this.injectClassMethodKeyPrefix, target ); const res = []; for (const [key, value] of originMap) { if ( key.indexOf( DecoratorManager.getDecoratorClsMethodPrefix(decoratorNameKey) ) !== -1 ) { res.push(value); } } return res; } } let manager = new DecoratorManager(); if (global['MIDWAY_GLOBAL_DECORATOR_MANAGER']) { console.warn( 'DecoratorManager not singleton and please check @midwayjs/decorator version by "npm ls @midwayjs/decorator"' ); manager = global['MIDWAY_GLOBAL_DECORATOR_MANAGER']; } else { global['MIDWAY_GLOBAL_DECORATOR_MANAGER'] = manager; } /** * save data to class * @param decoratorNameKey * @param data * @param target */ export function saveClassMetadata( decoratorNameKey: DecoratorKey, data, target ) { return manager.saveMetadata(decoratorNameKey, data, target); } /** * attach data to class * @param decoratorNameKey * @param data * @param target * @param groupBy */ export function attachClassMetadata( decoratorNameKey: DecoratorKey, data: any, target, groupBy?: string ) { return manager.attachMetadata( decoratorNameKey, data, target, undefined, groupBy ); } const testKeyMap = new Map<DecoratorKey, Error>(); /** * get data from class assign * @param decoratorNameKey * @param target */ export function getClassExtendedMetadata( decoratorNameKey: DecoratorKey, target ) { const extKey = DecoratorManager.getDecoratorClsExtendedKey(decoratorNameKey); let metadata = manager.getMetadata(extKey, target); if (metadata !== undefined) { return metadata; } const father = Reflect.getPrototypeOf(target); if (father.constructor !== Object) { metadata = mergeMeta( getClassExtendedMetadata(decoratorNameKey, father), manager.getMetadata(decoratorNameKey, target) ); } manager.saveMetadata(extKey, metadata || null, target); return metadata; } function mergeMeta(target: any, src: any) { if (!target) { target = src; src = null; } if (!target) { return null; } if (Array.isArray(target)) { return target.concat(src || []); } if (typeof target === 'object') { return Object.assign({}, target, src); } throw new Error('can not merge meta that type of ' + typeof target); } /** * get data from class * @param decoratorNameKey * @param target */ export function getClassMetadata(decoratorNameKey: DecoratorKey, target) { if (testKeyMap.size > 0 && testKeyMap.has(decoratorNameKey)) { throw testKeyMap.get(decoratorNameKey); } return manager.getMetadata(decoratorNameKey, target); } // TODO 因 https://github.com/microsoft/TypeScript/issues/38820 等 4.0 发布移除掉 export function throwErrorForTest(key: DecoratorKey, e: Error) { if (e) { testKeyMap.set(key, e); } else { testKeyMap.delete(key); } } /** * this method has deprecated and use savePropertyDataToClass instead * * @deprecated * @param decoratorNameKey * @param data * @param target * @param method */ export function saveMethodDataToClass( decoratorNameKey: DecoratorKey, data, target, method ) { return manager.savePropertyDataToClass( decoratorNameKey, data, target, method ); } /** * this method has deprecated and use attachPropertyDataToClass instead * * @deprecated * @param decoratorNameKey * @param data * @param target * @param method */ export function attachMethodDataToClass( decoratorNameKey: DecoratorKey, data, target, method ) { return manager.attachPropertyDataToClass( decoratorNameKey, data, target, method ); } /** * this method has deprecated and use getPropertyDataFromClass instead * * @deprecated * @param decoratorNameKey * @param target * @param method */ export function getMethodDataFromClass( decoratorNameKey: DecoratorKey, target, method ) { return manager.getPropertyDataFromClass(decoratorNameKey, target, method); } /** * list method data from class * @deprecated * @param decoratorNameKey * @param target */ export function listMethodDataFromClass( decoratorNameKey: DecoratorKey, target ) { return manager.listPropertyDataFromClass(decoratorNameKey, target); } /** * save method data * @deprecated * @param decoratorNameKey * @param data * @param target * @param method */ export function saveMethodMetadata( decoratorNameKey: DecoratorKey, data, target, method ) { return manager.saveMetadata(decoratorNameKey, data, target, method); } /** * attach method data * @deprecated * @param decoratorNameKey * @param data * @param target * @param method */ export function attachMethodMetadata( decoratorNameKey: DecoratorKey, data, target, method ) { return manager.attachMetadata(decoratorNameKey, data, target, method); } /** * get method data * @deprecated * @param decoratorNameKey * @param target * @param method */ export function getMethodMetadata( decoratorNameKey: DecoratorKey, target, method ) { return manager.getMetadata(decoratorNameKey, target, method); } /** * save property data to class * @param decoratorNameKey * @param data * @param target * @param propertyName */ export function savePropertyDataToClass( decoratorNameKey: DecoratorKey, data, target, propertyName ) { return manager.savePropertyDataToClass( decoratorNameKey, data, target, propertyName ); } /** * attach property data to class * @param decoratorNameKey * @param data * @param target * @param propertyName * @param groupBy */ export function attachPropertyDataToClass( decoratorNameKey: DecoratorKey, data, target, propertyName, groupBy?: string ) { return manager.attachPropertyDataToClass( decoratorNameKey, data, target, propertyName, groupBy ); } /** * get property data from class * @param decoratorNameKey * @param target * @param propertyName */ export function getPropertyDataFromClass( decoratorNameKey: DecoratorKey, target, propertyName ) { return manager.getPropertyDataFromClass( decoratorNameKey, target, propertyName ); } /** * list property data from class * @param decoratorNameKey * @param target */ export function listPropertyDataFromClass( decoratorNameKey: DecoratorKey, target ) { return manager.listPropertyDataFromClass(decoratorNameKey, target); } /** * save property data * @param decoratorNameKey * @param data * @param target * @param propertyName */ export function savePropertyMetadata( decoratorNameKey: DecoratorKey, data, target, propertyName ) { return manager.saveMetadata(decoratorNameKey, data, target, propertyName); } /** * attach property data * @param decoratorNameKey * @param data * @param target * @param propertyName */ export function attachPropertyMetadata( decoratorNameKey: DecoratorKey, data, target, propertyName ) { return manager.attachMetadata(decoratorNameKey, data, target, propertyName); } /** * get property data * @param decoratorNameKey * @param target * @param propertyName */ export function getPropertyMetadata( decoratorNameKey: DecoratorKey, target, propertyName ) { return manager.getMetadata(decoratorNameKey, target, propertyName); } /** * save preload module by target * @param target */ export function savePreloadModule(target) { return saveModule(PRELOAD_MODULE_KEY, target); } /** * list preload module */ export function listPreloadModule(): any[] { return listModule(PRELOAD_MODULE_KEY); } /** * save module to inner map * @param decoratorNameKey * @param target */ export function saveModule(decoratorNameKey: DecoratorKey, target) { return manager.saveModule(decoratorNameKey, target); } /** * list module from decorator key * @param decoratorNameKey */ export function listModule( decoratorNameKey: DecoratorKey, filter?: (module) => boolean ): any[] { const modules = manager.listModule(decoratorNameKey); if (filter) { return modules.filter(filter); } else { return modules; } } /** * reset module * @param decoratorNameKey */ export function resetModule(decoratorNameKey: DecoratorKey): void { return manager.resetModule(decoratorNameKey); } /** * clear all module */ export function clearAllModule() { return manager.clear(); } /** * get provider id from module * @param module */ export function getProviderId(module): string { const metaData = Reflect.getMetadata(TAGGED_CLS, module) as TagClsMetadata; let providerId; if (metaData) { providerId = metaData.id; } else { providerId = classNamed(module.name); } const meta = getClassMetadata(PRIVATE_META_DATA_KEY, module); if (providerId && meta) { providerId = generateProvideId(providerId, meta.namespace); } return providerId; } /** * 生成带 namespace 的 provideId * @param provideId provideId * @param namespace namespace */ export function generateProvideId(provideId: string, namespace?: string) { if (namespace && namespace !== MAIN_MODULE_KEY) { if (provideId.includes('@')) { return provideId.substr(1); } if (provideId.includes(':')) { return provideId; } if (namespace.includes('@')) { namespace = namespace.substr(1); } return namespace + ':' + provideId; } return provideId; } /** * get object definition metadata * @param module */ export function getObjectDefinition(module): ObjectDefinitionOptions { return Reflect.getMetadata(OBJ_DEF_CLS, module) as ObjectDefinitionOptions; } export interface TSDesignType { name: string; originDesign: any; isBaseType: boolean; } function transformTypeFromTSDesign(designFn): TSDesignType { if (isNullOrUndefined(designFn)) { return { name: 'undefined', isBaseType: true, originDesign: designFn }; } switch (designFn.name) { case 'String': return { name: 'string', isBaseType: true, originDesign: designFn }; case 'Number': return { name: 'number', isBaseType: true, originDesign: designFn }; case 'Boolean': return { name: 'boolean', isBaseType: true, originDesign: designFn }; case 'Symbol': return { name: 'symbol', isBaseType: true, originDesign: designFn }; case 'Object': return { name: 'object', isBaseType: true, originDesign: designFn }; case 'Function': return { name: 'function', isBaseType: true, originDesign: designFn }; default: return { name: designFn.name, isBaseType: false, originDesign: designFn, }; } } /** * get parameters type by reflect-metadata */ export function getMethodParamTypes(target, propertyKey: string | symbol) { return Reflect.getMetadata('design:paramtypes', target, propertyKey); } export function getPropertyType(target, propertyKey: string | symbol) { return transformTypeFromTSDesign( Reflect.getMetadata('design:type', target, propertyKey) ); } export function getMethodReturnTypes(target, propertyKey: string | symbol) { return Reflect.getMetadata('design:returntype', target, propertyKey); } function _tagParameterOrProperty( metadataKey: string, annotationTarget: any, propertyName: string, metadata: TagPropsMetadata, parameterIndex?: number ) { let paramsOrPropertiesMetadata: ReflectResult = {}; const isParameterDecorator = typeof parameterIndex === 'number'; const key: string = parameterIndex !== undefined && isParameterDecorator ? parameterIndex.toString() : propertyName; // if the decorator is used as a parameter decorator, the property name must be provided if (isParameterDecorator && propertyName !== undefined) { throw new Error(INVALID_DECORATOR_OPERATION); } // read metadata if available if (Reflect.hasOwnMetadata(metadataKey, annotationTarget)) { paramsOrPropertiesMetadata = Reflect.getMetadata( metadataKey, annotationTarget ); } // get metadata for the decorated parameter by its index let paramOrPropertyMetadata: TagPropsMetadata[] = paramsOrPropertiesMetadata[key]; if (!Array.isArray(paramOrPropertyMetadata)) { paramOrPropertyMetadata = []; } else { for (const m of paramOrPropertyMetadata) { if (m.key === metadata.key) { throw new Error(`${DUPLICATED_METADATA} ${m.key.toString()}`); } } } // set metadata paramOrPropertyMetadata.push(metadata); paramsOrPropertiesMetadata[key] = paramOrPropertyMetadata; Reflect.defineMetadata( metadataKey, paramsOrPropertiesMetadata, annotationTarget ); } export function attachConstructorDataOnClass(identifier, clz, type, index) { if (!identifier) { const args = getParamNames(clz); if (clz.length === args.length && index < clz.length) { identifier = args[index]; } } // save constructor index on class let constructorMetaValue = getClassMetadata(CLASS_KEY_CONSTRUCTOR, clz); if (!constructorMetaValue) { constructorMetaValue = {}; } constructorMetaValue[index] = { key: identifier, type, }; saveClassMetadata(CLASS_KEY_CONSTRUCTOR, constructorMetaValue, clz); } interface InjectOptions { identifier: ObjectIdentifier; target: any; targetKey: string; index?: number; args?: any; } /** * 构造器注入 * @param opts 参数 */ export function saveConstructorInject(opts: InjectOptions) { let identifier = opts.identifier; if (!identifier) { const args = getParamNames(opts.target); if (opts.target.length === args.length && opts.index < opts.target.length) { identifier = args[opts.index]; } } else if (identifier.includes('@') && !identifier.includes(':')) { const args = getParamNames(opts.target); if (opts.target.length === args.length && opts.index < opts.target.length) { identifier = `${identifier}:${args[opts.index]}`; } } const metadata = new Metadata(INJECT_TAG, identifier); metadata.args = opts.args; _tagParameterOrProperty( TAGGED, opts.target, opts.targetKey, metadata, opts.index ); } export function getConstructorInject(target: any): TagPropsMetadata[] { return Reflect.getMetadata(TAGGED, target); } /** * 属性注入 * @param opts 参数 */ export function savePropertyInject(opts: InjectOptions) { let identifier = opts.identifier; if (!identifier) { const type = getPropertyType(opts.target, opts.targetKey); if ( !type.isBaseType && isClass(type.originDesign) && isProvide(type.originDesign) ) { identifier = getProviderUUId(type.originDesign) ?? getProviderId(type.originDesign); } if (!identifier) { identifier = opts.targetKey; } } if (identifier.includes('@') && !identifier.includes(':')) { identifier = `${identifier}:${opts.targetKey}`; } const metadata = new Metadata(INJECT_TAG, identifier); metadata.args = opts.args; _tagParameterOrProperty( TAGGED_PROP, opts.target.constructor, opts.targetKey, metadata ); } export function getPropertyInject(target: any): TagPropsMetadata[] { return Reflect.getMetadata(TAGGED_PROP, target); } /** * class 元数据定义 * @param target class * @param props 属性 */ export function saveObjectDefProps(target: any, props = {}) { if (Reflect.hasMetadata(OBJ_DEF_CLS, target)) { const originProps = Reflect.getMetadata(OBJ_DEF_CLS, target); Reflect.defineMetadata( OBJ_DEF_CLS, Object.assign(originProps, props), target ); } else { Reflect.defineMetadata(OBJ_DEF_CLS, props, target); } return target; } export function getObjectDefProps(target: any): ObjectDefinitionOptions { return Reflect.getMetadata(OBJ_DEF_CLS, target); } /** * class provider id * @param identifier id * @param target class * @param override 是否覆盖 */ export function saveProviderId( identifier: ObjectIdentifier, target: any, override?: boolean ) { if (Reflect.hasOwnMetadata(TAGGED_CLS, target) && !override) { throw new Error(DUPLICATED_INJECTABLE_DECORATOR); } if (!identifier) { identifier = classNamed(target.name); } const uuid = generateRandomId(); Reflect.defineMetadata( TAGGED_CLS, { id: identifier, originName: target.name, uuid, }, target ); if (!Reflect.hasMetadata(OBJ_DEF_CLS, target)) { Reflect.defineMetadata(OBJ_DEF_CLS, {}, target); } return target; } /** * 是否使用了 saveProviderId * @param target class */ export function isProvide(target: any): boolean { return Reflect.hasOwnMetadata(TAGGED_CLS, target); } export function getProviderUUId(module): string { const metaData: any = Reflect.getMetadata( TAGGED_CLS, module ) as TagClsMetadata; if (metaData && metaData.uuid) { return metaData.uuid; } }
the_stack
import { hierarchy, stratify as d3Stratify, tree as d3Tree, } from 'd3-hierarchy'; import { zoom as d3Zoom, zoomIdentity } from 'd3-zoom'; import { select, Selection } from 'd3-selection'; import { Lineage, LineageItem } from 'interfaces'; import { ANIMATION_DURATION, CHART_DEFAULT_DIMENSIONS, CHART_DEFAULT_LABELS, LINEAGE_SCENE_MARGIN, NODE_STATUS_Y_OFFSET, NODE_LABEL_X_OFFSET, NODE_LABEL_Y_OFFSET, UPSTREAM_LABEL_OFFSET, } from './constants'; import { Coordinates, Dimensions, Labels, TreeLineageNode } from './types'; export interface LineageChartData { lineage: Lineage; dimensions: Dimensions; labels: Labels; } export interface LineageChart { (selection: any): any; } // We support up to 1000 direct nodes. const NODE_LIMIT = 1000; const ROOT_RADIUS = 12; const NODE_RADIUS = 8; const CHARACTER_OFFSET = 10; /** * Generates a fixed node ID from original and offset */ export const generateNodeId = (originalId: number, offset: number): number => originalId + NODE_LIMIT * offset; /** * Generate a cartesian path between two nodes. */ export const generatePath = (src: Coordinates, dst: Coordinates) => // Multiline return for ease of reading `M ${src.y} ${src.x} C ${(src.y + dst.y) / 2} ${src.x}, ${(src.y + dst.y) / 2} ${dst.x}, ${dst.y} ${dst.x}`; /** * Determines X position for a child node based on parents average. */ export const nodeXFromParents = (parents) => parents.reduce((sum: number, p) => sum + p.x, 0) / parents.length; /** * Access the open or collapsed children of a node. */ export const getChildren = ({ children, _children, }: LineageItem & { children?: any; _children?: any }) => children || _children || []; /** * Returns the label of a node based on its data and index. */ const getNodeLabel = (d, idx) => idx !== 0 && d.data.data.name ? d.data.data.schema + '.' + d.data.data.name : ''; /** * Returns the X-axis offset for the node labels. */ const getLabelXOffset = (d) => d.y < 0 ? NODE_LABEL_X_OFFSET : -NODE_LABEL_X_OFFSET; /** * Returns the Y-axis offset for the node labels. */ const getLabelYOffset = (d) => d.parent === null ? NODE_LABEL_Y_OFFSET : NODE_STATUS_Y_OFFSET; /** * Returns the node width based on label length. */ // eslint-disable-next-line id-blacklist const getNodeWidth = (n, depthMaxNodeWidthMapping: { number: number }) => { const { depth, y } = n; const widthSum: number = Object.entries(depthMaxNodeWidthMapping) .filter( (entries) => entries[0] !== '0' && parseInt(entries[0], 10) <= depth ) .reduce((sum, entries) => sum + entries[1], 0); if (y < 0) { return -widthSum; } return widthSum; }; /** * Returns the text-anchor for the node labels. */ const getTextAnchor = (d) => { const { parent, y } = d; if (parent === null) { return 'middle'; } if (y < 0) { return 'start'; } return 'end'; }; /** * Transposes the descendats of a tree across the Y axis. */ const transposeTreeY = (t) => t?.descendants().map((n) => { // Transpose Y only if not already done. if (n.y > 0) { n.y *= -1; } return n; }); /** * Add x/y origins for a node and generate an ID if one is not already set. */ export const prepareNodeForRender = (n, idx): TreeLineageNode => { n.x0 = n.x; n.y0 = n.y; if (!n.id) { // @ts-ignore n.id = generateNodeId(idx, 0); } return n; }; /** * Render the upstream/downstream labels on the lineage graph */ const renderLabels = ( svg: Selection<SVGSVGElement, any, null, any>, dimensions: Dimensions, labels: Labels ) => { svg .append('foreignObject') // @ts-ignore .attr('class', 'graph-direction-label upstream-label') .attr( 'transform', `translate(${ dimensions.width / 2 - UPSTREAM_LABEL_OFFSET - LINEAGE_SCENE_MARGIN.right }, ${LINEAGE_SCENE_MARGIN.top})` ) .html(labels.upstream); svg .append('foreignObject') // @ts-ignore .attr('class', 'graph-direction-label downstream-label') .attr( 'transform', `translate(${dimensions.width / 2 + LINEAGE_SCENE_MARGIN.left}, ${ LINEAGE_SCENE_MARGIN.top })` ) .html(labels.downstream); }; /** * The rendering approach we currently use is bidirectional: * - Two graphs are rendered across the Y axis from a single root. * - For downstream, this flows as is from the API response * - For upstream however, we need to inverse the parent/child * relationships. */ export const reflowLineage = (items: LineageItem[]): LineageItem[] => { const rootNode = items.find((n) => n.level === 0); const lineageByKey = items.reduce( (acc, i) => ({ ...acc, [i.key]: i, }), {} ); return items.reduce((acc, item) => { const parentLevel = item.parent && lineageByKey[item.parent] ? lineageByKey[item.parent].level : -1; const shouldSwapRelationship = parentLevel > 0 && parentLevel > item.level; let itemsToAdd: LineageItem[] = []; if (item.level === 0) { // Add the root node without further processing return [...acc, item]; } if (item.level === 1) { // Level 1 nodes have implicit root parent in all cases. itemsToAdd = [{ ...item, parent: rootNode?.key } as LineageItem]; } else if (!shouldSwapRelationship && parentLevel !== -1) { itemsToAdd = [item]; } if (shouldSwapRelationship) { // If we are here, we need to change the node direction. const childToSwitch = item.parent; if (childToSwitch) { itemsToAdd = [ ...itemsToAdd, { ...lineageByKey[childToSwitch], parent: item.key, }, ]; } } return [...acc, ...itemsToAdd]; }, [] as LineageItem[]); }; /** * The d3 Hierarchy module renders single parent relationships only. * we compact the lineage to merge duplicate nodes before rendering. */ export const compactLineage = ( items: LineageItem[] ): (LineageItem & { _parents: string[] })[] => { const rootNode = items.find((n) => n.level === 0); return Object.values( items.reduce((acc, n) => { if (n.level === 1 && !n.parent && rootNode) { n.parent = rootNode.key; } if (acc.hasOwnProperty(n.key)) { acc[n.key]._parents.push(n.parent); } else { acc[n.key] = n; acc[n.key]._parents = [n.parent]; } return acc; }, {}) ); }; /** * Allows us to unfurl the list of relationships post stratify-ing, so we can * still build the custom edges for multiple parents. The d3 hierarchy keeps * a reference to all nodes internally, and we need to not break this reference * - e.g. adding a new object overlapping with existing node is ok, replacing * an existing node would produce unexpected rendering behaviour */ export const decompactLineage = (nodes): TreeLineageNode[] => { const uniqueIds: number[] = []; const depthMaxNodeWidthMapping = nodes.reduce( (obj, item) => ({ ...obj, [item.depth]: 0, }), { 0: 0 } ); nodes.forEach((d, idx) => { const nodeLabel = getNodeLabel(d, idx); // Offset 10 pixels for each character const currentNodeWidth = nodeLabel.length * CHARACTER_OFFSET + NODE_RADIUS; if (currentNodeWidth > depthMaxNodeWidthMapping[d.depth]) { depthMaxNodeWidthMapping[d.depth] = currentNodeWidth; } }); return nodes.reduce((acc, n) => { n.y = getNodeWidth(n, depthMaxNodeWidthMapping); if (n.data.data._parents && n.data.data._parents.length > 1) { const parents = nodes.filter((p: TreeLineageNode) => n.data.data._parents.includes(p.data.data.key) ); // Determine layout position of the node based on number of parents. n.x = nodeXFromParents(parents); // Insert nodes while keeping reference to original one parents.forEach((p, idx: number) => { const id = generateNodeId(n.id, idx); // Attach to children if missing from response. if (!p._children) { if (!Array.isArray(p.children)) { // Init if no current children p.children = [n]; } else if (!p.children.map((c) => c.id).includes(n.id)) { // Add if not inbetween the children p.children.push(n); } } if (!uniqueIds.includes(id)) { if (idx === 0) { // Add the original n.parent = p; acc.push(n); } else { // Add a shadow node acc.push({ ...n, id, parent: p, }); } uniqueIds.push(id); } }); } else if (!uniqueIds.includes(n.id)) { acc.push(n); uniqueIds.push(n.id); } return acc; }, [] as TreeLineageNode[]); }; /** * Render all edges between connected nodes and seed animations. */ export const buildEdges = (g, targetNode, nodes) => { const treeSelection = g .selectAll('path.graph-link') .data(nodes, ({ id }) => id); // Enter any new links at the parent's previous position. const edgeEnter = treeSelection .enter() .insert('path', 'g') .attr('class', 'graph-link') .attr('d', (d) => { const coordinates = d.parent === null ? { x: targetNode.x0 || 0, y: targetNode.y0 || 0 } : { x: d.parent.x, y: d.parent.y }; return generatePath(coordinates, coordinates); }); // Render connection edgeEnter .merge(treeSelection) .transition() .duration(ANIMATION_DURATION) .attr('d', (d) => generatePath(d, d.parent)); // Render multiparent connections // Transition out on exit. treeSelection .exit() .transition() .duration(ANIMATION_DURATION) .attr('d', (d) => { const coordinates = { x: d.parent.x, y: d.parent.y }; return generatePath(coordinates, coordinates); }) .remove(); }; /** * Render all nodes and setup transitions as required */ export const buildNodes = (g, targetNode, nodes, onClick) => { const nodeSelection = g .selectAll('g.graph-node') // eslint-disable-next-line no-return-assign .data(nodes, ({ id }) => id); // Toggle children on click. // Enter any new modes at the parent's previous position. const nodeEnter = nodeSelection .enter() .append('g') .attr('class', 'graph-node') .attr('transform', (d) => d.parent === null ? `translate(${targetNode.y0},${targetNode.x0}` : `translate(${d.parent.y},${d.parent.x})` ) .on('click', (_, clicked) => onClick(clicked, nodes)); // Draw circle around the nodes nodeEnter.append('circle').attr('class', 'graph-node').attr('r', 0); // Position node label nodeEnter .append('text') .attr('x', getLabelXOffset) .attr('dy', getLabelYOffset) .attr('text-anchor', getTextAnchor) .text(getNodeLabel); // Position visual state for for fold/unfold nodeEnter .append('text') .attr('dy', NODE_STATUS_Y_OFFSET) .attr('class', 'plus') .attr('text-anchor', 'middle'); const nodeUpdate = nodeEnter.merge(nodeSelection); // Transition to the proper position for the node nodeUpdate .transition() .duration(ANIMATION_DURATION) .attr('transform', (d) => { // DO NOT UPDATE THE POSITION OF ROOT NODE if (d.parent === null) { d.y = targetNode.y0; d.x = targetNode.x0; } return 'translate(' + d.y + ',' + d.x + ')'; }); // Update the node attributes and style nodeUpdate .select('circle.graph-node') .attr('r', ({ depth }) => (depth === 0 ? ROOT_RADIUS : NODE_RADIUS)) .attr('cursor', 'pointer'); nodeUpdate.select('text.plus').text((n: TreeLineageNode) => { let nodeActionLabel = ''; if (n.children) { nodeActionLabel = '-'; } else if (n._children) { nodeActionLabel = '+'; } return nodeActionLabel; }); // Remove any exiting nodes const nodeExit = nodeSelection .exit() .transition() .duration(ANIMATION_DURATION) .attr('transform', (d) => `translate(${d.parent.y},${d.parent.x})`) .remove(); // On exit reduce the node circles size to 0 nodeExit.select('circle').attr('r', 1e-6); // On exit reduce the opacity of text labels nodeExit.select('text').style('fill-opacity', 1e-6); }; /** * Creates the d3 tree hierarchy from lineage items. */ const buildTree = (treemap, stratify, lineage: LineageItem[]) => Array.isArray(lineage) && lineage.length > 0 ? treemap(hierarchy(stratify(lineage), ({ children }) => children)) : null; /** * Create a toggler function with a render callback */ export const toggler = (renderer) => (target, nodes) => { let roots = nodes.filter((n) => n.parent === null); let toUpdate: TreeLineageNode[] = []; if (target.parent) { if (target.children || target._children) { toUpdate = [ target, ...nodes.filter((n) => { const targetChildren = getChildren(target); const children = getChildren(n); return ( target.id !== n.id && children && children.some((c) => targetChildren.find((tc) => c.data.id === tc.data.id) ) ); }), ]; } else { roots = []; } } else { toUpdate = roots; } toUpdate.map((n: TreeLineageNode) => { if (n.children) { n._children = n.children; n.children = undefined; } else { n.children = n._children; n._children = undefined; } return false; }); return roots.map((r: TreeLineageNode) => renderer(r)); }; /** * Confirm presence of nodes to render. */ export const hasLineageData = (lineage: Lineage) => lineage.downstream_entities.length > 0 || lineage.upstream_entities.length > 0; /** * Get the hierarchy without the two root nodes (upstream and downstream) */ export const removeRoots = (nodes) => nodes.filter(({ depth }) => depth !== 0); /** * Builds an svg out of an element */ export const buildSVG = (el: HTMLElement, dimensions: Dimensions) => { const svg = select(el) .append('svg') .classed('svg-content', true) .attr('width', dimensions.width) .attr('height', dimensions.height) .attr('viewBox', `0 0 ${dimensions.width} ${dimensions.height}`) .attr('preserveAspectRatio', 'xMinYMin meet'); const g = svg .append('g') .attr('transform', `translate(${dimensions.width / 2})`); return { svg, g }; }; const lc = (): LineageChart => { let svg: Selection<SVGSVGElement, any, null, any>; let g; let dimensions: Dimensions = CHART_DEFAULT_DIMENSIONS; let labels: Labels = CHART_DEFAULT_LABELS; let lineage: Lineage; function renderGraph() { const stratify = d3Stratify() .id(({ key }: TreeLineageNode) => key) .parentId(({ parent }) => parent); // Create the treemaps only once per graph and then internally maintain them. const treemap = d3Tree().size([ dimensions.height, (dimensions.width - (LINEAGE_SCENE_MARGIN.left + LINEAGE_SCENE_MARGIN.right)) / 2, ]); const upstreamTree = buildTree( treemap, stratify, lineage.upstream_entities ); const downstreamTree = buildTree( treemap, stratify, lineage.downstream_entities ); // jsdom does not support SVGAnimation, to test rendering // disable if running inside jest. if ( typeof navigator.userAgent !== 'string' || !navigator.userAgent.includes('jsdom') ) { const zoom = d3Zoom().on('zoom', (e) => { const { transform } = e; // By default make sure to place the graph in center if (!e.sourceEvent) { transform.x = dimensions.width / 2; } g.attr('transform', transform); // This is awkward, defined as css/js var. g.style('stroke-width', 3 / Math.sqrt(transform.k)); }); svg.call(zoom).call(zoom.transform, zoomIdentity); } function renderRelativeTo(targetPosition: TreeLineageNode) { // Transpose upstream over Y axis const upstreamNodes = transposeTreeY(upstreamTree) || []; const downstreamNodes = downstreamTree?.descendants() || []; const nodes = upstreamNodes .concat(downstreamNodes) .map(prepareNodeForRender); const nodesToRender = decompactLineage(nodes as TreeLineageNode[]); buildNodes(g, targetPosition, nodesToRender, toggler(renderRelativeTo)); buildEdges(g, targetPosition, removeRoots(nodesToRender)); } renderRelativeTo({ x0: dimensions.height / 2, y0: 0, } as TreeLineageNode); } const chart = (( _selection: Selection<HTMLElement, LineageChartData, any, any> ) => { _selection.each(function bc(_data: LineageChartData) { ({ dimensions, labels, lineage } = _data); if (!svg) { ({ svg, g } = buildSVG(this, dimensions)); } renderLabels(svg, dimensions, labels); if (hasLineageData(lineage)) { lineage = { upstream_entities: compactLineage( reflowLineage(lineage.upstream_entities) ), downstream_entities: compactLineage(lineage.downstream_entities), }; renderGraph(); } }); }) as LineageChart; return chart; }; export default lc;
the_stack
import { HexBuffer } from '../HexBuffer'; import { W3Buffer } from '../W3Buffer'; import { WarResult, JsonResult } from '../CommonInterfaces' interface Terrain { tileset: string; customTileset: boolean; tilePalette: string[]; cliffTilePalette: string[]; map: Map; // "Masks" groundHeight: number[], waterHeight: number[], boundaryFlag: boolean[], flags: number[], groundTexture: number[], groundVariation: number[], cliffVariation: number[], cliffTexture: number[], layerHeight: number[] } interface Map { width: number; height: number; offset: Offset; } interface Offset { x: number; y: number; } function splitLargeArrayIntoWidthArrays(array: any[], width: number) { const rows = []; for(let i = 0; i < array.length / width; i++) { rows.push(array.slice(i * width, (i+1) * width)); } return rows; } export abstract class TerrainTranslator { public static jsonToWar(terrainJson: Terrain): WarResult { const outBufferToWar = new HexBuffer(); /* * Header */ outBufferToWar.addChars('W3E!'); // file id outBufferToWar.addInt(11); // file version outBufferToWar.addChar(terrainJson.tileset); // base tileset outBufferToWar.addInt(+terrainJson.customTileset); // 1 = using custom tileset, 0 = not /* * Tiles */ outBufferToWar.addInt(terrainJson.tilePalette.length); terrainJson.tilePalette.forEach((tile) => { outBufferToWar.addChars(tile); }); /* * Cliffs */ outBufferToWar.addInt(terrainJson.cliffTilePalette.length); terrainJson.cliffTilePalette.forEach((cliffTile) => { outBufferToWar.addChars(cliffTile); }); /* * Map size data */ outBufferToWar.addInt(terrainJson.map.width + 1); outBufferToWar.addInt(terrainJson.map.height + 1); /* * Map offset */ outBufferToWar.addFloat(terrainJson.map.offset.x); outBufferToWar.addFloat(terrainJson.map.offset.y); /* * Tile points */ // Partition the terrainJson masks into "chunks" (i.e. rows) of (width+1) length, // reverse that list of rows (due to vertical flipping), and then write the rows out const rows = { groundHeight: splitLargeArrayIntoWidthArrays(terrainJson.groundHeight, terrainJson.map.width + 1), waterHeight: splitLargeArrayIntoWidthArrays(terrainJson.waterHeight, terrainJson.map.width + 1), boundaryFlag: splitLargeArrayIntoWidthArrays(terrainJson.boundaryFlag, terrainJson.map.width + 1), flags: splitLargeArrayIntoWidthArrays(terrainJson.flags, terrainJson.map.width + 1), groundTexture: splitLargeArrayIntoWidthArrays(terrainJson.groundTexture, terrainJson.map.width + 1), groundVariation: splitLargeArrayIntoWidthArrays(terrainJson.groundVariation, terrainJson.map.width + 1), cliffVariation: splitLargeArrayIntoWidthArrays(terrainJson.cliffVariation, terrainJson.map.width + 1), cliffTexture: splitLargeArrayIntoWidthArrays(terrainJson.cliffTexture, terrainJson.map.width + 1), layerHeight: splitLargeArrayIntoWidthArrays(terrainJson.layerHeight, terrainJson.map.width + 1) }; rows.groundHeight.reverse(); rows.waterHeight.reverse(); rows.boundaryFlag.reverse(); rows.flags.reverse(); rows.groundTexture.reverse(); rows.groundVariation.reverse(); rows.cliffVariation.reverse(); rows.cliffTexture.reverse(); rows.layerHeight.reverse(); for(let i = 0; i < rows.groundHeight.length; i++) { for(let j = 0; j < rows.groundHeight[i].length; j++) { // these bit operations are based off documentation from https://github.com/stijnherfst/HiveWE/wiki/war3map.w3e-Terrain const groundHeight = rows.groundHeight[i][j]; const waterHeight = rows.waterHeight[i][j]; const boundaryFlag = rows.boundaryFlag[i][j]; const flags = rows.flags[i][j]; const groundTexture = rows.groundTexture[i][j]; const groundVariation = rows.groundVariation[i][j]; const cliffVariation = rows.cliffVariation[i][j]; const cliffTexture = rows.cliffTexture[i][j]; const layerHeight = rows.layerHeight[i][j]; const hasBoundaryFlag = boundaryFlag ? 0x4000 : 0; outBufferToWar.addShort(groundHeight); outBufferToWar.addShort(waterHeight | hasBoundaryFlag); outBufferToWar.addByte(flags | groundTexture); outBufferToWar.addByte(groundVariation | cliffVariation); outBufferToWar.addByte(cliffTexture | layerHeight); } } return { errors: [], buffer: outBufferToWar.getBuffer() }; } public static warToJson(buffer: Buffer): JsonResult<Terrain> { // create buffer const result: Terrain = { tileset: '', customTileset: false, tilePalette: [], cliffTilePalette: [], map: { width: 1, height: 1, offset: { x: 0, y: 0 } }, groundHeight: [], waterHeight: [], boundaryFlag: [], flags: [], groundTexture: [], groundVariation: [], cliffVariation: [], cliffTexture: [], layerHeight: [] }; const outBufferToJSON = new W3Buffer(buffer); /** * Header */ const w3eHeader = outBufferToJSON.readChars(4); // W3E! const version = outBufferToJSON.readInt(); // 0B 00 00 00 const tileset = outBufferToJSON.readChars(1); // tileset const customTileset = (outBufferToJSON.readInt() === 1); result.tileset = tileset; result.customTileset = customTileset; /** * Tiles */ const numTilePalettes = outBufferToJSON.readInt(); const tilePalettes = []; for (let i = 0; i < numTilePalettes; i++) { tilePalettes.push(outBufferToJSON.readChars(4)); } result.tilePalette = tilePalettes; /** * Cliffs */ const numCliffTilePalettes = outBufferToJSON.readInt(); const cliffPalettes = []; for (let i = 0; i < numCliffTilePalettes; i++) { const cliffPalette = outBufferToJSON.readChars(4); cliffPalettes.push(cliffPalette); } result.cliffTilePalette = cliffPalettes; /** * map dimensions */ const width = outBufferToJSON.readInt() - 1; const height = outBufferToJSON.readInt() - 1; result.map = { width, height, offset: { x: 0, y: 0 } }; const offsetX = outBufferToJSON.readFloat(); const offsetY = outBufferToJSON.readFloat(); result.map.offset = { x: offsetX, y: offsetY }; /** * map tiles */ const arr_groundHeight = []; const arr_waterHeight = []; const arr_boundaryFlag = []; const arr_flags = []; const arr_groundTexture = []; const arr_groundVariation = []; const arr_cliffVariation = []; const arr_cliffTexture = []; const arr_layerHeight = []; while(!outBufferToJSON.isExhausted()) { const groundHeight = outBufferToJSON.readShort(); const waterHeightAndBoundary = outBufferToJSON.readShort(); const flagsAndGroundTexture = outBufferToJSON.readByte(); const groundAndCliffVariation = outBufferToJSON.readByte(); const cliffTextureAndLayerHeight = outBufferToJSON.readByte(); // parse out different bits (based on documentation from https://github.com/stijnherfst/HiveWE/wiki/war3map.w3e-Terrain) const waterHeight = waterHeightAndBoundary & 32767; const boundaryFlag = (waterHeightAndBoundary & 0x4000) === 0x4000; const flags = flagsAndGroundTexture & 240; const groundTexture = flagsAndGroundTexture & 15; const groundVariation = groundAndCliffVariation & 248; const cliffVariation = groundAndCliffVariation & 7; const cliffTexture = cliffTextureAndLayerHeight & 240; const layerHeight = cliffTextureAndLayerHeight & 15; arr_groundHeight.push(groundHeight); arr_waterHeight.push(waterHeight); arr_boundaryFlag.push(boundaryFlag); arr_flags.push(flags); arr_groundTexture.push(groundTexture); arr_groundVariation.push(groundVariation); arr_cliffVariation.push(cliffVariation); arr_cliffTexture.push(cliffTexture); arr_layerHeight.push(layerHeight); } function convertArrayOfArraysIntoFlatArray(arr) { return arr.reduce((a, b) => { return [...a, ...b] }); } // The map was read in "backwards" because wc3 maps have origin (0,0) // at the bottom left instead of top left as we desire. Flip the rows // vertically to fix this. result.groundHeight = convertArrayOfArraysIntoFlatArray(splitLargeArrayIntoWidthArrays(arr_groundHeight, result.map.width + 1).reverse()) result.waterHeight = convertArrayOfArraysIntoFlatArray(splitLargeArrayIntoWidthArrays(arr_waterHeight, result.map.width + 1).reverse()) result.boundaryFlag = convertArrayOfArraysIntoFlatArray(splitLargeArrayIntoWidthArrays(arr_boundaryFlag, result.map.width + 1).reverse()) result.flags = convertArrayOfArraysIntoFlatArray(splitLargeArrayIntoWidthArrays(arr_flags, result.map.width + 1).reverse()) result.groundTexture = convertArrayOfArraysIntoFlatArray(splitLargeArrayIntoWidthArrays(arr_groundTexture, result.map.width + 1).reverse()) result.groundVariation = convertArrayOfArraysIntoFlatArray(splitLargeArrayIntoWidthArrays(arr_groundVariation, result.map.width + 1).reverse()) result.cliffVariation = convertArrayOfArraysIntoFlatArray(splitLargeArrayIntoWidthArrays(arr_cliffVariation, result.map.width + 1).reverse()) result.cliffTexture = convertArrayOfArraysIntoFlatArray(splitLargeArrayIntoWidthArrays(arr_cliffTexture, result.map.width + 1).reverse()) result.layerHeight = convertArrayOfArraysIntoFlatArray(splitLargeArrayIntoWidthArrays(arr_layerHeight, result.map.width + 1).reverse()) return { errors: [], json: result }; } }
the_stack
import { deepStrictEqual, ok, strictEqual } from "assert"; import { getAnyExtensionFromPath, getBaseFileName, getDirectoryPath, getPathComponents, getRootLength, isUrl, joinPaths, normalizeSlashes, reducePathComponents, resolvePath, } from "../core/path-utils.js"; describe("compiler: path utils", () => { it("normalizeSlashes", () => { strictEqual(normalizeSlashes("a"), "a"); strictEqual(normalizeSlashes("a/b"), "a/b"); strictEqual(normalizeSlashes("a\\b"), "a/b"); strictEqual(normalizeSlashes("\\\\server\\path"), "//server/path"); }); it("getRootLength", () => { strictEqual(getRootLength("a"), 0); strictEqual(getRootLength("/"), 1); strictEqual(getRootLength("/path"), 1); strictEqual(getRootLength("c:"), 2); strictEqual(getRootLength("c:d"), 0); strictEqual(getRootLength("c:/"), 3); strictEqual(getRootLength("c:\\"), 3); strictEqual(getRootLength("//server"), 8); strictEqual(getRootLength("//server/share"), 9); strictEqual(getRootLength("\\\\server"), 8); strictEqual(getRootLength("\\\\server\\share"), 9); strictEqual(getRootLength("file:///"), 8); strictEqual(getRootLength("file:///path"), 8); strictEqual(getRootLength("file:///c:"), 10); strictEqual(getRootLength("file:///c:d"), 8); strictEqual(getRootLength("file:///c:/path"), 11); strictEqual(getRootLength("file:///c%3a"), 12); strictEqual(getRootLength("file:///c%3ad"), 8); strictEqual(getRootLength("file:///c%3a/path"), 13); strictEqual(getRootLength("file:///c%3A"), 12); strictEqual(getRootLength("file:///c%3Ad"), 8); strictEqual(getRootLength("file:///c%3A/path"), 13); strictEqual(getRootLength("file://localhost"), 16); strictEqual(getRootLength("file://localhost/"), 17); strictEqual(getRootLength("file://localhost/path"), 17); strictEqual(getRootLength("file://localhost/c:"), 19); strictEqual(getRootLength("file://localhost/c:d"), 17); strictEqual(getRootLength("file://localhost/c:/path"), 20); strictEqual(getRootLength("file://localhost/c%3a"), 21); strictEqual(getRootLength("file://localhost/c%3ad"), 17); strictEqual(getRootLength("file://localhost/c%3a/path"), 22); strictEqual(getRootLength("file://localhost/c%3A"), 21); strictEqual(getRootLength("file://localhost/c%3Ad"), 17); strictEqual(getRootLength("file://localhost/c%3A/path"), 22); strictEqual(getRootLength("file://server"), 13); strictEqual(getRootLength("file://server/"), 14); strictEqual(getRootLength("file://server/path"), 14); strictEqual(getRootLength("file://server/c:"), 14); strictEqual(getRootLength("file://server/c:d"), 14); strictEqual(getRootLength("file://server/c:/d"), 14); strictEqual(getRootLength("file://server/c%3a"), 14); strictEqual(getRootLength("file://server/c%3ad"), 14); strictEqual(getRootLength("file://server/c%3a/d"), 14); strictEqual(getRootLength("file://server/c%3A"), 14); strictEqual(getRootLength("file://server/c%3Ad"), 14); strictEqual(getRootLength("file://server/c%3A/d"), 14); strictEqual(getRootLength("http://server"), 13); strictEqual(getRootLength("http://server/path"), 14); }); it("isUrl", () => { // NOT url ok(!isUrl("a")); ok(!isUrl("/")); ok(!isUrl("c:")); ok(!isUrl("c:d")); ok(!isUrl("c:/")); ok(!isUrl("c:\\")); ok(!isUrl("//server")); ok(!isUrl("//server/share")); ok(!isUrl("\\\\server")); ok(!isUrl("\\\\server\\share")); // Is Url ok(isUrl("file:///path")); ok(isUrl("file:///c:")); ok(isUrl("file:///c:d")); ok(isUrl("file:///c:/path")); ok(isUrl("file://server")); ok(isUrl("file://server/path")); ok(isUrl("http://server")); ok(isUrl("http://server/path")); }); it("getDirectoryPath", () => { strictEqual(getDirectoryPath(""), ""); strictEqual(getDirectoryPath("a"), ""); strictEqual(getDirectoryPath("a/b"), "a"); strictEqual(getDirectoryPath("/"), "/"); strictEqual(getDirectoryPath("/a"), "/"); strictEqual(getDirectoryPath("/a/"), "/"); strictEqual(getDirectoryPath("/a/b"), "/a"); strictEqual(getDirectoryPath("/a/b/"), "/a"); strictEqual(getDirectoryPath("c:"), "c:"); strictEqual(getDirectoryPath("c:d"), ""); strictEqual(getDirectoryPath("c:/"), "c:/"); strictEqual(getDirectoryPath("c:/path"), "c:/"); strictEqual(getDirectoryPath("c:/path/"), "c:/"); strictEqual(getDirectoryPath("//server"), "//server"); strictEqual(getDirectoryPath("//server/"), "//server/"); strictEqual(getDirectoryPath("//server/share"), "//server/"); strictEqual(getDirectoryPath("//server/share/"), "//server/"); strictEqual(getDirectoryPath("\\\\server"), "//server"); strictEqual(getDirectoryPath("\\\\server\\"), "//server/"); strictEqual(getDirectoryPath("\\\\server\\share"), "//server/"); strictEqual(getDirectoryPath("\\\\server\\share\\"), "//server/"); strictEqual(getDirectoryPath("file:///"), "file:///"); strictEqual(getDirectoryPath("file:///path"), "file:///"); strictEqual(getDirectoryPath("file:///path/"), "file:///"); strictEqual(getDirectoryPath("file:///c:"), "file:///c:"); strictEqual(getDirectoryPath("file:///c:d"), "file:///"); strictEqual(getDirectoryPath("file:///c:/"), "file:///c:/"); strictEqual(getDirectoryPath("file:///c:/path"), "file:///c:/"); strictEqual(getDirectoryPath("file:///c:/path/"), "file:///c:/"); strictEqual(getDirectoryPath("file://server"), "file://server"); strictEqual(getDirectoryPath("file://server/"), "file://server/"); strictEqual(getDirectoryPath("file://server/path"), "file://server/"); strictEqual(getDirectoryPath("file://server/path/"), "file://server/"); strictEqual(getDirectoryPath("http://server"), "http://server"); strictEqual(getDirectoryPath("http://server/"), "http://server/"); strictEqual(getDirectoryPath("http://server/path"), "http://server/"); strictEqual(getDirectoryPath("http://server/path/"), "http://server/"); }); it("getBaseFileName", () => { strictEqual(getBaseFileName(""), ""); strictEqual(getBaseFileName("a"), "a"); strictEqual(getBaseFileName("a/"), "a"); strictEqual(getBaseFileName("/"), ""); strictEqual(getBaseFileName("/a"), "a"); strictEqual(getBaseFileName("/a/"), "a"); strictEqual(getBaseFileName("/a/b"), "b"); strictEqual(getBaseFileName("c:"), ""); strictEqual(getBaseFileName("c:d"), "c:d"); strictEqual(getBaseFileName("c:/"), ""); strictEqual(getBaseFileName("c:\\"), ""); strictEqual(getBaseFileName("c:/path"), "path"); strictEqual(getBaseFileName("c:/path/"), "path"); strictEqual(getBaseFileName("//server"), ""); strictEqual(getBaseFileName("//server/"), ""); strictEqual(getBaseFileName("//server/share"), "share"); strictEqual(getBaseFileName("//server/share/"), "share"); strictEqual(getBaseFileName("file:///"), ""); strictEqual(getBaseFileName("file:///path"), "path"); strictEqual(getBaseFileName("file:///path/"), "path"); strictEqual(getBaseFileName("file:///c:"), ""); strictEqual(getBaseFileName("file:///c:/"), ""); strictEqual(getBaseFileName("file:///c:d"), "c:d"); strictEqual(getBaseFileName("file:///c:/d"), "d"); strictEqual(getBaseFileName("file:///c:/d/"), "d"); strictEqual(getBaseFileName("http://server"), ""); strictEqual(getBaseFileName("http://server/"), ""); strictEqual(getBaseFileName("http://server/a"), "a"); strictEqual(getBaseFileName("http://server/a/"), "a"); strictEqual(getBaseFileName("/path/a.ext", ".ext", /*ignoreCase*/ false), "a"); strictEqual(getBaseFileName("/path/a.ext", ".EXT", /*ignoreCase*/ true), "a"); strictEqual(getBaseFileName("/path/a.ext", "ext", /*ignoreCase*/ false), "a"); strictEqual(getBaseFileName("/path/a.b", ".ext", /*ignoreCase*/ false), "a.b"); strictEqual(getBaseFileName("/path/a.b", [".b", ".c"], /*ignoreCase*/ false), "a"); strictEqual(getBaseFileName("/path/a.c", [".b", ".c"], /*ignoreCase*/ false), "a"); strictEqual(getBaseFileName("/path/a.d", [".b", ".c"], /*ignoreCase*/ false), "a.d"); }); it("getAnyExtensionFromPath", () => { strictEqual(getAnyExtensionFromPath(""), ""); strictEqual(getAnyExtensionFromPath(".ext"), ".ext"); strictEqual(getAnyExtensionFromPath("a.ext"), ".ext"); strictEqual(getAnyExtensionFromPath("/a.ext"), ".ext"); strictEqual(getAnyExtensionFromPath("a.ext/"), ".ext"); strictEqual(getAnyExtensionFromPath("a.ext", ".ext", /*ignoreCase*/ false), ".ext"); strictEqual(getAnyExtensionFromPath("a.ext", ".EXT", /*ignoreCase*/ true), ".ext"); strictEqual(getAnyExtensionFromPath("a.ext", "ext", /*ignoreCase*/ false), ".ext"); strictEqual(getAnyExtensionFromPath("a.b", ".ext", /*ignoreCase*/ false), ""); strictEqual(getAnyExtensionFromPath("a.b", [".b", ".c"], /*ignoreCase*/ false), ".b"); strictEqual(getAnyExtensionFromPath("a.c", [".b", ".c"], /*ignoreCase*/ false), ".c"); strictEqual(getAnyExtensionFromPath("a.d", [".b", ".c"], /*ignoreCase*/ false), ""); }); it("getPathComponents", () => { deepStrictEqual(getPathComponents(""), [""]); deepStrictEqual(getPathComponents("a"), ["", "a"]); deepStrictEqual(getPathComponents("./a"), ["", ".", "a"]); deepStrictEqual(getPathComponents("/"), ["/"]); deepStrictEqual(getPathComponents("/a"), ["/", "a"]); deepStrictEqual(getPathComponents("/a/"), ["/", "a"]); deepStrictEqual(getPathComponents("c:"), ["c:"]); deepStrictEqual(getPathComponents("c:d"), ["", "c:d"]); deepStrictEqual(getPathComponents("c:/"), ["c:/"]); deepStrictEqual(getPathComponents("c:/path"), ["c:/", "path"]); deepStrictEqual(getPathComponents("//server"), ["//server"]); deepStrictEqual(getPathComponents("//server/"), ["//server/"]); deepStrictEqual(getPathComponents("//server/share"), ["//server/", "share"]); deepStrictEqual(getPathComponents("file:///"), ["file:///"]); deepStrictEqual(getPathComponents("file:///path"), ["file:///", "path"]); deepStrictEqual(getPathComponents("file:///c:"), ["file:///c:"]); deepStrictEqual(getPathComponents("file:///c:d"), ["file:///", "c:d"]); deepStrictEqual(getPathComponents("file:///c:/"), ["file:///c:/"]); deepStrictEqual(getPathComponents("file:///c:/path"), ["file:///c:/", "path"]); deepStrictEqual(getPathComponents("file://server"), ["file://server"]); deepStrictEqual(getPathComponents("file://server/"), ["file://server/"]); deepStrictEqual(getPathComponents("file://server/path"), ["file://server/", "path"]); deepStrictEqual(getPathComponents("http://server"), ["http://server"]); deepStrictEqual(getPathComponents("http://server/"), ["http://server/"]); deepStrictEqual(getPathComponents("http://server/path"), ["http://server/", "path"]); }); it("reducePathComponents", () => { deepStrictEqual(reducePathComponents([]), []); deepStrictEqual(reducePathComponents([""]), [""]); deepStrictEqual(reducePathComponents(["", "."]), [""]); deepStrictEqual(reducePathComponents(["", ".", "a"]), ["", "a"]); deepStrictEqual(reducePathComponents(["", "a", "."]), ["", "a"]); deepStrictEqual(reducePathComponents(["", ".."]), ["", ".."]); deepStrictEqual(reducePathComponents(["", "..", ".."]), ["", "..", ".."]); deepStrictEqual(reducePathComponents(["", "..", ".", ".."]), ["", "..", ".."]); deepStrictEqual(reducePathComponents(["", "a", ".."]), [""]); deepStrictEqual(reducePathComponents(["", "..", "a"]), ["", "..", "a"]); deepStrictEqual(reducePathComponents(["/"]), ["/"]); deepStrictEqual(reducePathComponents(["/", "."]), ["/"]); deepStrictEqual(reducePathComponents(["/", ".."]), ["/"]); deepStrictEqual(reducePathComponents(["/", "a", ".."]), ["/"]); }); it("joinPaths", () => { strictEqual(joinPaths("/", "/node_modules/@types"), "/node_modules/@types"); strictEqual(joinPaths("/a/..", ""), "/a/.."); strictEqual(joinPaths("/a/..", "b"), "/a/../b"); strictEqual(joinPaths("/a/..", "b/"), "/a/../b/"); strictEqual(joinPaths("/a/..", "/"), "/"); strictEqual(joinPaths("/a/..", "/b"), "/b"); }); it("resolvePath", () => { strictEqual(resolvePath(""), ""); strictEqual(resolvePath("."), ""); strictEqual(resolvePath("./"), ""); strictEqual(resolvePath(".."), ".."); strictEqual(resolvePath("../"), "../"); strictEqual(resolvePath("/"), "/"); strictEqual(resolvePath("/."), "/"); strictEqual(resolvePath("/./"), "/"); strictEqual(resolvePath("/../"), "/"); strictEqual(resolvePath("/a"), "/a"); strictEqual(resolvePath("/a/"), "/a/"); strictEqual(resolvePath("/a/."), "/a"); strictEqual(resolvePath("/a/./"), "/a/"); strictEqual(resolvePath("/a/./b"), "/a/b"); strictEqual(resolvePath("/a/./b/"), "/a/b/"); strictEqual(resolvePath("/a/.."), "/"); strictEqual(resolvePath("/a/../"), "/"); strictEqual(resolvePath("/a/../b"), "/b"); strictEqual(resolvePath("/a/../b/"), "/b/"); strictEqual(resolvePath("/a/..", "b"), "/b"); strictEqual(resolvePath("/a/..", "/"), "/"); strictEqual(resolvePath("/a/..", "b/"), "/b/"); strictEqual(resolvePath("/a/..", "/b"), "/b"); strictEqual(resolvePath("/a/.", "b"), "/a/b"); strictEqual(resolvePath("/a/.", "."), "/a"); strictEqual(resolvePath("a", "b", "c"), "a/b/c"); strictEqual(resolvePath("a", "b", "/c"), "/c"); strictEqual(resolvePath("a", "b", "../c"), "a/c"); }); });
the_stack
import * as React from 'react'; import { KEY_CODES } from '../../helpers/constants'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Wizard/wizard'; import { Modal, ModalVariant } from '../Modal'; import { WizardFooterInternal } from './WizardFooterInternal'; import { WizardToggle } from './WizardToggle'; import { WizardNav } from './WizardNav'; import { WizardNavItem, WizardNavItemProps } from './WizardNavItem'; import { WizardContextProvider } from './WizardContext'; import { PickOptional } from '../../helpers/typeUtils'; import { WizardHeader } from './WizardHeader'; export interface WizardStep { /** Optional identifier */ id?: string | number; /** The name of the step */ name: React.ReactNode; /** The component to render in the main body */ component?: any; /** Setting to true hides the side nav and footer */ isFinishedStep?: boolean; /** Enables or disables the step in the navigation. Enabled by default. */ canJumpTo?: boolean; /** Sub steps */ steps?: WizardStep[]; /** Props to pass to the WizardNavItem */ stepNavItemProps?: React.HTMLProps<HTMLButtonElement | HTMLAnchorElement> | WizardNavItemProps; /** (Unused if footer is controlled) Can change the Next button text. If nextButtonText is also set for the Wizard, this step specific one overrides it. */ nextButtonText?: React.ReactNode; /** (Unused if footer is controlled) The condition needed to enable the Next button */ enableNext?: boolean; /** (Unused if footer is controlled) True to hide the Cancel button */ hideCancelButton?: boolean; /** (Unused if footer is controlled) True to hide the Back button */ hideBackButton?: boolean; } export type WizardStepFunctionType = ( newStep: { id?: string | number; name: React.ReactNode }, prevStep: { prevId?: string | number; prevName: React.ReactNode } ) => void; export interface WizardProps extends React.HTMLProps<HTMLDivElement> { /** Custom width of the wizard */ width?: number | string; /** Custom height of the wizard */ height?: number | string; /** The wizard title to display if header is desired */ title?: string; /** An optional id for the title */ titleId?: string; /** An optional id for the description */ descriptionId?: string; /** The wizard description */ description?: React.ReactNode; /** Flag indicating whether the close button should be in the header */ hideClose?: boolean; /** Callback function to close the wizard */ onClose?: () => void; /** Callback function when a step in the nav is clicked */ onGoToStep?: WizardStepFunctionType; /** Additional classes spread to the Wizard */ className?: string; /** The wizard steps configuration object */ steps: WizardStep[]; /** The current step the wizard is on (1 or higher) */ startAtStep?: number; /** Aria-label for the Nav */ navAriaLabel?: string; /** Sets aria-labelledby on nav element */ navAriaLabelledBy?: string; /** Aria-label for the main element */ mainAriaLabel?: string; /** Sets aria-labelledby on the main element */ mainAriaLabelledBy?: string; /** Can remove the default padding around the main body content by setting this to true */ hasNoBodyPadding?: boolean; /** (Use to control the footer) Passing in a footer component lets you control the buttons yourself */ footer?: React.ReactNode; /** (Unused if footer is controlled) Callback function to save at the end of the wizard, if not specified uses onClose */ onSave?: () => void; /** (Unused if footer is controlled) Callback function after Next button is clicked */ onNext?: WizardStepFunctionType; /** (Unused if footer is controlled) Callback function after Back button is clicked */ onBack?: WizardStepFunctionType; /** (Unused if footer is controlled) The Next button text */ nextButtonText?: React.ReactNode; /** (Unused if footer is controlled) The Back button text */ backButtonText?: React.ReactNode; /** (Unused if footer is controlled) The Cancel button text */ cancelButtonText?: React.ReactNode; /** (Unused if footer is controlled) aria-label for the close button */ closeButtonAriaLabel?: string; /** The parent container to append the modal to. Defaults to document.body */ appendTo?: HTMLElement | (() => HTMLElement); /** Flag indicating Wizard modal is open. Wizard will be placed into a modal if this prop is provided */ isOpen?: boolean; /** Flag indicating nav items with sub steps are expandable */ isNavExpandable?: boolean; } interface WizardState { currentStep: number; isNavOpen: boolean; } export class Wizard extends React.Component<WizardProps, WizardState> { static displayName = 'Wizard'; private static currentId = 0; static defaultProps: PickOptional<WizardProps> = { title: null, description: '', className: '', startAtStep: 1, nextButtonText: 'Next', backButtonText: 'Back', cancelButtonText: 'Cancel', hideClose: false, closeButtonAriaLabel: 'Close', navAriaLabel: null, navAriaLabelledBy: null, mainAriaLabel: null, mainAriaLabelledBy: null, hasNoBodyPadding: false, onBack: null as WizardStepFunctionType, onNext: null as WizardStepFunctionType, onGoToStep: null as WizardStepFunctionType, width: null as string, height: null as string, footer: null as React.ReactNode, onClose: () => undefined as any, appendTo: null as HTMLElement, isOpen: undefined, isNavExpandable: false }; private titleId: string; private descriptionId: string; constructor(props: WizardProps) { super(props); const newId = Wizard.currentId++; this.titleId = props.titleId || `pf-wizard-title-${newId}`; this.descriptionId = props.descriptionId || `pf-wizard-description-${newId}`; this.state = { currentStep: this.props.startAtStep && Number.isInteger(this.props.startAtStep) ? this.props.startAtStep : 1, isNavOpen: false }; } private handleKeyClicks = (event: KeyboardEvent): void => { if (event.keyCode === KEY_CODES.ESCAPE_KEY) { if (this.state.isNavOpen) { this.setState({ isNavOpen: !this.state.isNavOpen }); } else if (this.props.isOpen) { this.props.onClose(); } } }; private onNext = (): void => { const { onNext, onClose, onSave } = this.props; const { currentStep } = this.state; const flattenedSteps = this.getFlattenedSteps(); const maxSteps = flattenedSteps.length; if (currentStep >= maxSteps) { // Hit the save button at the end of the wizard if (onSave) { return onSave(); } return onClose(); } else { const newStep = currentStep + 1; this.setState({ currentStep: newStep }); const { id: prevId, name: prevName } = flattenedSteps[currentStep - 1]; const { id, name } = flattenedSteps[newStep - 1]; return onNext && onNext({ id, name }, { prevId, prevName }); } }; private onBack = (): void => { const { onBack } = this.props; const { currentStep } = this.state; const flattenedSteps = this.getFlattenedSteps(); if (flattenedSteps.length < currentStep) { // Previous step was removed, just update the currentStep state const adjustedStep = flattenedSteps.length; this.setState({ currentStep: adjustedStep }); } else { const newStep = currentStep - 1 <= 0 ? 0 : currentStep - 1; this.setState({ currentStep: newStep }); const { id: prevId, name: prevName } = flattenedSteps[newStep]; const { id, name } = flattenedSteps[newStep - 1]; return onBack && onBack({ id, name }, { prevId, prevName }); } }; private goToStep = (step: number): void => { const { onGoToStep } = this.props; const { currentStep } = this.state; const flattenedSteps = this.getFlattenedSteps(); const maxSteps = flattenedSteps.length; if (step < 1) { step = 1; } else if (step > maxSteps) { step = maxSteps; } this.setState({ currentStep: step, isNavOpen: false }); const { id: prevId, name: prevName } = flattenedSteps[currentStep - 1]; const { id, name } = flattenedSteps[step - 1]; return onGoToStep && onGoToStep({ id, name }, { prevId, prevName }); }; private goToStepById = (stepId: number | string): void => { const flattenedSteps = this.getFlattenedSteps(); let step; for (let i = 0; i < flattenedSteps.length; i++) { if (flattenedSteps[i].id === stepId) { step = i + 1; break; } } if (step) { this.setState({ currentStep: step }); } }; private goToStepByName = (stepName: string): void => { const flattenedSteps = this.getFlattenedSteps(); let step; for (let i = 0; i < flattenedSteps.length; i++) { if (flattenedSteps[i].name === stepName) { step = i + 1; break; } } if (step) { this.setState({ currentStep: step }); } }; private getFlattenedSteps = (): WizardStep[] => { const { steps } = this.props; const flattenedSteps: WizardStep[] = []; for (const step of steps) { if (step.steps) { for (const childStep of step.steps) { flattenedSteps.push(childStep); } } else { flattenedSteps.push(step); } } return flattenedSteps; }; private getFlattenedStepsIndex = (flattenedSteps: WizardStep[], stepName: React.ReactNode): number => { for (let i = 0; i < flattenedSteps.length; i++) { if (flattenedSteps[i].name === stepName) { return i + 1; } } return 0; }; private initSteps = (steps: WizardStep[]): WizardStep[] => { // Set default Step values for (let i = 0; i < steps.length; i++) { if (steps[i].steps) { for (let j = 0; j < steps[i].steps.length; j++) { steps[i].steps[j] = Object.assign({ canJumpTo: true }, steps[i].steps[j]); } } steps[i] = Object.assign({ canJumpTo: true }, steps[i]); } return steps; }; getElement = (appendTo: HTMLElement | (() => HTMLElement)) => { if (typeof appendTo === 'function') { return appendTo(); } return appendTo || document.body; }; componentDidMount() { const target = typeof document !== 'undefined' ? document.body : null; if (target) { target.addEventListener('keydown', this.handleKeyClicks, false); } } componentWillUnmount() { const target = (typeof document !== 'undefined' && document.body) || null; if (target) { target.removeEventListener('keydown', this.handleKeyClicks, false); } } render() { const { /* eslint-disable @typescript-eslint/no-unused-vars */ width, height, title, description, onClose, onSave, onBack, onNext, onGoToStep, className, steps, startAtStep, nextButtonText = 'Next', backButtonText = 'Back', cancelButtonText = 'Cancel', hideClose, closeButtonAriaLabel = 'Close', navAriaLabel, navAriaLabelledBy, mainAriaLabel, mainAriaLabelledBy, hasNoBodyPadding, footer, appendTo, isOpen, titleId, descriptionId, isNavExpandable, ...rest /* eslint-enable @typescript-eslint/no-unused-vars */ } = this.props; const { currentStep } = this.state; const flattenedSteps = this.getFlattenedSteps(); const adjustedStep = flattenedSteps.length < currentStep ? flattenedSteps.length : currentStep; const activeStep = flattenedSteps[adjustedStep - 1]; const computedSteps: WizardStep[] = this.initSteps(steps); const firstStep = activeStep === flattenedSteps[0]; const isValid = activeStep && activeStep.enableNext !== undefined ? activeStep.enableNext : true; const nav = (isWizardNavOpen: boolean) => { const wizNavAProps = { isOpen: isWizardNavOpen, 'aria-label': navAriaLabel, 'aria-labelledby': (title || navAriaLabelledBy) && (navAriaLabelledBy || this.titleId) }; return ( <WizardNav {...wizNavAProps}> {computedSteps.map((step, index) => { if (step.isFinishedStep) { // Don't show finished step in the side nav return; } let enabled; let navItemStep; if (step.steps) { let hasActiveChild = false; let canJumpToParent = false; for (const subStep of step.steps) { if (activeStep.name === subStep.name) { // one of the children matches hasActiveChild = true; } if (subStep.canJumpTo) { canJumpToParent = true; } } navItemStep = this.getFlattenedStepsIndex(flattenedSteps, step.steps[0].name); return ( <WizardNavItem key={index} content={step.name} isExpandable={isNavExpandable} isCurrent={hasActiveChild} isDisabled={!canJumpToParent} step={navItemStep} onNavItemClick={this.goToStep} > <WizardNav {...wizNavAProps} returnList> {step.steps.map((childStep: WizardStep, indexChild: number) => { if (childStep.isFinishedStep) { // Don't show finished step in the side nav return; } navItemStep = this.getFlattenedStepsIndex(flattenedSteps, childStep.name); enabled = childStep.canJumpTo; return ( <WizardNavItem key={`child_${indexChild}`} content={childStep.name} isCurrent={activeStep.name === childStep.name} isDisabled={!enabled} step={navItemStep} onNavItemClick={this.goToStep} /> ); })} </WizardNav> </WizardNavItem> ); } navItemStep = this.getFlattenedStepsIndex(flattenedSteps, step.name); enabled = step.canJumpTo; return ( <WizardNavItem {...step.stepNavItemProps} key={index} content={step.name} isCurrent={activeStep.name === step.name} isDisabled={!enabled} step={navItemStep} onNavItemClick={this.goToStep} /> ); })} </WizardNav> ); }; const context = { goToStepById: this.goToStepById, goToStepByName: this.goToStepByName, onNext: this.onNext, onBack: this.onBack, onClose, activeStep }; const divStyles = { ...(height ? { height } : {}), ...(width ? { width } : {}) }; const wizard = ( <WizardContextProvider value={context}> <div {...rest} className={css(styles.wizard, activeStep && activeStep.isFinishedStep && 'pf-m-finished', className)} style={Object.keys(divStyles).length ? divStyles : undefined} > {title && ( <WizardHeader titleId={this.titleId} descriptionId={this.descriptionId} onClose={onClose} title={title} description={description} closeButtonAriaLabel={closeButtonAriaLabel} hideClose={hideClose} /> )} <WizardToggle mainAriaLabel={mainAriaLabel} isInPage={isOpen === undefined} mainAriaLabelledBy={(title || mainAriaLabelledBy) && (mainAriaLabelledBy || this.titleId)} isNavOpen={this.state.isNavOpen} onNavToggle={isNavOpen => this.setState({ isNavOpen })} nav={nav} steps={steps} activeStep={activeStep} hasNoBodyPadding={hasNoBodyPadding} > {footer || ( <WizardFooterInternal onNext={this.onNext} onBack={this.onBack} onClose={onClose} isValid={isValid} firstStep={firstStep} activeStep={activeStep} nextButtonText={(activeStep && activeStep.nextButtonText) || nextButtonText} backButtonText={backButtonText} cancelButtonText={cancelButtonText} /> )} </WizardToggle> </div> </WizardContextProvider> ); if (isOpen !== undefined) { return ( <Modal width={width !== null ? width : undefined} isOpen={isOpen} variant={ModalVariant.large} aria-labelledby={this.titleId} aria-describedby={this.descriptionId} showClose={false} hasNoBodyWrapper > {wizard} </Modal> ); } return wizard; } }
the_stack
import path from 'path' import { getMonodeployConfig, withMonorepoContext } from '@monodeploy/test-utils' import { YarnContext } from '@monodeploy/types' import { Manifest, Workspace, structUtils } from '@yarnpkg/core' import { npath } from '@yarnpkg/fslib' import { patchPackageJsons } from '.' const identToWorkspace = (context: YarnContext, name: string): Workspace => context.project.getWorkspaceByIdent(structUtils.parseIdent(name)) const loadManifest = async (context: YarnContext, pkgName: string): Promise<Manifest> => { return await Manifest.fromFile( npath.toPortablePath(path.join(context.project.cwd, 'packages', pkgName, 'package.json')), ) } describe('Patch Package Manifests', () => { it('updates root version and dependencies from registry tags', async () => withMonorepoContext( { 'pkg-1': { dependencies: ['pkg-2'], peerDependencies: ['pkg-3'], }, 'pkg-2': { dependencies: ['pkg-3'] }, 'pkg-3': {}, }, async (context) => { const config = { ...(await getMonodeployConfig({ cwd: context.project.cwd, baseBranch: 'main', commitSha: 'shashasha', })), persistVersions: true, } const workspace1 = identToWorkspace(context, 'pkg-1') const workspace2 = identToWorkspace(context, 'pkg-2') const workspace3 = identToWorkspace(context, 'pkg-3') await patchPackageJsons( config, context, new Set([workspace1, workspace2, workspace3]), new Map([ ['pkg-1', '1.0.0'], ['pkg-2', '2.0.0'], ['pkg-3', '3.0.0'], ]), ) const manifest1 = await loadManifest(context, 'pkg-1') const manifest2 = await loadManifest(context, 'pkg-2') const manifest3 = await loadManifest(context, 'pkg-3') expect(manifest1.version).toEqual('1.0.0') expect(manifest2.version).toEqual('2.0.0') expect(manifest3.version).toEqual('3.0.0') expect(manifest1.dependencies.get(manifest2.name!.identHash)!.range).toEqual( 'workspace:^2.0.0', ) expect(manifest1.peerDependencies.get(manifest3.name!.identHash)!.range).toEqual( 'workspace:^3.0.0', ) expect(manifest2.dependencies.get(manifest3.name!.identHash)!.range).toEqual( 'workspace:^3.0.0', ) }, )) it('throws an error if workspace is missing a name', async () => withMonorepoContext( { 'pkg-1': { dependencies: ['pkg-2'], peerDependencies: ['pkg-3'], }, 'pkg-2': { dependencies: ['pkg-3'] }, 'pkg-3': {}, }, async (context) => { const config = { ...(await getMonodeployConfig({ cwd: context.project.cwd, baseBranch: 'main', commitSha: 'shashasha', })), persistVersions: true, } const workspace1 = identToWorkspace(context, 'pkg-1') const workspace2 = identToWorkspace(context, 'pkg-2') const workspace3 = identToWorkspace(context, 'pkg-3') await expect(async () => patchPackageJsons( config, context, new Set([workspace1, workspace2, workspace3]), new Map([ ['pkg-1', '1.0.0'], ['pkg-3', '3.0.0'], ]), ), ).rejects.toThrow('missing a version') }, )) it('skips dependencies it does not have a version for', async () => withMonorepoContext( { 'pkg-1': { dependencies: ['pkg-2'], peerDependencies: ['pkg-3'], }, 'pkg-2': { dependencies: ['pkg-3'] }, 'pkg-3': {}, }, async (context) => { const config = { ...(await getMonodeployConfig({ cwd: context.project.cwd, baseBranch: 'main', commitSha: 'shashasha', })), persistVersions: true, } const workspace1 = identToWorkspace(context, 'pkg-1') const workspace2 = identToWorkspace(context, 'pkg-2') await patchPackageJsons( config, context, new Set([workspace1, workspace2]), new Map([ ['pkg-1', '1.0.0'], ['pkg-2', '2.0.0'], ]), ) const manifest1 = await loadManifest(context, 'pkg-1') const manifest2 = await loadManifest(context, 'pkg-2') const manifest3 = await loadManifest(context, 'pkg-3') expect(manifest1.version).toEqual('1.0.0') expect(manifest2.version).toEqual('2.0.0') expect(manifest3.version).toEqual('0.0.0') expect(manifest1.dependencies.get(manifest2.name!.identHash)!.range).toEqual( 'workspace:^2.0.0', ) expect(manifest1.peerDependencies.get(manifest3.name!.identHash)!.range).toEqual( 'workspace:*', ) expect(manifest2.dependencies.get(manifest3.name!.identHash)!.range).toEqual( 'workspace:packages/pkg-3', ) }, )) it('does not update devDependencies', async () => withMonorepoContext( { 'pkg-1': { devDependencies: ['pkg-2'], peerDependencies: ['pkg-3'], }, 'pkg-2': { dependencies: ['pkg-3'] }, 'pkg-3': {}, }, async (context) => { const config = { ...(await getMonodeployConfig({ cwd: context.project.cwd, baseBranch: 'main', commitSha: 'shashasha', })), persistVersions: true, } const workspace1 = identToWorkspace(context, 'pkg-1') const workspace2 = identToWorkspace(context, 'pkg-2') await patchPackageJsons( config, context, new Set([workspace1, workspace2]), new Map([ ['pkg-1', '1.0.0'], ['pkg-2', '2.0.0'], ]), ) const manifest1 = await loadManifest(context, 'pkg-1') const manifest2 = await loadManifest(context, 'pkg-2') expect(manifest1.version).toEqual('1.0.0') expect(manifest2.version).toEqual('2.0.0') expect( manifest1.devDependencies .get(manifest2.name!.identHash)! .range.startsWith('workspace:'), ).toBe(true) }, )) it('only adds workspace protocol to disk, not in memory', async () => withMonorepoContext( { 'pkg-1': { dependencies: ['pkg-2', ['pkg-3', '*']], }, 'pkg-2': { dependencies: ['pkg-3'] }, 'pkg-3': {}, }, async (context) => { const config = { ...(await getMonodeployConfig({ cwd: context.project.cwd, baseBranch: 'main', commitSha: 'shashasha', })), persistVersions: true, } const workspace1 = identToWorkspace(context, 'pkg-1') const workspace2 = identToWorkspace(context, 'pkg-2') const workspace3 = identToWorkspace(context, 'pkg-3') await patchPackageJsons( config, context, new Set([workspace1, workspace2, workspace3]), new Map([ ['pkg-1', '1.0.0'], ['pkg-2', '2.0.0'], ['pkg-3', '3.0.0'], ]), ) // In memory we don't have the workspace protocol expect( workspace1.manifest.dependencies.get(workspace2.manifest.name!.identHash)! .range, ).toEqual('^2.0.0') // On disk we have workspace protocol const manifest1 = await loadManifest(context, 'pkg-1') const manifest2 = await loadManifest(context, 'pkg-2') const manifest3 = await loadManifest(context, 'pkg-3') // no workspace protocol as we define it using '*' in the package.json expect(manifest1.dependencies.get(manifest3.name!.identHash)!.range).toEqual( '^3.0.0', ) // preserves workspace protocol expect(manifest1.dependencies.get(manifest2.name!.identHash)!.range).toEqual( 'workspace:^2.0.0', ) }, )) it('does not modify disk in dry run mode', async () => withMonorepoContext( { 'pkg-1': { dependencies: ['pkg-2'], peerDependencies: ['pkg-3'], }, 'pkg-2': { dependencies: ['pkg-3'] }, 'pkg-3': {}, }, async (context) => { const config = { ...(await getMonodeployConfig({ cwd: context.project.cwd, baseBranch: 'main', commitSha: 'shashasha', })), persistVersions: true, dryRun: true, } const workspace1 = identToWorkspace(context, 'pkg-1') const workspace2 = identToWorkspace(context, 'pkg-2') const workspace3 = identToWorkspace(context, 'pkg-3') await patchPackageJsons( config, context, new Set([workspace1, workspace2, workspace3]), new Map([ ['pkg-1', '1.0.0'], ['pkg-2', '2.0.0'], ['pkg-3', '3.0.0'], ]), ) const manifest1 = await loadManifest(context, 'pkg-1') const manifest2 = await loadManifest(context, 'pkg-2') const manifest3 = await loadManifest(context, 'pkg-3') expect(manifest1.version).not.toEqual('1.0.0') expect(manifest2.version).not.toEqual('2.0.0') expect(manifest3.version).not.toEqual('3.0.0') expect(workspace1.manifest.version).toEqual('1.0.0') expect(workspace2.manifest.version).toEqual('2.0.0') expect(workspace3.manifest.version).toEqual('3.0.0') }, )) })
the_stack
import { spyMethod, stubMethod } from '@salesforce/ts-sinon'; import { assert, expect } from 'chai'; import { AuthInfo } from '../../src/authInfo'; import { AuthRemover } from '../../src/authRemover'; import { Aliases } from '../../src/config/aliases'; import { AuthInfoConfig } from '../../src/config/authInfoConfig'; import { Config } from '../../src/config/config'; import { testSetup } from '../../src/testSetup'; describe('AuthRemover', () => { const username = 'espresso@coffee.com'; const $$ = testSetup(); describe('resolveUsername', () => { it('should return username if no alias exists', async () => { const remover = await AuthRemover.create(); // @ts-ignore because private method const resolved = await remover.resolveUsername(username); expect(resolved).to.equal(username); }); it('should return username if given an alias', async () => { const alias = 'MyAlias'; $$.setConfigStubContents('Aliases', { contents: { orgs: { [alias]: username }, }, }); const remover = await AuthRemover.create(); // @ts-ignore because private method const resolved = await remover.resolveUsername(alias); expect(resolved).to.equal(username); }); }); describe('findAllAuthConfigs', () => { it('should return map of AuthInfoConfigs for all auth files', async () => { stubMethod($$.SANDBOX, AuthInfo, 'listAllAuthFiles').callsFake(async () => Promise.resolve([`${username}.json`, 'user@example.com.json']) ); const remover = await AuthRemover.create(); const authConfigs = await remover.findAllAuthConfigs(); expect(authConfigs.has(username)).to.equal(true); expect(authConfigs.get(username) instanceof AuthInfoConfig).to.be.true; expect(authConfigs.has('user@example.com')).to.equal(true); expect(authConfigs.get('user@example.com') instanceof AuthInfoConfig).to.be.true; }); }); describe('findAuthConfigs', () => { it('should return map of AuthInfoConfigs for provided username', async () => { stubMethod($$.SANDBOX, AuthInfo, 'listAllAuthFiles').callsFake(async () => Promise.resolve([`${username}.json`])); const remover = await AuthRemover.create(); const authConfigs = await remover.findAuthConfigs(username); expect(authConfigs.has(username)).to.equal(true); expect(authConfigs.get(username) instanceof AuthInfoConfig).to.be.true; }); it('should return map of AuthInfoConfigs for provided alias', async () => { const alias = 'MyAlias'; $$.setConfigStubContents('Aliases', { contents: { orgs: { [alias]: username }, }, }); stubMethod($$.SANDBOX, AuthInfo, 'listAllAuthFiles').callsFake(async () => Promise.resolve([`${username}.json`])); const remover = await AuthRemover.create(); const authConfigs = await remover.findAuthConfigs(alias); expect(authConfigs.has(username)).to.equal(true); expect(authConfigs.get(username) instanceof AuthInfoConfig).to.be.true; }); it('should return map of AuthInfoConfigs for defaultusername (set to username) if no username is provided', async () => { stubMethod($$.SANDBOX, AuthInfo, 'listAllAuthFiles').callsFake(async () => Promise.resolve([`${username}.json`])); $$.setConfigStubContents('Config', { contents: { [Config.DEFAULT_USERNAME]: username, }, }); const remover = await AuthRemover.create(); const authConfigs = await remover.findAuthConfigs(); expect(authConfigs.has(username)).to.equal(true); expect(authConfigs.get(username) instanceof AuthInfoConfig).to.be.true; }); it('should return map of AuthInfoConfigs for defaultusername (set to alias) if no username is provided', async () => { stubMethod($$.SANDBOX, AuthInfo, 'listAllAuthFiles').callsFake(async () => Promise.resolve([`${username}.json`])); const alias = 'MyAlias'; $$.setConfigStubContents('Aliases', { contents: { orgs: { [alias]: username }, }, }); $$.setConfigStubContents('Config', { contents: { [Config.DEFAULT_USERNAME]: alias, }, }); const remover = await AuthRemover.create(); const authConfigs = await remover.findAuthConfigs(); expect(authConfigs.has(username)).to.equal(true); expect(authConfigs.get(username) instanceof AuthInfoConfig).to.be.true; }); it('should return map of AuthInfoConfigs for defaultusername if provided username has no auth file ', async () => { stubMethod($$.SANDBOX, AuthInfo, 'listAllAuthFiles').callsFake(async () => Promise.resolve([`${username}.json`])); $$.setConfigStubContents('Config', { contents: { [Config.DEFAULT_USERNAME]: username, }, }); const remover = await AuthRemover.create(); const authConfigs = await remover.findAuthConfigs('user@example.com'); expect(authConfigs.has(username)).to.equal(true); expect(authConfigs.get(username) instanceof AuthInfoConfig).to.be.true; }); it('should throw an error if no username is provided and defaultusername is not set', async () => { stubMethod($$.SANDBOX, AuthInfo, 'listAllAuthFiles').callsFake(async () => Promise.resolve([`${username}.json`])); const remover = await AuthRemover.create(); try { await remover.findAuthConfigs(); assert.fail(); } catch (err) { expect(err.name).to.equal('NoOrgFound'); } }); }); describe('filterAuthFilesForDefaultUsername', () => { it('should return auth files that belong to the defaultusername (username)', async () => { $$.setConfigStubContents('Config', { contents: { [Config.DEFAULT_USERNAME]: username, }, }); const remover = await AuthRemover.create(); // @ts-ignore because private member const actual = await remover.filterAuthFilesForDefaultUsername([`${username}.json`, 'user@example.com']); expect(actual).to.deep.equal([`${username}.json`]); }); it('should return auth files that belong to the defaultusername (alias)', async () => { const alias = 'MyAlias'; $$.setConfigStubContents('Aliases', { contents: { orgs: { [alias]: username }, }, }); $$.setConfigStubContents('Config', { contents: { [Config.DEFAULT_USERNAME]: alias, }, }); const remover = await AuthRemover.create(); // @ts-ignore because private member const actual = await remover.filterAuthFilesForDefaultUsername([`${username}.json`, 'user@example.com']); expect(actual).to.deep.equal([`${username}.json`]); }); it('should throw an error if defaultusername is not set', async () => { const remover = await AuthRemover.create(); try { // @ts-ignore because private member await remover.filterAuthFilesForDefaultUsername([`${username}.json`]); assert.fail(); } catch (err) { expect(err.name).to.equal('NoOrgFound'); } }); }); describe('unsetConfigValues', () => { it('should unset config values for provided username locally and globally', async () => { const configWriteSpy = spyMethod($$.SANDBOX, Config.prototype, 'write'); const configUnsetSpy = spyMethod($$.SANDBOX, Config.prototype, 'unset'); const alias = 'MyAlias'; $$.setConfigStubContents('Aliases', { contents: { orgs: { [alias]: username }, }, }); $$.setConfigStubContents('Config', { contents: { [Config.DEFAULT_USERNAME]: alias, [Config.DEFAULT_DEV_HUB_USERNAME]: alias, }, }); const remover = await AuthRemover.create(); // @ts-ignore because private member await remover.unsetConfigValues(username); // expect 4 calls to unset: // 1. unset defaultusername locally // 2. unset defaultusername globally // 3. unset defaultdevhubusername locally // 4. unset defaultdevhubusername globally expect(configUnsetSpy.callCount).to.equal(4); expect(configUnsetSpy.args).to.deep.equal([ [Config.DEFAULT_USERNAME], [Config.DEFAULT_DEV_HUB_USERNAME], [Config.DEFAULT_USERNAME], [Config.DEFAULT_DEV_HUB_USERNAME], ]); // expect one call each for global and local config expect(configWriteSpy.callCount).to.equal(2); }); it('should unset config values for provided username globally', async () => { const configWriteSpy = spyMethod($$.SANDBOX, Config.prototype, 'write'); const configUnsetSpy = spyMethod($$.SANDBOX, Config.prototype, 'unset'); const alias = 'MyAlias'; $$.setConfigStubContents('Aliases', { contents: { orgs: { [alias]: username }, }, }); $$.setConfigStubContents('Config', { contents: { [Config.DEFAULT_USERNAME]: alias, [Config.DEFAULT_DEV_HUB_USERNAME]: alias, }, }); const remover = await AuthRemover.create(); // @ts-ignore because private member remover.localConfig = null; // @ts-ignore because private member await remover.unsetConfigValues(username); // expect 2 calls to unset: // 1. unset defaultdevhubusername locally // 2. unset defaultdevhubusername globally expect(configUnsetSpy.callCount).to.equal(2); expect(configUnsetSpy.args).to.deep.equal([[Config.DEFAULT_USERNAME], [Config.DEFAULT_DEV_HUB_USERNAME]]); // expect one call each for global and local config expect(configWriteSpy.callCount).to.equal(1); }); }); describe('unsetAliases', () => { it('should unset aliases for provided username', async () => { const aliasesSpy = spyMethod($$.SANDBOX, Aliases.prototype, 'unset'); $$.setConfigStubContents('Aliases', { contents: { orgs: { MyAlias: username, MyOtherAlias: username, }, }, }); const remover = await AuthRemover.create(); // @ts-ignore because private member await remover.unsetAliases(username); // expect 2 calls: one for each alias expect(aliasesSpy.callCount).to.equal(2); expect(aliasesSpy.args).to.deep.equal([['MyAlias'], ['MyOtherAlias']]); }); }); describe('unlinkConfigFile', () => { it('should unlink AuthConfigFile', async () => { stubMethod($$.SANDBOX, AuthInfoConfig.prototype, 'exists').returns(Promise.resolve(true)); const unlinkSpy = stubMethod($$.SANDBOX, AuthInfoConfig.prototype, 'unlink').returns(Promise.resolve()); stubMethod($$.SANDBOX, AuthInfo, 'listAllAuthFiles').callsFake(async () => Promise.resolve([`${username}.json`])); const remover = await AuthRemover.create(); await remover.findAllAuthConfigs(); // @ts-ignore because private member await remover.unlinkConfigFile(username); expect(unlinkSpy.callCount).to.equal(1); }); it('should unlink AuthConfigFile when username is not yet in this.authConfigs', async () => { stubMethod($$.SANDBOX, AuthInfoConfig.prototype, 'exists').returns(Promise.resolve(true)); stubMethod($$.SANDBOX, AuthInfo, 'listAllAuthFiles').callsFake(async () => Promise.resolve([`${username}.json`])); const unlinkSpy = stubMethod($$.SANDBOX, AuthInfoConfig.prototype, 'unlink').returns(Promise.resolve()); const findAuthConfigsSpy = spyMethod($$.SANDBOX, AuthRemover.prototype, 'findAuthConfigs'); const remover = await AuthRemover.create(); // @ts-ignore because private member await remover.unlinkConfigFile(username); expect(unlinkSpy.callCount).to.equal(1); expect(findAuthConfigsSpy.callCount).to.equal(1); expect(findAuthConfigsSpy.firstCall.args).to.deep.equal([username]); }); it('should do nothing when there is no auth file', async () => { stubMethod($$.SANDBOX, AuthInfoConfig.prototype, 'exists').returns(Promise.resolve(false)); stubMethod($$.SANDBOX, AuthInfo, 'listAllAuthFiles').callsFake(async () => Promise.resolve([])); const unlinkSpy = stubMethod($$.SANDBOX, AuthInfoConfig.prototype, 'unlink').returns(Promise.resolve()); stubMethod($$.SANDBOX, AuthRemover.prototype, 'findAuthConfigs').returns(Promise.resolve(new Map())); const remover = await AuthRemover.create(); // @ts-ignore because private member await remover.unlinkConfigFile(username); expect(unlinkSpy.callCount).to.equal(0); }); }); });
the_stack
const models = require('../../../../../db/mysqldb/index') import moment from 'moment' const { resClientJson } = require('../../../utils/resData') const Op = require('sequelize').Op const trimHtml = require('trim-html') const xss = require('xss') const clientWhere = require('../../../utils/clientWhere') const config = require('../../../../../config') const { TimeNow, TimeDistance } = require('../../../utils/time') import { statusList, userMessageAction, modelAction, modelName } from '../../../utils/constant' const { reviewSuccess, freeReview, pendingReview, reviewFail } = statusList const userMessage = require('../../../utils/userMessage') import userVirtual from '../../../common/userVirtual' /* 评论模块 */ class BooksComment { static async getBooksCommentList(req: any, res: any, next: any) { let books_id = req.query.books_id let page = req.query.page || 1 let pageSize = req.query.pageSize || 10 try { let { count, rows } = await models.books_comment.findAndCountAll({ // 默认一级评论 where: { books_id, parent_id: 0, status: { [Op.or]: [reviewSuccess, freeReview, pendingReview, reviewFail] } }, // 为空,获取全部,也可以自己添加条件 offset: (page - 1) * pageSize, // 开始的数据索引,比如当page=2 时offset=10 ,而pagesize我们定义为10,则现在为索引为10,也就是从第11条开始返回数据条目 limit: Number(pageSize), // 每页限制返回的数据条数 order: [['create_date', 'desc']] }) for (let i in rows) { rows[i].setDataValue( 'create_dt', await TimeDistance(rows[i].create_date) ) if (Number(rows[i].status) === pendingReview) { rows[i].setDataValue('content', '当前用户评论需要审核') } if (Number(rows[i].status) === reviewFail) { rows[i].setDataValue('content', '当前用户评论违规') } rows[i].setDataValue( 'user', await models.user.findOne({ where: { uid: rows[i].uid }, attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction'] }) ) } for (let item in rows) { // 循环取子评论 let childAllComment = await models.books_comment.findAll({ where: { parent_id: rows[item].id, status: { [Op.or]: [reviewSuccess, freeReview, pendingReview, reviewFail] } } }) rows[item].setDataValue('children', childAllComment) for (let childCommentItem in childAllComment) { // 循环取用户 代码有待优化,层次过于复杂 childAllComment[childCommentItem].setDataValue( 'create_dt', await TimeDistance(childAllComment[childCommentItem].create_date) ) childAllComment[childCommentItem].setDataValue( 'user', await models.user.findOne({ where: { uid: childAllComment[childCommentItem].uid }, attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction'] }) ) if ( childAllComment[childCommentItem].reply_uid !== 0 && childAllComment[childCommentItem].reply_uid !== childAllComment[childCommentItem].uid ) { childAllComment[childCommentItem].setDataValue( 'reply_user', await models.user.findOne({ where: { uid: childAllComment[childCommentItem].reply_uid }, attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction'] }) ) } } } await resClientJson(res, { state: 'success', message: '获取评论列表成功', data: { page, pageSize, count, comment_list: rows } }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * 新建评论post提交 * @param {object} ctx 上下文对象 */ static async createBooksComment(req: any, res: any, next: any) { let reqData = req.body let { user = '' } = req try { if (!reqData.content) { throw new Error('请输入评论内容') } let date = new Date() let currDate = moment(date.setHours(date.getHours())).format( 'YYYY-MM-DD HH:mm:ss' ) let oneBooks = await models.books.findOne({ where: { books_id: reqData.books_id } }) if (new Date(currDate).getTime() < new Date(user.ban_dt).getTime()) { throw new Error( `当前用户因违规已被管理员禁用发布评论,时间到:${moment( user.ban_dt ).format('YYYY年MM月DD日 HH时mm分ss秒')},如有疑问请联系网站管理员` ) } // 虚拟币判断是否可以进行继续的操作 const isVirtual = await userVirtual.isVirtual({ uid: user.uid, type: modelName.books, action: modelAction.comment }) if (!isVirtual) { throw new Error('贝壳余额不足!') } let allUserRole = await models.user_role.findAll({ where: { user_role_id: { [Op.or]: user.user_role_ids.split(',') }, user_role_type: 1 // 用户角色类型1是默认角色 } }) let userAuthorityIds = '' allUserRole.map((roleItem: any) => { userAuthorityIds += roleItem.user_authority_ids + ',' }) let status = ~userAuthorityIds.indexOf( config.BOOKS.dfNoReviewBooksCommentId ) ? freeReview // 免审核 : pendingReview // 待审核 await models.books_comment .create({ parent_id: reqData.parent_id || 0, books_id: reqData.books_id, star: reqData.star || 0, uid: user.uid, reply_uid: reqData.reply_uid || 0, content: xss(reqData.content), status }) .then(async (data: any) => { await models.books.update( { // 更新小书评论数 comment_count: await models.books_comment.count({ where: { books_id: reqData.books_id, parent_id: 0 } }) }, { where: { books_id: reqData.books_id } } ) const oneUser = await models.user.findOne({ where: { uid: user.uid } }) // 查询当前评论用户的信息 let _data = { // 组合返回的信息 ...data.get({ plain: true }), children: [], user: oneUser } if ( reqData.reply_uid && reqData.reply_uid !== 0 && reqData.reply_uid !== user.uid ) { _data.reply_user = await models.user.findOne({ where: { uid: reqData.reply_uid }, attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction'] }) } _data['create_dt'] = await TimeDistance(_data.create_date) // 虚拟币消耗后期开启事物 await userVirtual.setVirtual({ uid: user.uid, associate: reqData.books_id, type: modelName.books, action: modelAction.comment, ass_uid: oneBooks.uid }) if (oneBooks.uid !== user.uid) { // 屏蔽自己 await userVirtual.setVirtual({ uid: oneBooks.uid, associate: reqData.books_id, type: modelName.books, action: modelAction.obtain_comment, ass_uid: user.uid }) } if (oneBooks.uid !== user.uid && !reqData.reply_id) { await userMessage.setMessage({ uid: oneBooks.uid, sender_id: user.uid, action: userMessageAction.comment, // 动作:评论 type: modelName.books, // 类型:小书评论 content: reqData.books_id }) } if ( reqData.reply_id && reqData.reply_id !== 0 && reqData.reply_uid !== user.uid ) { await userMessage.setMessage({ uid: reqData.reply_uid, sender_id: user.uid, action: userMessageAction.reply, // 动作:回复 type: modelName.books, // 类型:小书回复 content: reqData.books_id }) } resClientJson(res, { state: 'success', data: _data, message: Number(status) === freeReview ? '评论成功' : '评论成功,待审核可见' }) }) .catch((err: any) => { resClientJson(res, { state: 'error', message: '回复失败:' + err }) }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * 删除评论post提交 * @param {object} ctx 上下文对象 */ static async deleteBooksComment(req: any, res: any, next: any) { let reqData = req.body let { user = '' } = req try { let allComment = await models.books_comment .findAll({ where: { parent_id: reqData.comment_id } }) .then((res: any) => { return res.map((item: any, key: string) => { return item.id }) }) if (allComment.length > 0) { // 判断当前评论下是否有子评论,有则删除子评论 await models.books_comment.destroy({ where: { id: { [Op.in]: allComment }, uid: user.uid } }) } await models.books_comment.destroy({ where: { id: reqData.comment_id, uid: user.uid } }) await models.books.update( { // 更新小书评论数 comment_count: await models.books_comment.count({ where: { books_id: reqData.books_id, parent_id: 0 } }) }, { where: { books_id: reqData.books_id } } ) resClientJson(res, { state: 'success', message: '删除成功' }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } } export default BooksComment
the_stack
import PrerenderManifest from "./prerender-manifest.json"; // @ts-ignore import Manifest from "./manifest.json"; // @ts-ignore import RoutesManifestJson from "./routes-manifest.json"; // @ts-ignore import lambdaAtEdgeCompat from "@sls-next/next-aws-cloudfront"; import { renderStaticPage } from "./render/renderStaticPage"; import { getCustomHeaders, handleDefault, handleFallback } from "@sls-next/core/dist/module/handle"; import { handlePublicFiles, routeDefault } from "@sls-next/core/dist/module/route"; import { getStaticRegenerationResponse, getThrottledStaticRegenerationCachePolicy } from "@sls-next/core/dist/module/revalidate"; import { ExternalRoute, PublicFileRoute, Route, StaticRoute, NextStaticFileRoute } from "@sls-next/core/dist/module/types"; import { CloudFrontRequest, CloudFrontResultResponse, CloudFrontS3Origin } from "aws-lambda"; import { OriginRequestDefaultHandlerManifest, OriginRequestEvent, OriginResponseEvent, RoutesManifest } from "./types"; import { PreRenderedManifest as PrerenderManifestType, PerfLogger } from "@sls-next/core/dist/module/types"; import { performance } from "perf_hooks"; import type { Readable } from "stream"; import { externalRewrite } from "./routing/rewriter"; import { removeBlacklistedHeaders } from "./headers/removeBlacklistedHeaders"; import { s3BucketNameFromEventRequest } from "./s3/s3BucketNameFromEventRequest"; import { triggerStaticRegeneration } from "./lib/triggerStaticRegeneration"; import { s3StorePage } from "./s3/s3StorePage"; import { createRedirectResponse } from "@sls-next/core/dist/module/route/redirect"; import { redirect } from "@sls-next/core/dist/module/handle/redirect"; import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3"; const basePath = RoutesManifestJson.basePath; const perfLogger = (logLambdaExecutionTimes?: boolean): PerfLogger => { if (logLambdaExecutionTimes) { return { now: () => performance.now(), log: (metricDescription: string, t1?: number, t2?: number): void => { if (!t1 || !t2) return; console.log(`${metricDescription}: ${t2 - t1} (ms)`); } }; } return { now: () => 0, // eslint-disable-next-line @typescript-eslint/no-empty-function log: () => {} }; }; const addS3HostHeader = ( req: CloudFrontRequest, s3DomainName: string ): void => { req.headers["host"] = [{ key: "host", value: s3DomainName }]; }; const normaliseS3OriginDomain = (s3Origin: CloudFrontS3Origin): string => { if (s3Origin.region === "us-east-1") { return s3Origin.domainName; } if (!s3Origin.domainName.includes(s3Origin.region)) { const regionalEndpoint = s3Origin.domainName.replace( "s3.amazonaws.com", `s3.${s3Origin.region}.amazonaws.com` ); return regionalEndpoint; } return s3Origin.domainName; }; export const handler = async ( event: OriginRequestEvent | OriginResponseEvent ): Promise<CloudFrontResultResponse | CloudFrontRequest> => { const manifest: OriginRequestDefaultHandlerManifest = Manifest; let response: CloudFrontResultResponse | CloudFrontRequest; const prerenderManifest: PrerenderManifestType = PrerenderManifest; const routesManifest: RoutesManifest = RoutesManifestJson; const { now, log } = perfLogger(manifest.logLambdaExecutionTimes); const tHandlerBegin = now(); if (isOriginResponse(event)) { response = await handleOriginResponse({ event, manifest, prerenderManifest, routesManifest }); } else { response = await handleOriginRequest({ event, manifest, prerenderManifest, routesManifest }); } // Remove blacklisted headers if (response.headers) { removeBlacklistedHeaders(response.headers); } const tHandlerEnd = now(); log("handler execution time", tHandlerBegin, tHandlerEnd); return response; }; const staticRequest = async ( event: OriginRequestEvent, file: string, path: string, route: Route, manifest: OriginRequestDefaultHandlerManifest, routesManifest: RoutesManifest ) => { const request = event.Records[0].cf.request; if (manifest.disableOriginResponseHandler) { const { req, res, responsePromise } = lambdaAtEdgeCompat( event.Records[0].cf, { enableHTTPCompression: manifest.enableHTTPCompression } ); const bucketName = s3BucketNameFromEventRequest(request) ?? ""; const s3Key = (path + file).slice(1); // need to remove leading slash from path for s3 key return await renderStaticPage({ route: route, request: request, req: req, res: res, responsePromise: responsePromise, manifest: manifest, routesManifest: routesManifest, bucketName: bucketName, s3Key: s3Key, s3Uri: file, basePath: basePath }); } else { const s3Origin = request.origin?.s3 as CloudFrontS3Origin; const s3Domain = normaliseS3OriginDomain(s3Origin); s3Origin.domainName = s3Domain; s3Origin.path = path; request.uri = file; addS3HostHeader(request, s3Domain); return request; } }; const reconstructOriginalRequestUri = ( s3Uri: string, manifest: OriginRequestDefaultHandlerManifest ) => { // For public files we do not replace .html as it can cause public HTML files to be classified with wrong status code const publicFile = handlePublicFiles(s3Uri, manifest); if (publicFile) { return `${basePath}${s3Uri}`; } let originalUri = `${basePath}${s3Uri.replace( /(\.html)?$/, manifest.trailingSlash ? "/" : "" )}`; // For index.html page, it will become "/index" or "/index/", which is not a route so normalize it to "/" originalUri = originalUri.replace( manifest.trailingSlash ? /\/index\/$/ : /\/index$/, "/" ); return originalUri; }; const handleOriginRequest = async ({ event, manifest, prerenderManifest, routesManifest }: { event: OriginRequestEvent; manifest: OriginRequestDefaultHandlerManifest; prerenderManifest: PrerenderManifestType; routesManifest: RoutesManifest; }) => { const request = event.Records[0].cf.request; const { req, res, responsePromise } = lambdaAtEdgeCompat( event.Records[0].cf, { enableHTTPCompression: manifest.enableHTTPCompression } ); const { now, log } = perfLogger(manifest.logLambdaExecutionTimes); let tBeforeSSR = null; const getPage = (pagePath: string) => { const tBeforePageRequire = now(); const page = require(`./${pagePath}`); // eslint-disable-line const tAfterPageRequire = (tBeforeSSR = now()); log("require JS execution time", tBeforePageRequire, tAfterPageRequire); return page; }; const route = await handleDefault( { req, res, responsePromise }, manifest, prerenderManifest, routesManifest, getPage ); if (tBeforeSSR) { const tAfterSSR = now(); log("SSR execution time", tBeforeSSR, tAfterSSR); } if (!route) { return await responsePromise; } if (route.isPublicFile) { const { file } = route as PublicFileRoute; return await staticRequest( event, file, `${routesManifest.basePath}/public`, route, manifest, routesManifest ); } if (route.isNextStaticFile) { const { file } = route as NextStaticFileRoute; return await staticRequest( event, file, `${routesManifest.basePath}/_next/static`, route, manifest, routesManifest ); } if (route.isStatic) { const { file, isData } = route as StaticRoute; const path = isData ? `${routesManifest.basePath}` : `${routesManifest.basePath}/static-pages/${manifest.buildId}`; const relativeFile = isData ? file : file.slice("pages".length); return await staticRequest( event, relativeFile, path, route, manifest, routesManifest ); } const external: ExternalRoute = route; const { path } = external; return externalRewrite(event, manifest.enableHTTPCompression, path); }; const handleOriginResponse = async ({ event, manifest, prerenderManifest, routesManifest }: { event: OriginResponseEvent; manifest: OriginRequestDefaultHandlerManifest; prerenderManifest: PrerenderManifestType; routesManifest: RoutesManifest; }) => { const response = event.Records[0].cf.response; const request = event.Records[0].cf.request; const bucketName = s3BucketNameFromEventRequest(request); // Reconstruct valid request uri for routing const s3Uri = request.uri; request.uri = reconstructOriginalRequestUri(s3Uri, manifest); const route = await routeDefault( request, manifest, prerenderManifest, routesManifest ); const staticRoute = route.isStatic ? (route as StaticRoute) : undefined; const statusCode = route?.statusCode; // These statuses are returned when S3 does not have access to the page. // 404 will also be returned if CloudFront has permissions to list objects. if (response.status !== "403" && response.status !== "404") { response.headers = { ...response.headers, ...getCustomHeaders(request.uri, routesManifest) }; // Set 404 status code for static 404 page. if (statusCode === 404) { response.status = "404"; response.statusDescription = "Not Found"; return response; } // Set 500 status code for static 500 page. if (statusCode === 500) { response.status = "500"; response.statusDescription = "Internal Server Error"; response.headers["cache-control"] = [ { key: "Cache-Control", value: "public, max-age=0, s-maxage=0, must-revalidate" // server error page should not be cached } ]; return response; } const staticRegenerationResponse = getStaticRegenerationResponse({ expiresHeader: response.headers?.expires?.[0]?.value || "", lastModifiedHeader: response.headers?.["last-modified"]?.[0]?.value || "", initialRevalidateSeconds: staticRoute?.revalidate }); if (staticRegenerationResponse) { response.headers["cache-control"] = [ { key: "Cache-Control", value: staticRegenerationResponse.cacheControl } ]; // We don't want the `expires` header to be sent to the client we manage // the cache at the edge using the s-maxage directive in the cache-control // header delete response.headers.expires; if ( staticRoute?.page && staticRegenerationResponse.secondsRemainingUntilRevalidation === 0 ) { const regenerationQueueName = manifest.regenerationQueueName ?? `${bucketName}.fifo`; // if queue name not specified, we used [bucketName].fifo as used in deployment if (!regenerationQueueName) { throw new Error("Regeneration queue name is undefined."); } const { throttle } = await triggerStaticRegeneration({ basePath, request, pageS3Path: s3Uri, eTag: response.headers["etag"]?.[0].value, lastModified: response.headers["etag"]?.[0].value, pagePath: staticRoute.page, queueName: regenerationQueueName }); // Occasionally we will get rate-limited by the Queue (in the event we // send it too many messages) and so we we use the cache to reduce // requests to the queue for a short period. if (throttle) { response.headers["cache-control"] = [ { key: "Cache-Control", value: getThrottledStaticRegenerationCachePolicy(1).cacheControl } ]; } } } return response; } // For PUT or DELETE just return the response as these should be unsupported S3 methods if (request.method === "PUT" || request.method === "DELETE") { return response; } const { req, res, responsePromise } = lambdaAtEdgeCompat( event.Records[0].cf, { enableHTTPCompression: manifest.enableHTTPCompression } ); const getPage = (pagePath: string) => { return require(`./${pagePath}`); }; const fallbackRoute = await handleFallback( { req, res, responsePromise }, route, manifest, routesManifest, getPage ); // Already handled dynamic error path if (!fallbackRoute) { return await responsePromise; } const s3 = new S3Client({ region: request.origin?.s3?.region, maxAttempts: 3 }); const s3BasePath = basePath ? `${basePath.replace(/^\//, "")}/` : ""; // Either a fallback: true page or a static error page if (fallbackRoute.isStatic) { const file = fallbackRoute.file.slice("pages".length); const s3Key = `${s3BasePath}static-pages/${manifest.buildId}${file}`; // S3 Body is stream per: https://github.com/aws/aws-sdk-js-v3/issues/1096 const getStream = await import("get-stream"); const s3Params = { Bucket: bucketName, Key: s3Key }; const s3Response = await s3.send(new GetObjectCommand(s3Params)); const bodyBuffer = await getStream.buffer(s3Response.Body as Readable); const statusCode = fallbackRoute.statusCode || 200; const is500 = statusCode === 500; const cacheControl = is500 ? "public, max-age=0, s-maxage=0, must-revalidate" // static 500 page should never be cached : s3Response.CacheControl ?? (fallbackRoute.fallback // Use cache-control from S3 response if possible, otherwise use defaults ? "public, max-age=0, s-maxage=0, must-revalidate" // fallback should never be cached : "public, max-age=0, s-maxage=2678400, must-revalidate"); res.writeHead(statusCode, { "Cache-Control": cacheControl, "Content-Type": "text/html" }); res.end(bodyBuffer); return await responsePromise; } // This is a fallback route that should be stored in S3 before returning it const { renderOpts, html } = fallbackRoute; // Check if response is a redirect if ( typeof renderOpts.pageData !== "undefined" && typeof renderOpts.pageData.pageProps !== "undefined" && typeof renderOpts.pageData.pageProps.__N_REDIRECT !== "undefined" ) { const statusCode = renderOpts.pageData.pageProps.__N_REDIRECT_STATUS; const redirectPath = renderOpts.pageData.pageProps.__N_REDIRECT; const redirectResponse = createRedirectResponse( redirectPath, request.querystring, statusCode ); redirect({ req, res, responsePromise }, redirectResponse); return await responsePromise; } const { expires } = await s3StorePage({ html, uri: s3Uri, basePath, bucketName: bucketName || "", buildId: manifest.buildId, pageData: renderOpts.pageData, region: request.origin?.s3?.region || "", revalidate: renderOpts.revalidate }); const isrResponse = expires ? getStaticRegenerationResponse({ expiresHeader: expires.toJSON(), lastModifiedHeader: undefined, initialRevalidateSeconds: staticRoute?.revalidate }) : null; const cacheControl = (isrResponse && isrResponse.cacheControl) || "public, max-age=0, s-maxage=2678400, must-revalidate"; res.setHeader("Cache-Control", cacheControl); if (fallbackRoute.route.isData) { res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify(renderOpts.pageData)); } else { res.setHeader("Content-Type", "text/html"); res.end(html); } return await responsePromise; }; const isOriginResponse = ( event: OriginRequestEvent | OriginResponseEvent ): event is OriginResponseEvent => { return event.Records[0].cf.config.eventType === "origin-response"; };
the_stack
import * as _ from 'lodash'; import {Message} from '@stomp/stompjs'; import { ApplicationRef, Component, ComponentFactoryResolver, ElementRef, EventEmitter, Injector, Input, OnDestroy, OnInit, Output } from '@angular/core'; import {Alert} from '@common/util/alert.util'; import {CommonConstant} from '@common/constant/common.constant'; import {CookieConstant} from '@common/constant/cookie.constant'; import {Datasource, Field, FieldRole, LogicalType} from '@domain/datasource/datasource'; import {Filter} from '@domain/workbook/configurations/filter/filter'; import {BoardConfiguration, BoardDataSource, Dashboard} from '@domain/dashboard/dashboard'; import {InclusionFilter} from '@domain/workbook/configurations/filter/inclusion-filter'; import {BoundFilter} from '@domain/workbook/configurations/filter/bound-filter'; import {TimeFilter} from '@domain/workbook/configurations/filter/time-filter'; import {TimeUnit} from '@domain/workbook/configurations/field/timestamp-field'; import {MeasureInequalityFilter} from '@domain/workbook/configurations/filter/measure-inequality-filter'; import {WildCardFilter} from '@domain/workbook/configurations/filter/wild-card-filter'; import {MeasurePositionFilter} from '@domain/workbook/configurations/filter/measure-position-filter'; import {AdvancedFilter} from '@domain/workbook/configurations/filter/advanced-filter'; import {AbstractFilterPopupComponent} from '../abstract-filter-popup.component'; import {ConfigureFiltersInclusionComponent} from '../inclusion-filter/configure-filters-inclusion.component'; import {ConfigureFiltersBoundComponent} from '../bound-filter/configure-filters-bound.component'; import {ConfigureFiltersTimeComponent} from '../time-filter/configure-filters-time.component'; import {DatasourceService} from '../../../datasource/service/datasource.service'; import {FilterUtil} from '../../util/filter.util'; @Component({ selector: 'app-essential-filter', templateUrl: './essential-filter.component.html' }) export class EssentialFilterComponent extends AbstractFilterPopupComponent implements OnInit, OnDestroy { /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ private _pseudoDashboard: Dashboard; // 원본 필터 // private _originalFilters: Filter[] = []; // 선택한 필드, 필터, 통신용 필터, 통신용 데이터소스 private _dataSource: BoardDataSource; private _dataSourceId: string; // 필드에 대한 필터 설정 컴퍼넌트 맵 private _compMap: any = {}; // ingest 완료 시 결과를 반환하기 위해서 임시 저장하는 변수 private _ingestResultFilters: Filter[] = []; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 대시보드 @Input('datasource') public inputDatasource: BoardDataSource; @Output() public done: EventEmitter<{ id: string, info: Datasource, dataSourceId: string, filters?: Filter[] }> = new EventEmitter(); // 필터 종류 public essentialFilters: Filter[] = []; // enum public logicalType = LogicalType; // 데이터소스 적재 관련 정보 public isShowProgress: boolean = false; // 프로그래스 팝업 표시 여부 public ingestionStatus: { progress: number, message: string, step?: number }; // 적재 진행 정보 public filterUtil = FilterUtil; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Constructor |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 생성자 constructor(private dataSourceService: DatasourceService, protected appRef: ApplicationRef, protected componentFactoryResolver: ComponentFactoryResolver, protected elementRef: ElementRef, protected injector: Injector) { super(elementRef, injector); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * Component Initialize Method */ public ngOnInit() { // Init super.ngOnInit(); // 데이터소스 설정 this._dataSource = new BoardDataSource(); const mainDs: BoardDataSource = this.inputDatasource; // 필드 나눔 this._setFields(mainDs.uiFields); if (mainDs.temporary) { // 재설정인 경우 this._dataSource.type = 'default'; this._dataSource.connType = 'LINK'; this._dataSource.temporary = mainDs.temporary; this._dataSource.name = mainDs.metaDataSource.name; this._dataSource.engineName = mainDs.metaDataSource.engineName; this._dataSourceId = mainDs.id; if (mainDs.metaDataSource['filters']) { this.essentialFilters = mainDs.metaDataSource['filters']; // 필수 필터 설정 } } else { // 초기 설정인 경우 this._dataSource.type = 'default'; this._dataSource.connType = 'LINK'; this._dataSource.name = mainDs.name; this._dataSource.engineName = mainDs.engineName; this._dataSourceId = mainDs.id; if (mainDs.uiFilters && 0 < mainDs.uiFilters.length) { this.essentialFilters = mainDs.uiFilters; } else { this.essentialFilters = this._setEssentialFilters(mainDs.uiFields); // 필수 필터 설정 } } this._pseudoDashboard = new Dashboard(); this._pseudoDashboard.configuration = new BoardConfiguration(); this._pseudoDashboard.configuration.dataSource = this._dataSource; this._pseudoDashboard.configuration.fields = mainDs.uiFields; // UI에서 표현할 수 있는 데이터로 Convert if (0 < this.essentialFilters.length) { // console.log('>>>>> this.essentialFilters', this.essentialFilters); this._convertServerSpecToUISpec(this.essentialFilters); // this._originalFilters = _.cloneDeep(this.essentialFilters); /* this.loadingShow(); this._setEssentialFilter([], 0).then(() => { // console.log(this.essentialFilters); this.loadingHide(); }).catch((error) => { console.log(error); this.commonExceptionHandler(error, this.translateService.instant('msg.board.alert.fail.load.essential')); this.loadingHide(); }); */ } else { this.ingest(); } } // function - ngOnInit /** * Component Destroy Method */ public ngOnDestroy() { super.ngOnDestroy(); } // function - ngOnDestroy /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 필드에 대한 아이콘 클래스 얻음 * @param {Filter} filter * @param {boolean} isDimension * @returns {string} */ public getIconClass(filter: Filter, isDimension: boolean = true): string { if (isDimension) { return Field.getDimensionTypeIconClass(this._getField(filter.field, filter.ref)); } else { return Field.getMeasureTypeIconClass(this._getField(filter.field, filter.ref)); } } // function - getIconClass /** * 컴포넌트 실행 * @param {ElementRef} elm * @param {Filter} filter */ public startComponent(elm: ElementRef, filter: Filter) { const field: Field = this._getField(filter.field, filter.ref); if ('include' === filter.type) { const confFilterCompFactory = this.componentFactoryResolver.resolveComponentFactory(ConfigureFiltersInclusionComponent); const inclusionComp = this.appRef.bootstrap(confFilterCompFactory, elm.nativeElement).instance; inclusionComp.showComponent(this._pseudoDashboard, filter as InclusionFilter, field, false); this._compMap[filter.field] = inclusionComp; } else if (FilterUtil.isTimeFilter(filter)) { const confFilterCompFactory = this.componentFactoryResolver.resolveComponentFactory(ConfigureFiltersTimeComponent); const timeComp = this.appRef.bootstrap(confFilterCompFactory, elm.nativeElement).instance; timeComp.showComponent(this._pseudoDashboard, filter as TimeFilter, field, false); this._compMap[filter.field] = timeComp; } else if ('bound' === filter.type) { const confFilterCompFactory = this.componentFactoryResolver.resolveComponentFactory(ConfigureFiltersBoundComponent); const boundComp = this.appRef.bootstrap(confFilterCompFactory, elm.nativeElement).instance; boundComp.showComponent(this._pseudoDashboard, filter as BoundFilter, field); this._compMap[filter.field] = boundComp; } } // function - startComponent /** * Ingest */ public ingest() { this.ingestionStatus = {progress: 0, message: '', step: 1}; this.isShowProgress = true; this._ingestResultFilters = this.essentialFilters.map(item => this._compMap[item.field].getData()); let filterParams: Filter[] = _.cloneDeep(this._ingestResultFilters); // 필터 설정 for (let filter of filterParams) { filter = FilterUtil.convertToServerSpec(filter); if ('include' === filter.type && filter['candidateValues']) { delete filter['candidateValues']; } } // 값이 없는 측정값 필터 제거 filterParams = filterParams.filter(item => { if ('bound' === item.type) { // Measure Filter return null !== item['min']; } else if ('include' === item.type) { // Dimension Filter return (item['valueList'] && 0 < item['valueList'].length); } else { // Time Filter ( TimeAllFilter 를 제외한 나머지 필터 ) return !FilterUtil.isTimeAllFilter(item); } }); this.checkAndConnectWebSocket(true).then(() => { this.safelyDetectChanges(); this.dataSourceService.createLinkedDatasourceTemporary(this._dataSourceId, filterParams) .then(result => { if (result['progressTopic']) { this.safelyDetectChanges(); this._processIngestion(result); } else { this._loadTempDatasourceDetail(result['id']); } }) .catch(err => { console.error(err); this.ingestionStatus.step = -1; this.ingestionStatus.progress = -1; this.commonExceptionHandler(err, this.translateService.instant('msg.board.alert.fail.ingestion')); }); }); } // function - ingest public closeProgress() { this.isShowProgress = false; if (0 === this.essentialFilters.length) { this.closeEvent.emit(); } } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // /** // * candidate용 파라미터 // * @param {Filter[]} filters // * @param {Filter} filter // * @param {BoardDataSource} dataSource // * @return {any} // */ // private _getCandidateParam(filters: Filter[], filter: Filter, dataSource: BoardDataSource): any { // // const param: any = {}; // param.dataSource = DashboardUtil.getDataSourceForApi(_.cloneDeep(dataSource)); // param.filters = (filters) ? _.cloneDeep(filters) : []; // param.filters = param.filters // .map(item => FilterUtil.convertToServerSpec(item)) // .filter(item => !(item.type === 'bound' && item['min'] == null)); // // if (filter.type === 'include') { // param.targetField = { // alias: filter.field, // name: filter.field, // type: 'dimension' // }; // } else if (FilterUtil.isTimeFilter(filter)) { // const timeFilter: TimeFilter = filter as TimeFilter; // param.targetField = { // type: 'timestamp', // name: timeFilter.field, // alias: timeFilter.field, // format: { // type: 'time_continuous', // discontinuous: FilterUtil.isDiscontinuousTimeFilter(timeFilter), // unit: timeFilter.timeUnit, // filteringType: FilterUtil.isTimeListFilter(timeFilter) ? FilteringType.LIST : FilteringType.RANGE // } // }; // (timeFilter.byTimeUnit) && (param.targetField.format.byUnit = timeFilter.byTimeUnit); // param.sortBy = 'VALUE'; // } // // return param; // } // function - _getCandidateParam /** * 필수 필터를 셋팅한다 * @param {Field[]} fields * @return {Filter[]} * @private */ private _setEssentialFilters(fields: Field[]) { const filters: Filter[] = []; // 필수 필터 설정 fields.forEach((field: Field) => { if (field.filtering) { if (FieldRole.DIMENSION === field.role) { if (field.logicalType === LogicalType.TIMESTAMP) { filters.push(FilterUtil.getTimeRangeFilter(field, TimeUnit.NONE, 'essential')); } else { const inclusionFilter: InclusionFilter = FilterUtil.getBasicInclusionFilter(field, 'essential'); // 정렬을 위함 임시정보 설정 inclusionFilter['showSortLayer'] = false; filters.push(inclusionFilter); } } else if (FieldRole.MEASURE === field.role) { filters.push(FilterUtil.getBasicBoundFilter(field, 'essential')); } } }); filters.sort((a: Filter, b: Filter) => a.ui.filteringSeq - b.ui.filteringSeq); return filters; } // function - _setEssentialFilters // /** // * 리커멘드 필터 재설정 // * @param {Filter[]} filters // * @param {number} idx // * @returns {Promise} // */ // private _setEssentialFilter(filters: Filter[], idx: number): Promise<any> { // return new Promise<any>((resolve, reject) => { // let index = idx; // // 값을 변경할 필터 // const filter = _.cloneDeep(this.essentialFilters[index]); // // // console.log('>>>>>> filters', filters); // // console.log('>>>>>> filter', filter); // // console.log('>>>>>> this._dataSource', this._dataSource); // // const params: any = this._getCandidateParam(filters, filter, this._dataSource); // // // candidate 서비스 요청 // this.dataSourceService.getCandidate(params).then((result) => { // // // 결과데이터로 필터에 값 셋팅 // if ('include' === filter.type) { // if (result && result.length > 0) { // // const apiFieldName: string = filter.field.replace(/(\S+\.)\S+/gi, '$1field'); // result = result.map(item => { // return {field: item[apiFieldName], count: item['.count']}; // }); // // if (result[0].field) (<InclusionFilter>filter).valueList = [result[0].field]; // else (<InclusionFilter>filter).valueList = [result[0][filter.field]]; // } else { // (<InclusionFilter>filter).valueList = []; // } // this.essentialFilters[index]['candidateValues'] = result; // } else if ('bound' === filter.type) { // this._setBoundFilter(this.essentialFilters[index], result[0]); // } else { // this._setTimeFilter(this.essentialFilters[index], result[0]); // } // // // api용 파라미터 filters에 현재 필터 추가 // filters.push(filter); // index = index + 1; // // // 다음 필터가 없거나 일반 필터일 경우 종료 // if (this.essentialFilters.length <= index) { // // console.log('>>>>>>>>> end'); // resolve(result); // } else { // // console.log('>>>>>>>>> recurrsive'); // // 아닐경우 재귀 // this._setEssentialFilter(filters, index).then(result => resolve(result)); // } // }).catch((error) => { // reject(error); // }); // }); // } // function - _setEssentialFilter // noinspection JSMethodCanBeStatic // /** // * BoundFilter Candidate 결과 처리 // * @param {Filter} filter // * @param result // * @private // */ // private _setBoundFilter(filter: Filter, result: any) { // const boundFilter = <BoundFilter>filter; // if (result && result.hasOwnProperty('maxValue')) { // if ((boundFilter.min === 0 && boundFilter.max === 0) || boundFilter.min == null) { // boundFilter.min = result.minValue; // boundFilter.max = result.maxValue; // } // boundFilter.maxValue = result.maxValue; // boundFilter.minValue = result.minValue; // } else { // boundFilter.min = null; // boundFilter.max = null; // boundFilter.maxValue = null; // boundFilter.minValue = null; // } // } // function - _setBoundFilter // noinspection JSMethodCanBeStatic // /** // * TimeFilter Candidate 결과 처리 // * @param {Filter} filter // * @param result // */ // private _setTimeFilter(filter: Filter, result: any) { // const rangeFilter: TimeRangeFilter = <TimeRangeFilter>filter; // if (rangeFilter.intervals == null || rangeFilter.intervals.length === 0) { // rangeFilter.intervals = [result.minTime + '/' + result.maxTime]; // } // } // function - _setTimeFilter /** * Reingestion 진행 * @param {any} tempDsInfo * @private */ private _processIngestion(tempDsInfo: { id: string, progressTopic: string }) { // id: "TEMP-c5a839ae-f8a7-41e0-93f6-86e487f68dbd" // progressTopic : "/topic/datasources/TEMP-c5a839ae-f8a7-41e0-93f6-86e487f68dbd/progress" try { const headers: any = {'X-AUTH-TOKEN': this.cookieService.get(CookieConstant.KEY.LOGIN_TOKEN)}; // 메세지 수신 const subscription = CommonConstant.stomp.watch(tempDsInfo.progressTopic) .subscribe((msg: Message) => { const data: { progress: number, message: string } = JSON.parse(msg.body); if (-1 === data.progress) { this.ingestionStatus = data; this.ingestionStatus.step = -1; Alert.error(data.message); this.safelyDetectChanges(); subscription.unsubscribe(); // Socket 응답 해제 } else if (100 === data.progress) { this.ingestionStatus = data; this.safelyDetectChanges(); subscription.unsubscribe(); // Socket 응답 해제 this._loadTempDatasourceDetail(tempDsInfo.id); } else { this.ingestionStatus = data; this.ingestionStatus.step = 2; this.safelyDetectChanges(); } }, headers); } catch (e) { console.log(e); } } // function - _processIngestion /** * 임시 데이터소스 상세정보를 불러온 후 화면을 닫는다. * @param {string} tempDsId * @private */ private _loadTempDatasourceDetail(tempDsId: string) { this.dataSourceService.getDatasourceDetail(tempDsId).then((ds: Datasource) => { setTimeout(() => { // Success 를 1초간 보여주기 위해 지연코드 추가함 this.done.emit({id: tempDsId, info: ds, dataSourceId: this._dataSourceId, filters: this._ingestResultFilters}); }, 1000); (this.ingestionStatus) && (this.ingestionStatus.step = 10); // 프로그레스 표시를 위해 변경 this.safelyDetectChanges(); }).catch(err => { this.commonExceptionHandler(err, this.translateService.instant('msg.board.alert.fail.ingestion')); if (this.ingestionStatus) { // 프로그레스 표시를 위해 변경 this.ingestionStatus.progress = -1; this.ingestionStatus.step = -1; } }); } // function - _loadTempDatasourceDetail /** * 필드를 구분하여 나눈다. (Dimension, Measure) * @param {Field[]} fields * @private */ private _setFields(fields: Field[]) { let fieldList: Field[] = _.cloneDeep(fields); if (!fieldList) { fieldList = []; } this.fields = []; this.fields = this.fields .concat(fieldList.filter(item => item.role !== FieldRole.MEASURE)) .concat(fieldList.filter(item => item.role === FieldRole.MEASURE)); } // function - _setFields /** * 필드명으로 필드 조회 */ private _getField(fieldName: string, ref: string): Field { const fields = this.fields; let field: Field; // 필드 조회 let idx: number; if (ref) idx = _.findIndex(fields, {ref, name: fieldName}); else idx = _.findIndex(fields, {name: fieldName}); if (idx > -1) field = fields[idx]; return field; } // function - _getField /** * 서버스펙을 UI스펙으로 변경 * @param {Filter[]} filters */ private _convertServerSpecToUISpec(filters: Filter[]) { filters.forEach((filter: Filter) => { if (filter.type === 'include') { this._convertInclusionSpecToUI(filter); } }); } // function - _convertServerSpecToUISpec /** * Inclusion Filter 의 서버스펙을 UI 스펙으로 변경함 * @param {Filter} filter * @return {InclusionFilter} */ private _convertInclusionSpecToUI(filter: Filter): InclusionFilter { const includeFilter: InclusionFilter = filter as InclusionFilter; let condition: MeasureInequalityFilter = new MeasureInequalityFilter(); let limitation: MeasurePositionFilter = new MeasurePositionFilter(); let wildcard: WildCardFilter = new WildCardFilter(); // 필터 구분 includeFilter.preFilters.forEach((preFilter: AdvancedFilter) => { if (preFilter.type === 'measure_inequality') condition = preFilter as MeasureInequalityFilter; else if (preFilter.type === 'measure_position') limitation = preFilter as MeasurePositionFilter; else if (preFilter.type === 'wildcard') wildcard = preFilter as WildCardFilter; }); this._setUIItem(this.aggregationTypeList, condition, 'aggregationType'); this._setUIItem(this.aggregationTypeList, limitation, 'aggregationType'); this._setUIItem(this.conditionTypeList, condition, 'inequality'); this._setUIItem(this.limitTypeList, limitation, 'position'); this._setUIItem(this.wildCardTypeList, wildcard, 'contains'); // MeasureFields this.summaryMeasureFields.forEach((item) => { if (item.name === condition.field) condition.field = item.name; if (item.name === limitation.field) limitation.field = item.name; }); // selector 변경 includeFilter.selectionRange = includeFilter.selector.toString().split('_')[0]; includeFilter.selectionComponent = includeFilter.selector.toString().split('_')[1]; return includeFilter; } // function - _convertInclusionSpecToUI /** * UI 아이템 설정 * @param list * @param uiItem * @param {string} key * @private */ private _setUIItem(list: any, uiItem: any, key: string) { list.forEach((item) => { if (item.value === uiItem[key]) { uiItem[key + 'UI'] = item; } }); } // function - _setUIItem }
the_stack
import { DefaultValueDateTypeEnum, IOrganization, PermissionsEnum, IRolePermission, IUser, LanguagesEnum, OrganizationPermissionsEnum, IOrganizationProject, ILanguage, IProposalViewModel, IFeatureToggle, IFeatureOrganization, FeatureEnum, ISelectedEmployee } from '@gauzy/contracts'; import { Injectable } from '@angular/core'; import { StoreConfig, Store as AkitaStore, Query } from '@datorama/akita'; import { NgxPermissionsService, NgxRolesService } from 'ngx-permissions'; import { ComponentEnum, SYSTEM_DEFAULT_LAYOUT } from '../constants/layout.constants'; import { ComponentLayoutStyleEnum } from '@gauzy/contracts'; import { map } from 'rxjs/operators'; import { merge, Subject } from 'rxjs'; import * as _ from 'underscore'; import * as camelCase from 'camelcase'; export interface AppState { user: IUser; userRolePermissions: IRolePermission[]; selectedOrganization: IOrganization; selectedEmployee: ISelectedEmployee; selectedProposal: IProposalViewModel; selectedProject: IOrganizationProject; selectedDate: Date; systemLanguages: ILanguage[]; featureToggles: IFeatureToggle[]; featureOrganizations: IFeatureOrganization[]; featureTenant: IFeatureOrganization[]; } export interface PersistState { organizationId?: string; clientId?: string; token: string; userId: string; serverConnection: number; preferredLanguage: LanguagesEnum; preferredComponentLayout: ComponentLayoutStyleEnum; componentLayout: any[]; //This would be a Map but since Maps can't be serialized/deserialized it is stored as an array } export function createInitialAppState(): AppState { return { selectedDate: new Date(), userRolePermissions: [], featureToggles: [], featureOrganizations: [], featureTenant: [] } as AppState; } export function createInitialPersistState(): PersistState { const token = localStorage.getItem('token') || null; const userId = localStorage.getItem('_userId') || null; const organizationId = localStorage.getItem('_organizationId') || null; const serverConnection = parseInt(localStorage.getItem('serverConnection')) || null; const preferredLanguage = localStorage.getItem('preferredLanguage') || null; const componentLayout = localStorage.getItem('componentLayout') || []; return { token, userId, organizationId, serverConnection, preferredLanguage, componentLayout } as PersistState; } @Injectable({ providedIn: 'root' }) @StoreConfig({ name: 'app' }) export class AppStore extends AkitaStore<AppState> { constructor() { super(createInitialAppState()); } } @Injectable({ providedIn: 'root' }) @StoreConfig({ name: 'persist' }) export class PersistStore extends AkitaStore<PersistState> { constructor() { super(createInitialPersistState()); } } @Injectable({ providedIn: 'root' }) export class AppQuery extends Query<AppState> { constructor(protected store: AppStore) { super(store); } } @Injectable({ providedIn: 'root' }) export class PersistQuery extends Query<PersistState> { constructor(protected store: PersistStore) { super(store); } } @Injectable({ providedIn: 'root' }) export class Store { constructor( protected appStore: AppStore, protected appQuery: AppQuery, protected persistStore: PersistStore, protected persistQuery: PersistQuery, protected permissionsService: NgxPermissionsService, protected ngxRolesService: NgxRolesService ) {} user$ = this.appQuery.select((state) => state.user); selectedOrganization$ = this.appQuery.select( (state) => state.selectedOrganization ); selectedEmployee$ = this.appQuery.select((state) => state.selectedEmployee); selectedProject$ = this.appQuery.select((state) => state.selectedProject); selectedDate$ = this.appQuery.select((state) => state.selectedDate); userRolePermissions$ = this.appQuery.select( (state) => state.userRolePermissions ); featureToggles$ = this.appQuery.select((state) => state.featureToggles); featureOrganizations$ = this.appQuery.select( (state) => state.featureOrganizations ); featureTenant$ = this.appQuery.select((state) => state.featureTenant); preferredLanguage$ = this.persistQuery.select( (state) => state.preferredLanguage ); preferredComponentLayout$ = this.persistQuery.select( (state) => state.preferredComponentLayout ); componentLayoutMap$ = this.persistQuery .select((state) => state.componentLayout) .pipe(map((componentLayout) => new Map(componentLayout))); systemLanguages$ = this.appQuery.select((state) => state.systemLanguages); subject = new Subject<ComponentEnum>(); /** * Observe any change to the component layout. * Returns the layout for the component given in the params in the following order of preference * 1. If overridden at component level, return that. * Else * 2. If preferred layout set, then return that * Else * 3. Return the system default layout */ componentLayout$(component: ComponentEnum) { return merge( this.persistQuery .select((state) => state.preferredComponentLayout) .pipe( map((preferredLayout) => { const dataLayout = this.getLayoutForComponent( component ); return ( dataLayout || preferredLayout || SYSTEM_DEFAULT_LAYOUT ); }) ), this.persistQuery .select((state) => state.componentLayout) .pipe( map((componentLayout) => { const componentMap = new Map(componentLayout); return ( componentMap.get(component) || this.preferredComponentLayout || SYSTEM_DEFAULT_LAYOUT ); }) ) ); } get selectedOrganization(): IOrganization { const { selectedOrganization } = this.appQuery.getValue(); return selectedOrganization; } set selectedEmployee(employee: ISelectedEmployee) { this.appStore.update({ selectedEmployee: employee }); } get selectedEmployee(): ISelectedEmployee { const { selectedEmployee } = this.appQuery.getValue(); return selectedEmployee; } set selectedOrganization(organization: IOrganization) { this.appStore.update({ selectedOrganization: organization }); this.loadPermissions(); } set selectedProject(project: IOrganizationProject) { this.appStore.update({ selectedProject: project }); } set systemLanguages(languages: ILanguage[]) { this.appStore.update({ systemLanguages: languages }); } get systemLanguages(): ILanguage[] { const { systemLanguages } = this.appQuery.getValue(); return systemLanguages; } get token(): string | null { const { token } = this.persistQuery.getValue(); return token; } set token(token: string) { this.persistStore.update({ token: token }); } get userId(): IUser['id'] | null { const { userId } = this.persistQuery.getValue(); return userId; } set userId(id: IUser['id'] | null) { this.persistStore.update({ userId: id }); } get organizationId(): IOrganization['id'] | null { const { organizationId } = this.persistQuery.getValue(); return organizationId; } set organizationId(id: IOrganization['id'] | null) { this.persistStore.update({ organizationId: id }); } get user(): IUser { const { user } = this.appQuery.getValue(); return user; } set user(user: IUser) { this.appStore.update({ user: user }); } get selectedDate() { const { selectedDate } = this.appQuery.getValue(); if (selectedDate instanceof Date) { return selectedDate; } const date = new Date(selectedDate); this.appStore.update({ selectedDate: date }); return date; } set selectedDate(date: Date) { this.appStore.update({ selectedDate: date }); } get selectedProposal(): IProposalViewModel { const { selectedProposal } = this.appQuery.getValue(); return selectedProposal; } set selectedProposal(proposal: IProposalViewModel) { this.appStore.update({ selectedProposal: proposal }); } get featureToggles(): IFeatureToggle[] { const { featureToggles } = this.appQuery.getValue(); return featureToggles; } set featureToggles(featureToggles: IFeatureToggle[]) { this.appStore.update({ featureToggles: featureToggles }); } get featureTenant(): IFeatureOrganization[] { const { featureTenant } = this.appQuery.getValue(); return featureTenant; } set featureTenant(featureOrganizations: IFeatureOrganization[]) { this.appStore.update({ featureTenant: featureOrganizations }); } get featureOrganizations(): IFeatureOrganization[] { const { featureOrganizations } = this.appQuery.getValue(); return featureOrganizations; } set featureOrganizations(featureOrganizations: IFeatureOrganization[]) { this.appStore.update({ featureOrganizations: featureOrganizations }); } /* * Check features are enabled/disabled for tenant organization */ hasFeatureEnabled(feature: FeatureEnum) { const { featureTenant = [], featureOrganizations = [], featureToggles = [] } = this.appQuery.getValue(); const filtered = _.uniq( [...featureOrganizations, ...featureTenant], (x) => x.featureId ); const unleashToggle = featureToggles.find( (toggle) => toggle.name === feature && toggle.enabled === false ); if (unleashToggle) { return unleashToggle.enabled; } return !!filtered.find( (item) => item.feature.code === feature && item.isEnabled ); } get userRolePermissions(): IRolePermission[] { const { userRolePermissions } = this.appQuery.getValue(); return userRolePermissions; } set userRolePermissions(rolePermissions: IRolePermission[]) { this.appStore.update({ userRolePermissions: rolePermissions }); this.loadPermissions(); } hasPermission(permission: PermissionsEnum) { const { userRolePermissions } = this.appQuery.getValue(); return !!(userRolePermissions || []).find( (p) => p.permission === permission && p.enabled ); } getDateFromOrganizationSettings() { const dateObj = this.selectedDate; switch ( this.selectedOrganization && this.selectedOrganization.defaultValueDateType ) { case DefaultValueDateTypeEnum.TODAY: { return new Date(Date.now()); } case DefaultValueDateTypeEnum.END_OF_MONTH: { return new Date(dateObj.getFullYear(), dateObj.getMonth(), 0); } case DefaultValueDateTypeEnum.START_OF_MONTH: { return new Date(dateObj.getFullYear(), dateObj.getMonth(), 1); } default: { return new Date(Date.now()); } } } get serverConnection() { const { serverConnection } = this.persistQuery.getValue(); return serverConnection; } set serverConnection(val: number) { this.persistStore.update({ serverConnection: val }); } get preferredLanguage(): any | null { const { preferredLanguage } = this.persistQuery.getValue(); return preferredLanguage; } set preferredLanguage(preferredLanguage) { this.persistStore.update({ preferredLanguage: preferredLanguage }); } get preferredComponentLayout(): any | null { const { preferredComponentLayout } = this.persistQuery.getValue(); return preferredComponentLayout; } set preferredComponentLayout(preferredComponentLayout) { this.persistStore.update({ preferredComponentLayout: preferredComponentLayout }); } clear() { this.appStore.reset(); this.persistStore.reset(); } loadRoles() { const { user } = this.appQuery.getValue(); this.ngxRolesService.flushRoles(); this.ngxRolesService.addRole(user.role.name, () => true); } loadPermissions() { const { selectedOrganization } = this.appQuery.getValue(); let permissions = []; // User permissions load here const userPermissions = Object.keys( PermissionsEnum ) .map((key) => PermissionsEnum[key]) .filter((permission) => this.hasPermission(permission)); permissions = permissions.concat(userPermissions); // Organization time tracking permissions load here if (selectedOrganization) { const organizationPermissions = Object.keys( OrganizationPermissionsEnum ) .map((permission) => OrganizationPermissionsEnum[permission]) .filter((permission) => selectedOrganization[camelCase(permission)]); permissions = permissions.concat(organizationPermissions); } this.permissionsService.flushPermissions(); this.permissionsService.loadPermissions(permissions); } getLayoutForComponent( componentName: ComponentEnum ): ComponentLayoutStyleEnum { const { componentLayout } = this.persistQuery.getValue(); const componentLayoutMap = new Map(componentLayout); return componentLayoutMap.get( componentName ) as ComponentLayoutStyleEnum; } setLayoutForComponent( componentName: ComponentEnum, style: ComponentLayoutStyleEnum ) { const { componentLayout } = this.persistQuery.getValue(); const componentLayoutMap = new Map(componentLayout); componentLayoutMap.set(componentName, style); const componentLayoutArray = Array.from( componentLayoutMap.entries() ) as any; this.persistStore.update({ componentLayout: componentLayoutArray }); } set componentLayout(componentLayout: any[]) { this.persistStore.update({ componentLayout }); } }
the_stack
/// <reference types="node" /> /** * A Node.js implementation of the PKCS#11 2.30 interface */ declare module "pkcs11js" { /** * PKCS#11 handle type */ type Handle = Buffer; /** * Structure that describes the version */ interface Version { /** * Major version number (the integer portion of the version) */ major: number; /** * minor version number (the hundredths portion of the version) */ minor: number; } /** * Provides general information about Cryptoki */ interface ModuleInfo { /** * Cryptoki interface version number, for compatibility with future revisions of this interface */ cryptokiVersion: Version; /** * ID of the Cryptoki library manufacturer. * Must be padded with the blank character (' '). */ manufacturerID: string; /** * Bit flags reserved for future versions. Must be zero for this version */ flags: number; /** * Character-string description of the library. * Must be padded with the blank character (' ') */ libraryDescription: string; /** * Cryptoki library version number */ libraryVersion: Version; } /** * Provides information about a slot */ interface SlotInfo { /** * Character-string description of the slot. * Must be padded with the blank character (' ') */ slotDescription: string; /** * ID of the slot manufacturer. * Must be padded with the blank character (' ') */ manufacturerID: string; /** * Bits flags that provide capabilities of the slot */ flags: number; /** * Version number of the slot's hardware */ hardwareVersion: Version; /** * Version number of the slot's firmware */ firmwareVersion: Version; } /** * Provides information about a token */ interface TokenInfo { /** * Application-defined label, assigned during token initialization. * Must be padded with the blank character (' ') */ label: string; /** * ID of the device manufacturer. * Must be padded with the blank character (' ') */ manufacturerID: string; /** * Model of the device. * Must be padded with the blank character (' ') */ model: string; /** * Character-string serial number of the device. * Must be padded with the blank character (' ') */ serialNumber: string; /** * Bit flags indicating capabilities and status of the device */ flags: number; /** * Maximum number of sessions that can be opened with the token at one time by a single application */ maxSessionCount: number; /** * Number of sessions that this application currently has open with the token */ sessionCount: number; /** * Maximum number of read/write sessions that can be opened with the token at one time by a single application */ maxRwSessionCount: number; /** * Number of read/write sessions that this application currently has open with the token */ rwSessionCount: number; /** * Maximum length in bytes of the PIN */ maxPinLen: number; /** * Minimum length in bytes of the PIN */ minPinLen: number; /** * version number of hardware */ hardwareVersion: Version; /** * Version number of firmware */ firmwareVersion: Version; /** * Current time as a character-string of length 16, represented in the format YYYYMMDDhhmmssxx * (4 characters for the year; 2 characters each for the month, the day, the hour, the minute, * and the second; and 2 additional reserved '0' characters). * The value of this field only makes sense for tokens equipped with a clock, * as indicated in the token information flags */ utcTime: string; /** * The total amount of memory on the token in bytes in which public objects may be stored */ totalPublicMemory: number; /** * The amount of free (unused) memory on the token in bytes for public objects */ freePublicMemory: number; /** * The total amount of memory on the token in bytes in which private objects may be stored */ totalPrivateMemory: number; /** * The amount of free (unused) memory on the token in bytes for private objects */ freePrivateMemory: number; } /** * Provides information about a particular mechanism */ interface MechanismInfo { /** * The minimum size of the key for the mechanism */ minKeySize: number; /** * The maximum size of the key for the mechanism */ maxKeySize: number; /** * Bit flags specifying mechanism capabilities */ flags: number; } /** * Provides information about a session */ interface SessionInfo { /** * ID of the slot that interfaces with the token */ slotID: Buffer; /** * The state of the session */ state: number; /** * Bit flags that define the type of session */ flags: number; /** * An error code defined by the cryptographic device */ deviceError: number; } type Template = Attribute[]; /** * A structure that includes the type and value of an attribute */ interface Attribute { /** * The attribute type */ type: number; /** * The value of the attribute */ value?: number | boolean | string | Buffer; } /** * A structure that specifies a particular mechanism and any parameters it requires */ interface Mechanism { /** * The type of mechanism */ mechanism: number; /** * The parameter if required by the mechanism */ parameter?: Buffer | IParams; } //#region Crypto parameters /** * A base structure of a parameter */ interface IParams { /** * Type of crypto param. Uses constants CK_PARAMS_* */ type: number; } /** * A structure that provides the parameters for the {@link CKM_ECDH1_DERIVE} and {@link CKM_ECDH1_COFACTOR_DERIVE} * key derivation mechanisms, where each party contributes one key pair */ interface ECDH1 extends IParams { /** * Key derivation function used on the shared secret value */ kdf: number; /** * Some data shared between the two parties */ sharedData?: Buffer; /** * The other party's EC public key */ publicData: Buffer; } interface AesCBC extends IParams { iv: Buffer; data?: Buffer; } interface AesCCM extends IParams { dataLen: number; nonce?: Buffer; aad?: Buffer; macLen: number; } interface AesGCM extends IParams { iv?: Buffer; aad?: Buffer; ivBits: number; tagBits: number; } interface RsaOAEP extends IParams { hashAlg: number; mgf: number; source: number; sourceData?: Buffer; } interface RsaPSS extends IParams { hashAlg: number; mgf: number; saltLen: number; } //#endregion interface KeyPair { privateKey: Handle; publicKey: Handle; } interface InitializationOptions { /** * NSS library parameters */ libraryParameters?: string; /** * bit flags specifying options for {@link C_Initialize} * - CKF_LIBRARY_CANT_CREATE_OS_THREADS. True if application threads which are executing calls to the library * may not use native operating system calls to spawn new threads; false if they may * - CKF_OS_LOCKING_OK. True if the library can use the native operation system threading model for locking; * false otherwise */ flags?: number; } /** * A Structure which contains a Cryptoki version and each function in the Cryptoki API */ export class PKCS11 { /** * Library path */ public libPath: string; /** * Loads dynamic library with PKCS#11 interface * @param path The path to PKCS#11 library * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public load(path: string): void; /** * Initializes the Cryptoki library * @param options Initialization options * Supports implementation of standard `CK_C_INITIALIZE_ARGS` and extended NSS format. * - if `options` is null or empty, it calls native `C_Initialize` with `NULL` * - if `options` doesn't have `libraryParameters`, it uses `CK_C_INITIALIZE_ARGS` structure * - if `options` has `libraryParameters`, it uses extended NSS structure * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_Initialize(options?: InitializationOptions): void; /** * Closes dynamic library * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public close(): void; /** * Indicates that an application is done with the Cryptoki library * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_Finalize(): void; /** * Returns general information about Cryptoki * @returns Information about Cryptoki * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_GetInfo(): ModuleInfo; //#region Slot and token management /** * Obtains a list of slots in the system * @param [tokenPresent] Only slots with tokens? * @returns Array of slot IDs * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_GetSlotList(tokenPresent?: boolean): Handle[]; /** * Obtains information about a particular slot in the system * @param slot The ID of the slot * @returns Information about a slot * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_GetSlotInfo(slot: Handle): SlotInfo; /** * Obtains information about a particular token in the system * @param slot ID of the token's slot * @returns Information about a token * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_GetTokenInfo(slot: Handle): TokenInfo; /** * Initializes a token * @param slot ID of the token's slot * @param [pin] The SO's initial PIN * @returns 32-byte token label (blank padded) * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_InitToken(slot: Handle, pin?: string, label?: string): string; /** * Initializes the normal user's PIN * @param session The session's handle * @param pin The normal user's PIN * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_InitPIN(session: Handle, pin?: string): void; /** * Modifies the PIN of the user who is logged in * @param session The session's handle * @param oldPin The old PIN * @param newPin The new PIN * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_SetPIN(session: Handle, oldPin: string, newPin: string): void; /** * Obtains a list of mechanism types supported by a token * @param slot ID of token's slot * @returns A list of mechanism types * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_GetMechanismList(slot: Handle): number[]; /** * Obtains information about a particular mechanism possibly supported by a token * @param slot ID of the token's slot * @param mech Type of mechanism * @returns Information about mechanism * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_GetMechanismInfo(slot: Handle, mech: number): MechanismInfo; //#endregion //#region Session management /** * Opens a session between an application and a token * @param slot The slot's ID * @param flags From CK_SESSION_INFO * @returns Session handle * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_OpenSession(slot: Handle, flags: number): Handle; /** * Closes a session between an application and a token * @param session The session's handle * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_CloseSession(session: Handle): void; /** * Closes all sessions with a token * @param slot The token's slot * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_CloseAllSessions(slot: Handle): void; /** * Obtains information about the session * @param session The session's handle * @returns Receives session info * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_GetSessionInfo(session: Handle): SessionInfo; /** * Logs a user into a token * @param session The session's handle * @param userType The user type * @param [pin] The user's PIN * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_Login(session: Handle, userType: number, pin?: string): void; /** * Logs a user out from a token * @param session The session's handle * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_Logout(session: Handle): void; //#endregion //#region Object management /** * Creates a new object * @param session The session's handle * @param template The object's template * @returns A new object's handle * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_CreateObject(session: Handle, template: Template): Handle; /** * Copies an object, creating a new object for the copy * @param session The session's handle * @param object The object's handle * @param template Template for new object * @returns A handle of copy * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_CopyObject(session: Handle, object: Handle, template: Template): Handle; /** * Destroys an object * @param session The session's handle * @param object The object's handle * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_DestroyObject(session: Handle, object: Handle): void; /** * Gets the size of an object in bytes * @param session The session's handle * @param object The object's handle * @returns Size of an object in bytes * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_GetObjectSize(session: Handle, object: Handle): number; /** * Initializes a search for token and session objects that match a template * @param session The session's handle * @param template Attribute values to match * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_FindObjectsInit(session: Handle, template: Template): void; /** * Continues a search for token and session * objects that match a template, obtaining additional object * handles * @param session The session's handle * @param session The maximum number of object handles to be returned * @returns List of handles * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_FindObjects(session: Handle, maxObjectCount: number): Handle[]; /** * Continues a search for token and session * objects that match a template, obtaining additional object * handles * @param session The session's handle * @returns Object's handle. If object is not found * the result is null * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_FindObjects(session: Handle): Handle | null; /** * Finishes a search for token and session objects * @param session The session's handle * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_FindObjectsFinal(session: Handle): void; /** * Obtains the value of one or more object attributes * @param session The session's handle * @param object The object's handle * @param template Specifies attrs; gets values * @returns List of Attributes with values * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_GetAttributeValue(session: Handle, object: Handle, template: Template): Template; /** * Modifies the value of one or more object attributes * @param session The session's handle * @param object The object's handle * @param template Specifies attrs and values * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_SetAttributeValue(session: Handle, object: Handle, template: Template): void; //#endregion //#region Encryption and decryption /** * Initializes an encryption operation * @param session The session's handle * @param mechanism The encryption mechanism * @param key Handle of encryption key * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_EncryptInit(session: Handle, mechanism: Mechanism, key: Handle): void; /** * Encrypts single-part data * @param session The session's handle * @param inData Incoming data * @param outData Output data * @returns Sliced output data with encrypted message * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_Encrypt(session: Handle, inData: Buffer, outData: Buffer): Buffer; /** * Encrypts single-part data * @param session The session's handle * @param inData Incoming data * @param outData Output data * @param cb Async callback with sliced output data * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_Encrypt(session: Handle, inData: Buffer, outData: Buffer, cb: (error: Error, data: Buffer) => void): void; /** * Encrypts single-part data * @param session The session's handle * @param inData Incoming data * @param outData Output data * @returns Sliced output data with encrypted message * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_EncryptAsync(session: Handle, inData: Buffer, outData: Buffer): Promise<Buffer>; /** * Continues a multiple-part encryption operation * @param session The session's handle * @param inData Incoming data * @param outData Output data * @returns Sliced output data * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_EncryptUpdate(session: Handle, inData: Buffer, outData: Buffer): Buffer; /** * Finishes a multiple-part encryption operation * @param session The session's handle * @param outData Last output data * @returns Sliced output data * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_EncryptFinal(session: Handle, outData: Buffer): Buffer; /** * Initializes a decryption operation * @param session The session's handle * @param mechanism The decryption mechanism * @param key Handle of decryption key * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_DecryptInit(session: Handle, mechanism: Mechanism, key: Handle): void; /** * Decrypts encrypted data in a single part * @param session The session's handle * @param inData Incoming data * @param outData Output data * @returns Sliced output data with decrypted message * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_Decrypt(session: Handle, inData: Buffer, outData: Buffer): Buffer; /** * Decrypts encrypted data in a single part * @param session The session's handle * @param inData Incoming data * @param outData Output data * @param cb Async callback with sliced output data * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_Decrypt(session: Handle, inData: Buffer, outData: Buffer, cb: (error: Error, data: Buffer) => void): void; /** * Decrypts encrypted data in a single part * @param session The session's handle * @param inData Incoming data * @param outData Output data * @returns Sliced output data with decrypted message * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_DecryptAsync(session: Handle, inData: Buffer, outData: Buffer): Promise<Buffer>; /** * continues a multiple-part decryption operation * @param session The session's handle * @param inData Incoming data * @param outData Output data * @returns Sliced output data with decrypted block * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_DecryptUpdate(session: Handle, inData: Buffer, outData: Buffer): Buffer; /** * Finishes a multiple-part decryption operation * @param session The session's handle * @param outData Last part of output data * @returns Sliced output data with decrypted final block * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_DecryptFinal(session: Handle, outData: Buffer): Buffer; /* Message digesting */ /** * Initializes a message-digesting operation * @param session The session's handle * @param mechanism Digesting mechanism * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_DigestInit(session: Handle, mechanism: Mechanism): void; /** * Digests data in a single part * @param session The session's handle * @param inData Incoming data * @param outData Output data * @returns Sliced output data * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_Digest(session: Handle, inData: Buffer, outData: Buffer): Buffer; /** * Digests data in a single part * @param session The session's handle * @param inData Incoming data * @param outData Output data * @param cb Async callback with sliced output data * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_Digest(session: Handle, inData: Buffer, outData: Buffer, cb: (error: Error, data: Buffer) => void): void; /** * Digests data in a single part * @param session The session's handle * @param inData Incoming data * @param outData Output data * @returns Sliced output data * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_DigestAsync(session: Handle, inData: Buffer, outData: Buffer): Promise<Buffer>; /** * continues a multiple-part message-digesting operation * operation, by digesting the value of a secret key as part of * the data already digested * @param session The session's handle * @param inData Incoming data * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_DigestUpdate(session: Handle, inData: Buffer): void; /** * Finishes a multiple-part message-digesting operation * @param session The session's handle * @param outData Output data * @returns Sliced output data * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_DigestFinal(session: Handle, outData: Buffer): Buffer; /** * Continues a multiple-part message-digesting operation by digesting the value of a secret key * @param session The session's handle * @param key The handle of the secret key to be digested * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_DigestKey(session: Handle, key: Handle): void; //#endregion //#region Signing and MACing /** * initializes a signature (private key encryption) * operation, where the signature is (will be) an appendix to * the data, and plaintext cannot be recovered from the * signature * @param session The session's handle * @param mechanism Signature mechanism * @param key Handle of signature key * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_SignInit(session: Handle, mechanism: Mechanism, key: Handle): void; /** * Signs (encrypts with private key) data in a single * part, where the signature is (will be) an appendix to the * data, and plaintext cannot be recovered from the signature * @param session The session's handle * @param inData Incoming data * @param outData Output data * @returns Sliced output data * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_Sign(session: Handle, inData: Buffer, outData: Buffer): Buffer; /** * Signs (encrypts with private key) data in a single * part, where the signature is (will be) an appendix to the * data, and plaintext cannot be recovered from the signature * @param session The session's handle * @param inData Incoming data * @param outData Output data * @param cb Async callback with sliced output data * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_Sign(session: Handle, inData: Buffer, outData: Buffer, cb: (error: Error, data: Buffer) => void): void; /** * Signs (encrypts with private key) data in a single * part, where the signature is (will be) an appendix to the * data, and plaintext cannot be recovered from the signature * @param session The session's handle * @param inData Incoming data * @param outData Output data * @returns Sliced output data * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_SignAsync(session: Handle, inData: Buffer, outData: Buffer): Promise<Buffer>; /** * Continues a multiple-part signature operation, * where the signature is (will be) an appendix to the data, * and plaintext cannot be recovered from the signature * @param session The session's handle * @param inData Incoming data * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_SignUpdate(session: Handle, inData: Buffer): void; /** * Finishes a multiple-part signature operation, * returning the signature * @param session The session's handle * @param outData Output data * @returns Sliced output data * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_SignFinal(session: Handle, outData: Buffer): Buffer; /** * Initializes a signature operation, where the data can be recovered from the signature * @param session The session's handle * @param mechanism The structure that specifies the signature mechanism * @param key The handle of the signature key * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_SignRecoverInit(session: Handle, mechanism: Mechanism, key: Handle): void; /** * Signs data in a single operation, where the data can be recovered from the signature * @param session * @param inData Incoming data * @param outData Output data * @returns Sliced output data * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_SignRecover(session: Handle, inData: Buffer, outData: Buffer): Buffer; //#endregion //#region Verifying signatures and MACs /** * initializes a verification operation, where the * signature is an appendix to the data, and plaintext cannot * cannot be recovered from the signature (e.g. DSA) * @param session The session's handle * @param mechanism Verification mechanism * @param key Verification key * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_VerifyInit(session: Handle, mechanism: Mechanism, key: Handle): void; /** * Verifies a signature in a single-part operation, * where the signature is an appendix to the data, and plaintext * cannot be recovered from the signature * @param session The session's handle * @param inData Incoming data * @param signature Signature to verify * @returns Verification result * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_Verify(session: Handle, inData: Buffer, signature: Buffer): boolean; /** * Verifies a signature in a single-part operation, * where the signature is an appendix to the data, and plaintext * cannot be recovered from the signature * @param session The session's handle * @param inData Incoming data * @param signature Signature to verify * @param cb Async callback with verification result * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_Verify(session: Handle, inData: Buffer, signature: Buffer, cb: (error: Error, verify: boolean) => void): void; /** * Verifies a signature in a single-part operation, * where the signature is an appendix to the data, and plaintext * cannot be recovered from the signature * @param session The session's handle * @param inData Incoming data * @param signature Signature to verify * @returns Verification result * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_VerifyAsync(session: Handle, inData: Buffer, signature: Buffer): Promise<boolean>; /** * Continues a multiple-part verification * operation, where the signature is an appendix to the data, * and plaintext cannot be recovered from the signature * @param session The session's handle * @param inData Incoming data * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_VerifyUpdate(session: Handle, inData: Buffer): void; /** * Finishes a multiple-part verification * operation, checking the signature * @param session The session's handle * @param signature Signature to verify * @returns * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_VerifyFinal(session: Handle, signature: Buffer): boolean; /** * Initializes a signature verification operation, where the data is recovered from the signature * @param session The session's handle * @param mechanism The structure that specifies the verification mechanism * @param key The handle of the verification key * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ C_VerifyRecoverInit(session: Handle, mechanism: Mechanism, key: Handle): void; /** * Verifies a signature in a single-part operation, where the data is recovered from the signature * @param session The session's handle * @param signature The signature to verify * @param outData The allocated buffer for recovered data * @return The sliced output data with recovered data * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ C_VerifyRecover(session: Handle, signature: Buffer, outData: Buffer): Buffer; //#endregion //#region Key management /** * Generates a secret key, creating a new key object * @param session The session's handle * @param mechanism Key generation mechanism * @param template Template for new key * @returns The handle of the new key * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_GenerateKey(session: Handle, mechanism: Mechanism, template: Template): Handle; /** * Generates a secret key, creating a new key object * @param session The session's handle * @param mechanism Key generation mechanism * @param template Template for new key * @param cb Async callback with handle of new key * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_GenerateKey(session: Handle, mechanism: Mechanism, template: Template, cb: (error: Error, key: Handle) => void): void; /** * Generates a secret key, creating a new key object * @param session The session's handle * @param mechanism The key generation mechanism * @param template The template for the new key * @returns The handle of the new key * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_GenerateKeyAsync(session: Handle, mechanism: Mechanism, template: Template): Promise<Handle>; /** * Generates a public-key/private-key pair, * creating new key objects * @param session The session's handle * @param mechanism Key generation mechanism * @param publicTmpl Template for public key * @param privateTmpl Template for private key * @returns The pair of handles for private and public keys * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_GenerateKeyPair(session: Handle, mechanism: Mechanism, publicTmpl: Template, privateTmpl: Template): KeyPair; /** * Generates a public-key/private-key pair, * creating new key objects * @param session The session's handle * @param mechanism Key generation mechanism * @param publicTmpl Template for public key * @param privateTmpl Template for private key * @param cb Async callback with handles for private and public keys * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_GenerateKeyPair(session: Handle, mechanism: Mechanism, publicTmpl: Template, privateTmpl: Template, cb: (error: Error, keys: KeyPair) => void): void; /** * Generates a public-key/private-key pair, * creating new key objects * @param session The session's handle * @param mechanism Key generation mechanism * @param publicTmpl Template for public key * @param privateTmpl Template for private key * @returns Handles for private and public keys * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_GenerateKeyPairAsync(session: Handle, mechanism: Mechanism, publicTmpl: Template, privateTmpl: Template): Promise<KeyPair>; /** * Wraps (i.e., encrypts) a key * @param session The session's handle * @param mechanism Wrapping mechanism * @param wrappingKey Wrapping key * @param key Key to be wrapped * @param wrappedKey Init buffer for wrapped key * @returns Sliced wrapped key * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_WrapKey(session: Handle, mechanism: Mechanism, wrappingKey: Handle, key: Handle, wrappedKey: Buffer): Buffer; /** * Wraps (i.e., encrypts) a key * @param session The session's handle * @param mechanism Wrapping mechanism * @param wrappingKey Wrapping key * @param key Key to be wrapped * @param wrappedKey Init buffer for wrapped key * @param cb Async callback with sliced wrapped key * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_WrapKey(session: Handle, mechanism: Mechanism, wrappingKey: Handle, key: Handle, wrappedKey: Buffer, cb: (error: Error, wrappedKey: Buffer) => void): void; /** * Wraps (i.e., encrypts) a key * @param session The session's handle * @param mechanism Wrapping mechanism * @param wrappingKey Wrapping key * @param key Key to be wrapped * @param wrappedKey Init buffer for wrapped key * @returns Sliced wrapped key * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_WrapKeyAsync(session: Handle, mechanism: Mechanism, wrappingKey: Handle, key: Handle, wrappedKey: Buffer): Promise<Buffer>; /** * Unwraps (decrypts) a wrapped key, creating a new key object * @param session The session's handle * @param mechanism Unwrapping mechanism * @param unwrappingKey Unwrapping key * @param wrappedKey Wrapped key * @param template New key template * @returns The unwrapped key handle * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_UnwrapKey(session: Handle, mechanism: Mechanism, unwrappingKey: Handle, wrappedKey: Buffer, template: Template): Handle; /** * Unwraps (decrypts) a wrapped key, creating a new key object * @param session The session's handle * @param mechanism Unwrapping mechanism * @param unwrappingKey Unwrapping key * @param wrappedKey Wrapped key * @param template New key template * @param cb Async callback with new key handle * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_UnwrapKey(session: Handle, mechanism: Mechanism, unwrappingKey: Handle, wrappedKey: Buffer, template: Template, cb: (error: Error, key: Handle) => void): void; /** * Unwraps (decrypts) a wrapped key, creating a new key object * @param session The session's handle * @param mechanism Unwrapping mechanism * @param unwrappingKey Unwrapping key * @param wrappedKey Wrapped key * @param template New key template * @returns The unwrapped key handle * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_UnwrapKeyAsync(session: Handle, mechanism: Mechanism, unwrappingKey: Handle, wrappedKey: Buffer, template: Template): Promise<Handle>; /** * Derives a key from a base key, creating a new key object * @param session The session's handle * @param mechanism The key derivation mechanism * @param key The base key * @param template The template for the new key * @returns The derived key handle * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_DeriveKey(session: Handle, mechanism: Mechanism, key: Handle, template: Template): Handle; /** * Derives a key from a base key, creating a new key object * @param session The session's handle * @param mechanism The key derivation mechanism * @param key The base key * @param template The template for the new key * @param cb Async callback with the derived key handle * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_DeriveKey(session: Handle, mechanism: Mechanism, key: Handle, template: Template, cb: (error: Error, hKey: Handle) => void): void; /** * Derives a key from a base key, creating a new key object * @param session The session's handle * @param mechanism The key derivation mechanism * @param key The base key * @param template The template for the new key * @returns The derived key handle * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_DeriveKeyAsync(session: Handle, mechanism: Mechanism, key: Handle, template: Template): Promise<Handle>; /** * Mixes additional seed material into the token's random number generator * @param session The session's handle * @param buf The seed material * @returns The seeded data * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_SeedRandom(session: Handle, buf: Buffer): Buffer; /** * Generates random data * @param session The session's handle * @param buf Init buffer * @returns The random data * @throws {@link NativeError} if native error occurs * @throws {@link Pkcs11Error} if Cryptoki error occurs */ public C_GenerateRandom(session: Handle, buf: Buffer): Buffer; //#endregion } //#region Attributes const CKA_CLASS: number; const CKA_TOKEN: number; const CKA_PRIVATE: number; const CKA_LABEL: number; const CKA_APPLICATION: number; const CKA_VALUE: number; const CKA_OBJECT_ID: number; const CKA_CERTIFICATE_TYPE: number; const CKA_ISSUER: number; const CKA_SERIAL_NUMBER: number; const CKA_AC_ISSUER: number; const CKA_OWNER: number; const CKA_ATTR_TYPES: number; const CKA_TRUSTED: number; const CKA_CERTIFICATE_CATEGORY: number; const CKA_JAVA_MIDP_SECURITY_DOMAIN: number; const CKA_URL: number; const CKA_HASH_OF_SUBJECT_PUBLIC_KEY: number; const CKA_HASH_OF_ISSUER_PUBLIC_KEY: number; const CKA_NAME_HASH_ALGORITHM: number; const CKA_CHECK_VALUE: number; const CKA_KEY_TYPE: number; const CKA_SUBJECT: number; const CKA_ID: number; const CKA_SENSITIVE: number; const CKA_ENCRYPT: number; const CKA_DECRYPT: number; const CKA_WRAP: number; const CKA_UNWRAP: number; const CKA_SIGN: number; const CKA_SIGN_RECOVER: number; const CKA_VERIFY: number; const CKA_VERIFY_RECOVER: number; const CKA_DERIVE: number; const CKA_START_DATE: number; const CKA_END_DATE: number; const CKA_MODULUS: number; const CKA_MODULUS_BITS: number; const CKA_PUBLIC_EXPONENT: number; const CKA_PRIVATE_EXPONENT: number; const CKA_PRIME_1: number; const CKA_PRIME_2: number; const CKA_EXPONENT_1: number; const CKA_EXPONENT_2: number; const CKA_COEFFICIENT: number; const CKA_PRIME: number; const CKA_SUBPRIME: number; const CKA_BASE: number; const CKA_PRIME_BITS: number; const CKA_SUBPRIME_BITS: number; const CKA_SUB_PRIME_BITS: number; const CKA_VALUE_BITS: number; const CKA_VALUE_LEN: number; const CKA_EXTRACTABLE: number; const CKA_LOCAL: number; const CKA_NEVER_EXTRACTABLE: number; const CKA_ALWAYS_SENSITIVE: number; const CKA_KEY_GEN_MECHANISM: number; const CKA_MODIFIABLE: number; const CKA_COPYABLE: number; const CKA_DESTROYABLE: number; const CKA_ECDSA_PARAMS: number; const CKA_EC_PARAMS: number; const CKA_EC_POINT: number; const CKA_SECONDARY_AUTH: number; const CKA_AUTH_PIN_FLAGS: number; const CKA_ALWAYS_AUTHENTICATE: number; const CKA_WRAP_WITH_TRUSTED: number; const CKA_WRAP_TEMPLATE: number; const CKA_UNWRAP_TEMPLATE: number; const CKA_DERIVE_TEMPLATE: number; const CKA_OTP_FORMAT: number; const CKA_OTP_LENGTH: number; const CKA_OTP_TIME_INTERVAL: number; const CKA_OTP_USER_FRIENDLY_MODE: number; const CKA_OTP_CHALLENGE_REQUIREMENT: number; const CKA_OTP_TIME_REQUIREMENT: number; const CKA_OTP_COUNTER_REQUIREMENT: number; const CKA_OTP_PIN_REQUIREMENT: number; const CKA_OTP_COUNTER: number; const CKA_OTP_TIME: number; const CKA_OTP_USER_IDENTIFIER: number; const CKA_OTP_SERVICE_IDENTIFIER: number; const CKA_OTP_SERVICE_LOGO: number; const CKA_OTP_SERVICE_LOGO_TYPE: number; const CKA_GOSTR3410_PARAMS: number; const CKA_GOSTR3411_PARAMS: number; const CKA_GOST28147_PARAMS: number; const CKA_HW_FEATURE_TYPE: number; const CKA_RESET_ON_INIT: number; const CKA_HAS_RESET: number; const CKA_PIXEL_X: number; const CKA_PIXEL_Y: number; const CKA_RESOLUTION: number; const CKA_CHAR_ROWS: number; const CKA_CHAR_COLUMNS: number; const CKA_COLOR: number; const CKA_BITS_PER_PIXEL: number; const CKA_CHAR_SETS: number; const CKA_ENCODING_METHODS: number; const CKA_MIME_TYPES: number; const CKA_MECHANISM_TYPE: number; const CKA_REQUIRED_CMS_ATTRIBUTES: number; const CKA_DEFAULT_CMS_ATTRIBUTES: number; const CKA_SUPPORTED_CMS_ATTRIBUTES: number; const CKA_ALLOWED_MECHANISMS: number; const CKA_VENDOR_DEFINED: number; //#endregion //#region Objects const CKO_DATA: number; const CKO_CERTIFICATE: number; const CKO_PUBLIC_KEY: number; const CKO_PRIVATE_KEY: number; const CKO_SECRET_KEY: number; const CKO_HW_FEATURE: number; const CKO_DOMAIN_PARAMETERS: number; const CKO_MECHANISM: number; const CKO_OTP_KEY: number; const CKO_VENDOR_DEFINED: number; //#endregion //#region Key types const CKK_RSA: number; const CKK_DSA: number; const CKK_DH: number; const CKK_ECDSA: number; const CKK_EC: number; const CKK_X9_42_DH: number; const CKK_KEA: number; const CKK_GENERIC_SECRET: number; const CKK_RC2: number; const CKK_RC4: number; const CKK_DES: number; const CKK_DES2: number; const CKK_DES3: number; const CKK_CAST: number; const CKK_CAST3: number; const CKK_CAST5: number; const CKK_CAST128: number; const CKK_RC5: number; const CKK_IDEA: number; const CKK_SKIPJACK: number; const CKK_BATON: number; const CKK_JUNIPER: number; const CKK_CDMF: number; const CKK_AES: number; const CKK_BLOWFISH: number; const CKK_TWOFISH: number; const CKK_SECURID: number; const CKK_HOTP: number; const CKK_ACTI: number; const CKK_CAMELLIA: number; const CKK_ARIA: number; const CKK_MD5_HMAC: number; const CKK_SHA_1_HMAC: number; const CKK_RIPEMD128_HMAC: number; const CKK_RIPEMD160_HMAC: number; const CKK_SHA256_HMAC: number; const CKK_SHA384_HMAC: number; const CKK_SHA512_HMAC: number; const CKK_SHA224_HMAC: number; const CKK_SEED: number; const CKK_GOSTR3410: number; const CKK_GOSTR3411: number; const CKK_GOST28147: number; const CKK_VENDOR_DEFINED: number; //#endregion //#region Mechanisms const CKM_RSA_PKCS_KEY_PAIR_GEN: number; const CKM_RSA_PKCS: number; const CKM_RSA_9796: number; const CKM_RSA_X_509: number; const CKM_MD2_RSA_PKCS: number; const CKM_MD5_RSA_PKCS: number; const CKM_SHA1_RSA_PKCS: number; const CKM_RIPEMD128_RSA_PKCS: number; const CKM_RIPEMD160_RSA_PKCS: number; const CKM_RSA_PKCS_OAEP: number; const CKM_RSA_X9_31_KEY_PAIR_GEN: number; const CKM_RSA_X9_31: number; const CKM_SHA1_RSA_X9_31: number; const CKM_RSA_PKCS_PSS: number; const CKM_SHA1_RSA_PKCS_PSS: number; const CKM_DSA_KEY_PAIR_GEN: number; const CKM_DSA: number; const CKM_DSA_SHA1: number; const CKM_DSA_SHA224: number; const CKM_DSA_SHA256: number; const CKM_DSA_SHA384: number; const CKM_DSA_SHA512: number; const CKM_DH_PKCS_KEY_PAIR_GEN: number; const CKM_DH_PKCS_DERIVE: number; const CKM_X9_42_DH_KEY_PAIR_GEN: number; const CKM_X9_42_DH_DERIVE: number; const CKM_X9_42_DH_HYBRID_DERIVE: number; const CKM_X9_42_MQV_DERIVE: number; const CKM_SHA256_RSA_PKCS: number; const CKM_SHA384_RSA_PKCS: number; const CKM_SHA512_RSA_PKCS: number; const CKM_SHA256_RSA_PKCS_PSS: number; const CKM_SHA384_RSA_PKCS_PSS: number; const CKM_SHA512_RSA_PKCS_PSS: number; const CKM_SHA224_RSA_PKCS: number; const CKM_SHA224_RSA_PKCS_PSS: number; const CKM_RC2_KEY_GEN: number; const CKM_RC2_ECB: number; const CKM_RC2_CBC: number; const CKM_RC2_MAC: number; const CKM_RC2_MAC_GENERAL: number; const CKM_RC2_CBC_PAD: number; const CKM_RC4_KEY_GEN: number; const CKM_RC4: number; const CKM_DES_KEY_GEN: number; const CKM_DES_ECB: number; const CKM_DES_CBC: number; const CKM_DES_MAC: number; const CKM_DES_MAC_GENERAL: number; const CKM_DES_CBC_PAD: number; const CKM_DES2_KEY_GEN: number; const CKM_DES3_KEY_GEN: number; const CKM_DES3_ECB: number; const CKM_DES3_CBC: number; const CKM_DES3_MAC: number; const CKM_DES3_MAC_GENERAL: number; const CKM_DES3_CBC_PAD: number; const CKM_DES3_CMAC_GENERAL: number; const CKM_DES3_CMAC: number; const CKM_CDMF_KEY_GEN: number; const CKM_CDMF_ECB: number; const CKM_CDMF_CBC: number; const CKM_CDMF_MAC: number; const CKM_CDMF_MAC_GENERAL: number; const CKM_CDMF_CBC_PAD: number; const CKM_DES_OFB64: number; const CKM_DES_OFB8: number; const CKM_DES_CFB64: number; const CKM_DES_CFB8: number; const CKM_MD2: number; const CKM_MD2_HMAC: number; const CKM_MD2_HMAC_GENERAL: number; const CKM_MD5: number; const CKM_MD5_HMAC: number; const CKM_MD5_HMAC_GENERAL: number; const CKM_SHA_1: number; const CKM_SHA_1_HMAC: number; const CKM_SHA_1_HMAC_GENERAL: number; const CKM_RIPEMD128: number; const CKM_RIPEMD128_HMAC: number; const CKM_RIPEMD128_HMAC_GENERAL: number; const CKM_RIPEMD160: number; const CKM_RIPEMD160_HMAC: number; const CKM_RIPEMD160_HMAC_GENERAL: number; const CKM_SHA256: number; const CKM_SHA256_HMAC: number; const CKM_SHA256_HMAC_GENERAL: number; const CKM_SHA224: number; const CKM_SHA224_HMAC: number; const CKM_SHA224_HMAC_GENERAL: number; const CKM_SHA384: number; const CKM_SHA384_HMAC: number; const CKM_SHA384_HMAC_GENERAL: number; const CKM_SHA512: number; const CKM_SHA512_HMAC: number; const CKM_SHA512_HMAC_GENERAL: number; const CKM_SECURID_KEY_GEN: number; const CKM_SECURID: number; const CKM_HOTP_KEY_GEN: number; const CKM_HOTP: number; const CKM_ACTI: number; const CKM_ACTI_KEY_GEN: number; const CKM_CAST_KEY_GEN: number; const CKM_CAST_ECB: number; const CKM_CAST_CBC: number; const CKM_CAST_MAC: number; const CKM_CAST_MAC_GENERAL: number; const CKM_CAST_CBC_PAD: number; const CKM_CAST3_KEY_GEN: number; const CKM_CAST3_ECB: number; const CKM_CAST3_CBC: number; const CKM_CAST3_MAC: number; const CKM_CAST3_MAC_GENERAL: number; const CKM_CAST3_CBC_PAD: number; const CKM_CAST5_KEY_GEN: number; const CKM_CAST128_KEY_GEN: number; const CKM_CAST5_ECB: number; const CKM_CAST128_ECB: number; const CKM_CAST5_CBC: number; const CKM_CAST128_CBC: number; const CKM_CAST5_MAC: number; const CKM_CAST128_MAC: number; const CKM_CAST5_MAC_GENERAL: number; const CKM_CAST128_MAC_GENERAL: number; const CKM_CAST5_CBC_PAD: number; const CKM_CAST128_CBC_PAD: number; const CKM_RC5_KEY_GEN: number; const CKM_RC5_ECB: number; const CKM_RC5_CBC: number; const CKM_RC5_MAC: number; const CKM_RC5_MAC_GENERAL: number; const CKM_RC5_CBC_PAD: number; const CKM_IDEA_KEY_GEN: number; const CKM_IDEA_ECB: number; const CKM_IDEA_CBC: number; const CKM_IDEA_MAC: number; const CKM_IDEA_MAC_GENERAL: number; const CKM_IDEA_CBC_PAD: number; const CKM_GENERIC_SECRET_KEY_GEN: number; const CKM_CONCATENATE_BASE_AND_KEY: number; const CKM_CONCATENATE_BASE_AND_DATA: number; const CKM_CONCATENATE_DATA_AND_BASE: number; const CKM_XOR_BASE_AND_DATA: number; const CKM_EXTRACT_KEY_FROM_KEY: number; const CKM_SSL3_PRE_MASTER_KEY_GEN: number; const CKM_SSL3_MASTER_KEY_DERIVE: number; const CKM_SSL3_KEY_AND_MAC_DERIVE: number; const CKM_SSL3_MASTER_KEY_DERIVE_DH: number; const CKM_TLS_PRE_MASTER_KEY_GEN: number; const CKM_TLS_MASTER_KEY_DERIVE: number; const CKM_TLS_KEY_AND_MAC_DERIVE: number; const CKM_TLS_MASTER_KEY_DERIVE_DH: number; const CKM_TLS_PRF: number; const CKM_SSL3_MD5_MAC: number; const CKM_SSL3_SHA1_MAC: number; const CKM_MD5_KEY_DERIVATION: number; const CKM_MD2_KEY_DERIVATION: number; const CKM_SHA1_KEY_DERIVATION: number; const CKM_SHA256_KEY_DERIVATION: number; const CKM_SHA384_KEY_DERIVATION: number; const CKM_SHA512_KEY_DERIVATION: number; const CKM_SHA224_KEY_DERIVATION: number; const CKM_PBE_MD2_DES_CBC: number; const CKM_PBE_MD5_DES_CBC: number; const CKM_PBE_MD5_CAST_CBC: number; const CKM_PBE_MD5_CAST3_CBC: number; const CKM_PBE_MD5_CAST5_CBC: number; const CKM_PBE_MD5_CAST128_CBC: number; const CKM_PBE_SHA1_CAST5_CBC: number; const CKM_PBE_SHA1_CAST128_CBC: number; const CKM_PBE_SHA1_RC4_128: number; const CKM_PBE_SHA1_RC4_40: number; const CKM_PBE_SHA1_DES3_EDE_CBC: number; const CKM_PBE_SHA1_DES2_EDE_CBC: number; const CKM_PBE_SHA1_RC2_128_CBC: number; const CKM_PBE_SHA1_RC2_40_CBC: number; const CKM_PKCS5_PBKD2: number; const CKM_PBA_SHA1_WITH_SHA1_HMAC: number; const CKM_WTLS_PRE_MASTER_KEY_GEN: number; const CKM_WTLS_MASTER_KEY_DERIVE: number; const CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC: number; const CKM_WTLS_PRF: number; const CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE: number; const CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE: number; const CKM_KEY_WRAP_LYNKS: number; const CKM_KEY_WRAP_SET_OAEP: number; const CKM_CAMELLIA_KEY_GEN: number; const CKM_CAMELLIA_ECB: number; const CKM_CAMELLIA_CBC: number; const CKM_CAMELLIA_MAC: number; const CKM_CAMELLIA_MAC_GENERAL: number; const CKM_CAMELLIA_CBC_PAD: number; const CKM_CAMELLIA_ECB_ENCRYPT_DATA: number; const CKM_CAMELLIA_CBC_ENCRYPT_DATA: number; const CKM_CAMELLIA_CTR: number; const CKM_ARIA_KEY_GEN: number; const CKM_ARIA_ECB: number; const CKM_ARIA_CBC: number; const CKM_ARIA_MAC: number; const CKM_ARIA_MAC_GENERAL: number; const CKM_ARIA_CBC_PAD: number; const CKM_ARIA_ECB_ENCRYPT_DATA: number; const CKM_ARIA_CBC_ENCRYPT_DATA: number; const CKM_SEED_KEY_GEN: number; const CKM_SEED_ECB: number; const CKM_SEED_CBC: number; const CKM_SEED_MAC: number; const CKM_SEED_MAC_GENERAL: number; const CKM_SEED_CBC_PAD: number; const CKM_SEED_ECB_ENCRYPT_DATA: number; const CKM_SEED_CBC_ENCRYPT_DATA: number; const CKM_SKIPJACK_KEY_GEN: number; const CKM_SKIPJACK_ECB64: number; const CKM_SKIPJACK_CBC64: number; const CKM_SKIPJACK_OFB64: number; const CKM_SKIPJACK_CFB64: number; const CKM_SKIPJACK_CFB32: number; const CKM_SKIPJACK_CFB16: number; const CKM_SKIPJACK_CFB8: number; const CKM_SKIPJACK_WRAP: number; const CKM_SKIPJACK_PRIVATE_WRAP: number; const CKM_SKIPJACK_RELAYX: number; const CKM_KEA_KEY_PAIR_GEN: number; const CKM_KEA_KEY_DERIVE: number; const CKM_FORTEZZA_TIMESTAMP: number; const CKM_BATON_KEY_GEN: number; const CKM_BATON_ECB128: number; const CKM_BATON_ECB96: number; const CKM_BATON_CBC128: number; const CKM_BATON_COUNTER: number; const CKM_BATON_SHUFFLE: number; const CKM_BATON_WRAP: number; const CKM_ECDSA_KEY_PAIR_GEN: number; const CKM_EC_KEY_PAIR_GEN: number; const CKM_ECDSA: number; const CKM_ECDSA_SHA1: number; const CKM_ECDSA_SHA224: number; const CKM_ECDSA_SHA256: number; const CKM_ECDSA_SHA384: number; const CKM_ECDSA_SHA512: number; const CKM_ECDH1_DERIVE: number; const CKM_ECDH1_COFACTOR_DERIVE: number; const CKM_ECMQV_DERIVE: number; const CKM_JUNIPER_KEY_GEN: number; const CKM_JUNIPER_ECB128: number; const CKM_JUNIPER_CBC128: number; const CKM_JUNIPER_COUNTER: number; const CKM_JUNIPER_SHUFFLE: number; const CKM_JUNIPER_WRAP: number; const CKM_FASTHASH: number; const CKM_AES_KEY_GEN: number; const CKM_AES_ECB: number; const CKM_AES_CBC: number; const CKM_AES_MAC: number; const CKM_AES_MAC_GENERAL: number; const CKM_AES_CBC_PAD: number; const CKM_AES_CTR: number; const CKM_AES_CTS: number; const CKM_AES_CMAC: number; const CKM_AES_CMAC_GENERAL: number; const CKM_BLOWFISH_KEY_GEN: number; const CKM_BLOWFISH_CBC: number; const CKM_TWOFISH_KEY_GEN: number; const CKM_TWOFISH_CBC: number; const CKM_AES_GCM: number; const CKM_AES_CCM: number; const CKM_AES_KEY_WRAP: number; const CKM_AES_KEY_WRAP_PAD: number; const CKM_BLOWFISH_CBC_PAD: number; const CKM_TWOFISH_CBC_PAD: number; const CKM_DES_ECB_ENCRYPT_DATA: number; const CKM_DES_CBC_ENCRYPT_DATA: number; const CKM_DES3_ECB_ENCRYPT_DATA: number; const CKM_DES3_CBC_ENCRYPT_DATA: number; const CKM_AES_ECB_ENCRYPT_DATA: number; const CKM_AES_CBC_ENCRYPT_DATA: number; const CKM_GOSTR3410_KEY_PAIR_GEN: number; const CKM_GOSTR3410: number; const CKM_GOSTR3410_WITH_GOSTR3411: number; const CKM_GOSTR3410_KEY_WRAP: number; const CKM_GOSTR3410_DERIVE: number; const CKM_GOSTR3411: number; const CKM_GOSTR3411_HMAC: number; const CKM_GOST28147_KEY_GEN: number; const CKM_GOST28147_ECB: number; const CKM_GOST28147: number; const CKM_GOST28147_MAC: number; const CKM_GOST28147_KEY_WRAP: number; const CKM_DSA_PARAMETER_GEN: number; const CKM_DH_PKCS_PARAMETER_GEN: number; const CKM_X9_42_DH_PARAMETER_GEN: number; const CKM_AES_OFB: number; const CKM_AES_CFB64: number; const CKM_AES_CFB8: number; const CKM_AES_CFB128: number; const CKM_RSA_PKCS_TPM_1_1: number; const CKM_RSA_PKCS_OAEP_TPM_1_1: number; const CKM_VENDOR_DEFINED: number; //#endregion //#region Session flags const CKF_RW_SESSION: number; const CKF_SERIAL_SESSION: number; //#endregion //#region Follows const CKF_HW: number; const CKF_ENCRYPT: number; const CKF_DECRYPT: number; const CKF_DIGEST: number; const CKF_SIGN: number; const CKF_SIGN_RECOVER: number; const CKF_VERIFY: number; const CKF_VERIFY_RECOVER: number; const CKF_GENERATE: number; const CKF_GENERATE_KEY_PAIR: number; const CKF_WRAP: number; const CKF_UNWRAP: number; const CKF_DERIVE: number; //#endregion //#region Token Information Flags const CKF_RNG: number; const CKF_WRITE_PROTECTED: number; const CKF_LOGIN_REQUIRED: number; const CKF_USER_PIN_INITIALIZED: number; const CKF_RESTORE_KEY_NOT_NEEDED: number; const CKF_CLOCK_ON_TOKEN: number; const CKF_PROTECTED_AUTHENTICATION_PATH: number; const CKF_DUAL_CRYPTO_OPERATIONS: number; const CKF_TOKEN_INITIALIZED: number; const CKF_SECONDARY_AUTHENTICATION: number; const CKF_USER_PIN_COUNT_LOW: number; const CKF_USER_PIN_FINAL_TRY: number; const CKF_USER_PIN_LOCKED: number; const CKF_USER_PIN_TO_BE_CHANGED: number; const CKF_SO_PIN_COUNT_LOW: number; const CKF_SO_PIN_FINAL_TRY: number; const CKF_SO_PIN_LOCKED: number; const CKF_SO_PIN_TO_BE_CHANGED: number; const CKF_ERROR_STATE: number; //#endregion //#region Certificates const CKC_X_509: number; const CKC_X_509_ATTR_CERT: number; const CKC_WTLS: number; //#endregion //#region MGFs const CKG_MGF1_SHA1: number; const CKG_MGF1_SHA256: number; const CKG_MGF1_SHA384: number; const CKG_MGF1_SHA512: number; const CKG_MGF1_SHA224: number; //#endregion //#region KDFs const CKD_NULL: number; const CKD_SHA1_KDF: number; const CKD_SHA1_KDF_ASN1: number; const CKD_SHA1_KDF_CONCATENATE: number; const CKD_SHA224_KDF: number; const CKD_SHA256_KDF: number; const CKD_SHA384_KDF: number; const CKD_SHA512_KDF: number; const CKD_CPDIVERSIFY_KDF: number; //#endregion //#region Mech params const CK_PARAMS_AES_CBC: number; const CK_PARAMS_AES_CCM: number; const CK_PARAMS_AES_GCM: number; const CK_PARAMS_RSA_OAEP: number; const CK_PARAMS_RSA_PSS: number; const CK_PARAMS_EC_DH: number; const CK_PARAMS_AES_GCM_v240: number; //#endregion //#region User types const CKU_SO: number; const CKU_USER: number; const CKU_CONTEXT_SPECIFIC: number; //#endregion // Initialize flags const CKF_LIBRARY_CANT_CREATE_OS_THREADS: number; const CKF_OS_LOCKING_OK: number; //#region Result values const CKR_OK: number; const CKR_CANCEL: number; const CKR_HOST_MEMORY: number; const CKR_SLOT_ID_INVALID: number; const CKR_GENERAL_ERROR: number; const CKR_FUNCTION_FAILED: number; const CKR_ARGUMENTS_BAD: number; const CKR_NO_EVENT: number; const CKR_NEED_TO_CREATE_THREADS: number; const CKR_CANT_LOCK: number; const CKR_ATTRIBUTE_READ_ONLY: number; const CKR_ATTRIBUTE_SENSITIVE: number; const CKR_ATTRIBUTE_TYPE_INVALID: number; const CKR_ATTRIBUTE_VALUE_INVALID: number; const CKR_DATA_INVALID: number; const CKR_DATA_LEN_RANGE: number; const CKR_DEVICE_ERROR: number; const CKR_DEVICE_MEMORY: number; const CKR_DEVICE_REMOVED: number; const CKR_ENCRYPTED_DATA_INVALID: number; const CKR_ENCRYPTED_DATA_LEN_RANGE: number; const CKR_FUNCTION_CANCELED: number; const CKR_FUNCTION_NOT_PARALLEL: number; const CKR_FUNCTION_NOT_SUPPORTED: number; const CKR_KEY_HANDLE_INVALID: number; const CKR_KEY_SIZE_RANGE: number; const CKR_KEY_TYPE_INCONSISTENT: number; const CKR_KEY_NOT_NEEDED: number; const CKR_KEY_CHANGED: number; const CKR_KEY_NEEDED: number; const CKR_KEY_INDIGESTIBLE: number; const CKR_KEY_FUNCTION_NOT_PERMITTED: number; const CKR_KEY_NOT_WRAPPABLE: number; const CKR_KEY_UNEXTRACTABLE: number; const CKR_MECHANISM_INVALID: number; const CKR_MECHANISM_PARAM_INVALID: number; const CKR_OBJECT_HANDLE_INVALID: number; const CKR_OPERATION_ACTIVE: number; const CKR_OPERATION_NOT_INITIALIZED: number; const CKR_PIN_INCORRECT: number; const CKR_PIN_INVALID: number; const CKR_PIN_LEN_RANGE: number; const CKR_PIN_EXPIRED: number; const CKR_PIN_LOCKED: number; const CKR_SESSION_CLOSED: number; const CKR_SESSION_COUNT: number; const CKR_SESSION_HANDLE_INVALID: number; const CKR_SESSION_PARALLEL_NOT_SUPPORTED: number; const CKR_SESSION_READ_ONLY: number; const CKR_SESSION_EXISTS: number; const CKR_SESSION_READ_ONLY_EXISTS: number; const CKR_SESSION_READ_WRITE_SO_EXISTS: number; const CKR_SIGNATURE_INVALID: number; const CKR_SIGNATURE_LEN_RANGE: number; const CKR_TEMPLATE_INCOMPLETE: number; const CKR_TEMPLATE_INCONSISTENT: number; const CKR_TOKEN_NOT_PRESENT: number; const CKR_TOKEN_NOT_RECOGNIZED: number; const CKR_TOKEN_WRITE_PROTECTED: number; const CKR_UNWRAPPING_KEY_HANDLE_INVALID: number; const CKR_UNWRAPPING_KEY_SIZE_RANGE: number; const CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT: number; const CKR_USER_ALREADY_LOGGED_IN: number; const CKR_USER_NOT_LOGGED_IN: number; const CKR_USER_PIN_NOT_INITIALIZED: number; const CKR_USER_TYPE_INVALID: number; const CKR_USER_ANOTHER_ALREADY_LOGGED_IN: number; const CKR_USER_TOO_MANY_TYPES: number; const CKR_WRAPPED_KEY_INVALID: number; const CKR_WRAPPED_KEY_LEN_RANGE: number; const CKR_WRAPPING_KEY_HANDLE_INVALID: number; const CKR_WRAPPING_KEY_SIZE_RANGE: number; const CKR_WRAPPING_KEY_TYPE_INCONSISTENT: number; const CKR_RANDOM_SEED_NOT_SUPPORTED: number; const CKR_RANDOM_NO_RNG: number; const CKR_DOMAIN_PARAMS_INVALID: number; const CKR_BUFFER_TOO_SMALL: number; const CKR_SAVED_STATE_INVALID: number; const CKR_INFORMATION_SENSITIVE: number; const CKR_STATE_UNSAVEABLE: number; const CKR_CRYPTOKI_NOT_INITIALIZED: number; const CKR_CRYPTOKI_ALREADY_INITIALIZED: number; const CKR_MUTEX_BAD: number; const CKR_MUTEX_NOT_LOCKED: number; const CKR_NEW_PIN_MODE: number; const CKR_NEXT_OTP: number; const CKR_EXCEEDED_MAX_ITERATIONS: number; const CKR_FIPS_SELF_TEST_FAILED: number; const CKR_LIBRARY_LOAD_FAILED: number; const CKR_PIN_TOO_WEAK: number; const CKR_PUBLIC_KEY_INVALID: number; const CKR_FUNCTION_REJECTED: number; //#endregion /** * Exception from native module */ class NativeError extends Error { /** * Native library call stack. Default is empty string */ public readonly nativeStack: string; /** * Native function name. Default is empty string */ public readonly method: string; /** * Initialize new instance of NativeError * @param message Error message */ public constructor(message?: string, method?: string); } /** * Exception with the name and value of PKCS#11 return value */ class Pkcs11Error extends NativeError { /** * PKCS#11 result value. Default is 0 */ public readonly code: number; /** * Initialize new instance of Pkcs11Error * @param message Error message * @param code PKCS#11 result value * @param method The name of PKCS#11 method */ public constructor(message?: string, code?: number, method?: string); } }
the_stack
import { CloudErrorMapper, BaseResourceMapper } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export const CloudError = CloudErrorMapper; export const BaseResource = BaseResourceMapper; export const Result: msRest.CompositeMapper = { serializedName: "Result", type: { name: "Composite", className: "Result", modelProperties: { sampleProperty: { serializedName: "sampleProperty", type: { name: "String" } } } } }; export const ErrorDefinition: msRest.CompositeMapper = { serializedName: "ErrorDefinition", type: { name: "Composite", className: "ErrorDefinition", modelProperties: { code: { required: true, serializedName: "code", type: { name: "String" } }, message: { required: true, serializedName: "message", type: { name: "String" } } } } }; export const ErrorResponse: msRest.CompositeMapper = { serializedName: "ErrorResponse", type: { name: "Composite", className: "ErrorResponse", modelProperties: { error: { serializedName: "error", type: { name: "Composite", className: "ErrorDefinition" } } } } }; export const ComplianceStatus: msRest.CompositeMapper = { serializedName: "ComplianceStatus", type: { name: "Composite", className: "ComplianceStatus", modelProperties: { complianceState: { readOnly: true, serializedName: "complianceState", type: { name: "String" } }, lastConfigApplied: { serializedName: "lastConfigApplied", type: { name: "DateTime" } }, message: { serializedName: "message", type: { name: "String" } }, messageLevel: { serializedName: "messageLevel", type: { name: "String" } } } } }; export const HelmOperatorProperties: msRest.CompositeMapper = { serializedName: "HelmOperatorProperties", type: { name: "Composite", className: "HelmOperatorProperties", modelProperties: { chartVersion: { serializedName: "chartVersion", type: { name: "String" } }, chartValues: { serializedName: "chartValues", type: { name: "String" } } } } }; export const SystemData: msRest.CompositeMapper = { serializedName: "systemData", type: { name: "Composite", className: "SystemData", modelProperties: { createdBy: { serializedName: "createdBy", type: { name: "String" } }, createdByType: { serializedName: "createdByType", type: { name: "String" } }, createdAt: { serializedName: "createdAt", type: { name: "DateTime" } }, lastModifiedBy: { serializedName: "lastModifiedBy", type: { name: "String" } }, lastModifiedByType: { serializedName: "lastModifiedByType", type: { name: "String" } }, lastModifiedAt: { serializedName: "lastModifiedAt", type: { name: "DateTime" } } } } }; export const Resource: msRest.CompositeMapper = { serializedName: "Resource", type: { name: "Composite", className: "Resource", modelProperties: { id: { readOnly: true, serializedName: "id", type: { name: "String" } }, name: { readOnly: true, serializedName: "name", type: { name: "String" } }, type: { readOnly: true, serializedName: "type", type: { name: "String" } } } } }; export const ProxyResource: msRest.CompositeMapper = { serializedName: "ProxyResource", type: { name: "Composite", className: "ProxyResource", modelProperties: { ...Resource.type.modelProperties } } }; export const SourceControlConfiguration: msRest.CompositeMapper = { serializedName: "SourceControlConfiguration", type: { name: "Composite", className: "SourceControlConfiguration", modelProperties: { ...ProxyResource.type.modelProperties, repositoryUrl: { serializedName: "properties.repositoryUrl", type: { name: "String" } }, operatorNamespace: { serializedName: "properties.operatorNamespace", defaultValue: 'default', type: { name: "String" } }, operatorInstanceName: { serializedName: "properties.operatorInstanceName", type: { name: "String" } }, operatorType: { serializedName: "properties.operatorType", type: { name: "String" } }, operatorParams: { serializedName: "properties.operatorParams", type: { name: "String" } }, configurationProtectedSettings: { serializedName: "properties.configurationProtectedSettings", type: { name: "Dictionary", value: { type: { name: "String" } } } }, operatorScope: { serializedName: "properties.operatorScope", defaultValue: 'cluster', type: { name: "String" } }, repositoryPublicKey: { readOnly: true, serializedName: "properties.repositoryPublicKey", type: { name: "String" } }, sshKnownHostsContents: { serializedName: "properties.sshKnownHostsContents", type: { name: "String" } }, enableHelmOperator: { serializedName: "properties.enableHelmOperator", type: { name: "Boolean" } }, helmOperatorProperties: { serializedName: "properties.helmOperatorProperties", type: { name: "Composite", className: "HelmOperatorProperties" } }, provisioningState: { readOnly: true, serializedName: "properties.provisioningState", type: { name: "String" } }, complianceStatus: { readOnly: true, serializedName: "properties.complianceStatus", type: { name: "Composite", className: "ComplianceStatus" } }, systemData: { serializedName: "systemData", type: { name: "Composite", className: "SystemData" } } } } }; export const ResourceProviderOperationDisplay: msRest.CompositeMapper = { serializedName: "ResourceProviderOperation_display", type: { name: "Composite", className: "ResourceProviderOperationDisplay", modelProperties: { provider: { serializedName: "provider", type: { name: "String" } }, resource: { serializedName: "resource", type: { name: "String" } }, operation: { serializedName: "operation", type: { name: "String" } }, description: { serializedName: "description", type: { name: "String" } } } } }; export const ResourceProviderOperation: msRest.CompositeMapper = { serializedName: "ResourceProviderOperation", type: { name: "Composite", className: "ResourceProviderOperation", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, display: { serializedName: "display", type: { name: "Composite", className: "ResourceProviderOperationDisplay" } }, isDataAction: { readOnly: true, serializedName: "isDataAction", type: { name: "Boolean" } } } } }; export const TrackedResource: msRest.CompositeMapper = { serializedName: "TrackedResource", type: { name: "Composite", className: "TrackedResource", modelProperties: { ...Resource.type.modelProperties, tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } }, location: { required: true, serializedName: "location", type: { name: "String" } } } } }; export const AzureEntityResource: msRest.CompositeMapper = { serializedName: "AzureEntityResource", type: { name: "Composite", className: "AzureEntityResource", modelProperties: { ...Resource.type.modelProperties, etag: { readOnly: true, serializedName: "etag", type: { name: "String" } } } } }; export const SourceControlConfigurationList: msRest.CompositeMapper = { serializedName: "SourceControlConfigurationList", type: { name: "Composite", className: "SourceControlConfigurationList", modelProperties: { value: { readOnly: true, serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "SourceControlConfiguration" } } } }, nextLink: { readOnly: true, serializedName: "nextLink", type: { name: "String" } } } } }; export const ResourceProviderOperationList: msRest.CompositeMapper = { serializedName: "ResourceProviderOperationList", type: { name: "Composite", className: "ResourceProviderOperationList", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "ResourceProviderOperation" } } } }, nextLink: { readOnly: true, serializedName: "nextLink", type: { name: "String" } } } } };
the_stack
import { render } from '@testing-library/react'; import React from 'react'; import { ToasterContainer } from 'baseui/toast'; import configureStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import cloneDeep from 'lodash/cloneDeep'; import flatten from 'lodash/flatten'; import { importJson } from '../processors/import'; import { Accessors } from '../types'; import * as Json from './constants/positive/json'; import { importJsonData } from '../thunk'; import { resetState } from '../../import/fileUpload/slice'; import { combineGraphs } from '../../../utils/graph-utils/utils'; import * as GraphSlice from '../slice'; import * as UiSlice from '../../ui/slice'; import * as GraphThunk from '../thunk'; const mockStore = configureStore([thunk]); const getStore = () => { const graphState = cloneDeep(GraphSlice.initialState); const store = { investigate: { ui: {}, widget: {}, graph: { present: graphState, }, }, }; return store; }; describe('Import JSON', () => { let store; beforeEach(() => { render(<ToasterContainer />); store = mockStore(getStore()); }); afterEach(() => { store.clearActions(); }); describe('Normal Import', () => { it('should determine whether graph possess duplicate connectivity', async (done) => { // arrange const importDataArr = [Json.simpleGraphWithGroupEdge]; const groupEdgeToggle = false; // act const batchDataPromises = importDataArr.map((graphData) => { const { data } = graphData; return importJson( data, GraphSlice.initialState.accessors, groupEdgeToggle, ); }); const graphDataArr = await Promise.all(batchDataPromises); const [firstGraphData] = flatten(graphDataArr); // group edge configuration arrangements const groupEdgeConfig = { availability: true, toggle: groupEdgeToggle, }; firstGraphData.metadata.groupEdges = groupEdgeConfig; // expected results const expectedActions = [ UiSlice.fetchBegin(), GraphSlice.addQuery([firstGraphData]), GraphSlice.processGraphResponse({ data: firstGraphData, accessors: GraphSlice.initialState.accessors, }), UiSlice.updateToast('toast-0'), resetState(), UiSlice.clearError(), UiSlice.fetchDone(), UiSlice.closeModal(), ]; const executions = GraphThunk.importJsonData( importDataArr as any, groupEdgeToggle, GraphSlice.initialState.accessors, ) as any; // assertions return store.dispatch(executions).then(() => { setTimeout(() => { expect(store.getActions()).toEqual(expectedActions); done(); }, 50); }); }); it('should process custom accessors with numeric values accurately', async (done) => { const importDataArr = [Json.simpleGraphThree]; const groupEdgeToggle = false; const customAccessors: Accessors = { nodeID: 'custom_id', edgeID: 'id', edgeSource: 'custom_source', edgeTarget: 'custom_target', }; // processes const batchDataPromises = importDataArr.map((graphData) => { const { data } = graphData; return importJson(data as any, customAccessors, groupEdgeToggle); }); const graphDataArr = await Promise.all(batchDataPromises); const [graphData] = flatten(graphDataArr); // group edge configuration arrangements const groupEdgeConfig = { availability: false, toggle: groupEdgeToggle }; Object.assign(graphData.metadata.groupEdges, groupEdgeConfig); const expectedActions = [ UiSlice.fetchBegin(), GraphSlice.addQuery([graphData]), GraphSlice.processGraphResponse({ data: graphData, accessors: customAccessors, }), UiSlice.updateToast('toast-0'), resetState(), UiSlice.clearError(), UiSlice.fetchDone(), UiSlice.closeModal(), ]; return store .dispatch( importJsonData( importDataArr as any, groupEdgeToggle, customAccessors, ), ) .then(() => { setTimeout(() => { expect(store.getActions()).toEqual(expectedActions); done(); }, 50); }); }); it('should receive array of importData and process graph responses accurately', async (done) => { // input const importDataArr = [Json.jsonDataOne, Json.jsonDataTwo]; const groupEdgeToggle = false; // processes const batchDataPromises = importDataArr.map((graphData) => { const { data } = graphData; return importJson( data as any, GraphSlice.initialState.accessors, groupEdgeToggle, ); }); const graphDataArr = await Promise.all(batchDataPromises); const [firstGraphData, secondGraphData] = flatten(graphDataArr); // group edge configuration arrangements const groupEdgeConfig = { availability: false, toggle: groupEdgeToggle }; Object.assign(firstGraphData.metadata.groupEdges, groupEdgeConfig); Object.assign(secondGraphData.metadata.groupEdges, groupEdgeConfig); const combinedGraph = combineGraphs([firstGraphData, secondGraphData]); // expected results const expectedActions = [ UiSlice.fetchBegin(), GraphSlice.addQuery([firstGraphData, secondGraphData]), GraphSlice.processGraphResponse({ data: combinedGraph, accessors: GraphSlice.initialState.accessors, }), UiSlice.updateToast('toast-0'), resetState(), UiSlice.clearError(), UiSlice.fetchDone(), UiSlice.closeModal(), ]; // assertions return store .dispatch( importJsonData( importDataArr as any, groupEdgeToggle, GraphSlice.initialState.accessors, ), ) .then(() => { setTimeout(() => { expect(store.getActions()).toEqual(expectedActions); done(); }, 50); }); }); it('should display different success message in toast with existing filter applied', async (done) => { const currentStore = getStore(); Object.assign(currentStore.investigate.graph.present.filterOptions, { value: 'something', }); const modifiedStore = mockStore(currentStore) as any; // input const importDataArr = [Json.jsonDataOne, Json.jsonDataTwo]; const groupEdgeToggle = false; // processes const batchDataPromises = importDataArr.map((graphData) => { const { data } = graphData; return importJson( data as any, GraphSlice.initialState.accessors, groupEdgeToggle, ); }); const graphDataArr = await Promise.all(batchDataPromises); const [firstGraphData, secondGraphData] = flatten(graphDataArr); // group edge configuration arrangements const groupEdgeConfig = { availability: false, toggle: groupEdgeToggle }; firstGraphData.metadata.groupEdges = groupEdgeConfig; secondGraphData.metadata.groupEdges = groupEdgeConfig; const mergedGraph = combineGraphs([firstGraphData, secondGraphData]); // expected results const expectedActions = [ UiSlice.fetchBegin(), GraphSlice.addQuery([firstGraphData, secondGraphData]), GraphSlice.processGraphResponse({ data: mergedGraph, accessors: GraphSlice.initialState.accessors, }), UiSlice.updateToast('toast-0'), resetState(), UiSlice.clearError(), UiSlice.fetchDone(), UiSlice.closeModal(), ]; // @ts-ignore return modifiedStore .dispatch( importJsonData( importDataArr as any, groupEdgeToggle, GraphSlice.initialState.accessors, ), ) .then(() => { setTimeout(() => { expect(modifiedStore.getActions()).toEqual(expectedActions); done(); }, 300); }); }); it('should import successfully without metadata', async (done) => { const graphWithoutMetadata = Json.simpleGraphOne; delete graphWithoutMetadata.data.metadata; const groupEdgeToggle = false; const importDataArr = [graphWithoutMetadata]; // processes const batchDataPromises = importDataArr.map((graphData) => { const { data } = graphData; return importJson( data as any, GraphSlice.initialState.accessors, groupEdgeToggle, ); }); const graphDataArr = await Promise.all(batchDataPromises); const [graphData] = flatten(graphDataArr); // group edge configuration arrangements const groupEdgeConfig = { availability: false, toggle: groupEdgeToggle, }; graphData.metadata.groupEdges = groupEdgeConfig; // expected results const expectedActions = [ UiSlice.fetchBegin(), GraphSlice.addQuery([graphData]), GraphSlice.processGraphResponse({ data: graphData, accessors: GraphSlice.initialState.accessors, }), UiSlice.updateToast('toast-0'), resetState(), UiSlice.clearError(), UiSlice.fetchDone(), UiSlice.closeModal(), ]; // assertions await store.dispatch( importJsonData( importDataArr as any, groupEdgeToggle, GraphSlice.initialState.accessors, ), ); setTimeout(() => { expect(store.getActions()).toEqual(expectedActions); done(); }, 300); }); it('should import with single file contains two graph lists', async (done) => { // input const importDataArr = [Json.simpleGraphTwo]; const groupEdgeToggle = false; // processes const batchDataPromises = importDataArr.map((graphData) => { const { data } = graphData; return importJson( data, GraphSlice.initialState.accessors, groupEdgeToggle, ); }); const graphDataArr = await Promise.all(batchDataPromises); const [firstGraphData, secondGraphData] = flatten(graphDataArr); // group edge configuration arrangements const groupEdgeConfig = { availability: false, toggle: groupEdgeToggle, }; firstGraphData.metadata.groupEdges = groupEdgeConfig; secondGraphData.metadata.groupEdges = groupEdgeConfig; const mergedGraph = combineGraphs([firstGraphData, secondGraphData]); // expected results const expectedActions = [ UiSlice.fetchBegin(), GraphSlice.addQuery([firstGraphData, secondGraphData]), GraphSlice.processGraphResponse({ data: mergedGraph, accessors: GraphSlice.initialState.accessors, }), UiSlice.updateToast('toast-0'), resetState(), UiSlice.clearError(), UiSlice.fetchDone(), UiSlice.closeModal(), ]; // assertions return store .dispatch( importJsonData( importDataArr as any, groupEdgeToggle, GraphSlice.initialState.accessors, ), ) .then(() => { setTimeout(() => { expect(store.getActions()).toEqual(expectedActions); done(); }, 300); }); }); it('should import with two files contain three graph lists', async (done) => { // input const importDataArr = [Json.simpleGraphOne, Json.simpleGraphTwo]; const groupEdgeToggle = false; // processes const batchDataPromises = importDataArr.map((graphData) => { const { data } = graphData; return importJson( data, GraphSlice.initialState.accessors, groupEdgeToggle, ); }); const graphDataArr = await Promise.all(batchDataPromises); const [firstGraphData, secondGraphData, thirdGraphData] = flatten(graphDataArr); // group edge configuration arrangements const groupEdgeConfig = { availability: false, toggle: groupEdgeToggle, }; firstGraphData.metadata.groupEdges = groupEdgeConfig; secondGraphData.metadata.groupEdges = groupEdgeConfig; thirdGraphData.metadata.groupEdges = groupEdgeConfig; const mergedGraph = combineGraphs([ firstGraphData, secondGraphData, thirdGraphData, ]); // expected results const expectedActions = [ UiSlice.fetchBegin(), GraphSlice.addQuery([firstGraphData, secondGraphData, thirdGraphData]), GraphSlice.processGraphResponse({ data: mergedGraph, accessors: GraphSlice.initialState.accessors, }), UiSlice.updateToast('toast-0'), resetState(), UiSlice.clearError(), UiSlice.fetchDone(), UiSlice.closeModal(), ]; // assertions return store .dispatch( importJsonData( importDataArr as any, groupEdgeToggle, GraphSlice.initialState.accessors, ), ) .then(() => { setTimeout(() => { expect(store.getActions()).toEqual(expectedActions); done(); }, 300); }); }); }); describe('Style Override Imports', () => { it('should overwrite styles with the last file', async (done) => { // input const importDataArr = [Json.jsonDataOne, Json.jsonDataTwo]; let { styleOptions } = GraphSlice.initialState; const groupEdgeToggle = false; // processes const batchDataPromises = importDataArr.map((graphData) => { const { data, style } = graphData as any; if (style) { styleOptions = style; } return importJson( data, GraphSlice.initialState.accessors, groupEdgeToggle, ); }); const graphDataArr = await Promise.all(batchDataPromises); const [firstGraphData, secondGraphData] = flatten(graphDataArr); // group edge configuration arrangements const groupEdgeConfig = { availability: false, toggle: groupEdgeToggle }; firstGraphData.metadata.groupEdges = groupEdgeConfig; secondGraphData.metadata.groupEdges = groupEdgeConfig; const mergedGraph = combineGraphs([firstGraphData, secondGraphData]); // expected results const expectedActions = [ UiSlice.fetchBegin(), GraphSlice.updateStyleOption(styleOptions), GraphSlice.addQuery([firstGraphData, secondGraphData]), GraphSlice.processGraphResponse({ data: mergedGraph, accessors: GraphSlice.initialState.accessors, }), UiSlice.updateToast('toast-0'), resetState(), UiSlice.clearError(), UiSlice.fetchDone(), UiSlice.closeModal(), ]; // assertions return store .dispatch( importJsonData( importDataArr as any, groupEdgeToggle, GraphSlice.initialState.accessors, true, ), ) .then(() => { setTimeout(() => { expect(store.getActions()).toEqual(expectedActions); done(); }, 300); }); }); it('should not overwrite styles if data has no style', async (done) => { // input const jsonOneWithoutStyle = { data: Json.jsonDataOne.data, }; const jsonTwoWithoutStyle = { data: Json.jsonDataTwo.data, }; const groupEdgeToggle = false; const importDataArr = [jsonOneWithoutStyle, jsonTwoWithoutStyle]; // eslint-disable-next-line @typescript-eslint/no-unused-vars-experimental let { styleOptions } = GraphSlice.initialState; // processes const batchDataPromises = importDataArr.map((graphData) => { const { data, style } = graphData as any; if (style) { styleOptions = style; } return importJson( data, GraphSlice.initialState.accessors, groupEdgeToggle, ); }); const graphDataArr = await Promise.all(batchDataPromises); const [firstGraphData, secondGraphData] = flatten(graphDataArr); // group edge configuration arrangements const groupEdgeConfig = { availability: false, toggle: groupEdgeToggle }; firstGraphData.metadata.groupEdges = groupEdgeConfig; secondGraphData.metadata.groupEdges = groupEdgeConfig; const mergedGraph = combineGraphs([firstGraphData, secondGraphData]); // expected results const expectedActions = [ UiSlice.fetchBegin(), GraphSlice.addQuery([firstGraphData, secondGraphData]), GraphSlice.processGraphResponse({ data: mergedGraph, accessors: GraphSlice.initialState.accessors, }), UiSlice.updateToast('toast-0'), resetState(), UiSlice.clearError(), UiSlice.fetchDone(), UiSlice.closeModal(), ]; // assertions return store .dispatch( importJsonData( importDataArr as any, groupEdgeToggle, GraphSlice.initialState.accessors, true, ), ) .then(() => { setTimeout(() => { expect(store.getActions()).toEqual(expectedActions); done(); }, 300); }); }); }); describe('Import With Filters', () => { it('should override both filter and style attributes', async (done) => { const groupEdgeToggle = false; const importDataArr = [Json.graphWithFilter]; // eslint-disable-next-line @typescript-eslint/no-unused-vars-experimental let { styleOptions, filterOptions } = GraphSlice.initialState; // processes const batchDataPromises = importDataArr.map((graphData) => { const { data, style, filter } = graphData as any; if (style) { styleOptions = style; } if (filter) { filterOptions = filter; } return importJson( data, GraphSlice.initialState.accessors, groupEdgeToggle, ); }); const graphDataArr = await Promise.all(batchDataPromises); const [firstGraphData] = flatten(graphDataArr); // group edge configuration arrangements const groupEdgeConfig = { availability: false, toggle: groupEdgeToggle }; firstGraphData.metadata.groupEdges = groupEdgeConfig; const mergedGraph = combineGraphs([firstGraphData]); // expected results const expectedActions = [ UiSlice.fetchBegin(), GraphSlice.updateStyleOption(styleOptions), GraphSlice.updateFilterOption(filterOptions), GraphSlice.addQuery([firstGraphData]), GraphSlice.processGraphResponse({ data: mergedGraph, accessors: GraphSlice.initialState.accessors, }), UiSlice.updateToast('toast-0'), resetState(), UiSlice.clearError(), UiSlice.fetchDone(), UiSlice.closeModal(), ]; // assertions return store .dispatch( importJsonData( importDataArr as any, groupEdgeToggle, GraphSlice.initialState.accessors, true, ), ) .then(() => { setTimeout(() => { expect(store.getActions()).toEqual(expectedActions); done(); }, 300); }); }); }); });
the_stack
import test from 'ava'; import * as args from './testArgs'; import { cleanUpPromise } from './helper'; import { Nohm, NohmModel, TTypedDefinitions, ValidationError } from '../ts'; import { integerProperty, IPropertyDiff, stringProperty, } from '../ts/model.header'; const nohm = Nohm; const redis = args.redis; /* * This file tests a bunch of Stuff for Typescript just by being compiled in addition to * being included in the nodeunit tests. */ interface IUserLinkProps { name: string; test: string; number: number; } // tslint:disable:max-classes-per-file class UserMockup extends NohmModel<IUserLinkProps> { public static modelName = 'UserMockup'; public publish = true; protected static idGenerator = 'increment'; protected static definitions = { name: { defaultValue: 'defaultName', type: stringProperty, validations: ['notEmpty'], }, number: { defaultValue: 123, type: integerProperty, validations: ['notEmpty'], }, test: { defaultValue: 'defaultTest', type: stringProperty, validations: ['notEmpty'], }, }; public testMethodTypecheck( _arg1: string, _arg2: number, ): undefined | string | (() => any) { return this.options.idGenerator; } } const userMockupClass = nohm.register(UserMockup); interface ICommentProps { text: string; } const commentMockup = nohm.register( class extends NohmModel<ICommentProps> { public static modelName = 'CommentMockup'; protected static definitions: TTypedDefinitions<ICommentProps> = { text: { defaultValue: 'defaultComment', type: 'string', validations: ['notEmpty'], }, }; get pName(): string { return this.allProperties().text; } set pName(value: string) { this.property('text', value); } }, ); interface IRoleLinkProps { name: string; } class RoleLinkMockup extends NohmModel<IRoleLinkProps> { public static modelName = 'RoleLinkMockup'; protected static definitions: TTypedDefinitions<IRoleLinkProps> = { name: { defaultValue: 'admin', type: 'string', }, }; get pName(): string { return this.allProperties().name; } } const roleLinkMockup = nohm.register(RoleLinkMockup); const prefix = args.prefix + 'typescript'; test.before(async () => { nohm.setPrefix(prefix); await args.setClient(nohm, redis); await cleanUpPromise(redis, prefix); }); test.afterEach(async () => { await cleanUpPromise(redis, prefix); }); test.serial('static methods', async (t) => { interface IAdditionalMethods { test1(): Promise<boolean>; test2(player: any): Promise<void>; } const simpleModel = nohm.model<IAdditionalMethods>( 'SimpleModelRegistration', { properties: { name: { defaultValue: 'simple', type: 'string', }, }, // tslint:disable-next-line:object-literal-sort-keys methods: { test1(): Promise<boolean> { return this.validate(); }, async test2(player: any) { await this.save(); this.link(player, 'leader'); this.link(player); }, }, }, ); t.is( typeof commentMockup.findAndLoad, 'function', 'findAndLoad was not set on commentMockup', ); t.is( typeof commentMockup.sort, 'function', 'findAndLoad was not set on commentMockup', ); t.is( typeof commentMockup.find, 'function', 'findAndLoad was not set on commentMockup', ); t.is( typeof simpleModel.findAndLoad, 'function', 'findAndLoad was not set on commentMockup', ); t.is( typeof simpleModel.sort, 'function', 'findAndLoad was not set on commentMockup', ); t.is( typeof simpleModel.find, 'function', 'findAndLoad was not set on commentMockup', ); const testInstance = new simpleModel(); testInstance.test1(); }); test.serial('instances', async (t) => { const comment = new commentMockup(); const user = await nohm.factory<UserMockup>('UserMockup'); try { const role = new RoleLinkMockup(); // do something with role so it doesn't cause a compile error await role.remove(); t.fail('Directly constructing a class did not throw an error.'); } catch (err) { t.is( err.message, 'Class is not extended properly. Use the return Nohm.register() instead of your class directly.', 'Directly constructing a class did not throw the correct error.', ); } t.is( comment.property('text'), 'defaultComment', 'Getting property text of comment failed', ); t.is( user.property('test'), 'defaultTest', 'Getting property test of user failed', ); t.is( user.allProperties().name, 'defaultName', 'Getting allProperties().name of user failed', ); t.is(await user.validate(), true, 'Checking validity failed'); t.deepEqual(user.errors.name, [], 'Error was set?'); await user.save(); const users = await userMockupClass.findAndLoad<UserMockup>({}); const numbers: Array<number> = users.map((x) => x.property('number')); t.deepEqual(numbers, [123]); }); test.serial( 'method declaration is type checked & idGenerator set from static', async (t) => { const testInstance = await nohm.factory<UserMockup>('UserMockup'); const idGenerator: | undefined | string | (() => any) = testInstance.testMethodTypecheck('asd', 123); t.is(idGenerator, 'increment', 'The type check method returned false.'); }, ); test.serial('typing in property()', async (t) => { const user = await nohm.factory<UserMockup>('UserMockup'); const name: string = user.property('name'); const num: number = user.property('number', 456); const multiple = user.property({ name: 'changedName', number: 789, }); t.is(name, 'defaultName', 'Getting assigned and typed name of user failed.'); t.is(num, 456, 'Getting assigned and typed number of user failed.'); t.is( multiple.name, 'changedName', 'Getting assigned and typed multi.name of user failed.', ); t.is( multiple.number, 789, 'Getting assigned and typed multi.number of user failed.', ); t.is( multiple.test, undefined, 'Getting assigned and typed multi.test of user failed.', ); }); test.serial('typing in find()', async (t) => { const user = await nohm.factory<UserMockup>('UserMockup'); try { await user.find({ name: 'changedName', number: 789, }); await userMockupClass.find<IUserLinkProps>({ name: 'changedName', number: 789, }); await userMockupClass.findAndLoad<UserMockup, IUserLinkProps>({ name: 'changedName', number: 789, }); } catch (e) { // properties aren't indexed, whatever... just testing that the generics are right and manually testing errors // in find options t.pass("I'm sure it's fine."); } }); test.serial('typing in subscribe()', async (t) => { await nohm.setPubSubClient(args.secondaryClient); const user = await nohm.factory<UserMockup>('UserMockup'); const role = new roleLinkMockup(); let propertyDiff: Array<void | IPropertyDiff<keyof IUserLinkProps>>; let userId: string; const initialProps = user.allProperties(); await user.subscribe('create', (payload) => { t.is(payload.target.id, user.id, 'id in create handler was wrong'); if (user.id) { userId = user.id; // used in other tests } t.is( payload.target.modelName, user.modelName, 'modelname in create handler was wrong', ); t.deepEqual( payload.target.properties, { ...initialProps, id: userId, }, 'properties in create handler were wrong', ); }); await user.subscribe('link', (payload) => { t.is(payload.child.id, user.id, 'id in link handler CHILD was wrong'); t.is( payload.child.modelName, user.modelName, 'modelname in link handler CHILD was wrong', ); t.deepEqual( payload.child.properties, user.allProperties(), 'properties in link handler CHILD were wrong', ); t.is(payload.parent.id, role.id, 'id in link handler PARENT was wrong'); t.is( payload.parent.modelName, role.modelName, 'modelname in link handler PARENT was wrong', ); t.deepEqual( payload.parent.properties, role.allProperties(), 'properties in link handler PARENT were wrong', ); }); await user.subscribe('update', (payload) => { t.is(payload.target.id, user.id, 'id in update handler was wrong'); t.is( payload.target.modelName, user.modelName, 'modelname in update handler was wrong', ); t.deepEqual( payload.target.properties, user.allProperties(), 'properties in update handler was wrong', ); t.deepEqual( payload.target.diff, propertyDiff, 'properties in update handler were wrong', ); }); await user.subscribe('remove', (payload) => { t.not(payload.target.id, null, 'id in remove handler was null'); t.is(payload.target.id, userId, 'id in remove handler was wrong'); t.is( payload.target.modelName, user.modelName, 'modelname in remove handler was wrong', ); t.deepEqual( payload.target.properties, user.allProperties(), 'properties in remove handler were wrong', ); }); await user.save(); user.link(role); user.property('name', 'foobar'); propertyDiff = user.propertyDiff(); await user.save(); await user.remove(); }); test.serial('validation errors', async (t) => { // see above for their different ways of setup/definition const user = await nohm.factory<UserMockup>('UserMockup'); user.property('name', ''); try { await user.save(); t.fail('No error thrown thrown'); } catch (err) { if (err instanceof ValidationError && err.modelName === 'UserMockup') { t.deepEqual((err as ValidationError<IUserLinkProps>).errors.name, [ 'notEmpty', ]); } else { t.fail('Wrong kind of error thrown.'); } } });
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormBusinessUnit_Information { interface tab_addresses_Sections { bill_to_address: DevKit.Controls.Section; ship_to_address: DevKit.Controls.Section; } interface tab_general_Sections { section_1: DevKit.Controls.Section; } interface tab_addresses extends DevKit.Controls.ITab { Section: tab_addresses_Sections; } interface tab_general extends DevKit.Controls.ITab { Section: tab_general_Sections; } interface Tabs { addresses: tab_addresses; general: tab_general; } interface Body { Tab: Tabs; /** City name for address 1. */ Address1_City: DevKit.Controls.String; /** Country/region name for address 1. */ Address1_Country: DevKit.Controls.String; /** First line for entering address 1 information. */ Address1_Line1: DevKit.Controls.String; /** Second line for entering address 1 information. */ Address1_Line2: DevKit.Controls.String; /** Third line for entering address 1 information. */ Address1_Line3: DevKit.Controls.String; /** ZIP Code or postal code for address 1. */ Address1_PostalCode: DevKit.Controls.String; /** State or province for address 1. */ Address1_StateOrProvince: DevKit.Controls.String; /** First telephone number associated with address 1. */ Address1_Telephone1: DevKit.Controls.String; /** Second telephone number associated with address 1. */ Address1_Telephone2: DevKit.Controls.String; /** Third telephone number associated with address 1. */ Address1_Telephone3: DevKit.Controls.String; /** City name for address 2. */ Address2_City: DevKit.Controls.String; /** Country/region name for address 2. */ Address2_Country: DevKit.Controls.String; /** First line for entering address 2 information. */ Address2_Line1: DevKit.Controls.String; /** Second line for entering address 2 information. */ Address2_Line2: DevKit.Controls.String; /** Third line for entering address 2 information. */ Address2_Line3: DevKit.Controls.String; /** ZIP Code or postal code for address 2. */ Address2_PostalCode: DevKit.Controls.String; /** State or province for address 2. */ Address2_StateOrProvince: DevKit.Controls.String; /** Name of the division to which the business unit belongs. */ DivisionName: DevKit.Controls.String; /** Email address for the business unit. */ EMailAddress: DevKit.Controls.String; /** Name of the business unit. */ Name: DevKit.Controls.String; /** Unique identifier for the parent business unit. */ ParentBusinessUnitId: DevKit.Controls.Lookup; /** Website URL for the business unit. */ WebSiteUrl: DevKit.Controls.String; } } class FormBusinessUnit_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form BusinessUnit_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form BusinessUnit_Information */ Body: DevKit.FormBusinessUnit_Information.Body; } class BusinessUnitApi { /** * DynamicsCrm.DevKit BusinessUnitApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier for address 1. */ Address1_AddressId: DevKit.WebApi.GuidValue; /** Type of address for address 1, such as billing, shipping, or primary address. */ Address1_AddressTypeCode: DevKit.WebApi.OptionSetValue; /** City name for address 1. */ Address1_City: DevKit.WebApi.StringValue; /** Country/region name for address 1. */ Address1_Country: DevKit.WebApi.StringValue; /** County name for address 1. */ Address1_County: DevKit.WebApi.StringValue; /** Fax number for address 1. */ Address1_Fax: DevKit.WebApi.StringValue; /** Latitude for address 1. */ Address1_Latitude: DevKit.WebApi.DoubleValue; /** First line for entering address 1 information. */ Address1_Line1: DevKit.WebApi.StringValue; /** Second line for entering address 1 information. */ Address1_Line2: DevKit.WebApi.StringValue; /** Third line for entering address 1 information. */ Address1_Line3: DevKit.WebApi.StringValue; /** Longitude for address 1. */ Address1_Longitude: DevKit.WebApi.DoubleValue; /** Name to enter for address 1. */ Address1_Name: DevKit.WebApi.StringValue; /** ZIP Code or postal code for address 1. */ Address1_PostalCode: DevKit.WebApi.StringValue; /** Post office box number for address 1. */ Address1_PostOfficeBox: DevKit.WebApi.StringValue; /** Method of shipment for address 1. */ Address1_ShippingMethodCode: DevKit.WebApi.OptionSetValue; /** State or province for address 1. */ Address1_StateOrProvince: DevKit.WebApi.StringValue; /** First telephone number associated with address 1. */ Address1_Telephone1: DevKit.WebApi.StringValue; /** Second telephone number associated with address 1. */ Address1_Telephone2: DevKit.WebApi.StringValue; /** Third telephone number associated with address 1. */ Address1_Telephone3: DevKit.WebApi.StringValue; /** United Parcel Service (UPS) zone for address 1. */ Address1_UPSZone: DevKit.WebApi.StringValue; /** UTC offset for address 1. This is the difference between local time and standard Coordinated Universal Time. */ Address1_UTCOffset: DevKit.WebApi.IntegerValue; /** Unique identifier for address 2. */ Address2_AddressId: DevKit.WebApi.GuidValue; /** Type of address for address 2, such as billing, shipping, or primary address. */ Address2_AddressTypeCode: DevKit.WebApi.OptionSetValue; /** City name for address 2. */ Address2_City: DevKit.WebApi.StringValue; /** Country/region name for address 2. */ Address2_Country: DevKit.WebApi.StringValue; /** County name for address 2. */ Address2_County: DevKit.WebApi.StringValue; /** Fax number for address 2. */ Address2_Fax: DevKit.WebApi.StringValue; /** Latitude for address 2. */ Address2_Latitude: DevKit.WebApi.DoubleValue; /** First line for entering address 2 information. */ Address2_Line1: DevKit.WebApi.StringValue; /** Second line for entering address 2 information. */ Address2_Line2: DevKit.WebApi.StringValue; /** Third line for entering address 2 information. */ Address2_Line3: DevKit.WebApi.StringValue; /** Longitude for address 2. */ Address2_Longitude: DevKit.WebApi.DoubleValue; /** Name to enter for address 2. */ Address2_Name: DevKit.WebApi.StringValue; /** ZIP Code or postal code for address 2. */ Address2_PostalCode: DevKit.WebApi.StringValue; /** Post office box number for address 2. */ Address2_PostOfficeBox: DevKit.WebApi.StringValue; /** Method of shipment for address 2. */ Address2_ShippingMethodCode: DevKit.WebApi.OptionSetValue; /** State or province for address 2. */ Address2_StateOrProvince: DevKit.WebApi.StringValue; /** First telephone number associated with address 2. */ Address2_Telephone1: DevKit.WebApi.StringValue; /** Second telephone number associated with address 2. */ Address2_Telephone2: DevKit.WebApi.StringValue; /** Third telephone number associated with address 2. */ Address2_Telephone3: DevKit.WebApi.StringValue; /** United Parcel Service (UPS) zone for address 2. */ Address2_UPSZone: DevKit.WebApi.StringValue; /** UTC offset for address 2. This is the difference between local time and standard Coordinated Universal Time. */ Address2_UTCOffset: DevKit.WebApi.IntegerValue; /** Unique identifier of the business unit. */ BusinessUnitId: DevKit.WebApi.GuidValue; /** Fiscal calendar associated with the business unit. */ CalendarId: DevKit.WebApi.LookupValue; /** Name of the business unit cost center. */ CostCenter: DevKit.WebApi.StringValue; /** Unique identifier of the user who created the business unit. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the business unit was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the businessunit. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Credit limit for the business unit. */ CreditLimit: DevKit.WebApi.DoubleValue; /** Description of the business unit. */ Description: DevKit.WebApi.StringValue; /** Reason for disabling the business unit. */ DisabledReason: DevKit.WebApi.StringValueReadonly; /** Name of the division to which the business unit belongs. */ DivisionName: DevKit.WebApi.StringValue; /** Email address for the business unit. */ EMailAddress: DevKit.WebApi.StringValue; /** Exchange rate for the currency associated with the businessunit with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Alternative name under which the business unit can be filed. */ FileAsName: DevKit.WebApi.StringValue; /** FTP site URL for the business unit. */ FtpSiteUrl: DevKit.WebApi.StringValue; /** Unique identifier of the data import or data migration that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Inheritance mask for the business unit. */ InheritanceMask: DevKit.WebApi.IntegerValue; /** Information about whether the business unit is enabled or disabled. */ IsDisabled: DevKit.WebApi.BooleanValue; /** Unique identifier of the user who last modified the business unit. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the business unit was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who last modified the businessunit. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for Warehouse associated with Business Unit. */ msdyn_Warehouse: DevKit.WebApi.LookupValue; /** Name of the business unit. */ Name: DevKit.WebApi.StringValue; /** Unique identifier of the organization associated with the business unit. */ OrganizationId: DevKit.WebApi.LookupValueReadonly; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Unique identifier for the parent business unit. */ ParentBusinessUnitId: DevKit.WebApi.LookupValue; /** Picture or diagram of the business unit. */ Picture: DevKit.WebApi.StringValue; /** Stock exchange on which the business is listed. */ StockExchange: DevKit.WebApi.StringValue; /** Stock exchange ticker symbol for the business unit. */ TickerSymbol: DevKit.WebApi.StringValue; /** Unique identifier of the currency associated with the businessunit. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; UserGroupId: DevKit.WebApi.GuidValueReadonly; /** UTC offset for the business unit. This is the difference between local time and standard Coordinated Universal Time. */ UTCOffset: DevKit.WebApi.IntegerValue; /** Version number of the business unit. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; /** Website URL for the business unit. */ WebSiteUrl: DevKit.WebApi.StringValue; /** Information about whether workflow or sales process rules have been suspended. */ WorkflowSuspended: DevKit.WebApi.BooleanValue; } } declare namespace OptionSet { namespace BusinessUnit { enum Address1_AddressTypeCode { /** 1 */ Default_Value } enum Address1_ShippingMethodCode { /** 1 */ Default_Value } enum Address2_AddressTypeCode { /** 1 */ Default_Value } enum Address2_ShippingMethodCode { /** 1 */ Default_Value } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import mixin from './util/mixin'; import Exception from './util/exception'; import * as plugin from './plugin' import Config from './config/config'; import {LifecycleContext} from "./core.types"; import {EventItem, EventObserverQueue, IFsm, Observer} from "./jsm.types"; import {State} from "./core.types"; const UNOBSERVED: EventItem = { event: null, observers: [], }; class JSM implements IFsm { public context: any; public config: Config; public state: State; public observers: Observer[]; private pending: boolean; constructor(context, config: Config) { this.context = context; this.config = config; this.state = config.init.from; this.observers = [context]; this.pending = false; } public init(args): void { // console.log(args); // console.log(this.config.data.apply(this.context, args)); mixin(this.context, this.config.data.apply(this.context, args)); plugin.hook(this, 'init'); if (this.config.init.active) return this.fire(this.config.init.name, []); } /** * is verifies the state of the machine * @param {string|string[]} state the state name to be verified, or a list of states that * may contain the state of the machine * @returns {boolean} verification result */ public is(state: string|string[]): boolean { return Array.isArray(state) ? (state.indexOf(this.state) >= 0) : (this.state === state); } /** * isPending checks if the machine is pending a transition * @returns {boolean} */ public isPending(): boolean { return this.pending; } /** * can queries if the transition can be executed. If the machine state is pending, * then no, otherwise, seeks if the transition is allowed depending on the current * state of the machine. * @param transition the transition name * @returns {boolean} */ public can(transition: string): boolean { return !this.isPending() && !!this.seek(transition); } /** * cannot does the opposite of can, see there for details. * @param transition the transition name * @returns {boolean} */ public cannot(transition): boolean { return !this.can(transition); } /** allStates returns all the potential states that * exist inside the state machine. * @returns {string[]} the list of states */ public allStates(): string[] { return this.config.allStates(); } /** allTransitions returns all the potential transitions that * exist inside the state machine. * @returns {string[]} the list of transitions */ public allTransitions(): string[] { return this.config.allTransitions(); } /** * transitions retrieves the list of transitions allowed for the current state * @returns {string[]} the list of transitions */ public transitions(): string[] { return this.config.transitionsFor(this.state); } /** * seek finds the "to" destination of a given transition. * @param {string} transition the transition name * @param {any | any[]=} args the arguments received from when user executes the transition (Optional). * @private */ private seek(transition: string, args?: any | any[]): any | Promise<string | undefined> { const { wildcard } = this.config.defaults; const entry = this.config.transitionFor(this.state, transition); const to = entry && entry.to; if (typeof to === 'function') { return to.apply(this.context, args); } else if (to === wildcard) return this.state; else return to; } public fire(transition: string, args?: any | any[]) { const toDestination = this.seek(transition, args); if (toDestination && typeof toDestination.then === 'function') { return toDestination.then((output) => this.transit(transition, this.state, output, args)); } else { return this.transit(transition, this.state, toDestination, args); } } /** * transit triggers a transition. * At this point, the "to" destination is already determined. * 1. Check if the transition will lead to a change of state. * 2. Make sure the "to" destination is valid. * 3. Make sure there is not an ongoing transition. * 4. Flag the JSM as there is a transition ongoing. * 5. If the "to" destination does not exist in JSM's internal lookup, add the new state. * 6. Trigger the transition by returning a function that runs the whole lifecycle. * @param transition the transition name * @param from the original state * @param {string | undefined} to the "to" destination * @param {any | any[]=} args the arguments received from when user executes the transition (Optional). * @private */ private transit(transition: string, from: string, to: string | undefined, args?: any | any[]) { const { lifecycle } = this.config; let changed; if ("observeUnchangedState" in this.config.options) { changed = this.config.options.observeUnchangedState || (from !== to); } else { changed = from !== to; } if (!to) return this.context.onInvalidTransition(transition, from, to); if (this.isPending()) return this.context.onPendingTransition(transition, from, to); this.config.addState(to); // might need to add this state if it's unknown (e.g. conditional transition or goto) this.beginTransit(); const lifeCycleContext: LifecycleContext = { transition: transition, from: from, to: to, fsm: this.context, event: null, }; args.unshift(lifeCycleContext); // this context will be passed to each lifecycle event observer return this.observeEvents([ this.observersForEvent(lifecycle.onBefore.transition /* onBeforeTransition */), this.observersForEvent(lifecycle.onBefore[transition] /* onBefore[Transition] */), changed ? this.observersForEvent(lifecycle.onLeave.state /* onLeaveState */) : UNOBSERVED, changed ? this.observersForEvent(lifecycle.onLeave[from] /* onLeave[FromState] */) : UNOBSERVED, this.observersForEvent(lifecycle.on.transition /* on[Transition] */), changed ? { event: 'doTransit', observers: [ this ] } : UNOBSERVED, changed ? this.observersForEvent(lifecycle.onEnter.state /* onEnterState */) : UNOBSERVED, changed ? this.observersForEvent(lifecycle.onEnter[to] /* onEnter[ToState] */) : UNOBSERVED, changed ? this.observersForEvent(lifecycle.on[to] /* on[ToState] */) : UNOBSERVED, this.observersForEvent(lifecycle.onAfter.transition /* onAfterTransition */), this.observersForEvent(lifecycle.onAfter[transition] /* onAfter[Transition] */), this.observersForEvent(lifecycle.on[transition] /* on[Transition] */) ], args); } /** * beginTransit flags the pending property to true to indicate * there is an ongoing transition. * @private */ private beginTransit(): void { this.pending = true; } /** * endTransit flags the pending property to false to indicate * the transition is done or stopped during a transition. * @param {boolean} result true - transition is done, false - transition is stopped * @returns {boolean} the result * @private */ private endTransit(result: boolean): boolean { this.pending = false; return result; } /** * failTransit flags the pending property to false to * indicate the transition is stopped because there is an error during transiton. * @param {Error} result error when transition failed * @returns {Error} the result * @private */ private failTransit(result): Error { this.pending = false; throw result; } private doTransit(lifecycle) { this.state = lifecycle.to; } /** * observe attaches an observer to the list of observers. * If the number of arguments is 2, the first would be * the lifecycle name, second would be the observer. If * the number of arguments is 1, then the observer should be * an object with the lifecycle as key, the observer function * as the value. * @param args */ public observe(args) { if (args.length === 2) { const observer = {}; observer[args[0]] = args[1]; this.observers.push(observer); } else { this.observers.push(args[0]); } } /** * observersForEvent constructs a list of observers that are interested * in the given event. * @param {string} event the event name * @returns {[string, Observer[], bool]} the event, list of observers, true * @private */ private observersForEvent(event: string): EventItem { // TODO: this could be cached const result = this.observers.filter((observer) => observer[event]); return { event, observers: result, pluggable: true, }; } /** * observeEvents * @param eventQueue the event queue that contains the list of observers * @param args * @param previousEvent * @param previousResult * @private */ private observeEvents(eventQueue: EventObserverQueue, args: [LifecycleContext, ...any], previousEvent?: string | null | undefined, previousResult?: undefined | boolean) { // Recursively dequeue the event queue // Stopping condition if (eventQueue.length === 0) { return this.endTransit(previousResult === undefined ? true : previousResult); } // Initial const { event: eventName, observers, pluggable } = eventQueue[0]; // Add eventName to the LifeCycleContext args[0].event = eventName; if (eventName && pluggable && eventName !== previousEvent) // Execute the plugins attached to the state machine // console.log(args); plugin.hook(this, 'lifecycle', args); // Execute the observer functions if (observers.length == 0) { eventQueue.shift(); // Dequeue return this.observeEvents(eventQueue, args, eventName, previousResult); } else { // Get the first observer const observer = observers.shift(); // Execute the observer if (eventName) { // const result = observer[eventName].apply(observer, args); const result = observer[eventName](...args); if (result && typeof result.then === 'function') { // result is a Promise return result.then(this.observeEvents.bind(this, eventQueue, args, eventName)) .catch(this.failTransit.bind(this)) } else if (result === false) { // Halt the transition return this.endTransit(false); } else { return this.observeEvents(eventQueue, args, eventName, result); } } } } /** * onInvalidTransition throws an error when the to destination is invalid * @param {JSM} this the JSM context (internal) * @param {string} transition the transition name * @param {string} from the original state * @param {string|undefined} to anything that is not an non-empty string */ public onInvalidTransition(this: JSM, transition: string, from: string, to: string): Exception { throw new Exception("transition is invalid in current state", transition, from, to, this.state); } /** * onPendingTransition throws an error when there is a transition trying to be fired when * there is already an ongoing transition. * @param {JSM} this the JSM context (internal) * @param {string} transition the transition name * @param {string} from the original state * @param {string|undefined} to anything that is not an non-empty string */ public onPendingTransition(this: JSM, transition: string, from: string, to: string): Exception { throw new Exception("transition is invalid while previous transition is still in progress", transition, from, to, this.state); } } export default JSM;
the_stack
import { Point } from '@pixi/math'; import { Plugin } from './Plugin'; import type { Decelerate } from './Decelerate'; import type { InteractionEvent } from '@pixi/interaction'; import type { IPointData } from '@pixi/math'; import type { Viewport } from '../Viewport'; /** Options for {@link Drag}. */ export interface IDragOptions { /** * direction to drag * * @default "all" */ direction?: string; /** * whether click to drag is active * * @default true */ pressDrag?: boolean; /** * Use wheel to scroll in direction (unless wheel plugin is active) * * @default true */ wheel?: boolean; /** * number of pixels to scroll with each wheel spin * * @default 1 */ wheelScroll?: number; /** * reverse the direction of the wheel scroll * * @default false */ reverse?: boolean; /** * clamp wheel(to avoid weird bounce with mouse wheel). Can be 'x' or 'y' or `true`. * * @default false */ clampWheel?: boolean | string; /** * where to place world if too small for screen * * @default "center" */ underflow?: string; /** * factor to multiply drag to increase the speed of movement * * @default 1 */ factor?: number; /** * Changes which mouse buttons trigger drag. * * Use: 'all', 'left', right' 'middle', or some combination, like, 'middle-right'; you may want to set * `viewport.options.disableOnContextMenu` if you want to use right-click dragging. * * @default "all" */ mouseButtons?: 'all' | string; /** * Array containing {@link key|https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code} codes of * keys that can be pressed for the drag to be triggered, e.g.: ['ShiftLeft', 'ShiftRight'}. * * @default null */ keyToPress?: string[] | null; /** * Ignore keyToPress for touch events. * * @default false */ ignoreKeyToPressOnTouch?: boolean; /** * Scaling factor for non-DOM_DELTA_PIXEL scrolling events. * * @default 20 */ lineHeight?: number; } const DEFAULT_DRAG_OPTIONS: Required<IDragOptions> = { direction: 'all', pressDrag: true, wheel: true, wheelScroll: 1, reverse: false, clampWheel: false, underflow: 'center', factor: 1, mouseButtons: 'all', keyToPress: null, ignoreKeyToPressOnTouch: false, lineHeight: 20, }; /** * Plugin to enable panning/dragging of the viewport to move around. * * @public */ export class Drag extends Plugin { /** Options used to initialize this plugin, cannot be modified later. */ public readonly options: Readonly<Required<IDragOptions>>; /** Flags when viewport is moving. */ protected moved: boolean; /** Factor to apply from {@link IDecelerateOptions}'s reverse. */ protected reverse: 1 | -1; /** Holds whether dragging is enabled along the x-axis. */ protected xDirection: boolean; /** Holds whether dragging is enabled along the y-axis. */ protected yDirection: boolean; /** Flags whether the keys required to drag are pressed currently. */ protected keyIsPressed: boolean; /** Holds whether the left, center, and right buttons are required to pan. */ protected mouse!: [boolean, boolean, boolean]; /** Underflow factor along x-axis */ protected underflowX!: -1 | 0 | 1; /** Underflow factor along y-axis */ protected underflowY!: -1 | 0 | 1; /** Last pointer position while panning. */ protected last?: IPointData | null; /** The ID of the pointer currently panning the viewport. */ protected current?: number; /** * This is called by {@link Viewport.drag}. */ constructor(parent: Viewport, options = {}) { super(parent); this.options = Object.assign({}, DEFAULT_DRAG_OPTIONS, options); this.moved = false; this.reverse = this.options.reverse ? 1 : -1; this.xDirection = !this.options.direction || this.options.direction === 'all' || this.options.direction === 'x'; this.yDirection = !this.options.direction || this.options.direction === 'all' || this.options.direction === 'y'; this.keyIsPressed = false; this.parseUnderflow(); this.mouseButtons(this.options.mouseButtons); if (this.options.keyToPress) { this.handleKeyPresses(this.options.keyToPress); } } /** * Handles keypress events and set the keyIsPressed boolean accordingly * * @param {array} codes - key codes that can be used to trigger drag event */ protected handleKeyPresses(codes: string[]): void { window.addEventListener('keydown', (e) => { if (codes.includes(e.code)) { this.keyIsPressed = true; } }); window.addEventListener('keyup', (e) => { if (codes.includes(e.code)) { this.keyIsPressed = false; } }); } /** * initialize mousebuttons array * @param {string} buttons */ protected mouseButtons(buttons: string): void { if (!buttons || buttons === 'all') { this.mouse = [true, true, true]; } else { this.mouse = [ buttons.indexOf('left') !== -1, buttons.indexOf('middle') !== -1, buttons.indexOf('right') !== -1 ]; } } protected parseUnderflow(): void { const clamp = this.options.underflow.toLowerCase(); if (clamp === 'center') { this.underflowX = 0; this.underflowY = 0; } else { if (clamp.includes('left')) { this.underflowX = -1; } else if (clamp.includes('right')) { this.underflowX = 1; } else { this.underflowX = 0; } if (clamp.includes('top')) { this.underflowY = -1; } else if (clamp.includes('bottom')) { this.underflowY = 1; } else { this.underflowY = 0; } } } /** * @param {PIXI.InteractionEvent} event * @returns {boolean} */ protected checkButtons(event: InteractionEvent): boolean { const isMouse = event.data.pointerType === 'mouse'; const count = this.parent.input.count(); if ((count === 1) || (count > 1 && !this.parent.plugins.get('pinch', true))) { if (!isMouse || this.mouse[event.data.button]) { return true; } } return false; } /** * @param {PIXI.InteractionEvent} event * @returns {boolean} */ protected checkKeyPress(event: InteractionEvent): boolean { return (!this.options.keyToPress || this.keyIsPressed || (this.options.ignoreKeyToPressOnTouch && event.data.pointerType === 'touch')); } public down(event: InteractionEvent): boolean { if (this.paused || !this.options.pressDrag) { return false; } if (this.checkButtons(event) && this.checkKeyPress(event)) { this.last = { x: event.data.global.x, y: event.data.global.y }; this.current = event.data.pointerId; return true; } this.last = null; return false; } get active(): boolean { return this.moved; } public move(event: InteractionEvent): boolean { if (this.paused || !this.options.pressDrag) { return false; } if (this.last && this.current === event.data.pointerId) { const x = event.data.global.x; const y = event.data.global.y; const count = this.parent.input.count(); if (count === 1 || (count > 1 && !this.parent.plugins.get('pinch', true))) { const distX = x - this.last.x; const distY = y - this.last.y; if (this.moved || ((this.xDirection && this.parent.input.checkThreshold(distX)) || (this.yDirection && this.parent.input.checkThreshold(distY)))) { const newPoint = { x, y }; if (this.xDirection) { this.parent.x += (newPoint.x - this.last.x) * this.options.factor; } if (this.yDirection) { this.parent.y += (newPoint.y - this.last.y) * this.options.factor; } this.last = newPoint; if (!this.moved) { this.parent.emit('drag-start', { event, screen: new Point(this.last.x, this.last.y), world: this.parent.toWorld(new Point(this.last.x, this.last.y)), viewport: this.parent }); } this.moved = true; this.parent.emit('moved', { viewport: this.parent, type: 'drag' }); return true; } } else { this.moved = false; } } return false; } public up(event: InteractionEvent): boolean { if (this.paused) { return false; } const touches = this.parent.input.touches; if (touches.length === 1) { const pointer = touches[0]; if (pointer.last) { this.last = { x: pointer.last.x, y: pointer.last.y }; this.current = pointer.id; } this.moved = false; return true; } else if (this.last) { if (this.moved) { const screen = new Point(this.last.x, this.last.y); this.parent.emit('drag-end', { event, screen, world: this.parent.toWorld(screen), viewport: this.parent, }); this.last = null; this.moved = false; return true; } } return false; } public wheel(event: WheelEvent): boolean { if (this.paused) { return false; } if (this.options.wheel) { const wheel = this.parent.plugins.get('wheel', true); if (!wheel || (!wheel.options.wheelZoom && !event.ctrlKey)) { const step = event.deltaMode ? this.options.lineHeight : 1; if (this.xDirection) { this.parent.x += event.deltaX * step * this.options.wheelScroll * this.reverse; } if (this.yDirection) { this.parent.y += event.deltaY * step * this.options.wheelScroll * this.reverse; } if (this.options.clampWheel) { this.clamp(); } this.parent.emit('wheel-scroll', this.parent); this.parent.emit('moved', { viewport: this.parent, type: 'wheel' }); if (!this.parent.options.passiveWheel) { event.preventDefault(); } if (this.parent.options.stopPropagation) { event.stopPropagation(); } return true; } } return false; } public resume(): void { this.last = null; this.paused = false; } public clamp(): void { const decelerate: Partial<Decelerate> = this.parent.plugins.get('decelerate', true) || {}; if (this.options.clampWheel !== 'y') { if (this.parent.screenWorldWidth < this.parent.screenWidth) { switch (this.underflowX) { case -1: this.parent.x = 0; break; case 1: this.parent.x = (this.parent.screenWidth - this.parent.screenWorldWidth); break; default: this.parent.x = (this.parent.screenWidth - this.parent.screenWorldWidth) / 2; } } else if (this.parent.left < 0) { this.parent.x = 0; decelerate.x = 0; } else if (this.parent.right > this.parent.worldWidth) { this.parent.x = (-this.parent.worldWidth * this.parent.scale.x) + this.parent.screenWidth; decelerate.x = 0; } } if (this.options.clampWheel !== 'x') { if (this.parent.screenWorldHeight < this.parent.screenHeight) { switch (this.underflowY) { case -1: this.parent.y = 0; break; case 1: this.parent.y = (this.parent.screenHeight - this.parent.screenWorldHeight); break; default: this.parent.y = (this.parent.screenHeight - this.parent.screenWorldHeight) / 2; } } else { if (this.parent.top < 0) { this.parent.y = 0; decelerate.y = 0; } if (this.parent.bottom > this.parent.worldHeight) { this.parent.y = (-this.parent.worldHeight * this.parent.scale.y) + this.parent.screenHeight; decelerate.y = 0; } } } } }
the_stack
import warning from 'warning'; import { MessengerClient } from 'messaging-api-messenger'; import { mocked } from 'ts-jest/utils'; import MessengerConnector from '../MessengerConnector'; import MessengerContext from '../MessengerContext'; import MessengerEvent from '../MessengerEvent'; import { MessengerRequestBody } from '../MessengerTypes'; jest.mock('messaging-api-messenger'); jest.mock('warning'); const ACCESS_TOKEN = 'FAKE_TOKEN'; const APP_SECRET = 'FAKE_SECRET'; const APP_ID = 'FAKE_ID'; const request: MessengerRequestBody = { object: 'page', entry: [ { id: '1895382890692545', time: 1486464322257, messaging: [ { sender: { id: '1412611362105802', }, recipient: { id: '1895382890692545', }, timestamp: 1486464322190, message: { mid: 'mid.1486464322190:cb04e5a654', text: 'text', }, }, ], }, ], }; const echoRequest: MessengerRequestBody = { object: 'page', entry: [ { id: '1134713619900975', // page id time: 1492414608999.0, messaging: [ { sender: { id: '1134713619900975', }, recipient: { id: '1244813222196986', // user id }, timestamp: 1492414608982.0, message: { isEcho: true, appId: 1821152484774199, mid: 'mid.$cAARS90328R5hrBz-Vlbete17ftIb', text: 'text', }, }, ], }, ], }; const batchRequest: MessengerRequestBody = { object: 'page', entry: [ { id: '1895382890692545', time: 1486464322257, messaging: [ { sender: { id: '1412611362105802', }, recipient: { id: '1895382890692545', }, timestamp: 1486464322190, message: { mid: 'mid.1486464322190:cb04e5a654', text: 'test 1', }, }, ], }, { id: '189538289069256', time: 1486464322257, messaging: [ { sender: { id: '1412611362105802', }, recipient: { id: '1895382890692545', }, timestamp: 1486464322190, message: { mid: 'mid.1486464322190:cb04e5a656', text: 'test 2', }, }, ], }, ], }; const standbyRequest: MessengerRequestBody = { object: 'page', entry: [ { id: '<PAGE_ID>', time: 1458692752478, standby: [ { sender: { id: '<USER_ID>', }, recipient: { id: '<PAGE_ID>', }, // FIXME: standby is still beta // https://developers.facebook.com/docs/messenger-platform/reference/webhook-events/standby /* ... */ }, ], }, ], }; const webhookTestRequest: MessengerRequestBody = { body: { entry: [ { changes: [ { field: 'messages', value: { pageId: '<PAGE_ID>', }, }, ], id: '0', time: 1514862760, }, ], object: 'page', }, }; function setup({ accessToken = ACCESS_TOKEN, appSecret = APP_SECRET, mapPageToAccessToken = jest.fn(), verifyToken = '1qaz2wsx', skipLegacyProfile = true, } = {}) { const connector = new MessengerConnector({ accessToken, appSecret, mapPageToAccessToken, verifyToken, skipLegacyProfile, }); const client = mocked(MessengerClient).mock.instances[0]; return { client, connector, }; } beforeEach(() => { console.error = jest.fn(); }); it('should use accessToken and appSecret (for appsecret_proof) to create default client', () => { setup({ accessToken: ACCESS_TOKEN, appSecret: APP_SECRET, }); expect(MessengerClient).toBeCalledWith({ accessToken: ACCESS_TOKEN, appSecret: APP_SECRET, }); }); describe('#platform', () => { it('should be messenger', () => { const { connector } = setup(); expect(connector.platform).toBe('messenger'); }); }); describe('#verifyToken', () => { it('should equal when be provided', () => { const { connector } = setup({ verifyToken: '1234' }); expect(connector.verifyToken).toBe('1234'); }); }); describe('#client', () => { it('should be client', () => { const { connector, client } = setup(); expect(connector.client).toBe(client); }); it('support custom client', () => { const client = new MessengerClient({ accessToken: ACCESS_TOKEN, appSecret: APP_SECRET, }); const connector = new MessengerConnector({ appId: APP_ID, appSecret: APP_SECRET, client, }); expect(connector.client).toBe(client); }); }); describe('#getUniqueSessionKey', () => { it('extract correct sender id', () => { const { connector } = setup(); const senderId = connector.getUniqueSessionKey(request); expect(senderId).toBe('1412611362105802'); }); it('return recipient id when request is an echo event', () => { const { connector } = setup(); const senderId = connector.getUniqueSessionKey(echoRequest); expect(senderId).toBe('1244813222196986'); }); it('extract sender id from first event', () => { const { connector } = setup(); const senderId = connector.getUniqueSessionKey(batchRequest); expect(senderId).toBe('1412611362105802'); }); it('return null if is not first event or echo event', () => { const { connector } = setup(); const senderId = connector.getUniqueSessionKey({}); expect(senderId).toBe(null); }); it('return null if is webhook test event or other null rawEvent requests', () => { const { connector } = setup(); const senderId = connector.getUniqueSessionKey(webhookTestRequest); expect(senderId).toBe(null); }); it('extract from messenger event', () => { const { connector } = setup(); const senderId = connector.getUniqueSessionKey( new MessengerEvent({ sender: { id: '1412611362105802', }, recipient: { id: '1895382890692545', }, timestamp: 1486464322190, message: { mid: 'mid.1486464322190:cb04e5a654', text: 'text', }, }) ); expect(senderId).toBe('1412611362105802'); }); }); describe('#updateSession', () => { it('update session with data needed', async () => { const { connector, client } = setup({ skipLegacyProfile: false, }); const user = { id: '1412611362105802', firstName: 'firstName', lastName: 'lastName', profilePic: 'https://example.com/pic.png', locale: 'en_US', timezone: 8, gender: 'male', }; mocked(client.getUserProfile).mockResolvedValue(user); const session = {}; await connector.updateSession(session, request); expect(client.getUserProfile).toBeCalledWith('1412611362105802'); expect(session).toEqual({ page: { _updatedAt: expect.any(String), id: '1895382890692545', }, user: { _updatedAt: expect.any(String), ...user, }, }); }); it('update session when profilePic expired', async () => { const { connector, client } = setup({ skipLegacyProfile: false, }); const user = { id: '1412611362105802', firstName: 'firstName', lastName: 'lastName', profilePic: 'https://example.com/pic.png', locale: 'en_US', timezone: 8, gender: 'male', }; mocked(client.getUserProfile).mockResolvedValue(user); const session = { user: { profilePic: 'https://example.com/pic.png?oe=386D4380', // expired at 2000-01-01T00:00:00.000Z }, }; await connector.updateSession(session, request); expect(client.getUserProfile).toBeCalledWith('1412611362105802'); expect(session).toEqual({ page: { _updatedAt: expect.any(String), id: '1895382890692545', }, user: { _updatedAt: expect.any(String), ...user, }, }); }); it('update session when expired date is invalid', async () => { const { connector, client } = setup({ skipLegacyProfile: false, }); const user = { id: '1412611362105802', firstName: 'firstName', lastName: 'lastName', profilePic: 'https://example.com/pic.png', locale: 'en_US', timezone: 8, gender: 'male', }; mocked(client.getUserProfile).mockResolvedValue(user); const session = { user: { profilePic: 'https://example.com/pic.png?oe=abc666666666', // wrong timestamp }, }; await connector.updateSession(session, request); expect(client.getUserProfile).toBeCalledWith('1412611362105802'); expect(session).toEqual({ page: { _updatedAt: expect.any(String), id: '1895382890692545', }, user: { _updatedAt: expect.any(String), ...user, }, }); }); it('update session when something wrong', async () => { const { connector, client } = setup({ skipLegacyProfile: false, }); const user = { id: '1412611362105802', firstName: 'firstName', lastName: 'lastName', profilePic: 'https://example.com/pic.png', locale: 'en_US', timezone: 8, gender: 'male', }; mocked(client.getUserProfile).mockResolvedValue(user); const session = { user: { profilePic123: 'https://example.com/pic.png?oe=386D4380', // wrong name }, }; await connector.updateSession(session, request); expect(client.getUserProfile).toBeCalledWith('1412611362105802'); expect(session).toEqual({ page: { _updatedAt: expect.any(String), id: '1895382890692545', }, user: { _updatedAt: expect.any(String), ...user, }, }); }); it('update session when getUserProfile() failed', async () => { const { connector, client } = setup({ skipLegacyProfile: false, }); const error = new Error('fail'); mocked(client.getUserProfile).mockRejectedValue(error); const session = {}; await connector.updateSession(session, request); expect(client.getUserProfile).toBeCalledWith('1412611362105802'); expect(session).toEqual({ page: { _updatedAt: expect.any(String), id: '1895382890692545', }, user: { _updatedAt: expect.any(String), id: '1412611362105802', }, }); expect(warning).toBeCalledWith( false, 'getUserProfile() failed, `session.user` will only have `id`' ); expect(console.error).toBeCalledWith(error); }); it(`update session without getting user's profile when skipLegacyProfile set to true`, async () => { const { connector, client } = setup({ skipLegacyProfile: true, }); const session = {}; await connector.updateSession(session, request); expect(client.getUserProfile).not.toBeCalled(); expect(session).toEqual({ page: { _updatedAt: expect.any(String), id: '1895382890692545', }, user: { _updatedAt: expect.any(String), id: '1412611362105802', }, }); }); }); describe('#mapRequestToEvents', () => { it('should map request to MessengerEvents', () => { const { connector } = setup(); const events = connector.mapRequestToEvents(request); expect(events).toHaveLength(1); expect(events[0]).toBeInstanceOf(MessengerEvent); expect(events[0].pageId).toBe('1895382890692545'); }); it('should work with batch entry', () => { const { connector } = setup(); const events = connector.mapRequestToEvents(batchRequest); expect(events).toHaveLength(2); expect(events[0]).toBeInstanceOf(MessengerEvent); expect(events[0].pageId).toBe('1895382890692545'); expect(events[1]).toBeInstanceOf(MessengerEvent); expect(events[1].pageId).toBe('1895382890692545'); }); it('should map request to standby MessengerEvents', () => { const { connector } = setup(); const events = connector.mapRequestToEvents(standbyRequest); expect(events).toHaveLength(1); expect(events[0]).toBeInstanceOf(MessengerEvent); expect(events[0].isStandby).toBe(true); expect(events[0].pageId).toBe('<PAGE_ID>'); }); it('should map request to echo MessengerEvents', () => { const { connector } = setup(); const events = connector.mapRequestToEvents(echoRequest); expect(events).toHaveLength(1); expect(events[0]).toBeInstanceOf(MessengerEvent); expect(events[0].pageId).toBe('1134713619900975'); }); it('should be filtered if body is not messaging or standby', () => { const otherRequest: MessengerRequestBody = { object: 'page', entry: [ { id: '<PAGE_ID>', time: 1458692752478, other: [ { sender: { id: '<USER_ID>', }, recipient: { id: '<PAGE_ID>', }, }, ], }, ], }; const { connector } = setup(); const events = connector.mapRequestToEvents(otherRequest); expect(events).toHaveLength(0); }); }); describe('#createContext', () => { it('should create MessengerContext', async () => { const { connector } = setup(); const event = { rawEvent: { recipient: { id: 'anyPageId', }, }, }; const session = {}; const context = await connector.createContext({ event, session, }); expect(context).toBeDefined(); expect(context).toBeInstanceOf(MessengerContext); }); it('should create MessengerContext and has customAccessToken', async () => { const mapPageToAccessToken = jest.fn().mockResolvedValue('anyToken'); const { connector } = setup({ mapPageToAccessToken }); const event = { rawEvent: { recipient: { id: 'anyPageId', }, }, }; const session = {}; const context = await connector.createContext({ event, session, }); expect(context).toBeDefined(); expect(context.accessToken).toBe('anyToken'); }); it('should call warning if it could not find pageId', async () => { const mapPageToAccessToken = jest.fn().mockResolvedValue('anyToken'); const { connector } = setup({ mapPageToAccessToken }); const event = { rawEvent: {}, }; const session = {}; await connector.createContext({ event, session, }); expect(warning).toBeCalledWith( false, 'Could not find pageId from request body.' ); }); }); describe('#verifySignature', () => { it('should return true if signature is equal app secret after crypto', () => { const { connector } = setup(); const result = connector.verifySignature( 'rawBody', 'sha1=0d814d436b45c33ef664a317ff4b8dc2d3d8fe2a' ); expect(result).toBe(true); }); it('should return false if signature is undefined', () => { const { connector } = setup(); const result = connector.verifySignature('rawBody', undefined); expect(result).toBe(false); }); it('should return false if signature dont have a sha1= prefix', () => { const { connector } = setup(); const result = connector.verifySignature('rawBody', 'sha256!!!'); expect(result).toBe(false); }); }); describe('#preprocess', () => { it('should return correct challenge if request method is get and verify_token match', () => { const { connector } = setup(); expect( connector.preprocess({ method: 'get', headers: {}, query: { 'hub.mode': 'subscribe', 'hub.verify_token': '1qaz2wsx', 'hub.challenge': 'abc', }, rawBody: '', body: {}, }) ).toEqual({ shouldNext: false, response: { status: 200, body: 'abc', }, }); }); it('should return 403 Forbidden if request method is get and verify_token does not match', () => { const { connector } = setup(); expect( connector.preprocess({ method: 'get', headers: {}, query: { 'hub.mode': 'subscribe', 'hub.verify_token': '3edc4rfv', 'hub.challenge': 'abc', }, rawBody: '', body: {}, }) ).toEqual({ shouldNext: false, response: { status: 403, body: 'Forbidden', }, }); }); it('should return shouldNext: true if signature match', () => { const { connector } = setup(); expect( connector.preprocess({ method: 'post', headers: { 'x-hub-signature': 'sha1=1c99183cb7c44ea27fb834746086b65b89800db8', }, query: {}, rawBody: '{}', body: {}, }) ).toEqual({ shouldNext: true, }); }); it('should return shouldNext: false and error if signature does not match', () => { const { connector } = setup(); expect( connector.preprocess({ method: 'post', headers: { 'x-hub-signature': 'sha1=0d814d436b45c33ef664a317ff4b8dc2d3d8fe2a', }, query: {}, rawBody: '{}', body: {}, }) ).toEqual({ shouldNext: false, response: { status: 400, body: { error: { message: 'Facebook Signature Validation Failed!', request: { headers: { 'x-hub-signature': 'sha1=0d814d436b45c33ef664a317ff4b8dc2d3d8fe2a', }, rawBody: '{}', }, }, }, }, }); }); });
the_stack
import { BatchType } from "../../common/batch/BatchOperation"; import BatchRequest from "../../common/batch/BatchRequest"; // import BatchSubResponse from "../../common/BatchSubResponse"; import { HttpMethod } from "../../table/generated/IRequest"; import { BatchSerialization } from "../../common/batch/BatchSerialization"; import TableBatchOperation from "../batch/TableBatchOperation"; import * as Models from "../generated/artifacts/models"; import TableBatchUtils from "./TableBatchUtils"; import StorageError from "../errors/StorageError"; import { truncatedISO8061Date } from "../../common/utils/utils"; /** * The semantics for entity group transactions are defined by the OData Protocol Specification. * https://www.odata.org/ * http://docs.oasis-open.org/odata/odata-json-format/v4.01/odata-json-format-v4.01.html#_Toc38457781 * * for now we are first getting the concrete implementation correct for table batch * we then need to figure out how to do this for blob, and what can be shared. * We set several headers in the responses to the same values that we see returned * from the Azure Storage Service. * * @export * @class TableBatchSerialization * @extends {BatchSerialization} */ export class TableBatchSerialization extends BatchSerialization { /** * Deserializes a batch request * * @param {string} batchRequestsString * @return {*} {TableBatchOperation[]} * @memberof TableBatchSerialization */ public deserializeBatchRequest( batchRequestsString: string ): TableBatchOperation[] { this.extractBatchBoundary(batchRequestsString); this.extractChangeSetBoundary(batchRequestsString); this.extractLineEndings(batchRequestsString); // we can't rely on case of strings we use in delimiters // ToDo: might be easier and more efficient to use i option on the regex here... const contentTypeHeaderString = this.extractRequestHeaderString( batchRequestsString, "(\\n)+(([c,C])+(ontent-)+([t,T])+(ype)+)+(?=:)+" ); const contentTransferEncodingString = this.extractRequestHeaderString( batchRequestsString, "(\\n)+(([c,C])+(ontent-)+([t,T])+(ransfer-)+([e,E])+(ncoding))+(?=:)+" ); // the line endings might be \r\n or \n const HTTP_LINE_ENDING = this.lineEnding; const subRequestPrefix = `--${this.changesetBoundary}${HTTP_LINE_ENDING}${contentTypeHeaderString}: application/http${HTTP_LINE_ENDING}${contentTransferEncodingString}: binary`; const splitBody = batchRequestsString.split(subRequestPrefix); // dropping first element as boundary if we have a batch with multiple requests let subRequests: string[]; if (splitBody.length > 1) { subRequests = splitBody.slice(1, splitBody.length); } else { subRequests = splitBody; } // This goes through each operation in the the request and maps the content // of the request by deserializing it into a BatchOperation Type const batchOperations: TableBatchOperation[] = subRequests.map( (subRequest) => { let requestType: RegExpMatchArray | null = []; requestType = subRequest.match( "(GET|PATCH|POST|PUT|MERGE|INSERT|DELETE)" ); if (requestType === null || requestType.length < 2) { throw new Error( `Couldn't extract verb from sub-Request:\n ${subRequest}` ); } const fullRequestURI = subRequest.match(/((http+s?)(\S)+)/); if (fullRequestURI === null || fullRequestURI.length < 3) { throw new Error( `Couldn't extract full request URL from sub-Request:\n ${subRequest}` ); } // extract the request path const path = this.extractPath(fullRequestURI[1]); if (path === null || path.length < 2) { throw new Error( `Couldn't extract path from URL in sub-Request:\n ${subRequest}` ); } const jsonOperationBody = subRequest.match(/{+.+}+/); // ToDo: not sure if this logic is valid, it might be better // to just have an empty body and then error out when determining routing of request in Handler if ( subRequests.length > 1 && null !== requestType && requestType[0] !== "DELETE" && (jsonOperationBody === null || jsonOperationBody.length < 1) ) { throw new Error( `Couldn't extract path from sub-Request:\n ${subRequest}` ); } let headers: string; let jsonBody: string; let subStringStart: number; let subStringEnd: number; // currently getting an invalid header in the first position // during table entity test for insert & merge subStringStart = subRequest.indexOf(fullRequestURI[1]); subStringStart += fullRequestURI[1].length + 1; // for the space if (jsonOperationBody != null) { // we need the jsonBody and request path extracted to be able to extract headers. subStringEnd = subRequest.indexOf(jsonOperationBody[0]); jsonBody = jsonOperationBody[0]; } else { // remove 1 \r\n subStringEnd = subRequest.length - 4; jsonBody = ""; } headers = subRequest.substring(subStringStart, subStringEnd); const operation = new TableBatchOperation(BatchType.table, headers); if (null !== requestType) { operation.httpMethod = requestType[0] as HttpMethod; } operation.path = path[1]; operation.uri = fullRequestURI[0]; operation.jsonRequestBody = jsonBody; return operation; } ); return batchOperations; } /** * Serializes an Insert entity response * * @param {BatchRequest} request * @param {Models.TableInsertEntityResponse} response * @return {*} {string} * @memberof TableBatchSerialization */ public serializeTableInsertEntityBatchResponse( request: BatchRequest, response: Models.TableInsertEntityResponse ): string { let serializedResponses: string = ""; serializedResponses = this.SetContentTypeAndEncoding(serializedResponses); serializedResponses = this.serializeHttpStatusCode( serializedResponses, response.statusCode ); // ToDo: Correct the handling of Content-ID if (request.contentID !== undefined) { serializedResponses += "Content-ID: " + request.contentID.toString() + "\r\n"; } serializedResponses = this.SerializeNoSniffNoCache(serializedResponses); serializedResponses = this.serializePreferenceApplied( request, serializedResponses ); serializedResponses = this.serializeDataServiceVersion( serializedResponses, request ); serializedResponses += "Location: " + this.SerializeEntityPath(serializedResponses, request); serializedResponses += "DataServiceId: " + this.SerializeEntityPath(serializedResponses, request); if (null !== response.eTag && undefined !== response.eTag) { serializedResponses += "ETag: " + response.eTag; } return serializedResponses; } /** * creates the serialized entitygrouptransaction / batch response body * which we return to the users batch request * * @param {BatchRequest} request * @param {Models.TableDeleteEntityResponse} response * @return {*} {string} * @memberof TableBatchSerialization */ public serializeTableDeleteEntityBatchResponse( request: BatchRequest, response: Models.TableDeleteEntityResponse ): string { // ToDo: keeping my life easy to start and defaulting to "return no content" let serializedResponses: string = ""; // create the initial boundary serializedResponses = this.SetContentTypeAndEncoding(serializedResponses); serializedResponses = this.serializeHttpStatusCode( serializedResponses, response.statusCode ); serializedResponses = this.SerializeNoSniffNoCache(serializedResponses); serializedResponses = this.serializeDataServiceVersion( serializedResponses, request ); return serializedResponses; } /** * Serializes the Update Entity Batch Response * * @param {BatchRequest} request * @param {Models.TableUpdateEntityResponse} response * @return {*} {string} * @memberof TableBatchSerialization */ public serializeTableUpdateEntityBatchResponse( request: BatchRequest, response: Models.TableUpdateEntityResponse ): string { let serializedResponses: string = ""; // create the initial boundary serializedResponses = this.SetContentTypeAndEncoding(serializedResponses); serializedResponses = this.serializeHttpStatusCode( serializedResponses, response.statusCode ); // ToDo_: Correct the handling of content-ID if (request.contentID) { serializedResponses += "Content-ID: " + request.contentID.toString() + "\r\n"; } serializedResponses = this.SerializeNoSniffNoCache(serializedResponses); serializedResponses = this.serializePreferenceApplied( request, serializedResponses ); serializedResponses = this.serializeDataServiceVersion( serializedResponses, request ); if (null !== response.eTag && undefined !== response.eTag) { serializedResponses += "ETag: " + response.eTag; } return serializedResponses; } /** * Serializes the preference applied header * * @private * @param {BatchRequest} request * @param {string} serializedResponses * @return {*} * @memberof TableBatchSerialization */ private serializePreferenceApplied( request: BatchRequest, serializedResponses: string ) { if (request.getHeader("Preference-Applied")) { serializedResponses += "Preference-Applied: " + request.getHeader("Preference-Applied") + "\r\n"; } return serializedResponses; } /** * Serializes the Merge Entity Response * * @param {BatchRequest} request * @param {Models.TableMergeEntityResponse} response * @return {*} {string} * @memberof TableBatchSerialization */ public serializeTablMergeEntityBatchResponse( request: BatchRequest, response: Models.TableMergeEntityResponse ): string { let serializedResponses: string = ""; serializedResponses = this.SetContentTypeAndEncoding(serializedResponses); serializedResponses = this.serializeHttpStatusCode( serializedResponses, response.statusCode ); serializedResponses = this.SerializeNoSniffNoCache(serializedResponses); // ToDo_: Correct the handling of content-ID if (request.contentID) { serializedResponses += "Content-ID: " + request.contentID.toString() + "\r\n"; } // ToDo: not sure about other headers like cache control etc right now // Service defaults to v1.0 serializedResponses = this.serializeDataServiceVersion( serializedResponses, request ); if (null !== response.eTag && undefined !== response.eTag) { serializedResponses += "ETag: " + response.eTag; } return serializedResponses; } /** * Serializes the Query Entity Response when using Partition and Row Key * * @param {BatchRequest} request * @param {Models.TableQueryEntitiesWithPartitionAndRowKeyResponse} response * @return {*} {Promise<string>} * @memberof TableBatchSerialization */ public async serializeTableQueryEntityWithPartitionAndRowKeyBatchResponse( request: BatchRequest, response: Models.TableQueryEntitiesWithPartitionAndRowKeyResponse ): Promise<string> { let serializedResponses: string = ""; // create the initial boundary serializedResponses = this.SetContentTypeAndEncoding(serializedResponses); serializedResponses = this.serializeHttpStatusCode( serializedResponses, response.statusCode ); serializedResponses = this.serializeDataServiceVersion( serializedResponses, request ); serializedResponses += "Content-Type: "; serializedResponses += request.params.queryOptions?.format; serializedResponses += ";streaming=true;charset=utf-8\r\n"; // getting this from service, so adding here as well serializedResponses = this.SerializeNoSniffNoCache(serializedResponses); if (response.eTag) { serializedResponses += "ETag: " + response.eTag; } serializedResponses += "\r\n"; // now we need to return the JSON body // ToDo: I don't like the stream to string to stream conversion here... // just not sure there is any way around it if (response.body != null) { try { serializedResponses += await TableBatchUtils.StreamToString( response.body ); } catch { // do nothing throw new Error("failed to deserialize body"); } } serializedResponses += "\r\n"; return serializedResponses; } /** * Serializes query entity response * * @param {BatchRequest} request * @param {Models.TableQueryEntitiesResponse} response * @return {*} {Promise<string>} * @memberof TableBatchSerialization */ public async serializeTableQueryEntityBatchResponse( request: BatchRequest, response: Models.TableQueryEntitiesResponse ): Promise<string> { let serializedResponses: string = ""; serializedResponses = this.SetContentTypeAndEncoding(serializedResponses); serializedResponses = this.serializeHttpStatusCode( serializedResponses, response.statusCode ); serializedResponses = this.serializeDataServiceVersion( serializedResponses, request ); serializedResponses += "Content-Type: "; serializedResponses += request.params.queryOptions?.format; serializedResponses += ";streaming=true;charset=utf-8\r\n"; // getting this from service, so adding as well // Azure Table service defaults to this in the response // X-Content-Type-Options: nosniff\r\n serializedResponses = this.SerializeNoSniffNoCache(serializedResponses); serializedResponses += "\r\n"; // now we need to return the JSON body // ToDo: I don't like the stream to string to stream conversion here... // just not sure there is any way around it if (response.body != null) { try { serializedResponses += await TableBatchUtils.StreamToString( response.body ); } catch { // Throw a more helpful error throw new Error("failed to deserialize body"); } } serializedResponses += "\r\n"; return serializedResponses; } /** * Serializes content type and encoding * * @private * @param {string} serializedResponses * @return {*} * @memberof TableBatchSerialization */ private SetContentTypeAndEncoding(serializedResponses: string) { serializedResponses += "\r\nContent-Type: application/http\r\n"; serializedResponses += "Content-Transfer-Encoding: binary\r\n"; serializedResponses += "\r\n"; return serializedResponses; } /** * Serializes Content Type Options and Cache Control * THese seem to be service defaults * * @private * @param {string} serializedResponses * @return {*} * @memberof TableBatchSerialization */ private SerializeNoSniffNoCache(serializedResponses: string) { serializedResponses = this.SerializeXContentTypeOptions( serializedResponses ); serializedResponses += "Cache-Control: no-cache\r\n"; return serializedResponses; } private SerializeXContentTypeOptions(serializedResponses: string) { serializedResponses += "X-Content-Type-Options: nosniff\r\n"; return serializedResponses; } /** * Serializes the HTTP response * ToDo: Need to check where we have implemented this elsewhere and see if we can reuse * * @private * @param {number} statusCode * @return {*} {string} * @memberof TableBatchSerialization */ private GetStatusMessageString(statusCode: number): string { switch (statusCode) { case 200: return "OK"; case 201: return "Created"; case 204: return "No Content"; case 404: return "Not Found"; case 400: return "Bad Request"; default: return "STATUS_CODE_NOT_IMPLEMENTED"; } } /** * extract a header request string * * @private * @param {string} batchRequestsString * @param {string} regExPattern * @return {*} * @memberof TableBatchSerialization */ private extractRequestHeaderString( batchRequestsString: string, regExPattern: string ) { const headerStringMatches = batchRequestsString.match(regExPattern); if (headerStringMatches == null) { throw StorageError; } return headerStringMatches[2]; } /** * Serialize HTTP Status Code * * @private * @param {string} serializedResponses * @param {*} response * @return {*} * @memberof TableBatchSerialization */ private serializeHttpStatusCode( serializedResponses: string, statusCode: number ) { serializedResponses += "HTTP/1.1 " + statusCode.toString() + " " + this.GetStatusMessageString(statusCode) + "\r\n"; return serializedResponses; } /** * Serializes the Location and DataServiceId for the response * These 2 headers should point to the result of the successful insert * https://docs.microsoft.com/de-de/dotnet/api/microsoft.azure.batch.addtaskresult.location?view=azure-dotnet#Microsoft_Azure_Batch_AddTaskResult_Location * https://docs.microsoft.com/de-de/dotnet/api/microsoft.azure.batch.protocol.models.taskgetheaders.dataserviceid?view=azure-dotnet * i.e. Location: http://127.0.0.1:10002/devstoreaccount1/SampleHubVSHistory(PartitionKey='7219c1f2e2674f249bf9589d31ab3c6e',RowKey='sentinel') * * @private * @param {string} serializedResponses * @param {BatchRequest} request * @return {string} * @memberof TableBatchSerialization */ private SerializeEntityPath( serializedResponses: string, request: BatchRequest ): string { let parenthesesPosition: number = request.getUrl().indexOf("("); parenthesesPosition--; if (parenthesesPosition < 0) { parenthesesPosition = request.getUrl().length; } const trimmedUrl: string = request .getUrl() .substring(0, parenthesesPosition); let entityPath = trimmedUrl + "(PartitionKey='"; entityPath += request.params.tableEntityProperties!.PartitionKey; entityPath += "',"; entityPath += "RowKey='"; entityPath += request.params.tableEntityProperties!.RowKey; entityPath += "')\r\n"; return entityPath; } /** * serializes data service version * * @private * @param {BatchRequest} request * @param {string} serializedResponses * @return {*} * @memberof TableBatchSerialization */ private serializeDataServiceVersion( serializedResponses: string, request: BatchRequest | undefined ) { if ( undefined !== request && undefined !== request.params && request.params.dataServiceVersion ) { serializedResponses += "DataServiceVersion: " + request.params.dataServiceVersion + ";\r\n"; } else { // default to 3.0 serializedResponses += "DataServiceVersion: 3.0;\r\n"; } return serializedResponses; } /** * Serializes an error generated during batch processing * https://docs.microsoft.com/en-us/rest/api/storageservices/performing-entity-group-transactions#sample-error-response * @private * @param {*} err * @return {*} {string} * @memberof TableBatchSerialization */ public serializeError( err: any, contentID: number, request: BatchRequest ): string { let errorReponse = ""; const odataError = err as StorageError; // Errors in batch processing generate Bad Request error errorReponse = this.serializeHttpStatusCode(errorReponse, 400); errorReponse += "Content-ID: " + contentID + "\r\n"; errorReponse = this.serializeDataServiceVersion(errorReponse, request); // ToDo: Check if we need to observe other odata formats for errors errorReponse += "Content-Type: application/json;odata=minimalmetadata;charset=utf-8\r\n"; errorReponse += "\r\n"; errorReponse += odataError.body + "\r\n"; return errorReponse; } /** * Serializes top level errors not generated from individual request processing * * @param {string} odataErrorString * @param {(string | undefined)} requestId * @return {*} {string} * @memberof TableBatchSerialization */ public serializeGeneralRequestError( odataErrorString: string, requestId: string | undefined ): string { const changesetBoundary = this.changesetBoundary.replace( "changeset", "changesetresponse" ); let errorReponse = ""; errorReponse += changesetBoundary + "\r\n"; // Errors in batch processing generate Bad Request error errorReponse = this.serializeHttpStatusCode(errorReponse, 400); errorReponse = this.SerializeXContentTypeOptions(errorReponse); errorReponse = this.serializeDataServiceVersion(errorReponse, undefined); // ToDo: Serialize Content type etc errorReponse += "Content-Type: application/json;odata=minimalmetadata;charset=utf-8\r\n"; errorReponse += "\r\n"; let requestIdResponseString = ""; if (requestId !== undefined) { requestIdResponseString = `RequestId:${requestId}\\n`; } // 2021-04-23T12:40:31.4944778 const date = truncatedISO8061Date(new Date(), true); errorReponse += `{\"odata.error\":{\"code\":\"InvalidInput\",\"message\":{\"lang\":\"en-US\",\"value\":\"${odataErrorString}\\n${requestIdResponseString}Time:${date}\"}}}\r\n`; return errorReponse; } }
the_stack
import {JSONObject, JSONValue} from 'proto3-json-serializer'; import {Field} from 'protobufjs'; import {google} from '../protos/http'; import {camelToSnakeCase, snakeToCamelCase} from './util'; export interface TranscodedRequest { httpMethod: 'get' | 'post' | 'put' | 'patch' | 'delete'; url: string; queryString: string; data: string | {}; } const httpOptionName = '(google.api.http)'; const fieldBehaviorOptionName = '(google.api.field_behavior)'; const proto3OptionalName = 'proto3_optional'; // The following type is here only to make tests type safe type allowedOptions = '(google.api.method_signature)'; // List of methods as defined in google/api/http.proto (see HttpRule) const supportedHttpMethods: Array<'get' | 'put' | 'post' | 'patch' | 'delete'> = ['get', 'post', 'put', 'patch', 'delete']; export type ParsedOptionsType = Array< { [httpOptionName]?: google.api.IHttpRule; } & { [option in allowedOptions]?: {} | string | number; } >; export function getField( request: JSONObject, field: string ): JSONValue | undefined { const parts = field.split('.'); let value: JSONValue = request; for (const part of parts) { if (typeof value !== 'object') { return undefined; } value = (value as JSONObject)[part] as JSONValue; } if (typeof value === 'object' && !Array.isArray(value) && value !== null) { return undefined; } return value; } export function deepCopy(request: JSONObject): JSONObject { if (typeof request !== 'object' || request === null) { return request; } const copy = Object.assign({}, request); for (const key in copy) { if (Array.isArray(copy[key])) { copy[key] = (copy[key] as JSONObject[]).map(deepCopy); } else if (typeof copy[key] === 'object' && copy[key] !== null) { copy[key] = deepCopy(copy[key] as JSONObject); } } return copy; } export function deleteField(request: JSONObject, field: string): void { const parts = field.split('.'); while (parts.length > 1) { if (typeof request !== 'object') { return; } const part = parts.shift() as string; request = request[part] as JSONObject; } const part = parts.shift() as string; if (typeof request !== 'object') { return; } delete request[part]; } export function buildQueryStringComponents( request: JSONObject, prefix = '' ): string[] { const resultList = []; for (const key in request) { if (Array.isArray(request[key])) { for (const value of request[key] as JSONObject[]) { resultList.push( `${prefix}${encodeWithoutSlashes(key)}=${encodeWithoutSlashes( value.toString() )}` ); } } else if (typeof request[key] === 'object' && request[key] !== null) { resultList.push( ...buildQueryStringComponents(request[key] as JSONObject, `${key}.`) ); } else { resultList.push( `${prefix}${encodeWithoutSlashes(key)}=${encodeWithoutSlashes( request[key] === null ? 'null' : request[key]!.toString() )}` ); } } return resultList; } export function encodeWithSlashes(str: string): string { return str .split('') .map(c => (c.match(/[-_.~0-9a-zA-Z]/) ? c : encodeURIComponent(c))) .join(''); } export function encodeWithoutSlashes(str: string): string { return str .split('') .map(c => (c.match(/[-_.~0-9a-zA-Z/]/) ? c : encodeURIComponent(c))) .join(''); } function escapeRegExp(str: string) { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } export function applyPattern( pattern: string, fieldValue: string ): string | undefined { if (!pattern || pattern === '*') { return encodeWithSlashes(fieldValue); } if (!pattern.includes('*') && pattern !== fieldValue) { return undefined; } // since we're converting the pattern to a regex, make necessary precautions: const regex = new RegExp( '^' + escapeRegExp(pattern) .replace(/\\\*\\\*/g, '(.+)') .replace(/\\\*/g, '([^/]+)') + '$' ); if (!fieldValue.match(regex)) { return undefined; } return encodeWithoutSlashes(fieldValue); } interface MatchResult { matchedFields: string[]; url: string; } export function match( request: JSONObject, pattern: string ): MatchResult | undefined { let url = pattern; const matchedFields = []; for (;;) { const match = url.match(/^(.*)\{([^}=]+)(?:=([^}]*))?\}(.*)/); if (!match) { break; } const [, before, field, pattern, after] = match; matchedFields.push(field); const fieldValue = getField(request, field); if (typeof fieldValue === 'undefined') { return undefined; } const appliedPattern = applyPattern( pattern, fieldValue === null ? 'null' : fieldValue!.toString() ); if (typeof appliedPattern === 'undefined') { return undefined; } url = before + appliedPattern + after; } return {matchedFields, url}; } export function flattenObject(request: JSONObject): JSONObject { const result: JSONObject = {}; for (const key in request) { if (typeof request[key] === 'undefined') { continue; } if (Array.isArray(request[key])) { // According to the http.proto comments, a repeated field may only // contain primitive types, so no extra recursion here. result[key] = request[key]; continue; } if (typeof request[key] === 'object' && request[key] !== null) { const nested = flattenObject(request[key] as JSONObject); for (const nestedKey in nested) { result[`${key}.${nestedKey}`] = nested[nestedKey]; } continue; } result[key] = request[key]; } return result; } export function requestChangeCaseAndCleanup( request: JSONObject, caseChangeFunc: (key: string) => string ) { if (!request || typeof request !== 'object') { return request; } const convertedRequest: JSONObject = {}; for (const field in request) { // cleaning up inherited properties if (!Object.prototype.hasOwnProperty.call(request, field)) { continue; } const convertedField = caseChangeFunc(field); const value = request[field]; if (Array.isArray(value)) { convertedRequest[convertedField] = value.map(v => requestChangeCaseAndCleanup(v as JSONObject, caseChangeFunc) ); } else { convertedRequest[convertedField] = requestChangeCaseAndCleanup( value as JSONObject, caseChangeFunc ); } } return convertedRequest; } export function isProto3OptionalField(field: Field) { return field && field.options && field.options![proto3OptionalName]; } export function isRequiredField(field: Field) { return ( field && field.options && field.options![fieldBehaviorOptionName] === 'REQUIRED' ); } export function getFieldNameOnBehavior( fields: {[k: string]: Field} | undefined ) { const requiredFields = new Set<string>(); const optionalFields = new Set<string>(); for (const fieldName in fields) { const field = fields[fieldName]; if (isRequiredField(field)) { requiredFields.add(fieldName); } if (isProto3OptionalField(field)) { optionalFields.add(fieldName); } } return {requiredFields, optionalFields}; } export function transcode( request: JSONObject, parsedOptions: ParsedOptionsType, requestFields?: {[k: string]: Field} ): TranscodedRequest | undefined { const {requiredFields, optionalFields} = getFieldNameOnBehavior(requestFields); // all fields annotated as REQUIRED MUST be emitted in the body. for (const requiredField of requiredFields) { if (!(requiredField in request) || request[requiredField] === 'undefined') { throw new Error( `Required field ${requiredField} is not present in the request.` ); } } // request is supposed to have keys in camelCase. const snakeRequest = requestChangeCaseAndCleanup(request, camelToSnakeCase); const httpRules = []; for (const option of parsedOptions) { if (!(httpOptionName in option)) { continue; } const httpRule = option[httpOptionName] as google.api.IHttpRule; httpRules.push(httpRule); if (httpRule?.additional_bindings) { const additionalBindings = Array.isArray(httpRule.additional_bindings) ? httpRule.additional_bindings : [httpRule.additional_bindings]; httpRules.push(...additionalBindings); } } for (const httpRule of httpRules) { for (const httpMethod of supportedHttpMethods) { if (!(httpMethod in httpRule)) { continue; } const pathTemplate = httpRule[ httpMethod as keyof google.api.IHttpRule ] as string; const matchResult = match(snakeRequest, pathTemplate); if (typeof matchResult === 'undefined') { continue; } const {url, matchedFields} = matchResult; if (httpRule.body === '*') { // all fields except the matched fields go to request data const data = deepCopy(snakeRequest); for (const field of matchedFields) { deleteField(data, field); } // Remove unset proto3 optional field from the request body. for (const key in data) { if ( optionalFields.has(snakeToCamelCase(key)) && (!(key in snakeRequest) || snakeRequest[key] === 'undefined') ) { delete data[key]; } } // HTTP endpoint expects camelCase but we have snake_case at this point const camelCaseData = requestChangeCaseAndCleanup( data, snakeToCamelCase ); return {httpMethod, url, queryString: '', data: camelCaseData}; } // one field possibly goes to request data, others go to query string const body = httpRule.body; let data: string | JSONObject = ''; const queryStringObject = deepCopy(request); // use camel case for query string if (body) { deleteField(queryStringObject, snakeToCamelCase(body)); // Unset optional field should not add in body request. data = optionalFields.has(body) && snakeRequest[body] === 'undefined' ? '' : (snakeRequest[body] as JSONObject); } for (const field of matchedFields) { deleteField(queryStringObject, snakeToCamelCase(field)); } // Unset proto3 optional field does not appear in the query params. for (const key in queryStringObject) { if (optionalFields.has(key) && request[key] === 'undefined') { delete queryStringObject[key]; } } const queryStringComponents = buildQueryStringComponents(queryStringObject); const queryString = queryStringComponents.join('&'); let camelCaseData: string | JSONObject; if (typeof data === 'string') { camelCaseData = data; } else { camelCaseData = requestChangeCaseAndCleanup(data, snakeToCamelCase); } return {httpMethod, url, queryString, data: camelCaseData}; } } return undefined; }
the_stack
import type { CodeWithSourceMap } from 'source-map'; import { SourceNode } from 'source-map'; import type { CompletionItem, Hover, Position } from 'vscode-languageserver'; import { CompletionItemKind, SymbolKind, Location, SignatureInformation, ParameterInformation, DocumentSymbol, SymbolInformation, TextEdit } from 'vscode-languageserver'; import chalk from 'chalk'; import * as path from 'path'; import type { Scope } from '../Scope'; import { DiagnosticCodeMap, diagnosticCodes, DiagnosticMessages } from '../DiagnosticMessages'; import { FunctionScope } from '../FunctionScope'; import type { Callable, CallableArg, CallableParam, CommentFlag, FunctionCall, BsDiagnostic, FileReference } from '../interfaces'; import type { Token } from '../lexer'; import { Lexer, TokenKind, AllowedLocalIdentifiers, Keywords } from '../lexer'; import { Parser, ParseMode } from '../parser'; import type { FunctionExpression, VariableExpression, Expression } from '../parser/Expression'; import type { ClassStatement, FunctionStatement, NamespaceStatement, ClassMethodStatement, AssignmentStatement, LibraryStatement, ImportStatement, Statement, ClassFieldStatement } from '../parser/Statement'; import type { FileLink, Program, SignatureInfoObj } from '../Program'; import { DynamicType } from '../types/DynamicType'; import { FunctionType } from '../types/FunctionType'; import { VoidType } from '../types/VoidType'; import { standardizePath as s, util } from '../util'; import { BrsTranspileState } from '../parser/BrsTranspileState'; import { Preprocessor } from '../preprocessor/Preprocessor'; import { LogLevel } from '../Logger'; import { serializeError } from 'serialize-error'; import { isCallExpression, isClassMethodStatement, isClassStatement, isCommentStatement, isDottedGetExpression, isFunctionExpression, isFunctionStatement, isFunctionType, isLibraryStatement, isLiteralExpression, isNamespaceStatement, isStringType, isVariableExpression, isXmlFile, isImportStatement, isClassFieldStatement } from '../astUtils/reflection'; import type { BscType } from '../types/BscType'; import { createVisitor, WalkMode } from '../astUtils/visitors'; import type { DependencyGraph } from '../DependencyGraph'; import { CommentFlagProcessor } from '../CommentFlagProcessor'; /** * Holds all details about this file within the scope of the whole program */ export class BrsFile { constructor( public pathAbsolute: string, /** * The full pkg path to this file */ public pkgPath: string, public program: Program ) { this.pathAbsolute = s`${this.pathAbsolute}`; this.pkgPath = s`${this.pkgPath}`; this.dependencyGraphKey = this.pkgPath.toLowerCase(); this.extension = util.getExtension(this.pathAbsolute); //all BrighterScript files need to be transpiled if (this.extension?.endsWith('.bs')) { this.needsTranspiled = true; this.parseMode = ParseMode.BrighterScript; } this.isTypedef = this.extension === '.d.bs'; if (!this.isTypedef) { this.typedefKey = util.getTypedefPath(this.pathAbsolute); } //global file doesn't have a program, so only resolve typedef info if we have a program if (this.program) { this.resolveTypedef(); } } /** * The parseMode used for the parser for this file */ public parseMode = ParseMode.BrightScript; /** * The key used to identify this file in the dependency graph */ public dependencyGraphKey: string; /** * The all-lowercase extension for this file (including the leading dot) */ public extension: string; private diagnostics = [] as BsDiagnostic[]; public getDiagnostics() { return [...this.diagnostics]; } public addDiagnostics(diagnostics: BsDiagnostic[]) { this.diagnostics.push(...diagnostics); } public commentFlags = [] as CommentFlag[]; public callables = [] as Callable[]; public functionCalls = [] as FunctionCall[]; private _functionScopes: FunctionScope[]; public get functionScopes(): FunctionScope[] { if (!this._functionScopes) { this.createFunctionScopes(); } return this._functionScopes; } /** * files referenced by import statements */ public ownScriptImports = [] as FileReference[]; /** * Does this file need to be transpiled? */ public needsTranspiled = false; /** * The AST for this file */ public get ast() { return this.parser.ast; } private documentSymbols: DocumentSymbol[]; private workspaceSymbols: SymbolInformation[]; /** * Get the token at the specified position * @param position */ public getTokenAt(position: Position) { for (let token of this.parser.tokens) { if (util.rangeContains(token.range, position)) { return token; } } } public get parser() { if (!this._parser) { //remove the typedef file (if it exists) this.hasTypedef = false; this.typedefFile = undefined; //parse the file (it should parse fully since there's no linked typedef this.parse(this.fileContents); //re-link the typedef (if it exists...which it should) this.resolveTypedef(); } return this._parser; } private _parser: Parser; public fileContents: string; /** * If this is a typedef file */ public isTypedef: boolean; /** * The key to find the typedef file in the program's files map. * A falsey value means this file is ineligable for a typedef */ public typedefKey?: string; /** * If the file was given type definitions during parse */ public hasTypedef; /** * A reference to the typedef file (if one exists) */ public typedefFile?: BrsFile; /** * An unsubscribe function for the dependencyGraph subscription */ private unsubscribeFromDependencyGraph: () => void; /** * Find and set the typedef variables (if a matching typedef file exists) */ private resolveTypedef() { this.typedefFile = this.program.getFileByPathAbsolute<BrsFile>(this.typedefKey); this.hasTypedef = !!this.typedefFile; } /** * Attach the file to the dependency graph so it can monitor changes. * Also notify the dependency graph of our current dependencies so other dependents can be notified. */ public attachDependencyGraph(dependencyGraph: DependencyGraph) { if (this.unsubscribeFromDependencyGraph) { this.unsubscribeFromDependencyGraph(); } //event that fires anytime a dependency changes this.unsubscribeFromDependencyGraph = dependencyGraph.onchange(this.dependencyGraphKey, () => { this.resolveTypedef(); }); const dependencies = this.ownScriptImports.filter(x => !!x.pkgPath).map(x => x.pkgPath.toLowerCase()); //if this is a .brs file, watch for typedef changes if (this.extension === '.brs') { dependencies.push( util.getTypedefPath(this.pkgPath) ); } dependencyGraph.addOrReplace(this.dependencyGraphKey, dependencies); } /** * Calculate the AST for this file * @param fileContents */ public parse(fileContents: string) { try { this.fileContents = fileContents; this.diagnostics = []; //if we have a typedef file, skip parsing this file if (this.hasTypedef) { return; } //tokenize the input file let lexer = this.program.logger.time(LogLevel.debug, ['lexer.lex', chalk.green(this.pathAbsolute)], () => { return Lexer.scan(fileContents, { includeWhitespace: false }); }); this.getCommentFlags(lexer.tokens); let preprocessor = new Preprocessor(); //remove all code inside false-resolved conditional compilation statements. //TODO preprocessor should go away in favor of the AST handling this internally (because it affects transpile) //currently the preprocessor throws exceptions on syntax errors...so we need to catch it try { this.program.logger.time(LogLevel.debug, ['preprocessor.process', chalk.green(this.pathAbsolute)], () => { preprocessor.process(lexer.tokens, this.program.getManifest()); }); } catch (error: any) { //if the thrown error is DIFFERENT than any errors from the preprocessor, add that error to the list as well if (this.diagnostics.find((x) => x === error) === undefined) { this.diagnostics.push(error); } } //if the preprocessor generated tokens, use them. let tokens = preprocessor.processedTokens.length > 0 ? preprocessor.processedTokens : lexer.tokens; this.program.logger.time(LogLevel.debug, ['parser.parse', chalk.green(this.pathAbsolute)], () => { this._parser = Parser.parse(tokens, { mode: this.parseMode, logger: this.program.logger }); }); //absorb all lexing/preprocessing/parsing diagnostics this.diagnostics.push( ...lexer.diagnostics as BsDiagnostic[], ...preprocessor.diagnostics as BsDiagnostic[], ...this._parser.diagnostics as BsDiagnostic[] ); //notify AST ready this.program.plugins.emit('afterFileParse', this); //extract all callables from this file this.findCallables(); //find all places where a sub/function is being called this.findFunctionCalls(); this.findAndValidateImportAndImportStatements(); //attach this file to every diagnostic for (let diagnostic of this.diagnostics) { diagnostic.file = this; } } catch (e) { this._parser = new Parser(); this.diagnostics.push({ file: this, range: util.createRange(0, 0, 0, Number.MAX_VALUE), ...DiagnosticMessages.genericParserMessage('Critical error parsing file: ' + JSON.stringify(serializeError(e))) }); } } public findAndValidateImportAndImportStatements() { let topOfFileIncludeStatements = [] as Array<LibraryStatement | ImportStatement>; for (let stmt of this.ast.statements) { //skip comments if (isCommentStatement(stmt)) { continue; } //if we found a non-library statement, this statement is not at the top of the file if (isLibraryStatement(stmt) || isImportStatement(stmt)) { topOfFileIncludeStatements.push(stmt); } else { //break out of the loop, we found all of our library statements break; } } let statements = [ ...this._parser.references.libraryStatements, ...this._parser.references.importStatements ]; for (let result of statements) { //register import statements if (isImportStatement(result) && result.filePathToken) { this.ownScriptImports.push({ filePathRange: result.filePathToken.range, pkgPath: util.getPkgPathFromTarget(this.pkgPath, result.filePath), sourceFile: this, text: result.filePathToken?.text }); } //if this statement is not one of the top-of-file statements, //then add a diagnostic explaining that it is invalid if (!topOfFileIncludeStatements.includes(result)) { if (isLibraryStatement(result)) { this.diagnostics.push({ ...DiagnosticMessages.libraryStatementMustBeDeclaredAtTopOfFile(), range: result.range, file: this }); } else if (isImportStatement(result)) { this.diagnostics.push({ ...DiagnosticMessages.importStatementMustBeDeclaredAtTopOfFile(), range: result.range, file: this }); } } } } /** * Find a class. This scans all scopes for this file, and returns the first matching class that is found. * Returns undefined if not found. * @param className - The class name, including the namespace of the class if possible * @param containingNamespace - The namespace used to resolve relative class names. (i.e. the namespace around the current statement trying to find a class) * @returns the first class in the first scope found, or undefined if not found */ public getClassFileLink(className: string, containingNamespace?: string): FileLink<ClassStatement> { const lowerClassName = className.toLowerCase(); const lowerContainingNamespace = containingNamespace?.toLowerCase(); const scopes = this.program.getScopesForFile(this); //find the first class in the first scope that has it for (let scope of scopes) { const cls = scope.getClassFileLink(lowerClassName, lowerContainingNamespace); if (cls) { return cls; } } } public findPropertyNameCompletions(): CompletionItem[] { //Build completion items from all the "properties" found in the file const { propertyHints } = this.parser.references; const results = [] as CompletionItem[]; for (const key of Object.keys(propertyHints)) { results.push({ label: propertyHints[key], kind: CompletionItemKind.Text }); } return results; } private _propertyNameCompletions: CompletionItem[]; public get propertyNameCompletions(): CompletionItem[] { if (!this._propertyNameCompletions) { this._propertyNameCompletions = this.findPropertyNameCompletions(); } return this._propertyNameCompletions; } /** * Find all comment flags in the source code. These enable or disable diagnostic messages. * @param lines - the lines of the program */ public getCommentFlags(tokens: Token[]) { const processor = new CommentFlagProcessor(this, ['rem', `'`], diagnosticCodes, [DiagnosticCodeMap.unknownDiagnosticCode]); this.commentFlags = []; for (let token of tokens) { if (token.kind === TokenKind.Comment) { processor.tryAdd(token.text, token.range); } } this.commentFlags.push(...processor.commentFlags); this.diagnostics.push(...processor.diagnostics); } public scopesByFunc = new Map<FunctionExpression, FunctionScope>(); /** * Create a scope for every function in this file */ private createFunctionScopes() { //find every function let functions = this.parser.references.functionExpressions; //create a functionScope for every function this._functionScopes = []; for (let func of functions) { let scope = new FunctionScope(func); //find parent function, and add this scope to it if found { let parentScope = this.scopesByFunc.get(func.parentFunction); //add this child scope to its parent if (parentScope) { parentScope.childrenScopes.push(scope); } //store the parent scope for this scope scope.parentScope = parentScope; } //add every parameter for (let param of func.parameters) { scope.variableDeclarations.push({ nameRange: param.name.range, lineIndex: param.name.range.start.line, name: param.name.text, type: param.type }); } //add all of ForEachStatement loop varibales func.body?.walk(createVisitor({ ForEachStatement: (stmt) => { scope.variableDeclarations.push({ nameRange: stmt.item.range, lineIndex: stmt.item.range.start.line, name: stmt.item.text, type: new DynamicType() }); }, LabelStatement: (stmt) => { const { identifier } = stmt.tokens; scope.labelStatements.push({ nameRange: identifier.range, lineIndex: identifier.range.start.line, name: identifier.text }); } }), { walkMode: WalkMode.visitStatements }); this.scopesByFunc.set(func, scope); //find every statement in the scope this._functionScopes.push(scope); } //find every variable assignment in the whole file let assignmentStatements = this.parser.references.assignmentStatements; for (let statement of assignmentStatements) { //find this statement's function scope let scope = this.scopesByFunc.get(statement.containingFunction); //skip variable declarations that are outside of any scope if (scope) { scope.variableDeclarations.push({ nameRange: statement.name.range, lineIndex: statement.name.range.start.line, name: statement.name.text, type: this.getBscTypeFromAssignment(statement, scope) }); } } } private getBscTypeFromAssignment(assignment: AssignmentStatement, scope: FunctionScope): BscType { try { //function if (isFunctionExpression(assignment.value)) { let functionType = new FunctionType(assignment.value.returnType); functionType.isSub = assignment.value.functionType.text === 'sub'; if (functionType.isSub) { functionType.returnType = new VoidType(); } functionType.setName(assignment.name.text); for (let param of assignment.value.parameters) { let isRequired = !param.defaultValue; //TODO compute optional parameters functionType.addParameter(param.name.text, param.type, isRequired); } return functionType; //literal } else if (isLiteralExpression(assignment.value)) { return assignment.value.type; //function call } else if (isCallExpression(assignment.value)) { let calleeName = (assignment.value.callee as any)?.name?.text; if (calleeName) { let func = this.getCallableByName(calleeName); if (func) { return func.type.returnType; } } } else if (isVariableExpression(assignment.value)) { let variableName = assignment.value?.name?.text; let variable = scope.getVariableByName(variableName); return variable.type; } } catch (e) { //do nothing. Just return dynamic } //fallback to dynamic return new DynamicType(); } private getCallableByName(name: string) { name = name ? name.toLowerCase() : undefined; if (!name) { return; } for (let func of this.callables) { if (func.name.toLowerCase() === name) { return func; } } } private findCallables() { for (let statement of this.parser.references.functionStatements ?? []) { let functionType = new FunctionType(statement.func.returnType); functionType.setName(statement.name.text); functionType.isSub = statement.func.functionType.text.toLowerCase() === 'sub'; if (functionType.isSub) { functionType.returnType = new VoidType(); } //extract the parameters let params = [] as CallableParam[]; for (let param of statement.func.parameters) { let callableParam = { name: param.name.text, type: param.type, isOptional: !!param.defaultValue, isRestArgument: false }; params.push(callableParam); let isRequired = !param.defaultValue; functionType.addParameter(callableParam.name, callableParam.type, isRequired); } this.callables.push({ isSub: statement.func.functionType.text.toLowerCase() === 'sub', name: statement.name.text, nameRange: statement.name.range, file: this, params: params, range: statement.func.range, type: functionType, getName: statement.getName.bind(statement), hasNamespace: !!statement.namespaceName, functionStatement: statement }); } } private findFunctionCalls() { this.functionCalls = []; //for every function in the file for (let func of this._parser.references.functionExpressions) { //for all function calls in this function for (let expression of func.callExpressions) { if ( //filter out dotted function invocations (i.e. object.doSomething()) (not currently supported. TODO support it) (expression.callee as any).obj || //filter out method calls on method calls for now (i.e. getSomething().getSomethingElse()) (expression.callee as any).callee || //filter out callees without a name (immediately-invoked function expressions) !(expression.callee as any).name ) { continue; } let functionName = (expression.callee as any).name.text; //callee is the name of the function being called let callee = expression.callee as VariableExpression; let columnIndexBegin = callee.range.start.character; let columnIndexEnd = callee.range.end.character; let args = [] as CallableArg[]; //TODO convert if stmts to use instanceof instead for (let arg of expression.args as any) { //is a literal parameter value if (isLiteralExpression(arg)) { args.push({ range: arg.range, type: arg.type, text: arg.token.text }); //is variable being passed into argument } else if (arg.name) { args.push({ range: arg.range, //TODO - look up the data type of the actual variable type: new DynamicType(), text: arg.name.text }); } else if (arg.value) { let text = ''; /* istanbul ignore next: TODO figure out why value is undefined sometimes */ if (arg.value.value) { text = arg.value.value.toString(); } let callableArg = { range: arg.range, //TODO not sure what to do here type: new DynamicType(), // util.valueKindToBrsType(arg.value.kind), text: text }; //wrap the value in quotes because that's how it appears in the code if (isStringType(callableArg.type)) { callableArg.text = '"' + callableArg.text + '"'; } args.push(callableArg); } else { args.push({ range: arg.range, type: new DynamicType(), //TODO get text from other types of args text: '' }); } } let functionCall: FunctionCall = { range: util.createRangeFromPositions(expression.range.start, expression.closingParen.range.end), functionScope: this.getFunctionScopeAtPosition(callee.range.start), file: this, name: functionName, nameRange: util.createRange(callee.range.start.line, columnIndexBegin, callee.range.start.line, columnIndexEnd), //TODO keep track of parameters args: args }; this.functionCalls.push(functionCall); } } } /** * Find the function scope at the given position. * @param position * @param functionScopes */ public getFunctionScopeAtPosition(position: Position, functionScopes?: FunctionScope[]): FunctionScope { if (!functionScopes) { functionScopes = this.functionScopes; } for (let scope of functionScopes) { if (util.rangeContains(scope.range, position)) { //see if any of that scope's children match the position also, and give them priority let childScope = this.getFunctionScopeAtPosition(position, scope.childrenScopes); if (childScope) { return childScope; } else { return scope; } } } } /** * Get completions available at the given cursor. This aggregates all values from this file and the current scope. */ public getCompletions(position: Position, scope?: Scope): CompletionItem[] { let result = [] as CompletionItem[]; //a map of lower-case names of all added options let names = {} as Record<string, boolean>; //handle script import completions let scriptImport = util.getScriptImportAtPosition(this.ownScriptImports, position); if (scriptImport) { return this.program.getScriptImportCompletions(this.pkgPath, scriptImport); } //if cursor is within a comment, disable completions let currentToken = this.getTokenAt(position); const tokenKind = currentToken?.kind; if (tokenKind === TokenKind.Comment) { return []; } else if (tokenKind === TokenKind.StringLiteral || tokenKind === TokenKind.TemplateStringQuasi) { const match = /^("?)(pkg|libpkg):/.exec(currentToken.text); if (match) { const [, openingQuote, fileProtocol] = match; //include every absolute file path from this scope for (const file of scope.getAllFiles()) { const pkgPath = `${fileProtocol}:/${file.pkgPath.replace(/\\/g, '/')}`; result.push({ label: pkgPath, textEdit: TextEdit.replace( util.createRange( currentToken.range.start.line, //+1 to step past the opening quote currentToken.range.start.character + (openingQuote ? 1 : 0), currentToken.range.end.line, //-1 to exclude the closing quotemark (or the end character if there is no closing quotemark) currentToken.range.end.character + (currentToken.text.endsWith('"') ? -1 : 0) ), pkgPath ), kind: CompletionItemKind.File }); } return result; } else { //do nothing. we don't want to show completions inside of strings... return []; } } let namespaceCompletions = this.getNamespaceCompletions(currentToken, this.parseMode, scope); if (namespaceCompletions.length > 0) { return namespaceCompletions; } //determine if cursor is inside a function let functionScope = this.getFunctionScopeAtPosition(position); if (!functionScope) { //we aren't in any function scope, so return the keyword completions and namespaces if (this.getTokenBefore(currentToken, TokenKind.New)) { // there's a new keyword, so only class types are viable here return [...this.getGlobalClassStatementCompletions(currentToken, this.parseMode)]; } else { return [...KeywordCompletions, ...this.getGlobalClassStatementCompletions(currentToken, this.parseMode), ...namespaceCompletions]; } } const classNameCompletions = this.getGlobalClassStatementCompletions(currentToken, this.parseMode); const newToken = this.getTokenBefore(currentToken, TokenKind.New); if (newToken) { //we are after a new keyword; so we can only be namespaces or classes at this point result.push(...classNameCompletions); result.push(...namespaceCompletions); return result; } if (this.tokenFollows(currentToken, TokenKind.Goto)) { return this.getLabelCompletion(functionScope); } if (this.isPositionNextToTokenKind(position, TokenKind.Dot)) { if (namespaceCompletions.length > 0) { //if we matched a namespace, after a dot, it can't be anything else but something from our namespace completions return namespaceCompletions; } const selfClassMemberCompletions = this.getClassMemberCompletions(position, currentToken, functionScope, scope); if (selfClassMemberCompletions.size > 0) { return [...selfClassMemberCompletions.values()].filter((i) => i.label !== 'new'); } if (!this.getClassFromMReference(position, currentToken, functionScope)) { //and anything from any class in scope to a non m class let classMemberCompletions = scope.getAllClassMemberCompletions(); result.push(...classMemberCompletions.values()); result.push(...scope.getPropertyNameCompletions().filter((i) => !classMemberCompletions.has(i.label))); } else { result.push(...scope.getPropertyNameCompletions()); } } else { //include namespaces result.push(...namespaceCompletions); //include class names result.push(...classNameCompletions); //include the global callables result.push(...scope.getCallablesAsCompletions(this.parseMode)); //add `m` because that's always valid within a function result.push({ label: 'm', kind: CompletionItemKind.Variable }); names.m = true; result.push(...KeywordCompletions); //include local variables let variables = functionScope.variableDeclarations; for (let variable of variables) { //skip duplicate variable names if (names[variable.name.toLowerCase()]) { continue; } names[variable.name.toLowerCase()] = true; result.push({ label: variable.name, kind: isFunctionType(variable.type) ? CompletionItemKind.Function : CompletionItemKind.Variable }); } if (this.parseMode === ParseMode.BrighterScript) { //include the first part of namespaces let namespaces = scope.getAllNamespaceStatements(); for (let stmt of namespaces) { let firstPart = stmt.nameExpression.getNameParts().shift(); //skip duplicate namespace names if (names[firstPart.toLowerCase()]) { continue; } names[firstPart.toLowerCase()] = true; result.push({ label: firstPart, kind: CompletionItemKind.Module }); } } } return result; } private getLabelCompletion(functionScope: FunctionScope) { return functionScope.labelStatements.map(label => ({ label: label.name, kind: CompletionItemKind.Reference })); } private getClassMemberCompletions(position: Position, currentToken: Token, functionScope: FunctionScope, scope: Scope) { let classStatement = this.getClassFromMReference(position, currentToken, functionScope); let results = new Map<string, CompletionItem>(); if (classStatement) { let classes = scope.getClassHierarchy(classStatement.item.getName(ParseMode.BrighterScript).toLowerCase()); for (let cs of classes) { for (let member of [...cs?.item?.fields ?? [], ...cs?.item?.methods ?? []]) { if (!results.has(member.name.text.toLowerCase())) { results.set(member.name.text.toLowerCase(), { label: member.name.text, kind: isClassFieldStatement(member) ? CompletionItemKind.Field : CompletionItemKind.Function }); } } } } return results; } public getClassFromMReference(position: Position, currentToken: Token, functionScope: FunctionScope): FileLink<ClassStatement> | undefined { let previousToken = this.getPreviousToken(currentToken); if (previousToken?.kind === TokenKind.Dot) { previousToken = this.getPreviousToken(previousToken); } if (previousToken?.kind === TokenKind.Identifier && previousToken?.text.toLowerCase() === 'm' && isClassMethodStatement(functionScope.func.functionStatement)) { return { item: this.parser.references.classStatements.find((cs) => util.rangeContains(cs.range, position)), file: this }; } return undefined; } private getGlobalClassStatementCompletions(currentToken: Token, parseMode: ParseMode): CompletionItem[] { if (parseMode === ParseMode.BrightScript) { return []; } let results = new Map<string, CompletionItem>(); let completionName = this.getPartialVariableName(currentToken, [TokenKind.New])?.toLowerCase(); if (completionName?.includes('.')) { return []; } let scopes = this.program.getScopesForFile(this); for (let scope of scopes) { let classMap = scope.getClassMap(); // let viableKeys = [...classMap.keys()].filter((k) => k.startsWith(completionName)); for (const key of [...classMap.keys()]) { let cs = classMap.get(key).item; if (!results.has(cs.name.text)) { results.set(cs.name.text, { label: cs.name.text, kind: CompletionItemKind.Class }); } } } return [...results.values()]; } private getNamespaceCompletions(currentToken: Token, parseMode: ParseMode, scope: Scope): CompletionItem[] { //BrightScript does not support namespaces, so return an empty list in that case if (parseMode === ParseMode.BrightScript) { return []; } let completionName = this.getPartialVariableName(currentToken, [TokenKind.New]); if (!completionName) { return []; } //remove any trailing identifer and then any trailing dot, to give us the //name of its immediate parent namespace let closestParentNamespaceName = completionName.replace(/\.([a-z0-9_]*)?$/gi, ''); let newToken = this.getTokenBefore(currentToken, TokenKind.New); let result = new Map<string, CompletionItem>(); for (let [, namespace] of scope.namespaceLookup) { //completionName = "NameA." //completionName = "NameA.Na //NameA //NameA.NameB //NameA.NameB.NameC if (namespace.fullName.toLowerCase() === closestParentNamespaceName.toLowerCase()) { //add all of this namespace's immediate child namespaces, bearing in mind if we are after a new keyword for (let [, ns] of namespace.namespaces) { if (!newToken || ns.statements.find((s) => isClassStatement(s))) { if (!result.has(ns.lastPartName)) { result.set(ns.lastPartName, { label: ns.lastPartName, kind: CompletionItemKind.Module }); } } } //add function and class statement completions for (let stmt of namespace.statements) { if (isClassStatement(stmt)) { if (!result.has(stmt.name.text)) { result.set(stmt.name.text, { label: stmt.name.text, kind: CompletionItemKind.Class }); } } else if (isFunctionStatement(stmt) && !newToken) { if (!result.has(stmt.name.text)) { result.set(stmt.name.text, { label: stmt.name.text, kind: CompletionItemKind.Function }); } } } } } return [...result.values()]; } private getNamespaceDefinitions(token: Token, file: BrsFile): Location { //BrightScript does not support namespaces, so return an empty list in that case if (!token) { return undefined; } let location; const nameParts = this.getPartialVariableName(token, [TokenKind.New]).split('.'); const endName = nameParts[nameParts.length - 1].toLowerCase(); const namespaceName = nameParts.slice(0, -1).join('.').toLowerCase(); const statementHandler = (statement: NamespaceStatement) => { if (!location && statement.getName(ParseMode.BrighterScript).toLowerCase() === namespaceName) { const namespaceItemStatementHandler = (statement: ClassStatement | FunctionStatement) => { if (!location && statement.name.text.toLowerCase() === endName) { const uri = util.pathToUri(file.pathAbsolute); location = Location.create(uri, statement.range); } }; file.parser.ast.walk(createVisitor({ ClassStatement: namespaceItemStatementHandler, FunctionStatement: namespaceItemStatementHandler }), { walkMode: WalkMode.visitStatements }); } }; file.parser.ast.walk(createVisitor({ NamespaceStatement: statementHandler }), { walkMode: WalkMode.visitStatements }); return location; } /** * Given a current token, walk */ public getPartialVariableName(currentToken: Token, excludeTokens: TokenKind[] = null) { let identifierAndDotKinds = [TokenKind.Identifier, ...AllowedLocalIdentifiers, TokenKind.Dot]; //consume tokens backwards until we find something other than a dot or an identifier let tokens = []; const parser = this.parser; for (let i = parser.tokens.indexOf(currentToken); i >= 0; i--) { currentToken = parser.tokens[i]; if (identifierAndDotKinds.includes(currentToken.kind) && (!excludeTokens || !excludeTokens.includes(currentToken.kind))) { tokens.unshift(currentToken.text); } else { break; } } //if we found name and dot tokens, join them together to make the namespace name if (tokens.length > 0) { return tokens.join(''); } else { return undefined; } } public isPositionNextToTokenKind(position: Position, tokenKind: TokenKind) { const closestToken = this.getClosestToken(position); const previousToken = this.getPreviousToken(closestToken); const previousTokenKind = previousToken?.kind; //next to matched token if (!closestToken || closestToken.kind === TokenKind.Eof) { return false; } else if (closestToken.kind === tokenKind) { return true; } else if (closestToken.kind === TokenKind.Newline || previousTokenKind === TokenKind.Newline) { return false; //next to an identifier, which is next to token kind } else if (closestToken.kind === TokenKind.Identifier && previousTokenKind === tokenKind) { return true; } else { return false; } } private getTokenBefore(currentToken: Token, tokenKind: TokenKind): Token { const index = this.parser.tokens.indexOf(currentToken); for (let i = index - 1; i >= 0; i--) { currentToken = this.parser.tokens[i]; if (currentToken.kind === TokenKind.Newline) { break; } else if (currentToken.kind === tokenKind) { return currentToken; } } return undefined; } private tokenFollows(currentToken: Token, tokenKind: TokenKind): boolean { const index = this.parser.tokens.indexOf(currentToken); if (index > 0) { return this.parser.tokens[index - 1].kind === tokenKind; } return false; } public getTokensUntil(currentToken: Token, tokenKind: TokenKind, direction: -1 | 1 = -1) { let tokens = []; for (let i = this.parser.tokens.indexOf(currentToken); direction === -1 ? i >= 0 : i === this.parser.tokens.length; i += direction) { currentToken = this.parser.tokens[i]; if (currentToken.kind === TokenKind.Newline || currentToken.kind === tokenKind) { break; } tokens.push(currentToken); } return tokens; } public getPreviousToken(token: Token) { const parser = this.parser; let idx = parser.tokens.indexOf(token); return parser.tokens[idx - 1]; } /** * Find the first scope that has a namespace with this name. * Returns false if no namespace was found with that name */ public calleeStartsWithNamespace(callee: Expression) { let left = callee as any; while (isDottedGetExpression(left)) { left = left.obj; } if (isVariableExpression(left)) { let lowerName = left.name.text.toLowerCase(); //find the first scope that contains this namespace let scopes = this.program.getScopesForFile(this); for (let scope of scopes) { if (scope.namespaceLookup.has(lowerName)) { return true; } } } return false; } /** * Determine if the callee (i.e. function name) is a known function declared on the given namespace. */ public calleeIsKnownNamespaceFunction(callee: Expression, namespaceName: string) { //if we have a variable and a namespace if (isVariableExpression(callee) && namespaceName) { let lowerCalleeName = callee?.name?.text?.toLowerCase(); if (lowerCalleeName) { let scopes = this.program.getScopesForFile(this); for (let scope of scopes) { let namespace = scope.namespaceLookup.get(namespaceName.toLowerCase()); if (namespace.functionStatements[lowerCalleeName]) { return true; } } } } return false; } /** * Get the token closest to the position. if no token is found, the previous token is returned * @param position * @param tokens */ public getClosestToken(position: Position) { let tokens = this.parser.tokens; for (let i = 0; i < tokens.length; i++) { let token = tokens[i]; if (util.rangeContains(token.range, position)) { return token; } //if the position less than this token range, then this position touches no token, if (util.positionIsGreaterThanRange(position, token.range) === false) { let t = tokens[i - 1]; //return the token or the first token return t ? t : tokens[0]; } } //return the last token return tokens[tokens.length - 1]; } /** * Builds a list of document symbols for this file. Used by LanguageServer's onDocumentSymbol functionality */ public getDocumentSymbols() { if (this.documentSymbols) { return this.documentSymbols; } let symbols = [] as DocumentSymbol[]; for (const statement of this.ast.statements) { const symbol = this.getDocumentSymbol(statement); if (symbol) { symbols.push(symbol); } } this.documentSymbols = symbols; return symbols; } /** * Builds a list of workspace symbols for this file. Used by LanguageServer's onWorkspaceSymbol functionality */ public getWorkspaceSymbols() { if (this.workspaceSymbols) { return this.workspaceSymbols; } let symbols = [] as SymbolInformation[]; for (const statement of this.ast.statements) { for (const symbol of this.generateWorkspaceSymbols(statement)) { symbols.push(symbol); } } this.workspaceSymbols = symbols; return symbols; } /** * Builds a single DocumentSymbol object for use by LanguageServer's onDocumentSymbol functionality */ private getDocumentSymbol(statement: Statement) { let symbolKind: SymbolKind; const children = [] as DocumentSymbol[]; if (isFunctionStatement(statement)) { symbolKind = SymbolKind.Function; } else if (isClassMethodStatement(statement)) { symbolKind = SymbolKind.Method; } else if (isClassFieldStatement(statement)) { symbolKind = SymbolKind.Field; } else if (isNamespaceStatement(statement)) { symbolKind = SymbolKind.Namespace; for (const childStatement of statement.body.statements) { const symbol = this.getDocumentSymbol(childStatement); if (symbol) { children.push(symbol); } } } else if (isClassStatement(statement)) { symbolKind = SymbolKind.Class; for (const childStatement of statement.body) { const symbol = this.getDocumentSymbol(childStatement); if (symbol) { children.push(symbol); } } } else { return; } const name = isClassFieldStatement(statement) ? statement.name.text : statement.getName(ParseMode.BrighterScript); return DocumentSymbol.create(name, '', symbolKind, statement.range, statement.range, children); } /** * Builds a single SymbolInformation object for use by LanguageServer's onWorkspaceSymbol functionality */ private generateWorkspaceSymbols(statement: Statement, containerStatement?: ClassStatement | NamespaceStatement) { let symbolKind: SymbolKind; const symbols = []; if (isFunctionStatement(statement)) { symbolKind = SymbolKind.Function; } else if (isClassMethodStatement(statement)) { symbolKind = SymbolKind.Method; } else if (isNamespaceStatement(statement)) { symbolKind = SymbolKind.Namespace; for (const childStatement of statement.body.statements) { for (const symbol of this.generateWorkspaceSymbols(childStatement, statement)) { symbols.push(symbol); } } } else if (isClassStatement(statement)) { symbolKind = SymbolKind.Class; for (const childStatement of statement.body) { for (const symbol of this.generateWorkspaceSymbols(childStatement, statement)) { symbols.push(symbol); } } } else { return symbols; } const name = statement.getName(ParseMode.BrighterScript); const uri = util.pathToUri(this.pathAbsolute); const symbol = SymbolInformation.create(name, symbolKind, statement.range, uri, containerStatement?.getName(ParseMode.BrighterScript)); symbols.push(symbol); return symbols; } /** * Given a position in a file, if the position is sitting on some type of identifier, * go to the definition of that identifier (where this thing was first defined) */ public getDefinition(position: Position) { let results: Location[] = []; //get the token at the position const token = this.getTokenAt(position); // While certain other tokens are allowed as local variables (AllowedLocalIdentifiers: https://github.com/rokucommunity/brighterscript/blob/master/src/lexer/TokenKind.ts#L418), these are converted by the parser to TokenKind.Identifier by the time we retrieve the token using getTokenAt let definitionTokenTypes = [ TokenKind.Identifier, TokenKind.StringLiteral ]; //throw out invalid tokens and the wrong kind of tokens if (!token || !definitionTokenTypes.includes(token.kind)) { return results; } let textToSearchFor = token.text.toLowerCase(); const previousToken = this.getTokenAt({ line: token.range.start.line, character: token.range.start.character }); if (previousToken?.kind === TokenKind.Callfunc) { for (const scope of this.program.getScopes()) { //to only get functions defined in interface methods const callable = scope.getAllCallables().find((c) => c.callable.name.toLowerCase() === textToSearchFor); // eslint-disable-line @typescript-eslint/no-loop-func if (callable) { results.push(Location.create(util.pathToUri((callable.callable.file as BrsFile).pathAbsolute), callable.callable.functionStatement.range)); } } return results; } let classToken = this.getTokenBefore(token, TokenKind.Class); if (classToken) { let cs = this.parser.references.classStatements.find((cs) => cs.classKeyword.range === classToken.range); if (cs?.parentClassName) { const nameParts = cs.parentClassName.getNameParts(); let extendedClass = this.getClassFileLink(nameParts[nameParts.length - 1], nameParts.slice(0, -1).join('.')); if (extendedClass) { results.push(Location.create(util.pathToUri(extendedClass.file.pathAbsolute), extendedClass.item.range)); } } return results; } if (token.kind === TokenKind.StringLiteral) { // We need to strip off the quotes but only if present const startIndex = textToSearchFor.startsWith('"') ? 1 : 0; let endIndex = textToSearchFor.length; if (textToSearchFor.endsWith('"')) { endIndex--; } textToSearchFor = textToSearchFor.substring(startIndex, endIndex); } //look through local variables first, get the function scope for this position (if it exists) const functionScope = this.getFunctionScopeAtPosition(position); if (functionScope) { //find any variable or label with this name for (const varDeclaration of functionScope.variableDeclarations) { //we found a variable declaration with this token text! if (varDeclaration.name.toLowerCase() === textToSearchFor) { const uri = util.pathToUri(this.pathAbsolute); results.push(Location.create(uri, varDeclaration.nameRange)); } } if (this.tokenFollows(token, TokenKind.Goto)) { for (const label of functionScope.labelStatements) { if (label.name.toLocaleLowerCase() === textToSearchFor) { const uri = util.pathToUri(this.pathAbsolute); results.push(Location.create(uri, label.nameRange)); } } } } const filesSearched = new Set<BrsFile>(); //look through all files in scope for matches for (const scope of this.program.getScopesForFile(this)) { for (const file of scope.getAllFiles()) { if (isXmlFile(file) || filesSearched.has(file)) { continue; } filesSearched.add(file); if (previousToken?.kind === TokenKind.Dot && file.parseMode === ParseMode.BrighterScript) { results.push(...this.getClassMemberDefinitions(textToSearchFor, file)); const namespaceDefinition = this.getNamespaceDefinitions(token, file); if (namespaceDefinition) { results.push(namespaceDefinition); } } const statementHandler = (statement: FunctionStatement) => { if (statement.getName(this.parseMode).toLowerCase() === textToSearchFor) { const uri = util.pathToUri(file.pathAbsolute); results.push(Location.create(uri, statement.range)); } }; file.parser.ast.walk(createVisitor({ FunctionStatement: statementHandler }), { walkMode: WalkMode.visitStatements }); } } return results; } public getClassMemberDefinitions(textToSearchFor: string, file: BrsFile): Location[] { let results: Location[] = []; //get class fields and members const statementHandler = (statement: ClassMethodStatement) => { if (statement.getName(file.parseMode).toLowerCase() === textToSearchFor) { results.push(Location.create(util.pathToUri(file.pathAbsolute), statement.range)); } }; const fieldStatementHandler = (statement: ClassFieldStatement) => { if (statement.name.text.toLowerCase() === textToSearchFor) { results.push(Location.create(util.pathToUri(file.pathAbsolute), statement.range)); } }; file.parser.ast.walk(createVisitor({ ClassMethodStatement: statementHandler, ClassFieldStatement: fieldStatementHandler }), { walkMode: WalkMode.visitStatements }); return results; } public getHover(position: Position): Hover { //get the token at the position let token = this.getTokenAt(position); let hoverTokenTypes = [ TokenKind.Identifier, TokenKind.Function, TokenKind.EndFunction, TokenKind.Sub, TokenKind.EndSub ]; //throw out invalid tokens and the wrong kind of tokens if (!token || !hoverTokenTypes.includes(token.kind)) { return null; } let lowerTokenText = token.text.toLowerCase(); //look through local variables first { //get the function scope for this position (if exists) let functionScope = this.getFunctionScopeAtPosition(position); if (functionScope) { //find any variable with this name for (const varDeclaration of functionScope.variableDeclarations) { //we found a variable declaration with this token text! if (varDeclaration.name.toLowerCase() === lowerTokenText) { let typeText: string; if (isFunctionType(varDeclaration.type)) { typeText = varDeclaration.type.toString(); } else { typeText = `${varDeclaration.name} as ${varDeclaration.type.toString()}`; } return { range: token.range, //append the variable name to the front for scope contents: typeText }; } } for (const labelStatement of functionScope.labelStatements) { if (labelStatement.name.toLocaleLowerCase() === lowerTokenText) { return { range: token.range, contents: `${labelStatement.name}: label` }; } } } } //look through all callables in relevant scopes { let scopes = this.program.getScopesForFile(this); for (let scope of scopes) { let callable = scope.getCallableByName(lowerTokenText); if (callable) { return { range: token.range, contents: callable.type.toString() }; } } } } public getSignatureHelpForNamespaceMethods(callableName: string, dottedGetText: string, scope: Scope): { key: string; signature: SignatureInformation }[] { if (!dottedGetText) { return []; } let resultsMap = new Map<string, SignatureInfoObj>(); for (let [, namespace] of scope.namespaceLookup) { //completionName = "NameA." //completionName = "NameA.Na //NameA //NameA.NameB //NameA.NameB.NameC if (namespace.fullName.toLowerCase() === dottedGetText.toLowerCase()) { //add function and class statement completions for (let stmt of namespace.statements) { if (isFunctionStatement(stmt) && stmt.name.text.toLowerCase() === callableName.toLowerCase()) { const result = (namespace.file as BrsFile)?.getSignatureHelpForStatement(stmt); if (!resultsMap.has(result.key)) { resultsMap.set(result.key, result); } } } } } return [...resultsMap.values()]; } public getSignatureHelpForStatement(statement: Statement): SignatureInfoObj { if (!isFunctionStatement(statement) && !isClassMethodStatement(statement)) { return undefined; } const func = statement.func; const funcStartPosition = func.range.start; // Get function comments in reverse order let currentToken = this.getTokenAt(funcStartPosition); let functionComments = [] as string[]; while (currentToken) { currentToken = this.getPreviousToken(currentToken); if (!currentToken) { break; } if (currentToken.range.start.line + 1 < funcStartPosition.line) { if (functionComments.length === 0) { break; } } const kind = currentToken.kind; if (kind === TokenKind.Comment) { // Strip off common leading characters to make it easier to read const commentText = currentToken.text.replace(/^[' *\/]+/, ''); functionComments.unshift(commentText); } else if (kind === TokenKind.Newline) { if (functionComments.length === 0) { continue; } // if we already had a new line as the last token then exit out if (functionComments[0] === currentToken.text) { break; } functionComments.unshift(currentToken.text); } else { break; } } const documentation = functionComments.join('').trim(); const lines = util.splitIntoLines(this.fileContents); let key = statement.name.text + documentation; const params = [] as ParameterInformation[]; for (const param of func.parameters) { params.push(ParameterInformation.create(param.name.text)); key += param.name.text; } const label = util.getTextForRange(lines, util.createRangeFromPositions(func.functionType.range.start, func.body.range.start)).trim(); const signature = SignatureInformation.create(label, documentation, ...params); const index = 1; return { key: key, signature: signature, index: index }; } private getClassMethod(classStatement: ClassStatement, name: string, walkParents = true): ClassMethodStatement | undefined { //TODO - would like to write this with getClassHieararchy; but got stuck on working out the scopes to use... :( let statement; const statementHandler = (e) => { if (!statement && e.name.text.toLowerCase() === name.toLowerCase()) { statement = e; } }; while (classStatement) { classStatement.walk(createVisitor({ ClassMethodStatement: statementHandler }), { walkMode: WalkMode.visitStatements }); if (statement) { break; } if (walkParents && classStatement.parentClassName) { const nameParts = classStatement.parentClassName.getNameParts(); classStatement = this.getClassFileLink(nameParts[nameParts.length - 1], nameParts.slice(0, -1).join('.'))?.item; } else { break; } } return statement; } public getClassSignatureHelp(classStatement: ClassStatement): SignatureInfoObj | undefined { const classConstructor = this.getClassMethod(classStatement, 'new'); let sigHelp = classConstructor ? this.getSignatureHelpForStatement(classConstructor) : undefined; if (sigHelp) { sigHelp.key = classStatement.getName(ParseMode.BrighterScript); sigHelp.signature.label = sigHelp.signature.label.replace(/(function|sub) new/, sigHelp.key); } return sigHelp; } public getReferences(position: Position) { const callSiteToken = this.getTokenAt(position); let locations = [] as Location[]; const searchFor = callSiteToken.text.toLowerCase(); const scopes = this.program.getScopesForFile(this); for (const scope of scopes) { const processedFiles = new Set<BrsFile>(); for (const file of scope.getAllFiles()) { if (isXmlFile(file) || processedFiles.has(file)) { continue; } processedFiles.add(file); file.ast.walk(createVisitor({ VariableExpression: (e) => { if (e.name.text.toLowerCase() === searchFor) { locations.push(Location.create(util.pathToUri(file.pathAbsolute), e.range)); } } }), { walkMode: WalkMode.visitExpressionsRecursive }); } } return locations; } /** * Convert the brightscript/brighterscript source code into valid brightscript */ public transpile(): CodeWithSourceMap { const state = new BrsTranspileState(this); let transpileResult: SourceNode | undefined; if (this.needsTranspiled) { transpileResult = new SourceNode(null, null, state.srcPath, this.ast.transpile(state)); } else if (this.program.options.sourceMap) { //emit code as-is with a simple map to the original file location transpileResult = util.simpleMap(state.srcPath, this.fileContents); } else { //simple SourceNode wrapping the entire file to simplify the logic below transpileResult = new SourceNode(null, null, state.srcPath, this.fileContents); } if (this.program.options.sourceMap) { return new SourceNode(null, null, null, [ transpileResult, //add the sourcemap reference comment `'//# sourceMappingURL=./${path.basename(state.srcPath)}.map` ]).toStringWithSourceMap(); } else { return { code: transpileResult.toString(), map: undefined }; } } public getTypedef() { const state = new BrsTranspileState(this); const typedef = this.ast.getTypedef(state); const programNode = new SourceNode(null, null, this.pathAbsolute, typedef); return programNode.toString(); } public dispose() { this._parser?.dispose(); } } /** * List of completions for all valid keywords/reserved words. * Build this list once because it won't change for the lifetime of this process */ export const KeywordCompletions = Object.keys(Keywords) //remove any keywords with whitespace .filter(x => !x.includes(' ')) //create completions .map(x => { return { label: x, kind: CompletionItemKind.Keyword } as CompletionItem; });
the_stack
// ==================================================== // GraphQL query operation: ConnectableTableBlokk // ==================================================== export interface ConnectableTableBlokk_blokk_Attachment_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ConnectableTableBlokk_blokk_Attachment_connection_user { __typename: "User"; name: string; } export interface ConnectableTableBlokk_blokk_Attachment_connection { __typename: "Connection"; can: ConnectableTableBlokk_blokk_Attachment_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ConnectableTableBlokk_blokk_Attachment_connection_user | null; } export interface ConnectableTableBlokk_blokk_Attachment_user { __typename: "User"; name: string; } export interface ConnectableTableBlokk_blokk_Attachment_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ConnectableTableBlokk_blokk_Attachment_source { __typename: "ConnectableSource"; url: string | null; provider_url: string | null; } export interface ConnectableTableBlokk_blokk_Attachment_counts { __typename: "BlockCounts"; public_channels: number | null; } export interface ConnectableTableBlokk_blokk_Attachment { __typename: "Attachment"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ConnectableTableBlokk_blokk_Attachment_connection | null; created_at: string | null; updated_at: string | null; title: string; user: ConnectableTableBlokk_blokk_Attachment_user | null; can: ConnectableTableBlokk_blokk_Attachment_can | null; source: ConnectableTableBlokk_blokk_Attachment_source | null; counts: ConnectableTableBlokk_blokk_Attachment_counts | null; file_url: string | null; image_url: string | null; } export interface ConnectableTableBlokk_blokk_Embed_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ConnectableTableBlokk_blokk_Embed_connection_user { __typename: "User"; name: string; } export interface ConnectableTableBlokk_blokk_Embed_connection { __typename: "Connection"; can: ConnectableTableBlokk_blokk_Embed_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ConnectableTableBlokk_blokk_Embed_connection_user | null; } export interface ConnectableTableBlokk_blokk_Embed_user { __typename: "User"; name: string; } export interface ConnectableTableBlokk_blokk_Embed_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ConnectableTableBlokk_blokk_Embed_source { __typename: "ConnectableSource"; url: string | null; provider_url: string | null; } export interface ConnectableTableBlokk_blokk_Embed_counts { __typename: "BlockCounts"; public_channels: number | null; } export interface ConnectableTableBlokk_blokk_Embed { __typename: "Embed"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ConnectableTableBlokk_blokk_Embed_connection | null; created_at: string | null; updated_at: string | null; title: string; user: ConnectableTableBlokk_blokk_Embed_user | null; can: ConnectableTableBlokk_blokk_Embed_can | null; source: ConnectableTableBlokk_blokk_Embed_source | null; counts: ConnectableTableBlokk_blokk_Embed_counts | null; embed_html: string | null; image_url: string | null; } export interface ConnectableTableBlokk_blokk_Image_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ConnectableTableBlokk_blokk_Image_connection_user { __typename: "User"; name: string; } export interface ConnectableTableBlokk_blokk_Image_connection { __typename: "Connection"; can: ConnectableTableBlokk_blokk_Image_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ConnectableTableBlokk_blokk_Image_connection_user | null; } export interface ConnectableTableBlokk_blokk_Image_user { __typename: "User"; name: string; } export interface ConnectableTableBlokk_blokk_Image_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ConnectableTableBlokk_blokk_Image_source { __typename: "ConnectableSource"; url: string | null; provider_url: string | null; } export interface ConnectableTableBlokk_blokk_Image_counts { __typename: "BlockCounts"; public_channels: number | null; } export interface ConnectableTableBlokk_blokk_Image { __typename: "Image"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ConnectableTableBlokk_blokk_Image_connection | null; created_at: string | null; updated_at: string | null; title: string; user: ConnectableTableBlokk_blokk_Image_user | null; can: ConnectableTableBlokk_blokk_Image_can | null; source: ConnectableTableBlokk_blokk_Image_source | null; find_original_url: string | null; counts: ConnectableTableBlokk_blokk_Image_counts | null; image_url: string | null; } export interface ConnectableTableBlokk_blokk_Link_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ConnectableTableBlokk_blokk_Link_connection_user { __typename: "User"; name: string; } export interface ConnectableTableBlokk_blokk_Link_connection { __typename: "Connection"; can: ConnectableTableBlokk_blokk_Link_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ConnectableTableBlokk_blokk_Link_connection_user | null; } export interface ConnectableTableBlokk_blokk_Link_user { __typename: "User"; name: string; } export interface ConnectableTableBlokk_blokk_Link_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ConnectableTableBlokk_blokk_Link_source { __typename: "ConnectableSource"; url: string | null; provider_url: string | null; } export interface ConnectableTableBlokk_blokk_Link_counts { __typename: "BlockCounts"; public_channels: number | null; } export interface ConnectableTableBlokk_blokk_Link { __typename: "Link"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ConnectableTableBlokk_blokk_Link_connection | null; created_at: string | null; updated_at: string | null; title: string; user: ConnectableTableBlokk_blokk_Link_user | null; can: ConnectableTableBlokk_blokk_Link_can | null; source: ConnectableTableBlokk_blokk_Link_source | null; counts: ConnectableTableBlokk_blokk_Link_counts | null; image_url: string | null; } export interface ConnectableTableBlokk_blokk_PendingBlock_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ConnectableTableBlokk_blokk_PendingBlock_connection_user { __typename: "User"; name: string; } export interface ConnectableTableBlokk_blokk_PendingBlock_connection { __typename: "Connection"; can: ConnectableTableBlokk_blokk_PendingBlock_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ConnectableTableBlokk_blokk_PendingBlock_connection_user | null; } export interface ConnectableTableBlokk_blokk_PendingBlock_user { __typename: "User"; name: string; } export interface ConnectableTableBlokk_blokk_PendingBlock_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ConnectableTableBlokk_blokk_PendingBlock_counts { __typename: "BlockCounts"; public_channels: number | null; } export interface ConnectableTableBlokk_blokk_PendingBlock { __typename: "PendingBlock"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ConnectableTableBlokk_blokk_PendingBlock_connection | null; created_at: string | null; updated_at: string | null; title: string; user: ConnectableTableBlokk_blokk_PendingBlock_user | null; can: ConnectableTableBlokk_blokk_PendingBlock_can | null; counts: ConnectableTableBlokk_blokk_PendingBlock_counts | null; } export interface ConnectableTableBlokk_blokk_Text_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ConnectableTableBlokk_blokk_Text_connection_user { __typename: "User"; name: string; } export interface ConnectableTableBlokk_blokk_Text_connection { __typename: "Connection"; can: ConnectableTableBlokk_blokk_Text_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ConnectableTableBlokk_blokk_Text_connection_user | null; } export interface ConnectableTableBlokk_blokk_Text_user { __typename: "User"; name: string; } export interface ConnectableTableBlokk_blokk_Text_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ConnectableTableBlokk_blokk_Text_source { __typename: "ConnectableSource"; url: string | null; } export interface ConnectableTableBlokk_blokk_Text_counts { __typename: "BlockCounts"; public_channels: number | null; } export interface ConnectableTableBlokk_blokk_Text { __typename: "Text"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ConnectableTableBlokk_blokk_Text_connection | null; created_at: string | null; updated_at: string | null; title: string; user: ConnectableTableBlokk_blokk_Text_user | null; can: ConnectableTableBlokk_blokk_Text_can | null; source: ConnectableTableBlokk_blokk_Text_source | null; counts: ConnectableTableBlokk_blokk_Text_counts | null; content: string; html: string; } export interface ConnectableTableBlokk_blokk_Channel_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ConnectableTableBlokk_blokk_Channel_connection_user { __typename: "User"; name: string; } export interface ConnectableTableBlokk_blokk_Channel_connection { __typename: "Connection"; can: ConnectableTableBlokk_blokk_Channel_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ConnectableTableBlokk_blokk_Channel_connection_user | null; } export interface ConnectableTableBlokk_blokk_Channel_user { __typename: "User"; name: string; } export interface ConnectableTableBlokk_blokk_Channel_can { __typename: "ChannelCan"; mute: boolean | null; } export interface ConnectableTableBlokk_blokk_Channel_counts { __typename: "ChannelCounts"; connected_to_channels: number | null; contents: number | null; } export interface ConnectableTableBlokk_blokk_Channel { __typename: "Channel"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ConnectableTableBlokk_blokk_Channel_connection | null; created_at: string | null; updated_at: string | null; title: string; user: ConnectableTableBlokk_blokk_Channel_user | null; can: ConnectableTableBlokk_blokk_Channel_can | null; visibility: string; counts: ConnectableTableBlokk_blokk_Channel_counts | null; } export type ConnectableTableBlokk_blokk = ConnectableTableBlokk_blokk_Attachment | ConnectableTableBlokk_blokk_Embed | ConnectableTableBlokk_blokk_Image | ConnectableTableBlokk_blokk_Link | ConnectableTableBlokk_blokk_PendingBlock | ConnectableTableBlokk_blokk_Text | ConnectableTableBlokk_blokk_Channel; export interface ConnectableTableBlokk { blokk: ConnectableTableBlokk_blokk | null; } export interface ConnectableTableBlokkVariables { id: string; }
the_stack
import { testTokenization } from '../test/testRunner'; testTokenization('mysql', [ // Comments [ { line: '-- a comment', tokens: [{ startIndex: 0, type: 'comment.sql' }] } ], [ { line: '---sticky -- comment', tokens: [{ startIndex: 0, type: 'comment.sql' }] } ], [ { line: '-almost a comment', tokens: [ { startIndex: 0, type: 'operator.sql' }, { startIndex: 1, type: 'identifier.sql' }, { startIndex: 7, type: 'white.sql' }, { startIndex: 8, type: 'identifier.sql' }, { startIndex: 9, type: 'white.sql' }, { startIndex: 10, type: 'identifier.sql' } ] } ], [ { line: '/* a full line comment */', tokens: [ { startIndex: 0, type: 'comment.quote.sql' }, { startIndex: 2, type: 'comment.sql' }, { startIndex: 23, type: 'comment.quote.sql' } ] } ], [ { line: '/* /// *** /// */', tokens: [ { startIndex: 0, type: 'comment.quote.sql' }, { startIndex: 2, type: 'comment.sql' }, { startIndex: 15, type: 'comment.quote.sql' } ] } ], [ { line: '# comment', tokens: [{ startIndex: 0, type: 'comment.sql' }] } ], [ { line: 'declare @x int = /* a simple comment */ 1;', tokens: [ { startIndex: 0, type: 'keyword.sql' }, { startIndex: 7, type: 'white.sql' }, { startIndex: 8, type: 'identifier.sql' }, { startIndex: 10, type: 'white.sql' }, { startIndex: 11, type: 'keyword.sql' }, { startIndex: 14, type: 'white.sql' }, { startIndex: 15, type: 'operator.sql' }, { startIndex: 16, type: 'white.sql' }, { startIndex: 17, type: 'comment.quote.sql' }, { startIndex: 19, type: 'comment.sql' }, { startIndex: 37, type: 'comment.quote.sql' }, { startIndex: 39, type: 'white.sql' }, { startIndex: 40, type: 'number.sql' }, { startIndex: 41, type: 'delimiter.sql' } ] } ], // Not supporting nested comments, as nested comments seem to not be standard? // i.e. http://stackoverflow.com/questions/728172/are-there-multiline-comment-delimiters-in-sql-that-are-vendor-agnostic [ { line: '@x=/* a /* nested comment 1*/;', tokens: [ { startIndex: 0, type: 'identifier.sql' }, { startIndex: 2, type: 'operator.sql' }, { startIndex: 3, type: 'comment.quote.sql' }, { startIndex: 5, type: 'comment.sql' }, { startIndex: 28, type: 'comment.quote.sql' }, { startIndex: 30, type: 'delimiter.sql' } ] } ], [ { line: '@x=/* another comment */ 1*/;', tokens: [ { startIndex: 0, type: 'identifier.sql' }, { startIndex: 2, type: 'operator.sql' }, { startIndex: 3, type: 'comment.quote.sql' }, { startIndex: 5, type: 'comment.sql' }, { startIndex: 22, type: 'comment.quote.sql' }, { startIndex: 24, type: 'white.sql' }, { startIndex: 25, type: 'number.sql' }, { startIndex: 26, type: 'operator.sql' }, { startIndex: 28, type: 'delimiter.sql' } ] } ], [ { line: '@x=/*/;', tokens: [ { startIndex: 0, type: 'identifier.sql' }, { startIndex: 2, type: 'operator.sql' }, { startIndex: 3, type: 'comment.quote.sql' }, { startIndex: 5, type: 'comment.sql' } ] } ], // Numbers [ { line: '123', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '-123', tokens: [ { startIndex: 0, type: 'operator.sql' }, { startIndex: 1, type: 'number.sql' } ] } ], [ { line: '0xaBc123', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '0XaBc123', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '0x', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '0x0', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '0xAB_CD', tokens: [ { startIndex: 0, type: 'number.sql' }, { startIndex: 4, type: 'identifier.sql' } ] } ], [ { line: '$', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '$-123', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '$-+-123', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '$123.5678', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '$0.99', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '$.99', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '$99.', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '$0.', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '$.0', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '.', tokens: [{ startIndex: 0, type: 'delimiter.sql' }] } ], [ { line: '123', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '123.5678', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '0.99', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '.99', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '99.', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '0.', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '.0', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '1E-2', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '1E+2', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '1E2', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '0.1E2', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '1.E2', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], [ { line: '.1E2', tokens: [{ startIndex: 0, type: 'number.sql' }] } ], // Identifiers [ { line: 'declare `abc 321`;', tokens: [ { startIndex: 0, type: 'keyword.sql' }, { startIndex: 7, type: 'white.sql' }, { startIndex: 8, type: 'identifier.quote.sql' }, { startIndex: 9, type: 'identifier.sql' }, { startIndex: 16, type: 'identifier.quote.sql' }, { startIndex: 17, type: 'delimiter.sql' } ] } ], [ { line: '`abc`` 321 `` xyz`', tokens: [ { startIndex: 0, type: 'identifier.quote.sql' }, { startIndex: 1, type: 'identifier.sql' }, { startIndex: 17, type: 'identifier.quote.sql' } ] } ], [ { line: '`abc', tokens: [ { startIndex: 0, type: 'identifier.quote.sql' }, { startIndex: 1, type: 'identifier.sql' } ] } ], [ { line: 'declare `abc 321`;', tokens: [ { startIndex: 0, type: 'keyword.sql' }, { startIndex: 7, type: 'white.sql' }, { startIndex: 8, type: 'identifier.quote.sql' }, { startIndex: 9, type: 'identifier.sql' }, { startIndex: 16, type: 'identifier.quote.sql' }, { startIndex: 17, type: 'delimiter.sql' } ] } ], [ { line: '`abc`` 321 `` xyz`', tokens: [ { startIndex: 0, type: 'identifier.quote.sql' }, { startIndex: 1, type: 'identifier.sql' }, { startIndex: 17, type: 'identifier.quote.sql' } ] } ], [ { line: '`abc', tokens: [ { startIndex: 0, type: 'identifier.quote.sql' }, { startIndex: 1, type: 'identifier.sql' } ] } ], [ { line: 'int', tokens: [{ startIndex: 0, type: 'keyword.sql' }] } ], [ { line: '`int`', tokens: [ { startIndex: 0, type: 'identifier.quote.sql' }, { startIndex: 1, type: 'identifier.sql' }, { startIndex: 4, type: 'identifier.quote.sql' } ] } ], // Strings [ { line: "declare @x='a string';", tokens: [ { startIndex: 0, type: 'keyword.sql' }, { startIndex: 7, type: 'white.sql' }, { startIndex: 8, type: 'identifier.sql' }, { startIndex: 10, type: 'operator.sql' }, { startIndex: 11, type: 'string.sql' }, { startIndex: 21, type: 'delimiter.sql' } ] } ], [ { line: 'declare @x="a string";', tokens: [ { startIndex: 0, type: 'keyword.sql' }, { startIndex: 7, type: 'white.sql' }, { startIndex: 8, type: 'identifier.sql' }, { startIndex: 10, type: 'operator.sql' }, { startIndex: 11, type: 'string.double.sql' }, { startIndex: 21, type: 'delimiter.sql' } ] } ], [ { line: "'a '' string with quotes'", tokens: [{ startIndex: 0, type: 'string.sql' }] } ], [ { line: '"a "" string with quotes"', tokens: [{ startIndex: 0, type: 'string.double.sql' }] } ], [ { line: "'a \" string with quotes'", tokens: [{ startIndex: 0, type: 'string.sql' }] } ], [ { line: '"a ` string with quotes"', tokens: [{ startIndex: 0, type: 'string.double.sql' }] } ], [ { line: "'a -- string with comment'", tokens: [{ startIndex: 0, type: 'string.sql' }] } ], [ { line: '"a -- string with comment"', tokens: [{ startIndex: 0, type: 'string.double.sql' }] } ], [ { line: "'a endless string", tokens: [{ startIndex: 0, type: 'string.sql' }] } ], [ { line: '"a endless string', tokens: [{ startIndex: 0, type: 'string.double.sql' }] } ], // Operators [ { line: 'SET @x=@x+1', tokens: [ { startIndex: 0, type: 'keyword.sql' }, { startIndex: 3, type: 'white.sql' }, { startIndex: 4, type: 'identifier.sql' }, { startIndex: 6, type: 'operator.sql' }, { startIndex: 7, type: 'identifier.sql' }, { startIndex: 9, type: 'operator.sql' }, { startIndex: 10, type: 'number.sql' } ] } ], [ { line: '@x^=@x', tokens: [ { startIndex: 0, type: 'identifier.sql' }, { startIndex: 2, type: 'operator.sql' }, { startIndex: 4, type: 'identifier.sql' } ] } ], [ { line: 'WHERE myfield IS NOT NULL', tokens: [ { startIndex: 0, type: 'keyword.sql' }, { startIndex: 5, type: 'white.sql' }, { startIndex: 6, type: 'identifier.sql' }, { startIndex: 13, type: 'white.sql' }, { startIndex: 14, type: 'operator.sql' }, { startIndex: 16, type: 'white.sql' }, { startIndex: 17, type: 'operator.sql' }, { startIndex: 20, type: 'white.sql' }, { startIndex: 21, type: 'operator.sql' } ] } ], [ { line: 'SELECT * FROM tbl WHERE MyColumn IN (1,2)', tokens: [ { startIndex: 0, type: 'keyword.sql' }, { startIndex: 6, type: 'white.sql' }, { startIndex: 7, type: 'operator.sql' }, { startIndex: 8, type: 'white.sql' }, { startIndex: 9, type: 'keyword.sql' }, { startIndex: 13, type: 'white.sql' }, { startIndex: 14, type: 'identifier.sql' }, { startIndex: 17, type: 'white.sql' }, { startIndex: 18, type: 'keyword.sql' }, { startIndex: 23, type: 'white.sql' }, { startIndex: 24, type: 'identifier.sql' }, { startIndex: 32, type: 'white.sql' }, { startIndex: 33, type: 'operator.sql' }, { startIndex: 35, type: 'white.sql' }, { startIndex: 36, type: 'delimiter.parenthesis.sql' }, { startIndex: 37, type: 'number.sql' }, { startIndex: 38, type: 'delimiter.sql' }, { startIndex: 39, type: 'number.sql' }, { startIndex: 40, type: 'delimiter.parenthesis.sql' } ] } ] ]);
the_stack
import { URLExt } from '@jupyterlab/coreutils'; import { ServerConnection } from '@jupyterlab/services'; import { Settings } from '@jupyterlab/settingregistry'; import { testEmission } from '@jupyterlab/testutils'; import 'jest'; import { platform } from 'os'; import { CondaEnvironments, CondaPackage } from '../services'; jest.mock('@jupyterlab/services', () => { return { __esModule: true, ServerConnection: { makeRequest: jest.fn(), makeSettings: jest.fn().mockReturnValue({ baseUrl: 'foo/' }) } }; }); jest.mock('@jupyterlab/settingregistry'); const itSkipIf = (condition: boolean) => (condition ? it.skip : it); describe('@mamba-org/gator-lab/services', () => { const settings = { baseUrl: 'foo/' }; beforeEach(() => { (ServerConnection.makeSettings as jest.Mock).mockReturnValue(settings); }); afterEach(() => { jest.resetAllMocks(); }); describe('server request', () => { it('should send a redirection location for long running task', async () => { // Given const name = 'dummy'; const redirectURL = URLExt.join('conda', 'tasks', '25'); (ServerConnection.makeRequest as jest.Mock) .mockResolvedValue( new Response('', { status: 200 }) // Default answer ) .mockResolvedValueOnce( // First answer new Response('', { headers: { Location: redirectURL }, status: 202 }) ); const envManager = new CondaEnvironments(); await envManager.create(name); expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join(settings.baseUrl, 'conda', 'environments'), { body: JSON.stringify({ name, packages: [''] }), method: 'POST' }, settings ); expect(ServerConnection.makeRequest).toHaveBeenLastCalledWith( URLExt.join(settings.baseUrl, redirectURL), { method: 'GET' }, settings ); }); itSkipIf(platform() === 'win32')( 'should cancel a redirection location for long running task', async () => { // Given const name = 'dummy'; let taskIdx = 21; const redirectURL = URLExt.join( 'conda', 'tasks', (taskIdx + 1).toString() ); (ServerConnection.makeRequest as jest.Mock).mockImplementation( ( url: string, request: RequestInit, settings: ServerConnection.ISettings ) => { if (url.indexOf('/tasks') < 0) { taskIdx += 1; return Promise.resolve( new Response('', { headers: { Location: URLExt.join('conda', 'tasks', taskIdx.toString()) }, status: 202 }) ); } else if (Number.parseInt(url.slice(url.length - 2)) !== 22) { return Promise.resolve( new Response(JSON.stringify({ packages: [] })) ); } // let resolve: (value: Response) => void; let reject: (reason?: any) => void; const promise = new Promise<Response>( (resolveFromPromise, rejectFromPromise) => { // resolve = resolveFromPromise; reject = rejectFromPromise; } ); setTimeout( () => { reject('Fail to cancel promise'); }, 5000 // Wait maximum for 5 sec ); return promise; } ); // when const pkgManager = new CondaPackage(name); pkgManager.refresh(false, name).catch(err => { expect(err.message).toEqual('cancelled'); }); try { await pkgManager.refresh(false, name); } catch (error) { console.debug(error); } // Then expect(ServerConnection.makeRequest).toHaveBeenNthCalledWith( 2, URLExt.join(settings.baseUrl, 'conda', 'environments', name), { method: 'GET' }, settings ); expect(ServerConnection.makeRequest).toHaveBeenCalledWith( URLExt.join(settings.baseUrl, redirectURL), { method: 'DELETE' }, settings ); } ); }); describe('CondaEnvironments', () => { describe('clone()', () => { it('should clone an environment', async () => { const name = 'twin'; const source = 'existing'; (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response('', { status: 200 }) ); const envManager = new CondaEnvironments(); const testSignal = testEmission(envManager.environmentChanged, { test: (manager, changes) => { expect(changes).toStrictEqual({ name, source, type: 'clone' }); } }); await envManager.clone(source, name); await testSignal; expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join(settings.baseUrl, 'conda', 'environments'), { body: JSON.stringify({ name, twin: source }), method: 'POST' }, settings ); }); }); describe('create()', () => { it('should create an empty environment', async () => { const name = 'dummy'; (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response('', { status: 200 }) ); const envManager = new CondaEnvironments(); const testSignal = testEmission(envManager.environmentChanged, { test: (manager, changes) => { expect(changes).toStrictEqual({ name, source: [''], type: 'create' }); } }); await envManager.create(name); await testSignal; expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join(settings.baseUrl, 'conda', 'environments'), { body: JSON.stringify({ name, packages: [''] }), method: 'POST' }, settings ); }); it('should create an environment with the provided packages', async () => { const name = 'dummy'; const pkgs = ['python', 'scipy']; (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response('', { status: 200 }) ); const envManager = new CondaEnvironments(); const testSignal = testEmission(envManager.environmentChanged, { test: (manager, changes) => { expect(changes).toStrictEqual({ name, source: pkgs, type: 'create' }); } }); await envManager.create(name, pkgs.join(' ')); await testSignal; expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join(settings.baseUrl, 'conda', 'environments'), { body: JSON.stringify({ name, packages: pkgs }), method: 'POST' }, settings ); }); }); // TODO describe("dispose()", () => {}); describe('export()', () => { it('should request to export in full format', async () => { const name = 'dummy'; (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response('', { status: 200 }) ); const envManager = new CondaEnvironments(); await envManager.export(name); const queryArgs = URLExt.objectToQueryString({ download: 1, history: 0 }); expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join(settings.baseUrl, 'conda', 'environments', name) + queryArgs, { method: 'GET' }, settings ); }); it('should request to export in history format', async () => { const name = 'dummy'; (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response('', { status: 200 }) ); const envManager = new CondaEnvironments(); await envManager.export(name, true); const queryArgs = URLExt.objectToQueryString({ download: 1, history: 1 }); expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join(settings.baseUrl, 'conda', 'environments', name) + queryArgs, { method: 'GET' }, settings ); }); }); // TODO describe("getChannels()", () => {}); // TODO describe("getEnvironmentFromType()", () => {}); describe('getPackageManager()', () => { it('should create a CondaPackage object', () => { // Mock API request (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response('', { status: 200 }) ); const name = 'base'; const envManager = new CondaEnvironments(); const pkgManager = envManager.getPackageManager(name); expect(pkgManager).toBeInstanceOf(CondaPackage); expect(pkgManager.environment).toBe(name); }); }); describe('import()', () => { it('should import an environment from a file', async () => { const name = 'importedFromX'; const source = 'theFileContent'; const filename = 'environment.yml'; (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response('', { status: 200 }) ); const envManager = new CondaEnvironments(); const testSignal = testEmission(envManager.environmentChanged, { test: (manager, changes) => { expect(changes).toStrictEqual({ name, source, type: 'import' }); } }); await envManager.import(name, source, filename); await testSignal; expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join(settings.baseUrl, 'conda', 'environments'), { body: JSON.stringify({ name, file: source, filename }), method: 'POST' }, settings ); }); }); describe('refresh()', () => { it('should request the list of environment', async () => { const dummyEnvs = ['a', 'b']; (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response(JSON.stringify({ environments: dummyEnvs }), { status: 200 }) ); const envManager = new CondaEnvironments(); const envs = await envManager.refresh(); expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join(settings.baseUrl, 'conda', 'environments') + URLExt.objectToQueryString({ whitelist: 0 }), { method: 'GET' }, settings ); expect(envs).toEqual(dummyEnvs); }); it('should request the whitelisted environments', async () => { const dummyEnvs = ['a', 'b']; (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response(JSON.stringify({ environments: dummyEnvs }), { status: 200 }) ); (Settings as jest.Mock).mockImplementation(() => { return { get: jest.fn().mockImplementation((key: string) => { // @ts-ignore return { fromHistory: { composite: false }, types: { composite: {} }, whitelist: { composite: true } }[key]; }), changed: { connect: jest.fn() } }; }); // @ts-ignore const envManager = new CondaEnvironments(new Settings()); const envs = await envManager.refresh(); expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join(settings.baseUrl, 'conda', 'environments') + URLExt.objectToQueryString({ whitelist: 1 }), { method: 'GET' }, settings ); expect(envs).toEqual(dummyEnvs); }); }); describe('remove()', () => { it('should request an environment deletion', async () => { const name = 'toDelete'; (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response('', { status: 200 }) ); const envManager = new CondaEnvironments(); const testSignal = testEmission(envManager.environmentChanged, { test: (manager, changes) => { expect(changes).toStrictEqual({ name, source: null, type: 'remove' }); } }); await envManager.remove(name); await testSignal; expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join(settings.baseUrl, 'conda', 'environments', name), { method: 'DELETE' }, settings ); }); }); describe('update()', () => { it('should update an environment from a file', async () => { const name = 'updatedFromX'; const source = 'theFileContent'; const filename = 'environment.yml'; (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response('', { status: 200 }) ); const envManager = new CondaEnvironments(); const testSignal = testEmission(envManager.environmentChanged, { test: (manager, changes) => { expect(changes).toStrictEqual({ name, source, type: 'update' }); } }); await envManager.update(name, source, filename); await testSignal; expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join(settings.baseUrl, 'conda', 'environments', name), { body: JSON.stringify({ file: source, filename }), method: 'PATCH' }, settings ); }); }); describe('environments', () => { it('should request a refresh and return the environments', async () => { const dummyEnvs = ['a', 'b']; (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response(JSON.stringify({ environments: dummyEnvs }), { status: 200 }) ); const envManager = new CondaEnvironments(); const envs = await envManager.environments; expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join(settings.baseUrl, 'conda', 'environments') + URLExt.objectToQueryString({ whitelist: 0 }), { method: 'GET' }, settings ); expect(envs).toEqual(dummyEnvs); }); }); }); describe('CondaPackage', () => { describe('check_updates()', () => { it('should return the list of updatable packages', async () => { const env = 'dummy'; const pkgs = ['alpha', 'beta', 'gamma']; const lst_pkgs = pkgs.map(pkg => { return { name: pkg }; }); (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response( JSON.stringify({ updates: lst_pkgs }), { status: 200 } ) ); const pkgManager = new CondaPackage(env); const updates = await pkgManager.check_updates(); const queryArgs = URLExt.objectToQueryString({ status: 'has_update' }); expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join(settings.baseUrl, 'conda', 'environments', env) + queryArgs, { method: 'GET' }, settings ); expect(updates).toEqual(pkgs); }); it('should use the explicitly provided environment', async () => { const env = 'dummy'; const wanted = 'dummier'; const pkgs = ['alpha', 'beta', 'gamma']; const lst_pkgs = pkgs.map(pkg => { return { name: pkg }; }); (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response( JSON.stringify({ updates: lst_pkgs }), { status: 200 } ) ); const pkgManager = new CondaPackage(env); const updates = await pkgManager.check_updates(wanted); const queryArgs = URLExt.objectToQueryString({ status: 'has_update' }); expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join(settings.baseUrl, 'conda', 'environments', wanted) + queryArgs, { method: 'GET' }, settings ); expect(updates).toEqual(pkgs); }); }); describe('develop()', () => { it('should request an installation in development mode', async () => { const env = 'dummy'; const path = '/dummy/path/to/package'; (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response('', { status: 200 }) ); const pkgManager = new CondaPackage(env); const testSignal = testEmission(pkgManager.packageChanged, { test: (manager, changes) => { expect(changes).toStrictEqual({ environment: env, packages: [path], type: 'develop' }); } }); await pkgManager.develop(path); await testSignal; const queryArgs = URLExt.objectToQueryString({ develop: 1 }); expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join( settings.baseUrl, 'conda', 'environments', env, 'packages' ) + queryArgs, { body: JSON.stringify({ packages: [path] }), method: 'POST' }, settings ); }); it('should prefer the provided environment', async () => { const env = 'dummy'; const wanted = 'dummier'; const path = '/dummy/path/to/package'; (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response('', { status: 200 }) ); const pkgManager = new CondaPackage(env); const testSignal = testEmission(pkgManager.packageChanged, { test: (manager, changes) => { expect(changes).toStrictEqual({ environment: wanted, packages: [path], type: 'develop' }); } }); await pkgManager.develop(path, wanted); await testSignal; const queryArgs = URLExt.objectToQueryString({ develop: 1 }); expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join( settings.baseUrl, 'conda', 'environments', wanted, 'packages' ) + queryArgs, { body: JSON.stringify({ packages: [path] }), method: 'POST' }, settings ); }); }); describe('install()', () => { it('should request the installation of some packages', async () => { const env = 'dummy'; const pkgs = ['alpha', 'beta', 'gamma']; (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response('', { status: 200 }) ); const pkgManager = new CondaPackage(env); const testSignal = testEmission(pkgManager.packageChanged, { test: (manager, changes) => { expect(changes).toStrictEqual({ environment: env, packages: pkgs, type: 'install' }); } }); await pkgManager.install(pkgs); await testSignal; expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join( settings.baseUrl, 'conda', 'environments', env, 'packages' ), { body: JSON.stringify({ packages: pkgs }), method: 'POST' }, settings ); }); it('should prefer the provided environment', async () => { const env = 'dummy'; const wanted = 'dummier'; const pkgs = ['alpha', 'beta', 'gamma']; (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response('', { status: 200 }) ); const pkgManager = new CondaPackage(env); const testSignal = testEmission(pkgManager.packageChanged, { test: (manager, changes) => { expect(changes).toStrictEqual({ environment: wanted, packages: pkgs, type: 'install' }); } }); await pkgManager.install(pkgs, wanted); await testSignal; expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join( settings.baseUrl, 'conda', 'environments', wanted, 'packages' ), { body: JSON.stringify({ packages: pkgs }), method: 'POST' }, settings ); }); }); // TODO describe("refresh()", () => {}); describe('remove()', () => { it('should request the removal of some packages', async () => { const env = 'dummy'; const pkgs = ['alpha', 'beta', 'gamma']; (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response('', { status: 200 }) ); const pkgManager = new CondaPackage(env); const testSignal = testEmission(pkgManager.packageChanged, { test: (manager, changes) => { expect(changes).toStrictEqual({ environment: env, packages: pkgs, type: 'remove' }); } }); await pkgManager.remove(pkgs); await testSignal; expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join( settings.baseUrl, 'conda', 'environments', env, 'packages' ), { body: JSON.stringify({ packages: pkgs }), method: 'DELETE' }, settings ); }); it('should prefer the provided environment', async () => { const env = 'dummy'; const wanted = 'dummier'; const pkgs = ['alpha', 'beta', 'gamma']; (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response('', { status: 200 }) ); const pkgManager = new CondaPackage(env); const testSignal = testEmission(pkgManager.packageChanged, { test: (manager, changes) => { expect(changes).toStrictEqual({ environment: wanted, packages: pkgs, type: 'remove' }); } }); await pkgManager.remove(pkgs, wanted); await testSignal; expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join( settings.baseUrl, 'conda', 'environments', wanted, 'packages' ), { body: JSON.stringify({ packages: pkgs }), method: 'DELETE' }, settings ); }); }); describe('update()', () => { it('should request the update for some packages', async () => { const env = 'dummy'; const pkgs = ['alpha', 'beta', 'gamma']; (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response('', { status: 200 }) ); const pkgManager = new CondaPackage(env); const testSignal = testEmission(pkgManager.packageChanged, { test: (manager, changes) => { expect(changes).toStrictEqual({ environment: env, packages: pkgs, type: 'update' }); } }); await pkgManager.update(pkgs); await testSignal; expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join( settings.baseUrl, 'conda', 'environments', env, 'packages' ), { body: JSON.stringify({ packages: pkgs }), method: 'PATCH' }, settings ); }); it('should prefer the provided environment', async () => { const env = 'dummy'; const wanted = 'dummier'; const pkgs = ['alpha', 'beta', 'gamma']; (ServerConnection.makeRequest as jest.Mock).mockResolvedValue( new Response('', { status: 200 }) ); const pkgManager = new CondaPackage(env); const testSignal = testEmission(pkgManager.packageChanged, { test: (manager, changes) => { expect(changes).toStrictEqual({ environment: wanted, packages: pkgs, type: 'update' }); } }); await pkgManager.update(pkgs, wanted); await testSignal; expect(ServerConnection.makeRequest).toBeCalledWith( URLExt.join( settings.baseUrl, 'conda', 'environments', wanted, 'packages' ), { body: JSON.stringify({ packages: pkgs }), method: 'PATCH' }, settings ); }); }); // TOD describe("refreshAvailablePackages()", () => {}) // TODO describe("hasDescription()", () => {}) }); });
the_stack
* @module Tree */ import * as React from "react"; import { Subscription } from "rxjs/internal/Subscription"; import { HierarchyUpdateRecord, PageOptions, UPDATE_FULL } from "@itwin/presentation-common"; import { IModelHierarchyChangeEventArgs, Presentation } from "@itwin/presentation-frontend"; import { computeVisibleNodes, isTreeModelNode, isTreeModelNodePlaceholder, MutableTreeModel, MutableTreeModelNode, PagedTreeNodeLoader, RenderedItemsRange, TreeModelNode, TreeModelNodeInput, TreeModelSource, TreeNodeItem, usePagedTreeNodeLoader, VisibleTreeNodes, } from "@itwin/components-react"; import { RulesetRegistrationHelper } from "../../common/RulesetRegistrationHelper"; import { PresentationTreeDataProvider, PresentationTreeDataProviderProps } from "../DataProvider"; import { IPresentationTreeDataProvider } from "../IPresentationTreeDataProvider"; import { createTreeNodeId, createTreeNodeItem, CreateTreeNodeItemProps } from "../Utils"; import { reloadTree } from "./TreeReloader"; import { useExpandedNodesTracking } from "./UseExpandedNodesTracking"; /** * Properties for [[usePresentationTreeNodeLoader]] hook. * @public */ export interface PresentationTreeNodeLoaderProps extends PresentationTreeDataProviderProps { /** * Number of nodes in a single page. The created loader always requests at least * a page nodes, so it should be optimized for usability vs performance (using * smaller pages gives better responsiveness, but makes overall performance * slightly worse). * * Note: The prop is already defined in `PresentationTreeDataProviderProps` but specified here again to make it required. */ pagingSize: number; /** * Auto-update the hierarchy when ruleset, ruleset variables or data in the iModel changes. * @alpha */ enableHierarchyAutoUpdate?: boolean; } /** * Return type for [[usePresentationTreeNodeLoader]] hook. * @public */ export interface PresentationTreeNodeLoaderResult { /** Tree node loader to be used with a tree component */ nodeLoader: PagedTreeNodeLoader<IPresentationTreeDataProvider>; /** * Callback for when rendered tree node item range changes. This property should be passed to * [ControlledTree]($components-react) when property `enableHierarchyAutoUpdate` is `true`. * @alpha */ onItemsRendered: (items: RenderedItemsRange) => void; } /** * Custom hooks which creates PagedTreeNodeLoader with PresentationTreeDataProvider using * supplied imodel and ruleset. * @public */ export function usePresentationTreeNodeLoader( props: PresentationTreeNodeLoaderProps, ): PresentationTreeNodeLoaderResult { const dataProviderProps: PresentationTreeDataProviderProps = React.useMemo( () => ({ imodel: props.imodel, ruleset: props.ruleset, pagingSize: props.pagingSize, appendChildrenCountForGroupingNodes: props.appendChildrenCountForGroupingNodes, dataSourceOverrides: props.dataSourceOverrides, ruleDiagnostics: props.ruleDiagnostics, devDiagnostics: props.devDiagnostics, }), [ props.appendChildrenCountForGroupingNodes, props.dataSourceOverrides, props.devDiagnostics, props.imodel, props.pagingSize, props.ruleDiagnostics, props.ruleset, ], ); const [ { modelSource, rulesetRegistration, dataProvider }, setTreeNodeLoaderState, ] = useResettableState<TreeNodeLoaderState>( () => ({ modelSource: new TreeModelSource(), rulesetRegistration: new RulesetRegistrationHelper(dataProviderProps.ruleset), dataProvider: new PresentationTreeDataProvider({ ...dataProviderProps, ruleset: typeof dataProviderProps.ruleset === "string" ? dataProviderProps.ruleset : /* istanbul ignore next */ dataProviderProps.ruleset.id, }), }), [dataProviderProps], ); React.useEffect(() => { return () => rulesetRegistration.dispose(); }, [rulesetRegistration]); React.useEffect(() => { return () => dataProvider.dispose(); }, [dataProvider]); const nodeLoader = usePagedTreeNodeLoader(dataProvider, props.pagingSize, modelSource); const params = { enable: !!props.enableHierarchyAutoUpdate, pageSize: props.pagingSize, modelSource, dataProviderProps, setTreeNodeLoaderState, }; const onItemsRendered = useModelSourceUpdateOnIModelHierarchyUpdate({ ...params, dataProvider, treeNodeItemCreationProps: { appendChildrenCountForGroupingNodes: props.appendChildrenCountForGroupingNodes }, }); useModelSourceUpdateOnRulesetModification(params); useModelSourceUpdateOnRulesetVariablesChange({ ...params, rulesetId: dataProvider.rulesetId }); return { nodeLoader, onItemsRendered }; } interface TreeNodeLoaderState { modelSource: TreeModelSource; rulesetRegistration: RulesetRegistrationHelper; dataProvider: IPresentationTreeDataProvider; } /** * Resets state to `initialValue` when dependencies change. Avoid using in new places because this hook is only intended * for use in poorly designed custom hooks. */ function useResettableState<T>(initialValue: () => T, dependencies: unknown[]): [T, React.Dispatch<React.SetStateAction<T>>] { const stateRef = React.useRef<T>() as React.MutableRefObject<T>; // eslint-disable-next-line react-hooks/exhaustive-deps React.useMemo(() => stateRef.current = initialValue(), dependencies); const [_, setState] = React.useState({}); const setNewStateRef = React.useRef((action: T | ((previousState: T) => T)) => { const newState = action instanceof Function ? action(stateRef.current) : /* istanbul ignore next */ action; // istanbul ignore else if (newState !== stateRef.current) { stateRef.current = newState; setState({}); } }); return [stateRef.current, setNewStateRef.current]; } function useModelSourceUpdateOnIModelHierarchyUpdate(params: { enable: boolean; dataProvider: IPresentationTreeDataProvider; dataProviderProps: PresentationTreeDataProviderProps; pageSize: number; modelSource: TreeModelSource; setTreeNodeLoaderState: React.Dispatch<React.SetStateAction<TreeNodeLoaderState>>; treeNodeItemCreationProps: CreateTreeNodeItemProps; }): (items: RenderedItemsRange) => void { const { enable, dataProvider, dataProviderProps, pageSize, modelSource, setTreeNodeLoaderState, treeNodeItemCreationProps, } = params; useExpandedNodesTracking({ modelSource, dataProvider, enableNodesTracking: enable }); const renderedItems = React.useRef<RenderedItemsRange | undefined>(undefined); const onItemsRendered = React.useCallback((items: RenderedItemsRange) => { renderedItems.current = items; }, []); React.useEffect( () => { if (!enable) { return; } let subscription: Subscription | undefined; const removeListener = Presentation.presentation.onIModelHierarchyChanged.addListener( async (args: IModelHierarchyChangeEventArgs) => { if (args.rulesetId !== dataProvider.rulesetId || args.imodelKey !== dataProvider.imodel.key) { return; } const newDataProvider = new PresentationTreeDataProvider({ ...dataProviderProps, ruleset: args.rulesetId }); if (args.updateInfo === UPDATE_FULL) { subscription = reloadTree(modelSource.getModel(), newDataProvider, pageSize).subscribe({ next: (newModelSource) => setTreeNodeLoaderState((prevState) => ({ modelSource: newModelSource, rulesetRegistration: prevState.rulesetRegistration, dataProvider: newDataProvider, })), }); } else { const newModelSource = await updateModelSourceAfterIModelChange( modelSource, args.updateInfo, newDataProvider, treeNodeItemCreationProps, renderedItems.current, ); setTreeNodeLoaderState((prevState) => ({ modelSource: newModelSource, rulesetRegistration: prevState.rulesetRegistration, dataProvider: newDataProvider, })); } }, ); return () => { removeListener(); subscription?.unsubscribe(); }; }, [dataProvider, modelSource, enable, pageSize, treeNodeItemCreationProps, dataProviderProps, setTreeNodeLoaderState], ); return onItemsRendered; } function useModelSourceUpdateOnRulesetModification(params: { enable: boolean; dataProviderProps: PresentationTreeDataProviderProps; pageSize: number; modelSource: TreeModelSource; setTreeNodeLoaderState: React.Dispatch<React.SetStateAction<TreeNodeLoaderState>>; }): void { const { enable, dataProviderProps, pageSize, modelSource, setTreeNodeLoaderState } = params; React.useEffect( () => { if (!enable) { return; } let subscription: Subscription | undefined; const removeListener = Presentation.presentation.rulesets().onRulesetModified.addListener((ruleset) => { const dataProvider = new PresentationTreeDataProvider({ ...dataProviderProps, ruleset: ruleset.id }); subscription = reloadTree(modelSource.getModel(), dataProvider, pageSize).subscribe({ next: (newModelSource) => setTreeNodeLoaderState((prevState) => ({ modelSource: newModelSource, rulesetRegistration: prevState.rulesetRegistration, dataProvider, })), }); }); return () => { removeListener(); subscription?.unsubscribe(); }; }, [dataProviderProps, enable, modelSource, pageSize, setTreeNodeLoaderState], ); } function useModelSourceUpdateOnRulesetVariablesChange(params: { enable: boolean; dataProviderProps: PresentationTreeDataProviderProps; pageSize: number; rulesetId: string; modelSource: TreeModelSource; setTreeNodeLoaderState: React.Dispatch<React.SetStateAction<TreeNodeLoaderState>>; }): void { const { enable, dataProviderProps, pageSize, rulesetId, modelSource, setTreeNodeLoaderState } = params; React.useEffect( () => { if (!enable) { return; } let subscription: Subscription | undefined; const removeListener = Presentation.presentation.vars(rulesetId).onVariableChanged.addListener(() => { // note: we should probably debounce these events while accumulating changed variables in case multiple vars are changed const dataProvider = new PresentationTreeDataProvider({ ...dataProviderProps, ruleset: rulesetId }); subscription = reloadTree(modelSource.getModel(), dataProvider, pageSize).subscribe({ next: (newModelSource) => setTreeNodeLoaderState((prevState) => ({ modelSource: newModelSource, rulesetRegistration: prevState.rulesetRegistration, dataProvider, })), }); }); return () => { removeListener(); subscription?.unsubscribe(); }; }, [dataProviderProps, enable, modelSource, pageSize, rulesetId, setTreeNodeLoaderState], ); } async function updateModelSourceAfterIModelChange( modelSource: TreeModelSource, hierarchyUpdateRecords: HierarchyUpdateRecord[], dataProvider: IPresentationTreeDataProvider, treeNodeItemCreationProps: CreateTreeNodeItemProps, renderedItems?: RenderedItemsRange, ): Promise<TreeModelSource> { const modelWithUpdateRecords = applyHierarchyChanges( modelSource.getModel() as MutableTreeModel, hierarchyUpdateRecords, [], treeNodeItemCreationProps, ); if (modelWithUpdateRecords === modelSource.getModel()) { return modelSource; } if (!renderedItems) { return new TreeModelSource(modelWithUpdateRecords); } const reloadedHierarchyParts = await reloadVisibleHierarchyParts(computeVisibleNodes(modelWithUpdateRecords), renderedItems, dataProvider); const newModel = applyHierarchyChanges(modelSource.getModel() as MutableTreeModel, hierarchyUpdateRecords, reloadedHierarchyParts, treeNodeItemCreationProps); return new TreeModelSource(newModel); } /** @internal */ export interface ReloadedHierarchyPart { parentId: string | undefined; nodeItems: TreeNodeItem[]; offset: number; } /** @internal */ export function applyHierarchyChanges( treeModel: MutableTreeModel, hierarchyUpdateRecords: HierarchyUpdateRecord[], reloadedHierarchyParts: ReloadedHierarchyPart[], treeNodeItemCreationProps: CreateTreeNodeItemProps ) { const modelSource = new TreeModelSource(treeModel); modelSource.modifyModel((model: MutableTreeModel) => { const updateParentIds = hierarchyUpdateRecords .map((record) => record.parent ? createTreeNodeId(record.parent) : undefined); for (const record of hierarchyUpdateRecords) { const parentNodeId = record.parent ? createTreeNodeId(record.parent) : undefined; const parentNode = parentNodeId ? model.getNode(parentNodeId) : model.getRootNode(); if (!parentNode) { continue; } model.clearChildren(parentNodeId); model.setNumChildren(parentNodeId, record.nodesCount); if (isTreeModelNode(parentNode) && !parentNode.isExpanded) continue; for (const expandedNode of record.expandedNodes ?? []) { const treeItem = createTreeNodeItem(expandedNode.node, parentNodeId, treeNodeItemCreationProps); const existingNode = treeModel.getNode(treeItem.id); model.setChildren(parentNodeId, [createModelNodeInput(existingNode, treeItem)], expandedNode.position); if (existingNode) { rebuildSubTree(treeModel, model, existingNode, updateParentIds); } } } for (const reloadedHierarchyPart of reloadedHierarchyParts) { let offset = reloadedHierarchyPart.offset; for (const item of reloadedHierarchyPart.nodeItems) { const newItem = createModelNodeInput(undefined, item); const existingItem = model.getNode(newItem.id); if (!existingItem) { model.setChildren(reloadedHierarchyPart.parentId, [newItem], offset); } offset++; } } }); return modelSource.getModel() as MutableTreeModel; } function rebuildSubTree(oldModel: MutableTreeModel, newModel: MutableTreeModel, parentNode: TreeModelNode, excludedNodeIds: Array<string | undefined>) { const oldChildren = oldModel.getChildren(parentNode.id); if (!oldChildren || !parentNode.isExpanded || excludedNodeIds.includes(parentNode.id)) return; newModel.setNumChildren(parentNode.id, oldChildren.getLength()); for (const [childId, index] of oldChildren.iterateValues()) { const childNode = oldModel.getNode(childId); // istanbul ignore else if (childNode) { newModel.setChildren(parentNode.id, [{ ...childNode }], index); rebuildSubTree(oldModel, newModel, childNode, excludedNodeIds); } } } function createModelNodeInput(oldNode: MutableTreeModelNode | undefined, newNode: TreeNodeItem): TreeModelNodeInput { const newInput = { description: newNode.description, isExpanded: !!newNode.autoExpand, id: newNode.id, item: newNode, label: newNode.label, isLoading: false, numChildren: 0, isSelected: false, }; if (!oldNode) { return newInput; } return { ...newInput, isExpanded: oldNode.isExpanded, isSelected: oldNode.isSelected, isLoading: oldNode.isLoading, }; } /** @internal */ export async function reloadVisibleHierarchyParts( visibleNodes: VisibleTreeNodes, renderedItems: RenderedItemsRange, dataProvider: IPresentationTreeDataProvider, ) { const itemsRange = getItemsRange(renderedItems, visibleNodes); interface ChildRange { parentItem: TreeNodeItem | undefined; startIndex: number; endIndex: number; } const partsToReload = new Map<string | undefined, ChildRange>(); for (let i = itemsRange.startIndex; i <= itemsRange.endIndex; i++) { const node = visibleNodes.getAtIndex(i); if (!node || !isTreeModelNodePlaceholder(node)) continue; const parentNode = node.parentId ? visibleNodes.getModel().getNode(node.parentId) : visibleNodes.getModel().getRootNode(); // istanbul ignore if if (!parentNode || isTreeModelNodePlaceholder(parentNode)) continue; const partToReload = partsToReload.get(parentNode.id); if (!partToReload) { partsToReload.set(parentNode.id, { parentItem: isTreeModelNode(parentNode) ? parentNode.item : undefined, startIndex: node.childIndex, endIndex: node.childIndex }); continue; } partToReload.endIndex = node.childIndex; } const reloadedHierarchyParts = new Array<ReloadedHierarchyPart>(); for (const [parentId, hierarchyPart] of partsToReload) { const pageOptions: PageOptions = { start: hierarchyPart.startIndex, size: hierarchyPart.endIndex - hierarchyPart.startIndex + 1, }; const reloadedPart: ReloadedHierarchyPart = { parentId, offset: hierarchyPart.startIndex, nodeItems: await dataProvider.getNodes(hierarchyPart.parentItem, pageOptions), }; reloadedHierarchyParts.push(reloadedPart); } return reloadedHierarchyParts; } function getItemsRange(renderedNodes: RenderedItemsRange, visibleNodes: VisibleTreeNodes) { if (renderedNodes.visibleStopIndex < visibleNodes.getNumNodes()) return { startIndex: renderedNodes.visibleStartIndex, endIndex: renderedNodes.visibleStopIndex }; const visibleNodesCount = renderedNodes.visibleStopIndex - renderedNodes.visibleStartIndex; const endPosition = visibleNodes.getNumNodes() - 1; const startPosition = endPosition - visibleNodesCount; return { startIndex: startPosition < 0 ? 0 : startPosition, endIndex: endPosition < 0 ? 0 : endPosition, }; }
the_stack
import * as TypeMoq from 'typemoq'; import * as assert from 'assert'; import { EventEmitter } from 'events'; import QueryRunner from './../src/controllers/queryRunner'; import { QueryNotificationHandler } from './../src/controllers/queryNotificationHandler'; import * as Utils from './../src/models/utils'; import SqlToolsServerClient from './../src/languageservice/serviceclient'; import { QueryExecuteParams, QueryExecuteCompleteNotificationResult, QueryExecuteBatchNotificationParams, QueryExecuteResultSetCompleteNotificationParams, ResultSetSummary, QueryExecuteSubsetResult } from './../src/models/contracts/queryExecute'; import VscodeWrapper from './../src/controllers/vscodeWrapper'; import StatusView from './../src/views/statusView'; import * as Constants from '../src/constants/constants'; import * as QueryExecuteContracts from '../src/models/contracts/queryExecute'; import * as QueryDisposeContracts from '../src/models/contracts/queryDispose'; import { ISlickRange, ISelectionData } from './../src/models/interfaces'; import * as stubs from './stubs'; import * as vscode from 'vscode'; import { expect } from 'chai'; // CONSTANTS ////////////////////////////////////////////////////////////////////////////////////// const standardUri: string = 'uri'; const standardTitle: string = 'title'; const standardSelection: ISelectionData = {startLine: 0, endLine: 0, startColumn: 3, endColumn: 3}; // TESTS ////////////////////////////////////////////////////////////////////////////////////////// suite('Query Runner tests', () => { let testSqlToolsServerClient: TypeMoq.IMock<SqlToolsServerClient>; let testQueryNotificationHandler: TypeMoq.IMock<QueryNotificationHandler>; let testVscodeWrapper: TypeMoq.IMock<VscodeWrapper>; let testStatusView: TypeMoq.IMock<StatusView>; setup(() => { testSqlToolsServerClient = TypeMoq.Mock.ofType(SqlToolsServerClient, TypeMoq.MockBehavior.Loose); testQueryNotificationHandler = TypeMoq.Mock.ofType(QueryNotificationHandler, TypeMoq.MockBehavior.Loose); testVscodeWrapper = TypeMoq.Mock.ofType(VscodeWrapper, TypeMoq.MockBehavior.Loose); testStatusView = TypeMoq.Mock.ofType(StatusView, TypeMoq.MockBehavior.Loose); }); test('Constructs properly', () => { let queryRunner = new QueryRunner('', '', testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object); assert.equal(typeof queryRunner !== undefined, true); }); test('Handles Query Request Result Properly', () => { // Setup: // ... Standard service to handle a execute request, standard query notification setupStandardQueryRequestServiceMock(testSqlToolsServerClient, () => { return Promise.resolve(new QueryExecuteContracts.QueryExecuteResult()); }); setupStandardQueryNotificationHandlerMock(testQueryNotificationHandler); // ... Mock up the view and VSCode wrapper to handle requests to update view testStatusView.setup(x => x.executingQuery(TypeMoq.It.isAnyString())); testVscodeWrapper.setup( x => x.logToOutputChannel(TypeMoq.It.isAnyString())); let testDoc: vscode.TextDocument = { getText: () => { return undefined; } } as any; testVscodeWrapper.setup( x => x.openTextDocument(TypeMoq.It.isAny())).returns(() => Promise.resolve(testDoc)); // ... Mock up a event emitter to accept a start event (only) let mockEventEmitter = TypeMoq.Mock.ofType(EventEmitter, TypeMoq.MockBehavior.Loose); mockEventEmitter.setup(x => x.emit('start')); // If: // ... I create a query runner let queryRunner = new QueryRunner( standardUri, standardTitle, testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object ); queryRunner.eventEmitter = mockEventEmitter.object; // ... And run a query return queryRunner.runQuery(standardSelection).then(() => { // Then: // ... The query notification handler should have registered the query runner testQueryNotificationHandler.verify(x => x.registerRunner(TypeMoq.It.isValue(queryRunner), TypeMoq.It.isValue(standardUri)), TypeMoq.Times.once()); // ... Start is the only event that should be emitted during successful query start mockEventEmitter.verify(x => x.emit('start', standardUri), TypeMoq.Times.once()); // ... The VS Code status should be updated testStatusView.verify<void>(x => x.executingQuery(standardUri), TypeMoq.Times.once()); testVscodeWrapper.verify<void>(x => x.logToOutputChannel(TypeMoq.It.isAnyString()), TypeMoq.Times.once()); // ... The query runner should indicate that it is running a query and elapsed time should be set to 0 assert.equal(queryRunner.isExecutingQuery, true); assert.equal(queryRunner.totalElapsedMilliseconds, 0); }); }); test('Handles Query Request Error Properly', () => { // Setup: // ... Setup the mock service client to return an error when the execute request is submitted // ... Setup standard notification mock setupStandardQueryRequestServiceMock(testSqlToolsServerClient, () => { return Promise.reject<QueryExecuteContracts.QueryExecuteResult>('failed'); }); setupStandardQueryNotificationHandlerMock(testQueryNotificationHandler); // ... Setup the status view to handle start and stop updates testStatusView.setup(x => x.executingQuery(TypeMoq.It.isAnyString())); testStatusView.setup(x => x.executedQuery(TypeMoq.It.isAnyString())); // ... Setup the vs code wrapper to handle output logging and error messages testVscodeWrapper.setup(x => x.logToOutputChannel(TypeMoq.It.isAnyString())); testVscodeWrapper.setup(x => x.showErrorMessage(TypeMoq.It.isAnyString())); let testDoc: vscode.TextDocument = { getText: () => { return undefined; } } as any; testVscodeWrapper.setup( x => x.openTextDocument(TypeMoq.It.isAny())).returns(() => Promise.resolve(testDoc)); // ... Setup the event emitter to handle nothing let testEventEmitter = TypeMoq.Mock.ofType(EventEmitter, TypeMoq.MockBehavior.Strict); // If: // ... I create a query runner let queryRunner = new QueryRunner( standardUri, standardTitle, testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object ); queryRunner.eventEmitter = testEventEmitter.object; // ... And I run a query that is going to fail to start return queryRunner.runQuery(standardSelection).then(undefined, () => { // Then: // ... The view status should have started and stopped testVscodeWrapper.verify(x => x.logToOutputChannel(TypeMoq.It.isAnyString()), TypeMoq.Times.once()); testStatusView.verify(x => x.executingQuery(standardUri), TypeMoq.Times.once()); testStatusView.verify(x => x.executedQuery(standardUri), TypeMoq.Times.once()); // ... The query runner should not be running a query assert.strictEqual(queryRunner.isExecutingQuery, false); // ... An error message should have been shown testVscodeWrapper.verify(x => x.showErrorMessage(TypeMoq.It.isAnyString()), TypeMoq.Times.once()); }); }); test('Notification - Batch Start', () => { // Setup: Create a batch start notification with appropriate values // NOTE: nulls are used because that's what comes back from the service. let batchStart: QueryExecuteBatchNotificationParams = { ownerUri: 'uri', batchSummary: { executionElapsed: null, // tslint:disable-line:no-null-keyword executionEnd: null, // tslint:disable-line:no-null-keyword executionStart: new Date().toISOString(), hasError: false, id: 0, selection: {startLine: 0, endLine: 0, startColumn: 3, endColumn: 3}, resultSetSummaries: null // tslint:disable-line:no-null-keyword } }; // If: I submit a batch start notification to the query runner let queryRunner = new QueryRunner( '', '', testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object ); let mockEventEmitter = TypeMoq.Mock.ofType(EventEmitter, TypeMoq.MockBehavior.Strict); mockEventEmitter.setup(x => x.emit('batchStart', TypeMoq.It.isAny())); queryRunner.eventEmitter = mockEventEmitter.object; queryRunner.handleBatchStart(batchStart); // Then: It should store the batch and emit a batch start assert.equal(queryRunner.batchSets.indexOf(batchStart.batchSummary), 0); mockEventEmitter.verify(x => x.emit('batchStart', TypeMoq.It.isAny()), TypeMoq.Times.once()); }); function testBatchCompleteNotification(sendBatchTime: boolean): void { // Setup: Create a batch completion result let configResult: {[key: string]: any} = {}; configResult[Constants.configShowBatchTime] = sendBatchTime; setupWorkspaceConfig(configResult); let dateNow = new Date(); let fiveSecondsAgo = new Date(dateNow.getTime() - 5000); let elapsedTimeString = Utils.parseNumAsTimeString(5000); let batchComplete: QueryExecuteBatchNotificationParams = { ownerUri: 'uri', batchSummary: { executionElapsed: elapsedTimeString, executionEnd: dateNow.toISOString(), executionStart: fiveSecondsAgo.toISOString(), hasError: false, id: 0, selection: {startLine: 0, endLine: 0, startColumn: 3, endColumn: 3}, resultSetSummaries: [] } }; // If: I submit a batch completion notification to the query runner that has a batch already started let queryRunner = new QueryRunner( '', '', testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object ); queryRunner.batchSets[0] = { executionElapsed: null, // tslint:disable-line:no-null-keyword executionEnd: null, // tslint:disable-line:no-null-keyword executionStart: new Date().toISOString(), hasError: false, id: 0, selection: {startLine: 0, endLine: 0, startColumn: 3, endColumn: 3}, resultSetSummaries: [] }; let mockEventEmitter = TypeMoq.Mock.ofType(EventEmitter, TypeMoq.MockBehavior.Strict); mockEventEmitter.setup(x => x.emit('batchComplete', TypeMoq.It.isAny())); mockEventEmitter.setup(x => x.emit('message', TypeMoq.It.isAny(), TypeMoq.It.isAny())); queryRunner.eventEmitter = mockEventEmitter.object; queryRunner.handleBatchComplete(batchComplete); // Then: It should the remainder of the information and emit a batch complete notification assert.equal(queryRunner.batchSets.length, 1); let storedBatch = queryRunner.batchSets[0]; assert.equal(storedBatch.executionElapsed, elapsedTimeString); assert.equal(typeof(storedBatch.executionEnd), typeof(batchComplete.batchSummary.executionEnd)); assert.equal(typeof(storedBatch.executionStart), typeof(batchComplete.batchSummary.executionStart)); assert.equal(storedBatch.hasError, batchComplete.batchSummary.hasError); // ... Result sets should not be set by the batch complete notification assert.equal(typeof(storedBatch.resultSetSummaries), typeof([])); assert.equal(storedBatch.resultSetSummaries.length, 0); mockEventEmitter.verify(x => x.emit('batchComplete', TypeMoq.It.isAny()), TypeMoq.Times.once()); let expectedMessageTimes = sendBatchTime ? TypeMoq.Times.once() : TypeMoq.Times.never(); mockEventEmitter.verify(x => x.emit('message', TypeMoq.It.isAny(), TypeMoq.It.isAny()), expectedMessageTimes); } test('Notification - Batch Complete no message', () => { testBatchCompleteNotification(false); }); test('Notification - Batch Complete with message', () => { testBatchCompleteNotification(true); }); test('Notification - ResultSet Complete w/no previous results', () => { // Setup: Create a resultset completion result let resultSetComplete: QueryExecuteResultSetCompleteNotificationParams = { ownerUri: 'uri', resultSetSummary: { batchId: 0, columnInfo: [], id: 0, rowCount: 10 } }; // If: I submit a resultSet completion notification to the query runner... let queryRunner = new QueryRunner('', '', testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object); queryRunner.batchSets[0] = { executionElapsed: null, // tslint:disable-line:no-null-keyword executionEnd: null, // tslint:disable-line:no-null-keyword executionStart: new Date().toISOString(), hasError: false, id: 0, selection: {startLine: 0, endLine: 0, startColumn: 3, endColumn: 3}, resultSetSummaries: [] }; let mockEventEmitter = TypeMoq.Mock.ofType(EventEmitter, TypeMoq.MockBehavior.Strict); mockEventEmitter.setup(x => x.emit('resultSet', TypeMoq.It.isAny())); queryRunner.eventEmitter = mockEventEmitter.object; queryRunner.handleResultSetComplete(resultSetComplete); // Then: // ... The pre-existing batch should contain the result set we got back assert.equal(queryRunner.batchSets[0].resultSetSummaries.length, 1); assert.equal(queryRunner.batchSets[0].resultSetSummaries[0], resultSetComplete.resultSetSummary); // ... The resultset complete event should have been emitted mockEventEmitter.verify(x => x.emit('resultSet', TypeMoq.It.isAny()), TypeMoq.Times.once()); }); test('Notification - ResultSet complete w/previous results', () => { // Setup: // ... Create resultset completion results let resultSetComplete1: QueryExecuteResultSetCompleteNotificationParams = { ownerUri: 'uri', resultSetSummary: {batchId: 0, columnInfo: [], id: 0, rowCount: 10 } }; let resultSetComplete2: QueryExecuteResultSetCompleteNotificationParams = { ownerUri: 'uri', resultSetSummary: {batchId: 0, columnInfo: [], id: 1, rowCount: 10 } }; // ... Create a mock event emitter to receive the events let mockEventEmitter = TypeMoq.Mock.ofType(EventEmitter, TypeMoq.MockBehavior.Strict); mockEventEmitter.setup(x => x.emit('resultSet', TypeMoq.It.isAny())); // If: // ... I submit a resultSet completion notification to the query runner let queryRunner = new QueryRunner('', '', testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object); queryRunner.batchSets[0] = { executionElapsed: null, // tslint:disable-line:no-null-keyword executionEnd: null, // tslint:disable-line:no-null-keyword executionStart: new Date().toISOString(), hasError: false, id: 0, selection: {startLine: 0, endLine: 0, startColumn: 3, endColumn: 3}, resultSetSummaries: [] }; queryRunner.eventEmitter = mockEventEmitter.object; queryRunner.handleResultSetComplete(resultSetComplete1); // ... And submit a second result set completion notification queryRunner.handleResultSetComplete(resultSetComplete2); // Then: // ... There should be two results in the batch summary assert.equal(queryRunner.batchSets[0].resultSetSummaries.length, 2); assert.equal(queryRunner.batchSets[0].resultSetSummaries[0], resultSetComplete1.resultSetSummary); assert.equal(queryRunner.batchSets[0].resultSetSummaries[1], resultSetComplete2.resultSetSummary); // ... The resultset complete event should have been emitted twice mockEventEmitter.verify(x => x.emit('resultSet', TypeMoq.It.isAny()), TypeMoq.Times.exactly(2)); }); test('Notification - Message', () => { // Setup: // ... Create a mock for an event emitter that handles message notifications let mockEventEmitter = TypeMoq.Mock.ofType(EventEmitter, TypeMoq.MockBehavior.Strict); mockEventEmitter.setup(x => x.emit('message', TypeMoq.It.isAny())); // ... Create a message notification with some message let message: QueryExecuteContracts.QueryExecuteMessageParams = { message: { batchId: 0, isError: false, message: 'Message!', time: new Date().toISOString() }, ownerUri: standardUri }; // If: // ... I have a query runner let queryRunner: QueryRunner = new QueryRunner( standardUri, standardTitle, testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object ); queryRunner.eventEmitter = mockEventEmitter.object; // ... And I ask to handle a message queryRunner.handleMessage(message); // Then: A message event should have been emitted mockEventEmitter.verify(x => x.emit('message', TypeMoq.It.isAny()), TypeMoq.Times.once()); }); test('Notification - Query complete', () => { // Setup: // ... Create a mock for an event emitter that handles complete notifications let mockEventEmitter = TypeMoq.Mock.ofType(EventEmitter, TypeMoq.MockBehavior.Strict); mockEventEmitter.setup(x => x.emit('complete', TypeMoq.It.isAnyString(), TypeMoq.It.isAny())); // ... Setup the VS Code view handlers testStatusView.setup(x => x.executedQuery(TypeMoq.It.isAny())); testVscodeWrapper.setup(x => x.logToOutputChannel(TypeMoq.It.isAnyString())); // ... Create a completion notification with bogus data let result: QueryExecuteCompleteNotificationResult = { ownerUri: 'uri', batchSummaries: [{ hasError: false, id: 0, selection: standardSelection, resultSetSummaries: [], executionElapsed: undefined, executionStart: new Date().toISOString(), executionEnd: new Date().toISOString() }] }; // If: // ... I have a query runner let queryRunner = new QueryRunner( standardUri, standardTitle, testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object ); queryRunner.eventEmitter = mockEventEmitter.object; // ... And I handle a query completion event queryRunner.handleQueryComplete(result); // Then: // ... The VS Code view should have stopped executing testStatusView.verify(x => x.executedQuery(standardUri), TypeMoq.Times.once()); // ... The event emitter should have gotten a complete event mockEventEmitter.verify(x => x.emit('complete', TypeMoq.It.isAnyString(), TypeMoq.It.isAny()), TypeMoq.Times.once()); // ... The state of the query runner has been updated assert.equal(queryRunner.batchSets.length, 1); assert.equal(queryRunner.isExecutingQuery, false); }); test('Correctly handles subset', () => { let testuri = 'test'; let testresult: QueryExecuteSubsetResult = { resultSubset: { rowCount: 5, rows: [ [{isNull: false, displayValue: '1'}, {isNull: false, displayValue: '2'}], [{isNull: false, displayValue: '3'}, {isNull: false, displayValue: '4'}], [{isNull: false, displayValue: '5'}, {isNull: false, displayValue: '6'}], [{isNull: false, displayValue: '7'}, {isNull: false, displayValue: '8'}], [{isNull: false, displayValue: '9'}, {isNull: false, displayValue: '10'}] ] } }; testSqlToolsServerClient.setup(x => x.sendRequest(TypeMoq.It.isAny(), TypeMoq.It.isAny())).callback(() => { // testing }).returns(() => { return Promise.resolve(testresult); }); testStatusView.setup(x => x.executingQuery(TypeMoq.It.isAnyString())); let queryRunner = new QueryRunner( testuri, testuri, testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object ); queryRunner.uri = testuri; return queryRunner.getRows(0, 5, 0, 0).then(result => { assert.equal(result, testresult); }); }); test('Correctly handles error from subset request', () => { let testuri = 'test'; let testresult = { message: 'failed' }; testSqlToolsServerClient.setup(x => x.sendRequest(TypeMoq.It.isAny(), TypeMoq.It.isAny())).callback(() => { // testing }).returns(() => { return Promise.resolve(testresult); }); testVscodeWrapper.setup(x => x.showErrorMessage(TypeMoq.It.isAnyString())); let queryRunner = new QueryRunner( testuri, testuri, testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object ); queryRunner.uri = testuri; return queryRunner.getRows(0, 5, 0, 0).then(undefined, () => { testVscodeWrapper.verify(x => x.showErrorMessage(TypeMoq.It.isAnyString()), TypeMoq.Times.once()); }); }); test('Toggle SQLCMD Mode sends request', async () => { let queryUri = 'test_uri'; let queryRunner = new QueryRunner(queryUri, queryUri, testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object); expect(queryRunner.isSqlCmd, 'Query Runner should have SQLCMD false be default').is.equal(false); testSqlToolsServerClient.setup(s => s.sendRequest(QueryExecuteContracts.QueryExecuteOptionsRequest.type, TypeMoq.It.isAny())).returns(() => { return Promise.resolve(true); }); await queryRunner.toggleSqlCmd(); testSqlToolsServerClient.verify(s => s.sendRequest(TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.once()); expect(queryRunner.isSqlCmd, 'SQLCMD Mode should be switched').is.equal(true); }); function setupWorkspaceConfig(configResult: {[key: string]: any}): void { let config = stubs.createWorkspaceConfiguration(configResult); testVscodeWrapper.setup(x => x.getConfiguration(TypeMoq.It.isAny(), TypeMoq.It.isAny())) .returns(x => { return config; }); } suite('Copy Tests', () => { // ------ Common inputs and setup for copy tests ------- const testuri = 'test'; let testresult: QueryExecuteSubsetResult = { resultSubset: { rowCount: 5, rows: [ [{isNull: false, displayValue: '1'}, {isNull: false, displayValue: '2'}], [{isNull: false, displayValue: '3'}, {isNull: false, displayValue: '4'}], [{isNull: false, displayValue: '5'}, {isNull: false, displayValue: '6'}], [{isNull: false, displayValue: '7'}, {isNull: false, displayValue: '8'}], [{isNull: false, displayValue: '9'}, {isNull: false, displayValue: '10 ∞'}] ] } }; process.env['LANG'] = 'C'; let testRange: ISlickRange[] = [{fromCell: 0, fromRow: 0, toCell: 1, toRow: 4}]; let result: QueryExecuteCompleteNotificationResult = { ownerUri: testuri, batchSummaries: [{ hasError: false, id: 0, selection: {startLine: 0, endLine: 0, startColumn: 3, endColumn: 3}, resultSetSummaries: <ResultSetSummary[]> [{ id: 0, rowCount: 5, columnInfo: [ { columnName: 'Col1' }, { columnName: 'Col2' } ] }], executionElapsed: undefined, executionStart: new Date().toISOString(), executionEnd: new Date().toISOString() }] }; setup(() => { testSqlToolsServerClient.setup(x => x.sendRequest(TypeMoq.It.isAny(), TypeMoq.It.isAny())).callback(() => { // testing }).returns(() => { return Promise.resolve(testresult); }); testStatusView.setup(x => x.executingQuery(TypeMoq.It.isAnyString())); testStatusView.setup(x => x.executedQuery(TypeMoq.It.isAnyString())); testVscodeWrapper.setup( x => x.logToOutputChannel(TypeMoq.It.isAnyString())); testVscodeWrapper.setup(x => x.clipboardWriteText(TypeMoq.It.isAnyString())).callback(() => { // testing }).returns(() => { return Promise.resolve(); }); }); // ------ Copy tests ------- test('Correctly copy pastes a selection', (done) => { let configResult: {[key: string]: any} = {}; configResult[Constants.copyIncludeHeaders] = false; setupWorkspaceConfig(configResult); let queryRunner = new QueryRunner( testuri, testuri, testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object ); queryRunner.uri = testuri; queryRunner.copyResults(testRange, 0, 0).then(() => { testVscodeWrapper.verify<void>(x => x.clipboardWriteText(TypeMoq.It.isAnyString()), TypeMoq.Times.once()); done(); }); }); test('Copies selection with column headers set in user config', () => { // Set column headers in the user config settings let configResult: {[key: string]: any} = {}; configResult[Constants.copyIncludeHeaders] = true; setupWorkspaceConfig(configResult); let queryRunner = new QueryRunner( testuri, testuri, testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object ); queryRunner.uri = testuri; // Call handleResult to ensure column header info is seeded queryRunner.handleQueryComplete(result); return queryRunner.copyResults(testRange, 0, 0).then(() => { testVscodeWrapper.verify<void>(x => x.clipboardWriteText(TypeMoq.It.isAnyString()), TypeMoq.Times.once()); }); }); test('Copies selection with headers when true passed as parameter', () => { // Do not set column config in user settings let configResult: {[key: string]: any} = {}; configResult[Constants.copyIncludeHeaders] = false; setupWorkspaceConfig(configResult); let queryRunner = new QueryRunner( testuri, testuri, testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object ); queryRunner.uri = testuri; // Call handleResult to ensure column header info is seeded queryRunner.handleQueryComplete(result); // call copyResults with additional parameter indicating to include headers return queryRunner.copyResults(testRange, 0, 0, true).then(() => { testVscodeWrapper.verify<void>(x => x.clipboardWriteText(TypeMoq.It.isAnyString()), TypeMoq.Times.once()); }); }); test('Copies selection without headers when false passed as parameter', () => { // Set column config in user settings let configResult: {[key: string]: any} = {}; configResult[Constants.copyIncludeHeaders] = true; setupWorkspaceConfig(configResult); let queryRunner = new QueryRunner( testuri, testuri, testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object ); queryRunner.uri = testuri; // Call handleResult to ensure column header info is seeded queryRunner.handleQueryComplete(result); // call copyResults with additional parameter indicating to not include headers return queryRunner.copyResults(testRange, 0, 0, false).then(() => { testVscodeWrapper.verify<void>(x => x.clipboardWriteText(TypeMoq.It.isAnyString()), TypeMoq.Times.once()); }); }); test('SetEditorSelection uses an existing editor if it is visible', (done) => { let queryUri = 'test_uri'; let queryColumn = 2; let queryRunner = new QueryRunner(queryUri, queryUri, testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object); let editor: vscode.TextEditor = { document: { uri: queryUri }, viewColumn: queryColumn, selection: undefined } as any; testVscodeWrapper.setup(x => x.textDocuments).returns(() => [editor.document]); testVscodeWrapper.setup(x => x.activeTextEditor).returns(() => editor); testVscodeWrapper.setup(x => x.openTextDocument(TypeMoq.It.isAny())).returns(() => Promise.resolve(editor.document)); testVscodeWrapper.setup(x => x.showTextDocument(editor.document, TypeMoq.It.isAny())).returns(() => Promise.resolve(editor)); // If I try to set a selection for the existing editor let selection: ISelectionData = { startColumn: 0, startLine: 0, endColumn: 1, endLine: 1 }; queryRunner.setEditorSelection(selection).then(() => { try { // Then showTextDocument gets called with the existing editor's column testVscodeWrapper.verify(x => x.showTextDocument(editor.document, TypeMoq.It.isAny()), TypeMoq.Times.once()); done(); } catch (err) { done(err); } }, err => done(err)); }); test('SetEditorSelection uses column 1 by default', (done) => { let queryUri = 'test_uri'; let queryRunner = new QueryRunner(queryUri, queryUri, testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object); let editor: vscode.TextEditor = { document: { uri: queryUri }, viewColumn: undefined, selection: undefined } as any; testVscodeWrapper.setup(x => x.textDocuments).returns(() => [editor.document]); testVscodeWrapper.setup(x => x.visibleEditors).returns(() => []); testVscodeWrapper.setup(x => x.openTextDocument(TypeMoq.It.isAny())).returns(() => Promise.resolve(editor.document)); testVscodeWrapper.setup(x => x.showTextDocument(editor.document, TypeMoq.It.isAny())).returns(() => Promise.resolve(editor)); // If I try to set a selection for an editor that is not currently visible queryRunner.setEditorSelection({ startColumn: 0, startLine: 0, endColumn: 1, endLine: 1 }).then(() => { try { // Then showTextDocument gets called with the default first column testVscodeWrapper.verify(x => x.showTextDocument(editor.document, TypeMoq.It.isAny()), TypeMoq.Times.once()); done(); } catch (err) { done(err); } }, err => done(err)); }); }); suite('Copy Tests with multiple selections', () => { // ------ Common inputs and setup for copy tests ------- let mockConfig: TypeMoq.IMock<vscode.WorkspaceConfiguration>; const testuri = 'test'; let testresult: QueryExecuteSubsetResult = { resultSubset: { rowCount: 5, rows: [ [{isNull: false, displayValue: '1'}, {isNull: false, displayValue: '2'}, {isNull: false, displayValue: '3'}], [{isNull: false, displayValue: '4'}, {isNull: false, displayValue: '5'}, {isNull: false, displayValue: '6'}], [{isNull: false, displayValue: '7'}, {isNull: false, displayValue: '8'}, {isNull: false, displayValue: '9'}], [{isNull: false, displayValue: '10'}, {isNull: false, displayValue: '11'}, {isNull: false, displayValue: '12'}], [{isNull: false, displayValue: '13'}, {isNull: false, displayValue: '14'}, {isNull: false, displayValue: '15'}] ] } }; process.env['LANG'] = 'C'; let testRange: ISlickRange[] = [{fromCell: 0, fromRow: 0, toCell: 1, toRow: 2}, {fromCell: 1, fromRow: 1, toCell: 2, toRow: 4}]; let result: QueryExecuteCompleteNotificationResult = { ownerUri: testuri, batchSummaries: [{ hasError: false, id: 0, selection: {startLine: 0, endLine: 0, startColumn: 3, endColumn: 3}, resultSetSummaries: <ResultSetSummary[]> [{ id: 0, rowCount: 5, columnInfo: [ { columnName: 'Col1' }, { columnName: 'Col2' }, { columnName: 'Col3' } ] }], executionElapsed: undefined, executionStart: new Date().toISOString(), executionEnd: new Date().toISOString() }] }; setup(() => { testSqlToolsServerClient.setup(x => x.sendRequest(TypeMoq.It.isAny(), TypeMoq.It.isAny())).callback(() => { // testing }).returns(() => { return Promise.resolve(testresult); }); testStatusView.setup(x => x.executingQuery(TypeMoq.It.isAnyString())); testStatusView.setup(x => x.executedQuery(TypeMoq.It.isAnyString())); testVscodeWrapper.setup( x => x.logToOutputChannel(TypeMoq.It.isAnyString())); testVscodeWrapper.setup(x => x.clipboardWriteText(TypeMoq.It.isAnyString())).callback(() => { // testing }).returns(() => { return Promise.resolve(); }); }); function setupMockConfig(): void { mockConfig = TypeMoq.Mock.ofType<vscode.WorkspaceConfiguration>(); mockConfig.setup(c => c.get(TypeMoq.It.isAnyString())).returns(() => false); testVscodeWrapper.setup(x => x.getConfiguration(TypeMoq.It.isAny(), TypeMoq.It.isAny())).returns(() => mockConfig.object); } // ------ Copy tests with multiple selections ------- test('Correctly copy pastes a selection', async () => { setupMockConfig(); let queryRunner = new QueryRunner( testuri, testuri, testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object ); queryRunner.uri = testuri; await queryRunner.copyResults(testRange, 0, 0); // Two selections mockConfig.verify(c => c.get(Constants.configCopyRemoveNewLine), TypeMoq.Times.atLeast(2)); // Once for new lines and once for headers testVscodeWrapper.verify(v => v.getConfiguration(TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.atLeast(2)); mockConfig.verify(c => c.get(Constants.copyIncludeHeaders), TypeMoq.Times.once()); testVscodeWrapper.verify<void>(x => x.clipboardWriteText(TypeMoq.It.isAnyString()), TypeMoq.Times.once()); }); test('Copies selection with column headers set in user config', async () => { setupMockConfig(); // Set column headers in the user config settings let queryRunner = new QueryRunner( testuri, testuri, testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object ); queryRunner.uri = testuri; // Call handleResult to ensure column header info is seeded queryRunner.handleQueryComplete(result); await queryRunner.copyResults(testRange, 0, 0); mockConfig.verify(c => c.get(Constants.copyIncludeHeaders), TypeMoq.Times.once()); // Two selections mockConfig.verify(c => c.get(Constants.configCopyRemoveNewLine), TypeMoq.Times.atLeast(2)); testVscodeWrapper.verify(v => v.getConfiguration(TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.atLeast(2)); testVscodeWrapper.verify<void>(x => x.clipboardWriteText(TypeMoq.It.isAnyString()), TypeMoq.Times.once()); }); test('Copies selection with headers when true passed as parameter', async () => { setupMockConfig(); // Do not set column config in user settings let queryRunner = new QueryRunner( testuri, testuri, testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object ); queryRunner.uri = testuri; // Call handleResult to ensure column header info is seeded queryRunner.handleQueryComplete(result); // call copyResults with additional parameter indicating to include headers await queryRunner.copyResults(testRange, 0, 0, true); testVscodeWrapper.verify(x => x.getConfiguration(TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.atLeastOnce()); mockConfig.verify(c => c.get(Constants.configCopyRemoveNewLine), TypeMoq.Times.atLeast(2)); mockConfig.verify(c => c.get(Constants.copyIncludeHeaders), TypeMoq.Times.never()); testVscodeWrapper.verify<void>(x => x.clipboardWriteText(TypeMoq.It.isAnyString()), TypeMoq.Times.once()); }); test('Copies selection without headers when false passed as parameter', async () => { setupMockConfig(); // Set column config in user settings let queryRunner = new QueryRunner( testuri, testuri, testStatusView.object, testSqlToolsServerClient.object, testQueryNotificationHandler.object, testVscodeWrapper.object ); queryRunner.uri = testuri; // Call handleResult to ensure column header info is seeded queryRunner.handleQueryComplete(result); // call copyResults with additional parameter indicating to not include headers await queryRunner.copyResults(testRange, 0, 0, false); testVscodeWrapper.verify(x => x.getConfiguration(TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.atLeastOnce()); mockConfig.verify(c => c.get(Constants.configCopyRemoveNewLine), TypeMoq.Times.atLeast(2)); mockConfig.verify(c => c.get(Constants.copyIncludeHeaders), TypeMoq.Times.never()); testVscodeWrapper.verify<void>(x => x.clipboardWriteText(TypeMoq.It.isAnyString()), TypeMoq.Times.once()); }); }); }); /** * Sets up a mock SQL Tools Service client with a handler for submitting a query execute request * @param testSqlToolsServerClient The mock service client to setup * @param returnCallback Function to execute when query execute request is called */ function setupStandardQueryRequestServiceMock( testSqlToolsServerClient: TypeMoq.IMock<SqlToolsServerClient>, returnCallback: (...x: any[]) => Thenable<QueryDisposeContracts.QueryDisposeResult> ): void { testSqlToolsServerClient.setup(x => x.sendRequest(TypeMoq.It.isValue(QueryExecuteContracts.QueryExecuteRequest.type), TypeMoq.It.isAny())) .callback((type, details: QueryExecuteParams) => { assert.equal(details.ownerUri, standardUri); assert.equal(details.querySelection.startLine, standardSelection.startLine); assert.equal(details.querySelection.startColumn, standardSelection.startColumn); assert.equal(details.querySelection.endLine, standardSelection.endLine); assert.equal(details.querySelection.endColumn, standardSelection.endColumn); }) .returns(returnCallback); } function setupStandardQueryNotificationHandlerMock(testQueryNotificationHandler: TypeMoq.IMock<QueryNotificationHandler>): void { testQueryNotificationHandler.setup(x => x.registerRunner(TypeMoq.It.isAny(), TypeMoq.It.isAnyString())) .callback((qr, u: string) => { assert.equal(u, standardUri); }); }
the_stack
import { Application } from '@nativescript/core'; import { CLog, CLogTypes, headersProperty, VideoCommon, videoSourceProperty } from './videoplayer-common'; declare const NSMutableDictionary; export class Video extends VideoCommon { private _playerController: AVPlayerViewController; private _src = ''; private _url; private _headers: NSMutableDictionary<string, string>; private _didPlayToEndTimeObserver: any; private _didPlayToEndTimeActive: boolean; private _observer: NSObject; private _observerActive: boolean; private _playbackTimeObserver: any; private _playbackTimeObserverActive: boolean; private _videoPlaying: boolean; private _videoFinished = false; private _owner: WeakRef<Video>; public nativeView: UIView; public player: AVPlayer; public videoLoaded = false; constructor() { super(); this._playerController = AVPlayerViewController.new(); CLog(CLogTypes.info, 'this._playerController', this._playerController); this.player = AVPlayer.new(); CLog(CLogTypes.info, 'this.player', this.player); this._playerController.player = this.player; // showsPlaybackControls must be set to false on init to avoid any potential 'Unable to simultaneously satisfy constraints' errors this._playerController.showsPlaybackControls = false; this.nativeView = this._playerController.view; this._observer = PlayerObserverClass.alloc().init(); CLog(CLogTypes.info, 'this._observer', this._observer); this._observer['_owner'] = this; (this._observer as any).owner = this; } // get ios(): any { // return this.nativeView; // } [headersProperty.setNative](value) { this._setHeader(value ? value : null); } [videoSourceProperty.setNative](value: AVPlayerItem) { this._setNativeVideo(value ? (value as any).ios : null); } public _setHeader(headers: Map<string, string>): void { CLog(CLogTypes.info, 'Video._setHeader ---', `headers: ${headers}`); if (headers && headers.size > 0) { this._headers = new NSMutableDictionary(); CLog( CLogTypes.info, `Video._setHeader ---`, `this._headers: ${this._headers}` ); headers.forEach((value: string, key: string) => { this._headers.setValueForKey(value, key); }); } if (this._src) { CLog(CLogTypes.info, 'Video._setHeader ---', `this._src: ${this._src}`); this._setNativePlayerSource(this._src); } } public _setNativeVideo(nativeVideoPlayer: any) { CLog( CLogTypes.info, 'Video._setNativeVideo ---', `nativeVideoPlayer: ${nativeVideoPlayer}` ); // if (this['_url'] && this._headers && this._headers.count > 0) { if (this._url && this._headers && this._headers.count > 0) { // adding headers if exist when loading video from URL CLog(CLogTypes.warning, 'Need to add headers!'); // const url = NSURL.URLWithString(this['_url']); const url = NSURL.URLWithString(this._url); CLog(CLogTypes.info, 'Video._setNativeVideo ---', `url: ${url}`); const options: any = NSDictionary.dictionaryWithDictionary(<any>{ AVURLAssetHTTPHeaderFieldsKey: this._headers }); const asset: AVURLAsset = AVURLAsset.alloc().initWithURLOptions( url, options ); const item: AVPlayerItem = AVPlayerItem.playerItemWithAsset(asset); nativeVideoPlayer = item; } if (nativeVideoPlayer != null) { const currentItem = this.player.currentItem; this._addStatusObserver(nativeVideoPlayer); this._autoplayCheck(); this._videoFinished = false; if (currentItem !== null) { this.videoLoaded = false; this._videoPlaying = false; this._removeStatusObserver(currentItem); // Need to set to null so the previous video is not shown while its loading this.player.replaceCurrentItemWithPlayerItem(null); this.player.replaceCurrentItemWithPlayerItem(nativeVideoPlayer); } else { this.player.replaceCurrentItemWithPlayerItem(nativeVideoPlayer); this._init(); } } } public updateAsset(nativeVideoAsset: AVAsset) { CLog( CLogTypes.info, 'Video.updateAsset ---', `nativeVideoAsset: ${nativeVideoAsset}` ); const newPlayerItem = AVPlayerItem.playerItemWithAsset(nativeVideoAsset); this._setNativeVideo(newPlayerItem); } public _setNativePlayerSource(nativePlayerSrc: string) { CLog( CLogTypes.info, 'Video._setNativePlayerSource ---', `nativePlayerSrc: ${nativePlayerSrc}` ); this._src = nativePlayerSrc; const url = NSURL.URLWithString(this._src); this.player = AVPlayer.new(); this._init(); } public play() { CLog(CLogTypes.info, 'Video.play'); if (this._videoFinished) { this._videoFinished = false; this.seekToTime(5); } if (this.observeCurrentTime && !this._playbackTimeObserverActive) { this._addPlaybackTimeObserver(); } this.player.play(); this.sendEvent(VideoCommon.playbackStartEvent); } public pause() { CLog(CLogTypes.info, 'Video.pause()'); this.player.pause(); this.sendEvent(VideoCommon.pausedEvent); if (this._playbackTimeObserverActive) { this._removePlaybackTimeObserver(); } } public mute(mute: boolean) { CLog(CLogTypes.info, 'Video.mute ---', `mute: ${mute}`); this.player.muted = mute; // send the event if (mute === true) { this.sendEvent(VideoCommon.mutedEvent); } else { this.sendEvent(VideoCommon.unmutedEvent); } } public seekToTime(ms: number) { CLog(CLogTypes.info, 'Video.seekToTime ---', `ms: ${ms}`); const seconds = ms / 1000.0; const time = CMTimeMakeWithSeconds( seconds, this.player.currentTime().timescale ); this.player.seekToTimeToleranceBeforeToleranceAfterCompletionHandler( time, kCMTimeZero, kCMTimeZero, isFinished => { CLog( CLogTypes.info, `Video.seekToTime ---`, 'emitting seekToTimeCompleteEvent' ); this.sendEvent(VideoCommon.seekToTimeCompleteEvent, { time: ms }); } ); } public getDuration(): number { const seconds = CMTimeGetSeconds(this.player.currentItem.asset.duration); const milliseconds = seconds * 1000.0; return milliseconds; } public getCurrentTime(): any { if (this.player === null) { return false; } const result = (this.player.currentTime().value / this.player.currentTime().timescale) * 1000; return result; } public setVolume(volume: number) { CLog(CLogTypes.info, 'Video.setVolume ---', `volume: ${volume}`); this.player.volume = volume; this.sendEvent(VideoCommon.volumeSetEvent); } public destroy() { CLog(CLogTypes.info, 'Video.destroy'); this._removeStatusObserver(this.player.currentItem); if (this._didPlayToEndTimeActive) { Application.ios.removeNotificationObserver( this._didPlayToEndTimeObserver, AVPlayerItemDidPlayToEndTimeNotification ); this._didPlayToEndTimeActive = false; } if (this._playbackTimeObserverActive) { this._removePlaybackTimeObserver(); } this.pause(); this.player.replaceCurrentItemWithPlayerItem(null); // de-allocates the AVPlayer this._playerController = null; this.player = null; } public getVideoSize(): { width: number; height: number } { const r = this._playerController.videoBounds; return { width: r.size.width, height: r.size.height }; } private _init() { CLog(CLogTypes.info, 'Video._init'); if (this.controls !== false) { this._playerController.showsPlaybackControls = true; } if (this.fill === true) { this._playerController.videoGravity = AVLayerVideoGravityResizeAspectFill; } this._playerController.player = this.player; if ( isNaN(parseInt(this.width.toString(), 10)) || isNaN(parseInt(this.height.toString(), 10)) ) { this.requestLayout(); } if (this.muted === true) { this.player.muted = true; } if (!this._didPlayToEndTimeActive) { this._didPlayToEndTimeObserver = Application.ios.addNotificationObserver( AVPlayerItemDidPlayToEndTimeNotification, this.AVPlayerItemDidPlayToEndTimeNotification.bind(this) ); this._didPlayToEndTimeActive = true; } } private AVPlayerItemDidPlayToEndTimeNotification(notification: any) { CLog( CLogTypes.info, 'Video.AVPlayerItemDidPlayToEndTimeNotification ---', `notification: ${notification}` ); if ( this.player.currentItem && this.player.currentItem === notification.object ) { // This will match exactly to the object from the notification so can ensure only looping and finished event for the video that has finished. // Notification is structured like so: NSConcreteNotification 0x61000024f690 {name = AVPlayerItemDidPlayToEndTimeNotification; object = <AVPlayerItem: 0x600000204190, asset = <AVURLAsset: 0x60000022b7a0, URL = https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4>>} CLog( CLogTypes.info, 'Video.AVPlayerItemDidPlayToEndTimeNotification ---', 'emmitting finishedEvent' ); this.sendEvent(VideoCommon.finishedEvent); this._videoFinished = true; if (this.loop === true && this.player !== null) { // Go in 5ms for more seamless looping this.player.seekToTime(CMTimeMake(5, 100)); this.player.play(); } } } private _addStatusObserver(currentItem) { CLog( CLogTypes.info, 'Video._addStatusObserver ---', `currentItem: ${currentItem}` ); this._observerActive = true; currentItem.addObserverForKeyPathOptionsContext( this._observer, 'status', 0, null ); } private _removeStatusObserver(currentItem) { CLog( CLogTypes.info, 'Video._removeStatusObserver ---', `currentItem: ${currentItem}` ); this._observerActive = false; currentItem.removeObserverForKeyPath(this._observer, 'status'); } private _addPlaybackTimeObserver() { CLog(CLogTypes.info, 'Video._addPlaybackTimeObserver'); this._playbackTimeObserverActive = true; const _interval = CMTimeMake(1, 5); this._playbackTimeObserver = this.player.addPeriodicTimeObserverForIntervalQueueUsingBlock( _interval, null, currentTime => { const _seconds = CMTimeGetSeconds(currentTime); const _milliseconds = _seconds * 1000.0; CLog( CLogTypes.info, `Video._addPlaybackTimeObserver ---`, 'emitting currentTimeUpdatedEvent' ); this.notify({ eventName: VideoCommon.currentTimeUpdatedEvent, object: this, position: _milliseconds }); } ); } private _removePlaybackTimeObserver() { CLog(CLogTypes.info, 'Video._removePlaybackTimeObserver'); this._playbackTimeObserverActive = false; this.player.removeTimeObserver(this._playbackTimeObserver); } private _autoplayCheck() { CLog( CLogTypes.info, 'Video._autoplayCheck ---', `this.autoplay ${this.autoplay}` ); if (this.autoplay) { this.play(); } } playbackReady() { this.videoLoaded = true; CLog( CLogTypes.info, `Video.playbackReady ---`, 'emitting playbackReadyEvent' ); this.sendEvent(VideoCommon.playbackReadyEvent); } playbackStart() { this._videoPlaying = true; CLog( CLogTypes.info, `Video.playbackStart ---`, 'emitting playbackStartEvent' ); this.sendEvent(VideoCommon.playbackStartEvent); } public setMode(mode: string, fill: boolean) { if (this.mode !== mode) { let transform = CGAffineTransformIdentity; if (mode === 'LANDSCAPE') { transform = CGAffineTransformRotate( transform, (90 * 3.14159265358979) / 180 ); this._playerController.view.transform = transform; const newFrame = CGRectMake( 0, 0, this.nativeView.bounds.size.width, this.nativeView.bounds.size.height ); this.nativeView.frame = newFrame; } else if (this.mode !== mode && mode === 'PORTRAIT') { transform = CGAffineTransformRotate( transform, (0 * 3.14159265358979) / 180 ); this._playerController.view.transform = transform; const newFrame = CGRectMake( 0, 0, this.nativeView.bounds.size.height, this.nativeView.bounds.size.width ); this.nativeView.frame = newFrame; } this.mode = mode; } if (this.fill !== fill) { if (fill) { this._playerController.videoGravity = AVLayerVideoGravityResizeAspectFill; } else { this._playerController.videoGravity = AVLayerVideoGravityResizeAspect; } this.fill = fill; } } } @NativeClass() class PlayerObserverClass extends NSObject { observeValueForKeyPathOfObjectChangeContext( path: string, obj: Object, change: NSDictionary<any, any>, context: any ) { CLog( CLogTypes.info, 'PlayerObserverClass.observeValueForKeyPathOfObjectChangeContext ---', `path: ${path}, obj: ${obj}, change: ${change}, context: ${context}` ); if (path === 'status') { const owner = (this as any).owner as Video; if (owner.player.currentItem.status === AVPlayerItemStatus.Failed) { const baseError = owner.player.currentItem.error.userInfo.objectForKey( NSUnderlyingErrorKey ); const error = new Error(); owner.sendEvent(VideoCommon.errorEvent, { error: { code: baseError.code, domain: baseError.domain }, stack: error.stack }); } if ( owner.player && owner.player.currentItem.status === AVPlayerItemStatus.ReadyToPlay && !owner.videoLoaded ) { owner.playbackReady(); } } } }
the_stack
import { BlobServiceClient, newPipeline, StorageSharedKeyCredential } from "@azure/storage-blob"; import * as assert from "assert"; import { EMULATOR_ACCOUNT_KIND, EMULATOR_ACCOUNT_SKUNAME } from "../../../src/blob/utils/constants"; import { configLogger } from "../../../src/common/Logger"; import BlobTestServerFactory from "../../BlobTestServerFactory"; import { EMULATOR_ACCOUNT_KEY, EMULATOR_ACCOUNT_NAME, getUniqueName } from "../../testutils"; // Set true to enable debug log configLogger(false); describe("ServiceAPIs", () => { const factory = new BlobTestServerFactory(); const server = factory.createServer(); const baseURL = `http://${server.config.host}:${server.config.port}/devstoreaccount1`; const serviceClient = new BlobServiceClient( baseURL, newPipeline( new StorageSharedKeyCredential( EMULATOR_ACCOUNT_NAME, EMULATOR_ACCOUNT_KEY ), { retryOptions: { maxTries: 1 }, // Make sure socket is closed once the operation is done. keepAliveOptions: { enable: false } } ) ); before(async () => { await server.start(); }); after(async () => { await server.close(); await server.clean(); }); it("GetServiceProperties @loki @sql", async () => { const result = await serviceClient.getProperties(); assert.ok(typeof result.requestId); assert.ok(result.requestId!.length > 0); assert.ok(typeof result.version); assert.ok(result.version!.length > 0); if (result.cors && result.cors!.length > 0) { assert.ok(result.cors![0].allowedHeaders.length >= 0); assert.ok(result.cors![0].allowedMethods.length > 0); assert.ok(result.cors![0].allowedOrigins.length > 0); assert.ok(result.cors![0].exposedHeaders.length >= 0); assert.ok(result.cors![0].maxAgeInSeconds >= 0); } assert.equal( result._response.request.headers.get("x-ms-client-request-id"), result.clientRequestId ); }); it("Set CORS with empty AllowedHeaders, ExposedHeaders @loki @sql", async () => { const serviceProperties = await serviceClient.getProperties(); const newCORS = { allowedHeaders: "", allowedMethods: "GET", allowedOrigins: "example.com", exposedHeaders: "", maxAgeInSeconds: 8888 }; serviceProperties.cors = [newCORS]; await serviceClient.setProperties(serviceProperties); const result = await serviceClient.getProperties(); assert.deepStrictEqual(result.cors![0], newCORS); }); it("SetServiceProperties @loki @sql", async () => { const serviceProperties = await serviceClient.getProperties(); serviceProperties.blobAnalyticsLogging = { deleteProperty: true, read: true, retentionPolicy: { days: 5, enabled: true }, version: "1.0", write: true }; serviceProperties.minuteMetrics = { enabled: true, includeAPIs: true, retentionPolicy: { days: 4, enabled: true }, version: "1.0" }; serviceProperties.hourMetrics = { enabled: true, includeAPIs: true, retentionPolicy: { days: 3, enabled: true }, version: "1.0" }; const newCORS = { allowedHeaders: "*", allowedMethods: "GET", allowedOrigins: "example.com", exposedHeaders: "*", maxAgeInSeconds: 8888 }; if (!serviceProperties.cors) { serviceProperties.cors = [newCORS]; } else if (serviceProperties.cors!.length < 5) { serviceProperties.cors.push(newCORS); } if (!serviceProperties.deleteRetentionPolicy) { serviceProperties.deleteRetentionPolicy = { days: 2, enabled: false }; } const result_set = await serviceClient.setProperties(serviceProperties); assert.equal( result_set._response.request.headers.get("x-ms-client-request-id"), result_set.clientRequestId ); const result = await serviceClient.getProperties(); assert.ok(typeof result.requestId); assert.ok(result.requestId!.length > 0); assert.ok(typeof result.version); assert.ok(result.version!.length > 0); assert.deepEqual(result.hourMetrics, serviceProperties.hourMetrics); assert.equal( result._response.request.headers.get("x-ms-client-request-id"), result.clientRequestId ); }); it("List containers in sorted order @loki @sql", async () => { const containerNamePrefix = getUniqueName("container"); const containerName1 = `${containerNamePrefix}cc`; const containerName2 = `${containerNamePrefix}aa`; const containerName3 = `${containerNamePrefix}bb`; const containerClient1 = serviceClient.getContainerClient(containerName1); const containerClient2 = serviceClient.getContainerClient(containerName2); const containerClient3 = serviceClient.getContainerClient(containerName3); await containerClient1.create(); await containerClient2.create(); await containerClient3.create(); const result = ( await serviceClient .listContainers({ prefix: containerNamePrefix }) .byPage() .next() ).value; assert.equal(result.containerItems.length, 3); assert.ok(result.containerItems[0].name.endsWith("aa")); assert.ok(result.containerItems[1].name.endsWith("bb")); assert.ok(result.containerItems[2].name.endsWith("cc")); await containerClient1.delete(); await containerClient2.delete(); await containerClient3.delete(); }); it("List containers with marker @loki @sql", async () => { const containerNamePrefix = getUniqueName("container"); const containerName1 = `${containerNamePrefix}cc`; const containerName2 = `${containerNamePrefix}aa`; const containerName3 = `${containerNamePrefix}bb`; const containerClient1 = serviceClient.getContainerClient(containerName1); const containerClient2 = serviceClient.getContainerClient(containerName2); const containerClient3 = serviceClient.getContainerClient(containerName3); await containerClient1.create(); await containerClient2.create(); await containerClient3.create(); const result = ( await serviceClient .listContainers({ prefix: containerNamePrefix }) .byPage({ continuationToken: containerName2 }) .next() ).value; assert.equal(result.containerItems.length, 2); assert.equal(result.containerItems[0].name, containerName3); assert.equal(result.containerItems[1].name, containerName1); await containerClient1.delete(); await containerClient2.delete(); await containerClient3.delete(); }); it("List containers with marker and max result length less than result size @loki @sql", async () => { const containerNamePrefix = getUniqueName("container"); const containerName1 = `${containerNamePrefix}cc`; const containerName2 = `${containerNamePrefix}aa`; const containerName3 = `${containerNamePrefix}bb`; const containerClient1 = serviceClient.getContainerClient(containerName1); const containerClient2 = serviceClient.getContainerClient(containerName2); const containerClient3 = serviceClient.getContainerClient(containerName3); await containerClient1.create(); await containerClient2.create(); await containerClient3.create(); const result1 = ( await serviceClient .listContainers({ prefix: containerNamePrefix }) .byPage({ continuationToken: containerName2, maxPageSize: 1 }) .next() ).value; assert.equal(result1.containerItems.length, 1); assert.equal(result1.containerItems[0].name, containerName3); assert.equal(result1.continuationToken, containerName3); const result2 = ( await serviceClient .listContainers({ prefix: containerNamePrefix }) .byPage({ continuationToken: result1.continuationToken, maxPageSize: 1 }) .next() ).value; assert.equal(result2.containerItems.length, 1); assert.ok(result2.containerItems[0].name, containerName1); assert.equal(result2.continuationToken, ""); await containerClient1.delete(); await containerClient2.delete(); await containerClient3.delete(); }); it("ListContainers with default parameters @loki @sql", async () => { const result = (await serviceClient.listContainers().byPage().next()).value; assert.ok(typeof result.requestId); assert.ok(result.requestId!.length > 0); assert.ok(typeof result.version); assert.ok(result.version!.length > 0); assert.ok(result.serviceEndpoint.length > 0); assert.ok(result.containerItems!.length >= 0); if (result.containerItems!.length > 0) { const container = result.containerItems![0]; assert.ok(container.name.length > 0); assert.ok(container.properties.etag.length > 0); assert.ok(container.properties.lastModified); } assert.equal( result._response.request.headers.get("x-ms-client-request-id"), result.clientRequestId ); }); it("ListContainers with all parameters configured @loki @sql", async () => { const containerNamePrefix = getUniqueName("container"); const containerName1 = `${containerNamePrefix}x1`; const containerName2 = `${containerNamePrefix}x2`; const containerClient1 = serviceClient.getContainerClient(containerName1); const containerClient2 = serviceClient.getContainerClient(containerName2); await containerClient1.create({ metadata: { key: "val" } }); await containerClient2.create({ metadata: { key: "val" } }); const result1 = ( await serviceClient .listContainers({ includeMetadata: true, prefix: containerNamePrefix }) .byPage({ maxPageSize: 1 }) .next() ).value; assert.ok(result1.continuationToken); assert.equal(result1.containerItems!.length, 1); assert.ok(result1.containerItems![0].name.startsWith(containerNamePrefix)); assert.ok(result1.containerItems![0].properties.etag.length > 0); assert.ok(result1.containerItems![0].properties.lastModified); assert.ok(!result1.containerItems![0].properties.leaseDuration); assert.ok(!result1.containerItems![0].properties.publicAccess); assert.deepEqual( result1.containerItems![0].properties.leaseState, "available" ); assert.deepEqual( result1.containerItems![0].properties.leaseStatus, "unlocked" ); assert.deepEqual(result1.containerItems![0].metadata!.key, "val"); assert.equal( result1._response.request.headers.get("x-ms-client-request-id"), result1.clientRequestId ); const result2 = ( await serviceClient .listContainers({ includeMetadata: true, prefix: containerNamePrefix }) .byPage({ continuationToken: result1.continuationToken, maxPageSize: 1 }) .next() ).value; assert.equal(result2.containerItems!.length, 1); assert.ok(result2.containerItems![0].name.startsWith(containerNamePrefix)); assert.ok(result2.containerItems![0].properties.etag.length > 0); assert.ok(result2.containerItems![0].properties.lastModified); assert.ok(!result2.containerItems![0].properties.leaseDuration); assert.ok(!result2.containerItems![0].properties.publicAccess); assert.deepEqual( result2.containerItems![0].properties.leaseState, "available" ); assert.deepEqual( result2.containerItems![0].properties.leaseStatus, "unlocked" ); assert.deepEqual(result2.containerItems![0].metadata!.key, "val"); await containerClient1.delete(); await containerClient2.delete(); }); it("get Account info @loki @sql", async () => { const result = await serviceClient.getAccountInfo(); assert.equal(result.accountKind, EMULATOR_ACCOUNT_KIND); assert.equal(result.skuName, EMULATOR_ACCOUNT_SKUNAME); assert.equal( result._response.request.headers.get("x-ms-client-request-id"), result.clientRequestId ); }); it("Get Account/Service Properties with Uri has suffix '/' after account name @loki @sql", async () => { const baseURL1 = `http://${server.config.host}:${server.config.port}/devstoreaccount1/`; const serviceClient1 = new BlobServiceClient( baseURL1, newPipeline( new StorageSharedKeyCredential( EMULATOR_ACCOUNT_NAME, EMULATOR_ACCOUNT_KEY ), { retryOptions: { maxTries: 1 }, // Make sure socket is closed once the operation is done. keepAliveOptions: { enable: false } } ) ); let result = await serviceClient1.getAccountInfo(); assert.equal(result.accountKind, EMULATOR_ACCOUNT_KIND); assert.equal(result.skuName, EMULATOR_ACCOUNT_SKUNAME); assert.equal( result._response.request.headers.get("x-ms-client-request-id"), result.clientRequestId ); result = await serviceClient1.getProperties(); assert.ok(typeof result.requestId); assert.ok(result.requestId!.length > 0); assert.ok(typeof result.version); assert.ok(result.version!.length > 0); assert.equal( result._response.request.headers.get("x-ms-client-request-id"), result.clientRequestId ); }); it("Get Blob service stats negative @loki", async () => { await serviceClient.getStatistics() .catch((err) => { assert.strictEqual(err.statusCode, 400); assert.strictEqual(err.details.Code, "InvalidQueryParameterValue"); assert.ok(err); });; }); }); describe("ServiceAPIs - secondary location endpoint", () => { const factory = new BlobTestServerFactory(); const server = factory.createServer(); const baseURL = `http://${server.config.host}:${server.config.port}/devstoreaccount1-secondary`; const serviceClient = new BlobServiceClient( baseURL, newPipeline( new StorageSharedKeyCredential( EMULATOR_ACCOUNT_NAME, EMULATOR_ACCOUNT_KEY ), { retryOptions: { maxTries: 1 }, // Make sure socket is closed once the operation is done. keepAliveOptions: { enable: false } } ) ); before(async () => { await server.start(); }); after(async () => { await server.close(); await server.clean(); }); it("Get Blob service stats @loki", async () => { await serviceClient.getStatistics() .then((result) => { assert.strictEqual(result.geoReplication?.status, "live"); }) .catch((err) => { assert.ifError(err); }); }); });
the_stack
import _ from "lodash"; // this means server needs to import lang import { SynthDefCompiler, SynthDefResultType, SynthDefCompileRequest } from "@supercollider/lang"; import Server, { whenNodeEnd, whenNodeGo, ServerArgs, msg } from "@supercollider/server"; // Store // import resolveOptions from "../server/src/resolveOptions"; // import { whenNodeEnd, whenNodeGo} from "../server/src/node-watcher"; // import { ServerArgs, defaults } from "../server/src/options"; import Store from "@supercollider/server/lib/internals/Store"; // import * as msg from "../server/src/osc/msg"; type Params = msg.Params; /** * scsynth Group * * See `server.group(...)` */ export class Group { id: number; server: ServerPlus; constructor(server: ServerPlus, id: number) { this.id = id; this.server = server; } /** * Stop the Group and remove it from the play graph on the server. */ free(): Promise<number> { this.server.send.msg(msg.nodeFree(this.id)); return whenNodeEnd(this.server, String(this.id), this.id); } /** * Update control parameters on the Synth. * * @example * ```js * synth.set({freq: 441, amp: 0.9}); * ``` * * This method works for Group and Synth. * For a Group it sends the set message to all children Synths * in the Group. */ set(settings: Params): void { this.server.send.msg(msg.nodeSet(this.id, settings)); } // moveAfter // moveBefore // onEnd // run // trace } /** * Created with `server.synth(...)` * * Extends Group */ export class Synth extends Group { // store def and args // synthDef // release // get } /** * scsynth audio bus * * See `server.audioBus(...)` * * These bus numbers (ids) and numChannels are allocated here in the client. * The server only gets bus ids for reading and writing to. */ export class AudioBus { id: number; server: ServerPlus; numChannels: number; constructor(server: ServerPlus, id: number, numChannels: number) { this.server = server; this.id = id; this.numChannels = numChannels; } /** * Deallocate the AudioBus, freeing it for resuse. */ free(): void { this.server.state.freeAudioBus(this.id, this.numChannels); } } /** * scsynth control bus * See `server.controlBus(...)` * * These bus numbers (ids) and numChannels are allocated here in the client. * The server only gets bus ids for reading and writing to. */ export class ControlBus extends AudioBus { /** * Deallocate the ControlBus, freeing it for resuse. */ free(): void { this.server.state.freeControlBus(this.id, this.numChannels); } // set // fill // get } /** * scsynth Buffer * * See `server.buffer(...)` and `server.readBuffer(...)` */ export class Buffer { id: number; server: ServerPlus; numFrames: number; numChannels: number; constructor(server: ServerPlus, id: number, numFrames: number, numChannels: number) { this.server = server; this.id = id; this.numFrames = numFrames; this.numChannels = numChannels; } /** * Deallocate the Buffer, freeing memory on the server. */ async free(): Promise<void> { await this.server.callAndResponse(msg.bufferFree(this.id)); this.server.state.freeBuffer(this.id, this.numChannels); } // read // write // zero // set frames // fill // gen // close // query // get } /** * scsynth SynthDef * * See `server.synthDefs(...)` * * These are currently compiled using sclang, * and the synthDefResult holds metadata about the compiled * synthdef and the raw compiled bytes. * * The SynthDef may have been compiled from a sourceCode string * or compiled from a file at path. */ export class SynthDef { server: ServerPlus; name: string; synthDefResult: SynthDefResultType; sourceCode?: string; path?: string; constructor( server: ServerPlus, defName: string, synthDefResult: SynthDefResultType, sourceCode?: string, path?: string, ) { this.server = server; this.name = defName; this.synthDefResult = synthDefResult; this.sourceCode = sourceCode; this.path = path; // SynthDefCompiler will watch the path } // free // setSource // get info about def } /** * Supplied to synthDefs */ // interface SynthDefsArgs { // [defName: string]: { // source?: string; // path?: string; // }; // } /** * This extends Server with convienient methods for creating Synth, Group, compiling SynthDefs, creating Buses, Buffers etc. * * All methods return Promises, and all arguments accept Promises. * This means that async actions (like starting a sclang interpreter, * compiling SynthDefs and sending them to the server) are complete and their results * are ready to be used by whatever they have been supplied to. */ export default class ServerPlus extends Server { private _synthDefCompiler?: SynthDefCompiler; /** * Create a Synth on the server */ async synth( synthDef: SynthDef, args: Params = {}, group?: Group, addAction: number = msg.AddActions.TAIL, ): Promise<Synth> { const [def, g] = await Promise.all([Promise.resolve(synthDef), Promise.resolve(group)]); const nodeId = this.state.nextNodeID(); // src/ServerPlus.ts:236:29 - error TS2532: Object is possibly 'undefined'. ? const sn = msg.synthNew((def as SynthDef).synthDefResult.name, nodeId, addAction, g ? g.id : 0, args); this.send.msg(sn); await whenNodeGo(this, String(nodeId), nodeId); return new Synth(this, nodeId); } // grainSynth with no id /** * Create a Group on the server */ async group(group?: Group, addAction: number = msg.AddActions.TAIL): Promise<Group> { const g = await Promise.resolve(group); const nodeId = this.state.nextNodeID(); const sn = msg.groupNew(nodeId, addAction, g ? g.id : 0); this.send.msg(sn); await whenNodeGo(this, String(nodeId), nodeId); return new Group(this, nodeId); } private get synthDefCompiler(): SynthDefCompiler { if (!this._synthDefCompiler) { this._synthDefCompiler = new SynthDefCompiler(); } return this._synthDefCompiler; } /** * Compile multiple SynthDefs either from source or path. * If you have more than one to compile then always use this * as calling `server.synthDef` multiple times will start up * multiple supercollider interpreters. This is harmless, but * very inefficient. * * @param defs - An object with `{defName: spec, ...}` where spec is * an object like `{source: "SynthDef('noise', { ...})"}` * or `{path: "./noise.scd"}` * @returns An object with the synthDef names as keys and Promises as values. * Each Promise will resolve with a SynthDef. * Each Promises can be supplied directly to `server.synth()` */ synthDefs(defs: { [defName: string]: SynthDefCompileRequest }): { [defName: string]: Promise<SynthDef> } { const compiling = this.synthDefCompiler.boot().then(() => { return this.synthDefCompiler.compileAndSend(defs, this); }); return _.mapValues(defs, async (requested, name) => { // for each def await the same promise which returns a dict const defsMap = await compiling; const result: SynthDefResultType = defsMap[name]; if (!result) { new Error(`${name} not found in compiled SynthDefs`); } const sourceCode = result.synthDesc.sourceCode; const synthDef = new SynthDef( this, result.name, result, sourceCode, "path" in requested ? requested.path : undefined, ); return synthDef; }); } private async _compileSynthDef(defName: string, sourceCode?: string, path?: string): Promise<SynthDef> { await this.synthDefCompiler.boot(); let compileRequest: SynthDefCompileRequest; if (sourceCode) { compileRequest = { source: sourceCode }; } else if (path) { compileRequest = { path: path }; } else { throw new Error(`Neither sourceCode nor path supplied for compileSynthDef ${defName}`); } const defs = await this.synthDefCompiler.compileAndSend( { [defName]: compileRequest, }, this, ); // what if defName does not match synthDefResult.name ? const synthDefResult = defs[defName]; if (!synthDefResult) { throw new Error(`SynthDefResult not found ${defName} in synthDefCompiler return values: ${defs}`); } return new SynthDef(this, defName, synthDefResult, sourceCode, path); } /** * Load and compile a SynthDef from path and send it to the server. */ loadSynthDef(defName: string, path: string): Promise<SynthDef> { return this._compileSynthDef(defName, undefined, path); } /** * Compile a SynthDef from supercollider source code and send it to the server. */ synthDef(defName: string, sourceCode: string): Promise<SynthDef> { return this._compileSynthDef(defName, sourceCode); } /** * Allocate a Buffer on the server. */ async buffer(numFrames: number, numChannels = 1): Promise<Buffer> { const id = this.state.allocBufferID(numChannels); await this.callAndResponse(msg.bufferAlloc(id, numFrames, numChannels)); return new Buffer(this, id, numFrames, numChannels); } /** * Allocate a Buffer on the server and load a sound file into it. * * Problem: scsynth uses however many channels there are in the sound file, * but the client (sclang or supercolliderjs) doesn't know how many there are. */ async readBuffer(path: string, numChannels = 2, startFrame = 0, numFramesToRead = -1): Promise<Buffer> { const id = this.state.allocBufferID(numChannels); await this.callAndResponse(msg.bufferAllocRead(id, path, startFrame, numFramesToRead)); return new Buffer(this, id, numFramesToRead, numChannels); } /** * Allocate an audio bus. */ audioBus(numChannels = 1): AudioBus { // TODO: should be a promise that rejects if you run out of busses const id = this.state.allocAudioBus(numChannels); return new AudioBus(this, id, numChannels); } /** * Allocate a control bus. */ controlBus(numChannels = 1): ControlBus { const id = this.state.allocControlBus(numChannels); return new ControlBus(this, id, numChannels); } } /** * Start the scsynth server with options: * * ```js * let server = await sc.server.boot({device: 'Soundflower (2ch)'}); * ``` * * @memberof server * * @param options - Optional command line options for server * @param store - optional external Store to hold Server state */ export async function boot(options?: ServerArgs, store?: Store): Promise<ServerPlus> { const s = new ServerPlus(options, store); await s.boot(); await s.connect(); return s; }
the_stack
import { MOD_KEY } from '../support/constants'; const TYPE_ICONS: { [key: string]: string } = { img: 'media', any: 'document', snd: 'music', vid: 'mobile-video', exe: 'application', arc: 'compressed', doc: 'align-left', cod: 'code', dir: 'folder-close', }; enum KEYS { Backspace = 8, Enter = 13, Escape = 27, Down = 40, Up = 38, PageDown = 34, PageUp = 33, } describe('filetable', () => { before(() => { cy.visit('http://127.0.0.1:8080'); }); beforeEach(() => { createStubs(); resetSelection(); }); let files: any; const stubs: any = { openDirectory: [], openFile: [], }; function resetSelection() { cy.window().then((win) => { win.appState.winStates[0].views.forEach((view: any) => { view.caches.forEach((cache: any) => { cache.reset(); }); }); }); } function createStubs() { stubs.openFile = []; stubs.openDirectory = []; stubs.openParentDirectory = []; stubs.rename = []; cy.window().then((win) => { const appState = win.appState; const views = appState.winStates[0].views; cy.spy(appState, 'updateSelection').as('updateSelection'); let count = 0; for (const view of views) { for (const cache of view.caches) { cy.stub(cache, 'openFile') .as('stub_openFile' + count) .resolves(); cy.stub(cache, 'openDirectory') .as('stub_openDirectory' + count) .resolves(); cy.stub(cache, 'openParentDirectory') .as('stub_openParentDirectory' + count) .resolves(); cy.stub(cache, 'rename') .as('stub_rename' + count) .resolves(); // this will be called but we don't care cy.stub(cache, 'isRoot').returns(false); count++; } } }); } beforeEach(() => { cy.get('#view_0 [data-cy-path]').type('/{enter}').focus().blur(); // load files cy.CDAndList(0, '/').then((array: any) => { files = array; }); }); describe('initial content', () => { it('should display files if cache is not empty', () => { // since we use a virtualized component which only displays visible rows // we cannot simply compare the number of rows to files.length cy.get('#view_0 [data-cy-file]').its('length').should('be.gt', 0); }); it('should use correct icons for each file type', () => { cy.get('#view_0 [data-cy-file] .file-label').as('rows'); files.forEach((file: any) => { const name = file.fullname; const icon = (file.isDir && TYPE_ICONS['dir']) || TYPE_ICONS[file.type]; cy.get('@rows').contains(name).prev().should('have.attr', 'icon').and('eq', icon); }); }); it('should show folders first', () => { // check that the first two elements are the folders of our files list cy.get('#view_0 [data-cy-file] .file-label') .first() .prev() .should('have.attr', 'icon') .and('eq', TYPE_ICONS['dir']); cy.get('#view_0 [data-cy-file] .file-label') .eq(1) .prev() .should('have.attr', 'icon') .and('eq', TYPE_ICONS['dir']); }); }); describe('mouse navigation', () => { it('should select an element when clicking on it', () => { cy.get('#view_0 [data-cy-file]:first').click().should('have.class', 'selected'); }); it('should remove element from selection if already selected when pressing click + shift', () => { cy.get('#view_0 [data-cy-file]:first').click().should('have.class', 'selected'); cy.get('body') .type('{shift}', { release: false }) .get('#view_0 [data-cy-file]:first') .click() .should('not.have.class', 'selected'); }); it('should add element to selection if not selected when pressing click + shift', () => { cy.get('#view_0 [data-cy-file]:first').click().should('have.class', 'selected'); cy.get('body') .type('{shift}', { release: false }) .get('#view_0 [data-cy-file]:eq(1)') .click() .should('have.class', 'selected'); cy.get('#view_0 [data-cy-file]:first').should('have.class', 'selected'); }); it('should call openDirectory when double-clicking on folder', () => { cy.get('#view_0 [data-cy-file]:first').dblclick(); cy.get('@stub_openDirectory0').should('be.called'); }); it('should call openFile when clicking on a file', () => { cy.get('#view_0 [data-cy-file]:eq(5)').dblclick(); cy.get('@stub_openFile0').should('be.called'); }); it('should unselect all files when clicking on empty grid area', () => { // refresh file list but only keep last file from fixture // only keep last file cy.get('#view_0 [data-cy-path]').type('/{enter}').focus().blur(); cy.CDAndList(0, '/', -1); cy.get('#view_0 [data-cy-file]:first').click().should('have.class', 'selected'); cy.get('#view_0 .fileListSizerWrapper').click('bottom'); cy.get('#view_0 [data-cy-file].selected').should('not.exist'); }); }); describe('keyboard navigation', () => { it('should select the next element when pressing arrow down', () => { // one press: select the first one cy.get('#view_0') .trigger('keydown', { keyCode: KEYS.Down }) .find('[data-cy-file]') .first() .should('have.class', 'selected'); // it's the only one that's selected cy.get('#view_0 [data-cy-file].selected').its('length').should('eq', 1); // another press, select the second one cy.get('#view_0') .trigger('keydown', { keyCode: KEYS.Down }) .find('[data-cy-file]') .eq(1) .should('have.class', 'selected'); // it's the only one that's selected cy.get('#view_0 [data-cy-file].selected').its('length').should('eq', 1); }); it('should select the last element when rapidly pressing arrow down key', () => { cy.get('#view_0') .trigger('keydown', { keyCode: KEYS.Down }) .find('[data-cy-file]') .first() .should('have.class', 'selected'); for (let i = 0; i <= files.length; ++i) { cy.get('#view_0').trigger('keydown', { keyCode: KEYS.Down }); } cy.get('#view_0 [data-cy-file]').last().should('have.class', 'selected'); // it's the only one that's selected cy.get('#view_0 [data-cy-file].selected').its('length').should('eq', 1); }); it('should scroll down the table if needed when pressing arrow down key', () => { // first make sure the last element is hidden cy.get('#view_0 [data-cy-file').last().should('not.be.visible'); // press arrow down key until the last item is selected: it should now be visible & selected for (let i = 0; i <= files.length; ++i) { cy.get('#view_0').trigger('keydown', { keyCode: KEYS.Down }); } cy.get('#view_0 [data-cy-file]').last().should('have.class', 'selected').and('be.visible'); // it's the only one that's selected cy.get('#view_0 [data-cy-file].selected').its('length').should('eq', 1); }); it('should select the previous element when pressing arrow up key', () => { // be sure to be in a predictable state, without any selected element cy.triggerHotkey(`${MOD_KEY}a`); cy.triggerHotkey(`${MOD_KEY}i`); // activate the first then second element cy.get('#view_0').trigger('keydown', { keyCode: KEYS.Down }); cy.get('#view_0').trigger('keydown', { keyCode: KEYS.Down }); // activate previous element: should be the second one cy.get('#view_0') .trigger('keydown', { keyCode: KEYS.Up }) .find('[data-cy-file]') .eq(1) .should('have.class', 'selected'); // it's the only one that's selected cy.get('#view_0 [data-cy-file].selected').its('length').should('eq', 1); }); it('should scroll up the table if needed when pressing arrow up key', () => { // press arrow down key until the last item is selected: it should now be visible & selected for (let i = 0; i <= files.length; ++i) { cy.get('#view_0').trigger('keydown', { keyCode: KEYS.Down }); } // check that the first element isn't visible anymore cy.get('#view_0 [data-cy-file]').first().should('not.be.visible'); // press up arrow key until the first item is selected for (let i = 0; i <= files.length; ++i) { cy.get('#view_0').trigger('keydown', { keyCode: KEYS.Up }); } // it should now be visible & selected cy.get('#view_0 [data-cy-file]').first().should('be.visible').and('have.class', 'selected'); // it's the only one that's selected cy.get('#view_0 [data-cy-file].selected').its('length').should('eq', 1); }); it('should open folder if folder is selected and mod + o is pressed', () => { cy.get('#view_0 [data-cy-file]').first().click(); cy.get('body').type(`${MOD_KEY}o`); cy.get('@stub_openDirectory0').should('be.called'); }); it('should open file if a file is selected and mod + o is pressed', () => { cy.get('#view_0 [data-cy-file]').eq(5).click(); cy.get('body').type(`${MOD_KEY}o`); cy.get('@stub_openFile0').should('be.called'); }); it('should open parent directory if backspace is pressed', () => { cy.get('body').type('{backspace}'); cy.get('@stub_openParentDirectory0').should('be.called'); }); it('should select all files if mod + a is pressed', () => { cy.get('body') .type(`${MOD_KEY}a`) .then(() => { const length = files.length; // check that appState.updateSelection is called with every elements cy.get('@updateSelection') .should('be.called') .and((spy: any) => { const calls = spy.getCalls(); const { args } = calls[0]; expect(args[1].length).to.equal(length); }); // and also check that every visible row is selected cy.get('#view_0 [data-cy-file].selected').filter(':visible').should('have.class', 'selected'); }); }); it('should invert selection if mod + i is pressed', () => { cy.get('body').type(`${MOD_KEY}a`); cy.wait(1000); cy.get('body') .type(`${MOD_KEY}i`) .then(() => { // check that appState.updateSelection is called with every elements cy.get('@updateSelection') .should('be.called') .and((spy: any) => { const calls = spy.getCalls(); // get the last call const { args } = calls.pop(); expect(args[1].length).to.equal(0); }); // and also check that every visible row is selected cy.get('#view_0 [data-cy-file].selected').should('not.exist'); }); }); }); describe('rename feature', () => { it('should activate rename for selected element if enter key is pressed and a file is selected', () => { cy.get('#view_0') .trigger('keydown', { keyCode: KEYS.Down }) .trigger('keydown', { keyCode: KEYS.Enter }) .find('[data-cy-file]:first') .find('.file-label') .should('have.attr', 'contenteditable', 'true'); }); it('should activate rename for selected element if the user keeps mousedown', () => { cy.get('#view_0 [data-cy-file]:first .file-label').click(); cy.wait(1000); cy.get('#view_0 [data-cy-file]:first .file-label').click().should('have.attr', 'contenteditable', 'true'); }); it('should select only left part of the filename', () => { // select the second element which is archive.tar.gz cy.get('#view_0 [data-cy-file]:eq(2) .file-label').click(); cy.wait(1000); cy.get('#view_0 [data-cy-file]:eq(2) .file-label').click().should('have.attr', 'contenteditable', 'true'); cy.window().then((window: Window) => { const selection: any = window.getSelection(); cy.get('#view_0 [data-cy-file].selected .file-label') .invoke('text') .then((selectedFilename: any) => { const expectedSelection = 'archive'; const actualSelection = selectedFilename.substr(selection.baseOffset, selection.extentOffset); expect(actualSelection).to.equal(expectedSelection); }); }); }); it('should call cache.rename when pressing enter in edit mode', () => { cy.get('#view_0') .trigger('keydown', { keyCode: KEYS.Down }) .trigger('keydown', { keyCode: KEYS.Enter }) .find('[data-cy-file]:first') .find('.file-label') .type('bar{enter}') // we need to restore previous text to avoid the next test to crash // because React isn't aware of our inline edit since we created a stub for cache.rename // (it's supposed to reload the file cache, which in turns causes a new render of FileTable) .invoke('text', 'folder2'); cy.get('@stub_rename0').should('be.called'); }); it('should not call cache.rename & restore previous filename when pressing escape in edit mode', () => { cy.get('#view_0') .trigger('keydown', { keyCode: KEYS.Down }) .trigger('keydown', { keyCode: KEYS.Enter }) .find('[data-cy-file]:first') .find('.file-label') .type('bar{esc}'); // previous label must have been restored cy.get('#view_0 [data-cy-file].selected').should('contain', 'folder2'); cy.get('@stub_rename0').should('not.be.called'); }); it('renaming should be cancelled if rename input field gets blur event while active', () => { cy.get('#view_0') .trigger('keydown', { keyCode: KEYS.Down }) .trigger('keydown', { keyCode: KEYS.Enter }) .find('[data-cy-file]:first') .find('.file-label') .focus() .type('bar') .blur() .should('contain', 'folder2'); cy.get('@stub_rename0').should('not.be.called'); }); }); });
the_stack
import { concat as observableConcat, empty as observableEmpty, from as observableFrom, merge as observableMerge, of as observableOf, Observable, Subject, Subscription, } from "rxjs"; import { catchError, finalize, map, mergeAll, mergeMap, last, publish, publishReplay, reduce, refCount, tap, } from "rxjs/operators"; import { FilterCreator, FilterFunction } from "./FilterCreator"; import { FilterExpression } from "./FilterExpression"; import { GraphCalculator } from "./GraphCalculator"; import { Image } from "./Image"; import { ImageCache } from "./ImageCache"; import { Sequence } from "./Sequence"; import { GraphConfiguration } from "./interfaces/GraphConfiguration"; import { EdgeCalculator } from "./edge/EdgeCalculator"; import { NavigationEdge } from "./edge/interfaces/NavigationEdge"; import { PotentialEdge } from "./edge/interfaces/PotentialEdge"; import { APIWrapper } from "../api/APIWrapper"; import { SpatialImageEnt } from "../api/ents/SpatialImageEnt"; import { LngLat } from "../api/interfaces/LngLat"; import { GraphMapillaryError } from "../error/GraphMapillaryError"; import { SpatialImagesContract } from "../api/contracts/SpatialImagesContract"; import { ImagesContract } from "../api/contracts/ImagesContract"; import { SequenceContract } from "../api/contracts/SequenceContract"; import { CoreImagesContract } from "../api/contracts/CoreImagesContract"; type NodeTiles = { cache: string[]; caching: string[]; }; type SpatialArea = { all: { [key: string]: Image; }; cacheKeys: string[]; cacheNodes: { [key: string]: Image; }; }; type NodeAccess = { node: Image; accessed: number; }; type TileAccess = { nodes: Image[]; accessed: number; }; type SequenceAccess = { sequence: Sequence; accessed: number; }; export type NodeIndexItem = { lat: number; lng: number; node: Image; }; /** * @class Graph * * @classdesc Represents a graph of nodes with edges. */ export class Graph { private static _spatialIndex: new (...args: any[]) => any; private _api: APIWrapper; /** * Nodes that have initialized cache with a timestamp of last access. */ private _cachedNodes: { [key: string]: NodeAccess; }; /** * Nodes for which the required tiles are cached. */ private _cachedNodeTiles: { [key: string]: boolean; }; /** * Sequences for which the nodes are cached. */ private _cachedSequenceNodes: { [sequenceKey: string]: boolean; }; /** * Nodes for which the spatial edges are cached. */ private _cachedSpatialEdges: { [key: string]: Image; }; /** * Cached tiles with a timestamp of last access. */ private _cachedTiles: { [h: string]: TileAccess; }; /** * Nodes for which fill properties are being retreived. */ private _cachingFill$: { [key: string]: Observable<Graph>; }; /** * Nodes for which full properties are being retrieved. */ private _cachingFull$: { [key: string]: Observable<Graph>; }; /** * Sequences for which the nodes are being retrieved. */ private _cachingSequenceNodes$: { [sequenceKey: string]: Observable<Graph>; }; /** * Sequences that are being retrieved. */ private _cachingSequences$: { [sequenceKey: string]: Observable<Graph>; }; /** * Nodes for which the spatial area fill properties are being retrieved. */ private _cachingSpatialArea$: { [key: string]: Observable<Graph>[]; }; /** * Tiles that are being retrieved. */ private _cachingTiles$: { [h: string]: Observable<Graph>; }; private _changed$: Subject<Graph>; private _defaultAlt: number; private _edgeCalculator: EdgeCalculator; private _graphCalculator: GraphCalculator; private _configuration: GraphConfiguration; private _filter: FilterFunction; private _filterCreator: FilterCreator; private _filterSubject$: Subject<FilterFunction>; private _filter$: Observable<FilterFunction>; private _filterSubscription: Subscription; /** * All nodes in the graph. */ private _nodes: { [key: string]: Image; }; /** * Contains all nodes in the graph. Used for fast spatial lookups. */ private _nodeIndex: any; /** * All node index items sorted in tiles for easy uncache. */ private _nodeIndexTiles: { [h: string]: NodeIndexItem[]; }; /** * Node to tile dictionary for easy tile access updates. */ private _nodeToTile: { [key: string]: string; }; /** * Nodes retrieved before tiles, stored on tile level. */ private _preStored: { [h: string]: { [key: string]: Image; }; }; /** * Tiles required for a node to retrive spatial area. */ private _requiredNodeTiles: { [key: string]: NodeTiles; }; /** * Other nodes required for node to calculate spatial edges. */ private _requiredSpatialArea: { [key: string]: SpatialArea; }; /** * All sequences in graph with a timestamp of last access. */ private _sequences: { [skey: string]: SequenceAccess; }; private _tileThreshold: number; /** * Create a new graph instance. * * @param {APIWrapper} [api] - API instance for retrieving data. * @param {rbush.RBush<NodeIndexItem>} [nodeIndex] - Node index for fast spatial retreival. * @param {GraphCalculator} [graphCalculator] - Instance for graph calculations. * @param {EdgeCalculator} [edgeCalculator] - Instance for edge calculations. * @param {FilterCreator} [filterCreator] - Instance for filter creation. * @param {GraphConfiguration} [configuration] - Configuration struct. */ constructor( api: APIWrapper, nodeIndex?: any, graphCalculator?: GraphCalculator, edgeCalculator?: EdgeCalculator, filterCreator?: FilterCreator, configuration?: GraphConfiguration) { this._api = api; this._cachedNodes = {}; this._cachedNodeTiles = {}; this._cachedSequenceNodes = {}; this._cachedSpatialEdges = {}; this._cachedTiles = {}; this._cachingFill$ = {}; this._cachingFull$ = {}; this._cachingSequenceNodes$ = {}; this._cachingSequences$ = {}; this._cachingSpatialArea$ = {}; this._cachingTiles$ = {}; this._changed$ = new Subject<Graph>(); this._filterCreator = filterCreator ?? new FilterCreator(); this._filter = this._filterCreator.createFilter(undefined); this._filterSubject$ = new Subject<FilterFunction>(); this._filter$ = observableConcat( observableOf(this._filter), this._filterSubject$).pipe( publishReplay(1), refCount()); this._filterSubscription = this._filter$.subscribe(() => { /*noop*/ }); this._defaultAlt = 2; this._edgeCalculator = edgeCalculator ?? new EdgeCalculator(); this._graphCalculator = graphCalculator ?? new GraphCalculator(); this._configuration = configuration ?? { maxSequences: 50, maxUnusedImages: 100, maxUnusedPreStoredImages: 30, maxUnusedTiles: 20, }; this._nodes = {}; this._nodeIndex = nodeIndex ?? new Graph._spatialIndex(16); this._nodeIndexTiles = {}; this._nodeToTile = {}; this._preStored = {}; this._requiredNodeTiles = {}; this._requiredSpatialArea = {}; this._sequences = {}; this._tileThreshold = 20; } public static register(spatialIndex: new (...args: any[]) => any): void { Graph._spatialIndex = spatialIndex; } /** * Get api. * * @returns {APIWrapper} The API instance used by * the graph. */ public get api(): APIWrapper { return this._api; } /** * Get changed$. * * @returns {Observable<Graph>} Observable emitting * the graph every time it has changed. */ public get changed$(): Observable<Graph> { return this._changed$; } /** * Get filter$. * * @returns {Observable<FilterFunction>} Observable emitting * the filter every time it has changed. */ public get filter$(): Observable<FilterFunction> { return this._filter$; } /** * Caches the full node data for all images within a bounding * box. * * @description The node assets are not cached. * * @param {LngLat} sw - South west corner of bounding box. * @param {LngLat} ne - North east corner of bounding box. * @returns {Observable<Array<Image>>} Observable emitting * the full nodes in the bounding box. */ public cacheBoundingBox$(sw: LngLat, ne: LngLat): Observable<Image[]> { const cacheTiles$ = this._api.data.geometry.bboxToCellIds(sw, ne) .filter( (h: string): boolean => { return !(h in this._cachedTiles); }) .map( (h: string): Observable<Graph> => { return h in this._cachingTiles$ ? this._cachingTiles$[h] : this._cacheTile$(h); }); if (cacheTiles$.length === 0) { cacheTiles$.push(observableOf(this)); } return observableFrom(cacheTiles$).pipe( mergeAll(), last(), mergeMap( (): Observable<Image[]> => { const nodes = <Image[]>this._nodeIndex .search({ maxX: ne.lng, maxY: ne.lat, minX: sw.lng, minY: sw.lat, }) .map( (item: NodeIndexItem): Image => { return item.node; }); const fullNodes: Image[] = []; const coreNodes: string[] = []; for (const node of nodes) { if (node.complete) { fullNodes.push(node); } else { coreNodes.push(node.id); } } const coreNodeBatches: string[][] = []; const batchSize = 200; while (coreNodes.length > 0) { coreNodeBatches.push(coreNodes.splice(0, batchSize)); } const fullNodes$ = observableOf(fullNodes); const fillNodes$ = coreNodeBatches .map((batch: string[]): Observable<Image[]> => { return this._api .getSpatialImages$(batch) .pipe( map((items: SpatialImagesContract) : Image[] => { const result: Image[] = []; for (const item of items) { const exists = this .hasNode(item.node_id); if (!exists) { continue; } const node = this .getNode(item.node_id); if (!node.complete) { this._makeFull(node, item.node); } result.push(node); } return result; })); }); return observableMerge( fullNodes$, observableFrom(fillNodes$).pipe( mergeAll())); }), reduce( (acc: Image[], value: Image[]): Image[] => { return acc.concat(value); })); } /** * Caches the full node data for all images of a cell. * * @description The node assets are not cached. * * @param {string} cellId - Cell id. * @returns {Observable<Array<Image>>} Observable * emitting the full nodes of the cell. */ public cacheCell$(cellId: string): Observable<Image[]> { const cacheCell$ = cellId in this._cachedTiles ? observableOf(this) : cellId in this._cachingTiles$ ? this._cachingTiles$[cellId] : this._cacheTile$(cellId); return cacheCell$.pipe( mergeMap((): Observable<Image[]> => { const cachedCell = this._cachedTiles[cellId]; cachedCell.accessed = new Date().getTime(); const cellNodes = cachedCell.nodes; const fullNodes: Image[] = []; const coreNodes: string[] = []; for (const node of cellNodes) { if (node.complete) { fullNodes.push(node); } else { coreNodes.push(node.id); } } const coreNodeBatches: string[][] = []; const batchSize: number = 200; while (coreNodes.length > 0) { coreNodeBatches.push(coreNodes.splice(0, batchSize)); } const fullNodes$ = observableOf(fullNodes); const fillNodes$ = coreNodeBatches .map((batch: string[]): Observable<Image[]> => { return this._api.getSpatialImages$(batch).pipe( map((items: SpatialImagesContract): Image[] => { const filled: Image[] = []; for (const item of items) { if (!item.node) { console.warn( `Image is empty (${item.node})`); continue; } const id = item.node_id; if (!this.hasNode(id)) { continue; } const node = this.getNode(id); if (!node.complete) { this._makeFull(node, item.node); } filled.push(node); } return filled; })); }); return observableMerge( fullNodes$, observableFrom(fillNodes$).pipe( mergeAll())); }), reduce( (acc: Image[], value: Image[]): Image[] => { return acc.concat(value); })); } /** * Retrieve and cache node fill properties. * * @param {string} key - Key of node to fill. * @returns {Observable<Graph>} Observable emitting the graph * when the node has been updated. * @throws {GraphMapillaryError} When the operation is not valid on the * current graph. */ public cacheFill$(key: string): Observable<Graph> { if (key in this._cachingFull$) { throw new GraphMapillaryError(`Cannot fill node while caching full (${key}).`); } if (!this.hasNode(key)) { throw new GraphMapillaryError(`Cannot fill node that does not exist in graph (${key}).`); } if (key in this._cachingFill$) { return this._cachingFill$[key]; } const node = this.getNode(key); if (node.complete) { throw new GraphMapillaryError(`Cannot fill node that is already full (${key}).`); } this._cachingFill$[key] = this._api.getSpatialImages$([key]).pipe( tap( (items: SpatialImagesContract): void => { for (const item of items) { if (!item.node) { console.warn(`Image is empty ${item.node_id}`); } if (!node.complete) { this._makeFull(node, item.node); } delete this._cachingFill$[item.node_id]; } }), map((): Graph => { return this; }), finalize( (): void => { if (key in this._cachingFill$) { delete this._cachingFill$[key]; } this._changed$.next(this); }), publish(), refCount()); return this._cachingFill$[key]; } /** * Retrieve and cache full node properties. * * @param {string} key - Key of node to fill. * @returns {Observable<Graph>} Observable emitting the graph * when the node has been updated. * @throws {GraphMapillaryError} When the operation is not valid on the * current graph. */ public cacheFull$(key: string): Observable<Graph> { if (key in this._cachingFull$) { return this._cachingFull$[key]; } if (this.hasNode(key)) { throw new GraphMapillaryError(`Cannot cache full node that already exist in graph (${key}).`); } this._cachingFull$[key] = this._api.getImages$([key]).pipe( tap( (items: ImagesContract): void => { for (const item of items) { if (!item.node) { throw new GraphMapillaryError( `Image does not exist (${key}, ${item.node}).`); } const id = item.node_id; if (this.hasNode(id)) { const node = this.getNode(key); if (!node.complete) { this._makeFull(node, item.node); } } else { if (item.node.sequence.id == null) { throw new GraphMapillaryError( `Image has no sequence key (${key}).`); } const node = new Image(item.node); this._makeFull(node, item.node); const cellId = this._api.data.geometry .lngLatToCellId(node.originalLngLat); this._preStore(cellId, node); this._setNode(node); delete this._cachingFull$[id]; } } }), map((): Graph => this), finalize( (): void => { if (key in this._cachingFull$) { delete this._cachingFull$[key]; } this._changed$.next(this); }), publish(), refCount()); return this._cachingFull$[key]; } /** * Retrieve and cache a node sequence. * * @param {string} key - Key of node for which to retrieve sequence. * @returns {Observable<Graph>} Observable emitting the graph * when the sequence has been retrieved. * @throws {GraphMapillaryError} When the operation is not valid on the * current graph. */ public cacheNodeSequence$(key: string): Observable<Graph> { if (!this.hasNode(key)) { throw new GraphMapillaryError(`Cannot cache sequence edges of node that does not exist in graph (${key}).`); } let node: Image = this.getNode(key); if (node.sequenceId in this._sequences) { throw new GraphMapillaryError(`Sequence already cached (${key}), (${node.sequenceId}).`); } return this._cacheSequence$(node.sequenceId); } /** * Retrieve and cache a sequence. * * @param {string} sequenceKey - Key of sequence to cache. * @returns {Observable<Graph>} Observable emitting the graph * when the sequence has been retrieved. * @throws {GraphMapillaryError} When the operation is not valid on the * current graph. */ public cacheSequence$(sequenceKey: string): Observable<Graph> { if (sequenceKey in this._sequences) { throw new GraphMapillaryError(`Sequence already cached (${sequenceKey})`); } return this._cacheSequence$(sequenceKey); } /** * Cache sequence edges for a node. * * @param {string} key - Key of node. * @throws {GraphMapillaryError} When the operation is not valid on the * current graph. */ public cacheSequenceEdges(key: string): void { let node: Image = this.getNode(key); if (!(node.sequenceId in this._sequences)) { throw new GraphMapillaryError(`Sequence is not cached (${key}), (${node.sequenceId})`); } let sequence: Sequence = this._sequences[node.sequenceId].sequence; let edges: NavigationEdge[] = this._edgeCalculator.computeSequenceEdges(node, sequence); node.cacheSequenceEdges(edges); } /** * Retrieve and cache full nodes for all keys in a sequence. * * @param {string} sequenceKey - Key of sequence. * @param {string} referenceNodeKey - Key of node to use as reference * for optimized caching. * @returns {Observable<Graph>} Observable emitting the graph * when the nodes of the sequence has been cached. */ public cacheSequenceNodes$(sequenceKey: string, referenceNodeKey?: string): Observable<Graph> { if (!this.hasSequence(sequenceKey)) { throw new GraphMapillaryError( `Cannot cache sequence nodes of sequence that does not exist in graph (${sequenceKey}).`); } if (this.hasSequenceNodes(sequenceKey)) { throw new GraphMapillaryError(`Sequence nodes already cached (${sequenceKey}).`); } const sequence: Sequence = this.getSequence(sequenceKey); if (sequence.id in this._cachingSequenceNodes$) { return this._cachingSequenceNodes$[sequence.id]; } const batches: string[][] = []; const keys: string[] = sequence.imageIds.slice(); const referenceBatchSize: number = 50; if (!!referenceNodeKey && keys.length > referenceBatchSize) { const referenceIndex: number = keys.indexOf(referenceNodeKey); const startIndex: number = Math.max( 0, Math.min( referenceIndex - referenceBatchSize / 2, keys.length - referenceBatchSize)); batches.push(keys.splice(startIndex, referenceBatchSize)); } const batchSize: number = 200; while (keys.length > 0) { batches.push(keys.splice(0, batchSize)); } let batchesToCache: number = batches.length; const sequenceNodes$: Observable<Graph> = observableFrom(batches).pipe( mergeMap( (batch: string[]): Observable<Graph> => { return this._api.getImages$(batch).pipe( tap( (items: ImagesContract): void => { for (const item of items) { if (!item.node) { console.warn( `Image empty (${item.node_id})`); continue; } const id = item.node_id; if (this.hasNode(id)) { const node = this.getNode(id); if (!node.complete) { this._makeFull(node, item.node); } } else { if (item.node.sequence.id == null) { console.warn(`Sequence missing, discarding node (${item.node_id})`); } const node = new Image(item.node); this._makeFull(node, item.node); const cellId = this._api.data.geometry .lngLatToCellId(node.originalLngLat); this._preStore(cellId, node); this._setNode(node); } } batchesToCache--; }), map((): Graph => this)); }, 6), last(), finalize( (): void => { delete this._cachingSequenceNodes$[sequence.id]; if (batchesToCache === 0) { this._cachedSequenceNodes[sequence.id] = true; } }), publish(), refCount()); this._cachingSequenceNodes$[sequence.id] = sequenceNodes$; return sequenceNodes$; } /** * Retrieve and cache full nodes for a node spatial area. * * @param {string} key - Key of node for which to retrieve sequence. * @returns {Observable<Graph>} Observable emitting the graph * when the nodes in the spatial area has been made full. * @throws {GraphMapillaryError} When the operation is not valid on the * current graph. */ public cacheSpatialArea$(key: string): Observable<Graph>[] { if (!this.hasNode(key)) { throw new GraphMapillaryError(`Cannot cache spatial area of node that does not exist in graph (${key}).`); } if (key in this._cachedSpatialEdges) { throw new GraphMapillaryError(`Image already spatially cached (${key}).`); } if (!(key in this._requiredSpatialArea)) { throw new GraphMapillaryError(`Spatial area not determined (${key}).`); } let spatialArea: SpatialArea = this._requiredSpatialArea[key]; if (Object.keys(spatialArea.cacheNodes).length === 0) { throw new GraphMapillaryError(`Spatial nodes already cached (${key}).`); } if (key in this._cachingSpatialArea$) { return this._cachingSpatialArea$[key]; } let batches: string[][] = []; while (spatialArea.cacheKeys.length > 0) { batches.push(spatialArea.cacheKeys.splice(0, 200)); } let batchesToCache: number = batches.length; let spatialNodes$: Observable<Graph>[] = []; for (let batch of batches) { let spatialNodeBatch$: Observable<Graph> = this._api.getSpatialImages$(batch).pipe( tap( (items: SpatialImagesContract): void => { for (const item of items) { if (!item.node) { console.warn(`Image is empty (${item.node_id})`); continue; } const id = item.node_id; const spatialNode = spatialArea.cacheNodes[id]; if (spatialNode.complete) { delete spatialArea.cacheNodes[id]; continue; } this._makeFull(spatialNode, item.node); delete spatialArea.cacheNodes[id]; } if (--batchesToCache === 0) { delete this._cachingSpatialArea$[key]; } }), map((): Graph => { return this; }), catchError( (error: Error): Observable<Graph> => { for (let batchKey of batch) { if (batchKey in spatialArea.all) { delete spatialArea.all[batchKey]; } if (batchKey in spatialArea.cacheNodes) { delete spatialArea.cacheNodes[batchKey]; } } if (--batchesToCache === 0) { delete this._cachingSpatialArea$[key]; } throw error; }), finalize( (): void => { if (Object.keys(spatialArea.cacheNodes).length === 0) { this._changed$.next(this); } }), publish(), refCount()); spatialNodes$.push(spatialNodeBatch$); } this._cachingSpatialArea$[key] = spatialNodes$; return spatialNodes$; } /** * Cache spatial edges for a node. * * @param {string} key - Key of node. * @throws {GraphMapillaryError} When the operation is not valid on the * current graph. */ public cacheSpatialEdges(key: string): void { if (key in this._cachedSpatialEdges) { throw new GraphMapillaryError(`Spatial edges already cached (${key}).`); } let node: Image = this.getNode(key); let sequence: Sequence = this._sequences[node.sequenceId].sequence; let fallbackKeys: string[] = []; let prevKey: string = sequence.findPrev(node.id); if (prevKey != null) { fallbackKeys.push(prevKey); } let nextKey: string = sequence.findNext(node.id); if (nextKey != null) { fallbackKeys.push(nextKey); } let allSpatialNodes: { [key: string]: Image; } = this._requiredSpatialArea[key].all; let potentialNodes: Image[] = []; let filter: FilterFunction = this._filter; for (let spatialNodeKey in allSpatialNodes) { if (!allSpatialNodes.hasOwnProperty(spatialNodeKey)) { continue; } let spatialNode: Image = allSpatialNodes[spatialNodeKey]; if (filter(spatialNode)) { potentialNodes.push(spatialNode); } } let potentialEdges: PotentialEdge[] = this._edgeCalculator.getPotentialEdges(node, potentialNodes, fallbackKeys); let edges: NavigationEdge[] = this._edgeCalculator.computeStepEdges( node, potentialEdges, prevKey, nextKey); edges = edges.concat(this._edgeCalculator.computeTurnEdges(node, potentialEdges)); edges = edges.concat(this._edgeCalculator.computeSphericalEdges(node, potentialEdges)); edges = edges.concat(this._edgeCalculator.computePerspectiveToSphericalEdges(node, potentialEdges)); edges = edges.concat(this._edgeCalculator.computeSimilarEdges(node, potentialEdges)); node.cacheSpatialEdges(edges); this._cachedSpatialEdges[key] = node; delete this._requiredSpatialArea[key]; delete this._cachedNodeTiles[key]; } /** * Retrieve and cache tiles for a node. * * @param {string} key - Key of node for which to retrieve tiles. * @returns {Array<Observable<Graph>>} Array of observables emitting * the graph for each tile required for the node has been cached. * @throws {GraphMapillaryError} When the operation is not valid on the * current graph. */ public cacheTiles$(key: string): Observable<Graph>[] { if (key in this._cachedNodeTiles) { throw new GraphMapillaryError(`Tiles already cached (${key}).`); } if (key in this._cachedSpatialEdges) { throw new GraphMapillaryError(`Spatial edges already cached so tiles considered cached (${key}).`); } if (!(key in this._requiredNodeTiles)) { throw new GraphMapillaryError(`Tiles have not been determined (${key}).`); } let nodeTiles: NodeTiles = this._requiredNodeTiles[key]; if (nodeTiles.cache.length === 0 && nodeTiles.caching.length === 0) { throw new GraphMapillaryError(`Tiles already cached (${key}).`); } if (!this.hasNode(key)) { throw new GraphMapillaryError(`Cannot cache tiles of node that does not exist in graph (${key}).`); } let hs: string[] = nodeTiles.cache.slice(); nodeTiles.caching = this._requiredNodeTiles[key].caching.concat(hs); nodeTiles.cache = []; let cacheTiles$: Observable<Graph>[] = []; for (let h of nodeTiles.caching) { const cacheTile$: Observable<Graph> = h in this._cachingTiles$ ? this._cachingTiles$[h] : this._cacheTile$(h); cacheTiles$.push( cacheTile$.pipe( tap( (graph: Graph): void => { let index: number = nodeTiles.caching.indexOf(h); if (index > -1) { nodeTiles.caching.splice(index, 1); } if (nodeTiles.caching.length === 0 && nodeTiles.cache.length === 0) { delete this._requiredNodeTiles[key]; this._cachedNodeTiles[key] = true; } }), catchError( (error: Error): Observable<Graph> => { let index: number = nodeTiles.caching.indexOf(h); if (index > -1) { nodeTiles.caching.splice(index, 1); } if (nodeTiles.caching.length === 0 && nodeTiles.cache.length === 0) { delete this._requiredNodeTiles[key]; this._cachedNodeTiles[key] = true; } throw error; }), finalize( (): void => { this._changed$.next(this); }), publish(), refCount())); } return cacheTiles$; } /** * Initialize the cache for a node. * * @param {string} key - Key of node. * @throws {GraphMapillaryError} When the operation is not valid on the * current graph. */ public initializeCache(key: string): void { if (key in this._cachedNodes) { throw new GraphMapillaryError(`Image already in cache (${key}).`); } const node: Image = this.getNode(key); const provider = this._api.data; node.initializeCache(new ImageCache(provider)); const accessed: number = new Date().getTime(); this._cachedNodes[key] = { accessed: accessed, node: node }; this._updateCachedTileAccess(key, accessed); } /** * Get a value indicating if the graph is fill caching a node. * * @param {string} key - Key of node. * @returns {boolean} Value indicating if the node is being fill cached. */ public isCachingFill(key: string): boolean { return key in this._cachingFill$; } /** * Get a value indicating if the graph is fully caching a node. * * @param {string} key - Key of node. * @returns {boolean} Value indicating if the node is being fully cached. */ public isCachingFull(key: string): boolean { return key in this._cachingFull$; } /** * Get a value indicating if the graph is caching a sequence of a node. * * @param {string} key - Key of node. * @returns {boolean} Value indicating if the sequence of a node is * being cached. */ public isCachingNodeSequence(key: string): boolean { let node: Image = this.getNode(key); return node.sequenceId in this._cachingSequences$; } /** * Get a value indicating if the graph is caching a sequence. * * @param {string} sequenceKey - Key of sequence. * @returns {boolean} Value indicating if the sequence is * being cached. */ public isCachingSequence(sequenceKey: string): boolean { return sequenceKey in this._cachingSequences$; } /** * Get a value indicating if the graph is caching sequence nodes. * * @param {string} sequenceKey - Key of sequence. * @returns {boolean} Value indicating if the sequence nodes are * being cached. */ public isCachingSequenceNodes(sequenceKey: string): boolean { return sequenceKey in this._cachingSequenceNodes$; } /** * Get a value indicating if the graph is caching the tiles * required for calculating spatial edges of a node. * * @param {string} key - Key of node. * @returns {boolean} Value indicating if the tiles of * a node are being cached. */ public isCachingTiles(key: string): boolean { return key in this._requiredNodeTiles && this._requiredNodeTiles[key].cache.length === 0 && this._requiredNodeTiles[key].caching.length > 0; } /** * Get a value indicating if the cache has been initialized * for a node. * * @param {string} key - Key of node. * @returns {boolean} Value indicating if the cache has been * initialized for a node. */ public hasInitializedCache(key: string): boolean { return key in this._cachedNodes; } /** * Get a value indicating if a node exist in the graph. * * @param {string} key - Key of node. * @returns {boolean} Value indicating if a node exist in the graph. */ public hasNode(key: string): boolean { let accessed: number = new Date().getTime(); this._updateCachedNodeAccess(key, accessed); this._updateCachedTileAccess(key, accessed); return key in this._nodes; } /** * Get a value indicating if a node sequence exist in the graph. * * @param {string} key - Key of node. * @returns {boolean} Value indicating if a node sequence exist * in the graph. */ public hasNodeSequence(key: string): boolean { let node: Image = this.getNode(key); let sequenceKey: string = node.sequenceId; let hasNodeSequence: boolean = sequenceKey in this._sequences; if (hasNodeSequence) { this._sequences[sequenceKey].accessed = new Date().getTime(); } return hasNodeSequence; } /** * Get a value indicating if a sequence exist in the graph. * * @param {string} sequenceKey - Key of sequence. * @returns {boolean} Value indicating if a sequence exist * in the graph. */ public hasSequence(sequenceKey: string): boolean { let hasSequence: boolean = sequenceKey in this._sequences; if (hasSequence) { this._sequences[sequenceKey].accessed = new Date().getTime(); } return hasSequence; } /** * Get a value indicating if sequence nodes has been cached in the graph. * * @param {string} sequenceKey - Key of sequence. * @returns {boolean} Value indicating if a sequence nodes has been * cached in the graph. */ public hasSequenceNodes(sequenceKey: string): boolean { return sequenceKey in this._cachedSequenceNodes; } /** * Get a value indicating if the graph has fully cached * all nodes in the spatial area of a node. * * @param {string} key - Key of node. * @returns {boolean} Value indicating if the spatial area * of a node has been cached. */ public hasSpatialArea(key: string): boolean { if (!this.hasNode(key)) { throw new GraphMapillaryError(`Spatial area nodes cannot be determined if node not in graph (${key}).`); } if (key in this._cachedSpatialEdges) { return true; } if (key in this._requiredSpatialArea) { return Object .keys(this._requiredSpatialArea[key].cacheNodes) .length === 0; } let node = this.getNode(key); let bbox = this._graphCalculator .boundingBoxCorners( node.lngLat, this._tileThreshold); let spatialItems = <NodeIndexItem[]>this._nodeIndex .search({ maxX: bbox[1].lng, maxY: bbox[1].lat, minX: bbox[0].lng, minY: bbox[0].lat, }); let spatialNodes: SpatialArea = { all: {}, cacheKeys: [], cacheNodes: {}, }; for (let spatialItem of spatialItems) { spatialNodes.all[spatialItem.node.id] = spatialItem.node; if (!spatialItem.node.complete) { spatialNodes.cacheKeys.push(spatialItem.node.id); spatialNodes.cacheNodes[spatialItem.node.id] = spatialItem.node; } } this._requiredSpatialArea[key] = spatialNodes; return spatialNodes.cacheKeys.length === 0; } /** * Get a value indicating if the graph has a tiles required * for a node. * * @param {string} key - Key of node. * @returns {boolean} Value indicating if the the tiles required * by a node has been cached. */ public hasTiles(key: string): boolean { if (key in this._cachedNodeTiles) { return true; } if (key in this._cachedSpatialEdges) { return true; } if (!this.hasNode(key)) { throw new GraphMapillaryError(`Image does not exist in graph (${key}).`); } let nodeTiles: NodeTiles = { cache: [], caching: [] }; if (!(key in this._requiredNodeTiles)) { const node = this.getNode(key); const [sw, ne] = this._graphCalculator .boundingBoxCorners( node.lngLat, this._tileThreshold); nodeTiles.cache = this._api.data.geometry .bboxToCellIds(sw, ne) .filter( (h: string): boolean => { return !(h in this._cachedTiles); }); if (nodeTiles.cache.length > 0) { this._requiredNodeTiles[key] = nodeTiles; } } else { nodeTiles = this._requiredNodeTiles[key]; } return nodeTiles.cache.length === 0 && nodeTiles.caching.length === 0; } /** * Get a node. * * @param {string} key - Key of node. * @returns {Image} Retrieved node. */ public getNode(key: string): Image { let accessed: number = new Date().getTime(); this._updateCachedNodeAccess(key, accessed); this._updateCachedTileAccess(key, accessed); return this._nodes[key]; } /** * Get a sequence. * * @param {string} sequenceKey - Key of sequence. * @returns {Image} Retrieved sequence. */ public getSequence(sequenceKey: string): Sequence { let sequenceAccess: SequenceAccess = this._sequences[sequenceKey]; sequenceAccess.accessed = new Date().getTime(); return sequenceAccess.sequence; } /** * Reset all spatial edges of the graph nodes. */ public resetSpatialEdges(): void { let cachedKeys: string[] = Object.keys(this._cachedSpatialEdges); for (let cachedKey of cachedKeys) { let node: Image = this._cachedSpatialEdges[cachedKey]; node.resetSpatialEdges(); delete this._cachedSpatialEdges[cachedKey]; } } /** * Reset the complete graph but keep the nodes corresponding * to the supplied keys. All other nodes will be disposed. * * @param {Array<string>} keepKeys - Keys for nodes to keep * in graph after reset. */ public reset(keepKeys: string[]): void { const nodes: Image[] = []; for (const key of keepKeys) { if (!this.hasNode(key)) { throw new Error(`Image does not exist ${key}`); } const node: Image = this.getNode(key); node.resetSequenceEdges(); node.resetSpatialEdges(); nodes.push(node); } for (let cachedKey of Object.keys(this._cachedNodes)) { if (keepKeys.indexOf(cachedKey) !== -1) { continue; } this._cachedNodes[cachedKey].node.dispose(); delete this._cachedNodes[cachedKey]; } this._cachedNodeTiles = {}; this._cachedSpatialEdges = {}; this._cachedTiles = {}; this._cachingFill$ = {}; this._cachingFull$ = {}; this._cachingSequences$ = {}; this._cachingSpatialArea$ = {}; this._cachingTiles$ = {}; this._nodes = {}; this._nodeToTile = {}; this._preStored = {}; for (const node of nodes) { this._nodes[node.id] = node; const h: string = this._api.data.geometry.lngLatToCellId(node.originalLngLat); this._preStore(h, node); } this._requiredNodeTiles = {}; this._requiredSpatialArea = {}; this._sequences = {}; this._nodeIndexTiles = {}; this._nodeIndex.clear(); } /** * Set the spatial node filter. * * @emits FilterFunction The filter function to the {@link Graph.filter$} * observable. * * @param {FilterExpression} filter - Filter expression to be applied * when calculating spatial edges. */ public setFilter(filter: FilterExpression): void { this._filter = this._filterCreator.createFilter(filter); this._filterSubject$.next(this._filter); } /** * Uncache the graph according to the graph configuration. * * @description Uncaches unused tiles, unused nodes and * sequences according to the numbers specified in the * graph configuration. Sequences does not have a direct * reference to either tiles or nodes and may be uncached * even if they are related to the nodes that should be kept. * * @param {Array<string>} keepIds - Ids of nodes to keep in * graph unrelated to last access. Tiles related to those keys * will also be kept in graph. * @param {Array<string>} keepCellIds - Ids of cells to keep in * graph unrelated to last access. The nodes of the cells may * still be uncached if not specified in the keep ids param * but are guaranteed to not be disposed. * @param {string} keepSequenceId - Optional id of sequence * for which the belonging nodes should not be disposed or * removed from the graph. These nodes may still be uncached if * not specified in keep ids param but are guaranteed to not * be disposed. */ public uncache( keepIds: string[], keepCellIds: string[], keepSequenceId?: string) : void { const idsInUse: { [id: string]: boolean; } = {}; this._addNewKeys(idsInUse, this._cachingFull$); this._addNewKeys(idsInUse, this._cachingFill$); this._addNewKeys(idsInUse, this._cachingSpatialArea$); this._addNewKeys(idsInUse, this._requiredNodeTiles); this._addNewKeys(idsInUse, this._requiredSpatialArea); for (const key of keepIds) { if (key in idsInUse) { continue; } idsInUse[key] = true; } const tileThreshold = this._tileThreshold; const calculator = this._graphCalculator; const geometry = this._api.data.geometry; const keepCells = new Set<string>(keepCellIds); for (let id in idsInUse) { if (!idsInUse.hasOwnProperty(id)) { continue; } const node = this._nodes[id]; const [sw, ne] = calculator .boundingBoxCorners( node.lngLat, tileThreshold, ); const nodeCellIds = geometry.bboxToCellIds(sw, ne); for (const nodeCellId of nodeCellIds) { if (!keepCells.has(nodeCellId)) { keepCells.add(nodeCellId); } } } const potentialCells: [string, TileAccess][] = []; for (let cellId in this._cachedTiles) { if (!this._cachedTiles.hasOwnProperty(cellId) || keepCells.has(cellId)) { continue; } potentialCells.push([cellId, this._cachedTiles[cellId]]); } const uncacheCells = potentialCells .sort( (h1: [string, TileAccess], h2: [string, TileAccess]): number => { return h2[1].accessed - h1[1].accessed; }) .slice(this._configuration.maxUnusedTiles) .map( (h: [string, TileAccess]): string => { return h[0]; }); for (let uncacheCell of uncacheCells) { this._uncacheTile(uncacheCell, keepSequenceId); } const potentialPreStored: [NodeAccess, string][] = []; const nonCachedPreStored: [string, string][] = []; for (let cellId in this._preStored) { if (!this._preStored.hasOwnProperty(cellId) || cellId in this._cachingTiles$) { continue; } const prestoredNodes = this._preStored[cellId]; for (let id in prestoredNodes) { if (!prestoredNodes.hasOwnProperty(id) || id in idsInUse) { continue; } if (prestoredNodes[id].sequenceId === keepSequenceId) { continue; } if (id in this._cachedNodes) { potentialPreStored.push([this._cachedNodes[id], cellId]); } else { nonCachedPreStored.push([id, cellId]); } } } const uncachePreStored = potentialPreStored .sort( ([na1]: [NodeAccess, string], [na2]: [NodeAccess, string]): number => { return na2.accessed - na1.accessed; }) .slice(this._configuration.maxUnusedPreStoredImages) .map( ([na, h]: [NodeAccess, string]): [string, string] => { return [na.node.id, h]; }); this._uncachePreStored(nonCachedPreStored); this._uncachePreStored(uncachePreStored); const potentialNodes: NodeAccess[] = []; for (let id in this._cachedNodes) { if (!this._cachedNodes.hasOwnProperty(id) || id in idsInUse) { continue; } potentialNodes.push(this._cachedNodes[id]); } const uncacheNodes = potentialNodes .sort( (n1: NodeAccess, n2: NodeAccess): number => { return n2.accessed - n1.accessed; }) .slice(this._configuration.maxUnusedImages); for (const nodeAccess of uncacheNodes) { nodeAccess.node.uncache(); const id = nodeAccess.node.id; delete this._cachedNodes[id]; if (id in this._cachedNodeTiles) { delete this._cachedNodeTiles[id]; } if (id in this._cachedSpatialEdges) { delete this._cachedSpatialEdges[id]; } } const potentialSequences: SequenceAccess[] = []; for (let sequenceId in this._sequences) { if (!this._sequences.hasOwnProperty(sequenceId) || sequenceId in this._cachingSequences$ || sequenceId === keepSequenceId) { continue; } potentialSequences.push(this._sequences[sequenceId]); } const uncacheSequences = potentialSequences .sort( (s1: SequenceAccess, s2: SequenceAccess): number => { return s2.accessed - s1.accessed; }) .slice(this._configuration.maxSequences); for (const sequenceAccess of uncacheSequences) { const sequenceId = sequenceAccess.sequence.id; delete this._sequences[sequenceId]; if (sequenceId in this._cachedSequenceNodes) { delete this._cachedSequenceNodes[sequenceId]; } sequenceAccess.sequence.dispose(); } } /** * Updates existing cells with new core nodes. * * @description Non-existing cells are discarded * and not requested at all. * * Existing nodes are not changed. * * New nodes are not made full or getting assets * cached. * * @param {Array<string>} cellIds - Cell ids. * @returns {Observable<Array<Image>>} Observable * emitting the updated cells. */ public updateCells$(cellIds: string[]): Observable<string> { const cachedCells = this._cachedTiles; const cachingCells = this._cachingTiles$; return observableFrom(cellIds) .pipe( mergeMap( (cellId: string): Observable<string> => { if (cellId in cachedCells) { return this._updateCell$(cellId); } if (cellId in cachingCells) { return cachingCells[cellId] .pipe( catchError((): Observable<Graph> => { return observableOf(this); }), mergeMap(() => this._updateCell$(cellId))); } return observableEmpty(); } )); } /** * Unsubscribes all subscriptions. * * @description Afterwards, you must not call any other methods * on the graph instance. */ public unsubscribe(): void { this._filterSubscription.unsubscribe(); } private _addNewKeys<T>(keys: { [key: string]: boolean; }, dict: { [key: string]: T; }): void { for (let key in dict) { if (!dict.hasOwnProperty(key) || !this.hasNode(key)) { continue; } if (!(key in keys)) { keys[key] = true; } } } private _cacheSequence$(sequenceId: string): Observable<Graph> { if (sequenceId in this._cachingSequences$) { return this._cachingSequences$[sequenceId]; } this._cachingSequences$[sequenceId] = this._api .getSequence$(sequenceId) .pipe( tap( (sequence: SequenceContract): void => { if (!sequence) { console.warn( `Sequence does not exist ` + `(${sequenceId})`); } else { if (!(sequence.id in this._sequences)) { this._sequences[sequence.id] = { accessed: new Date().getTime(), sequence: new Sequence(sequence), }; } delete this._cachingSequences$[sequenceId]; } }), map((): Graph => { return this; }), finalize( (): void => { if (sequenceId in this._cachingSequences$) { delete this._cachingSequences$[sequenceId]; } this._changed$.next(this); }), publish(), refCount()); return this._cachingSequences$[sequenceId]; } private _cacheTile$(cellId: string): Observable<Graph> { this._cachingTiles$[cellId] = this._api .getCoreImages$(cellId) .pipe( tap((contract: CoreImagesContract): void => { if (cellId in this._cachedTiles) { return; } const cores = contract.images; this._nodeIndexTiles[cellId] = []; this._cachedTiles[cellId] = { accessed: new Date().getTime(), nodes: [], }; const hCache = this._cachedTiles[cellId].nodes; const preStored = this._removeFromPreStore(cellId); for (const core of cores) { if (!core) { break; } if (core.sequence.id == null) { console.warn(`Sequence missing, discarding ` + `node (${core.id})`); continue; } if (preStored != null && core.id in preStored) { const preStoredNode = preStored[core.id]; delete preStored[core.id]; hCache.push(preStoredNode); const preStoredNodeIndexItem: NodeIndexItem = { lat: preStoredNode.lngLat.lat, lng: preStoredNode.lngLat.lng, node: preStoredNode, }; this._nodeIndex.insert(preStoredNodeIndexItem); this._nodeIndexTiles[cellId] .push(preStoredNodeIndexItem); this._nodeToTile[preStoredNode.id] = cellId; continue; } const node = new Image(core); hCache.push(node); const nodeIndexItem: NodeIndexItem = { lat: node.lngLat.lat, lng: node.lngLat.lng, node: node, }; this._nodeIndex.insert(nodeIndexItem); this._nodeIndexTiles[cellId].push(nodeIndexItem); this._nodeToTile[node.id] = cellId; this._setNode(node); } delete this._cachingTiles$[cellId]; }), map((): Graph => this), catchError( (error: Error): Observable<Graph> => { delete this._cachingTiles$[cellId]; throw error; }), publish(), refCount()); return this._cachingTiles$[cellId]; } private _makeFull(node: Image, fillNode: SpatialImageEnt): void { if (fillNode.computed_altitude == null) { fillNode.computed_altitude = this._defaultAlt; } if (fillNode.computed_rotation == null) { fillNode.computed_rotation = this._graphCalculator.rotationFromCompass(fillNode.compass_angle, fillNode.exif_orientation); } node.makeComplete(fillNode); } private _preStore(h: string, node: Image): void { if (!(h in this._preStored)) { this._preStored[h] = {}; } this._preStored[h][node.id] = node; } private _removeFromPreStore(h: string): { [key: string]: Image; } { let preStored: { [key: string]: Image; } = null; if (h in this._preStored) { preStored = this._preStored[h]; delete this._preStored[h]; } return preStored; } private _setNode(node: Image): void { let key: string = node.id; if (this.hasNode(key)) { throw new GraphMapillaryError(`Image already exist (${key}).`); } this._nodes[key] = node; } private _uncacheTile(h: string, keepSequenceKey: string): void { for (let node of this._cachedTiles[h].nodes) { let key: string = node.id; delete this._nodeToTile[key]; if (key in this._cachedNodes) { delete this._cachedNodes[key]; } if (key in this._cachedNodeTiles) { delete this._cachedNodeTiles[key]; } if (key in this._cachedSpatialEdges) { delete this._cachedSpatialEdges[key]; } if (node.sequenceId === keepSequenceKey) { this._preStore(h, node); node.uncache(); } else { delete this._nodes[key]; if (node.sequenceId in this._cachedSequenceNodes) { delete this._cachedSequenceNodes[node.sequenceId]; } node.dispose(); } } for (let nodeIndexItem of this._nodeIndexTiles[h]) { this._nodeIndex.remove(nodeIndexItem); } delete this._nodeIndexTiles[h]; delete this._cachedTiles[h]; } private _uncachePreStored(preStored: [string, string][]): void { let hs: { [h: string]: boolean; } = {}; for (let [key, h] of preStored) { if (key in this._nodes) { delete this._nodes[key]; } if (key in this._cachedNodes) { delete this._cachedNodes[key]; } let node: Image = this._preStored[h][key]; if (node.sequenceId in this._cachedSequenceNodes) { delete this._cachedSequenceNodes[node.sequenceId]; } delete this._preStored[h][key]; node.dispose(); hs[h] = true; } for (let h in hs) { if (!hs.hasOwnProperty(h)) { continue; } if (Object.keys(this._preStored[h]).length === 0) { delete this._preStored[h]; } } } private _updateCachedTileAccess(key: string, accessed: number): void { if (key in this._nodeToTile) { this._cachedTiles[this._nodeToTile[key]].accessed = accessed; } } private _updateCachedNodeAccess(key: string, accessed: number): void { if (key in this._cachedNodes) { this._cachedNodes[key].accessed = accessed; } } private _updateCell$(cellId: string): Observable<string> { return this._api.getCoreImages$(cellId).pipe( mergeMap( (contract: CoreImagesContract): Observable<string> => { if (!(cellId in this._cachedTiles)) { return observableEmpty(); } const nodeIndex = this._nodeIndex; const nodeIndexCell = this._nodeIndexTiles[cellId]; const nodeToCell = this._nodeToTile; const cell = this._cachedTiles[cellId]; cell.accessed = new Date().getTime(); const cellNodes = cell.nodes; const cores = contract.images; for (const core of cores) { if (core == null) { break; } if (this.hasNode(core.id)) { continue; } if (core.sequence.id == null) { console.warn(`Sequence missing, discarding ` + `node (${core.id})`); continue; } const node = new Image(core); cellNodes.push(node); const nodeIndexItem: NodeIndexItem = { lat: node.lngLat.lat, lng: node.lngLat.lng, node: node, }; nodeIndex.insert(nodeIndexItem); nodeIndexCell.push(nodeIndexItem); nodeToCell[node.id] = cellId; this._setNode(node); } return observableOf(cellId); }), catchError( (error: Error): Observable<string> => { console.error(error); return observableEmpty(); })); } }
the_stack
namespace Kurve { export class Scopes { private static rootUrl = "https://graph.microsoft.com/"; static General = { OpenId: "openid", OfflineAccess: "offline_access", } static User = { Read: Scopes.rootUrl + "User.Read", ReadAll: Scopes.rootUrl + "User.Read.All", ReadWrite: Scopes.rootUrl + "User.ReadWrite", ReadWriteAll: Scopes.rootUrl + "User.ReadWrite.All", ReadBasicAll: Scopes.rootUrl + "User.ReadBasic.All", } static Contacts = { Read: Scopes.rootUrl + "Contacts.Read", ReadWrite: Scopes.rootUrl + "Contacts.ReadWrite", } static Directory = { ReadAll: Scopes.rootUrl + "Directory.Read.All", ReadWriteAll: Scopes.rootUrl + "Directory.ReadWrite.All", AccessAsUserAll: Scopes.rootUrl + "Directory.AccessAsUser.All", } static Group = { ReadAll: Scopes.rootUrl + "Group.Read.All", ReadWriteAll: Scopes.rootUrl + "Group.ReadWrite.All", AccessAsUserAll: Scopes.rootUrl + "Directory.AccessAsUser.All" } static Mail = { Read: Scopes.rootUrl + "Mail.Read", ReadWrite: Scopes.rootUrl + "Mail.ReadWrite", Send: Scopes.rootUrl + "Mail.Send", } static Calendars = { Read: Scopes.rootUrl + "Calendars.Read", ReadWrite: Scopes.rootUrl + "Calendars.ReadWrite", } static Files = { Read: Scopes.rootUrl + "Files.Read", ReadAll: Scopes.rootUrl + "Files.Read.All", ReadWrite: Scopes.rootUrl + "Files.ReadWrite", ReadWriteAppFolder: Scopes.rootUrl + "Files.ReadWrite.AppFolder", ReadWriteSelected: Scopes.rootUrl + "Files.ReadWrite.Selected", } static Tasks = { ReadWrite: Scopes.rootUrl + "Tasks.ReadWrite", } static People = { Read: Scopes.rootUrl + "People.Read", ReadWrite: Scopes.rootUrl + "People.ReadWrite", } static Notes = { Create: Scopes.rootUrl + "Notes.Create", ReadWriteCreatedByApp: Scopes.rootUrl + "Notes.ReadWrite.CreatedByApp", Read: Scopes.rootUrl + "Notes.Read", ReadAll: Scopes.rootUrl + "Notes.Read.All", ReadWriteAll: Scopes.rootUrl + "Notes.ReadWrite.All", } } const queryUnion = (query1:string, query2:string) => (query1 ? query1 + (query2 ? "&" + query2 : "" ) : query2); export class OData { constructor(public query?:string) { } toString = () => this.query; odata = (query:string) => { this.query = queryUnion(this.query, query); return this; } select = (...fields:string[]) => this.odata(`$select=${fields.join(",")}`); expand = (...fields:string[]) => this.odata(`$expand=${fields.join(",")}`); filter = (query:string) => this.odata(`$filter=${query}`); orderby = (...fields:string[]) => this.odata(`$orderby=${fields.join(",")}`); top = (items:Number) => this.odata(`$top=${items}`); skip = (items:Number) => this.odata(`$skip=${items}`); } type ODataQuery = OData | string; const pathWithQuery = (path:string, odataQuery?:ODataQuery) => { let query = odataQuery && odataQuery.toString(); return path + (query ? "?" + query : ""); } export type GraphObject<Model, N extends Node> = Model & { _context: N }; export interface Context<N extends Node> { (id:string): N } export abstract class Node { constructor(protected graph:Graph, protected path?:string) { } //Only adds scopes when linked to a v2 Oauth of kurve identity protected scopesForV2 = (scopes: string[]) => this.graph.endpointVersion === EndpointVersion.v2 ? scopes : null; pathWithQuery = (odataQuery?:ODataQuery, pathSuffix:string = "") => pathWithQuery(this.graph.root + this.path + pathSuffix, odataQuery); protected graphObjectFromResponse = <Model, N extends Node>(response:any, node:N, context?:Context<N>) => { const object = response as GraphObject<Model, N>; object._context = context && object["id"] ? context(object["id"]) : node; return object; } protected get<Model, N extends Node>(path:string, node:N, scopes?:string[], context?:Context<N>, responseType?:string): Promise<GraphObject<Model, N>, Error> { console.log("GET", path, scopes); const d = new Deferred<GraphObject<Model, N>, Error>(); this.graph.get(path, (error, result) => { if (error) { d.reject(error); } else if (!responseType) { const jsonResult = JSON.parse(result) ; if (jsonResult.error) { const errorODATA = new Error(); errorODATA.other = jsonResult.error; d.reject(errorODATA); return; } d.resolve(this.graphObjectFromResponse<Model, N>(jsonResult, node, context)); } else { d.resolve(this.graphObjectFromResponse<Model, N>(result, node)); } }, responseType, scopes); return d.promise; } protected post<Model, N extends Node>(object:Model, path:string, node:N, scopes?:string[]): Promise<GraphObject<Model, N>, Error> { console.log("POST", path, scopes); const d = new Deferred<GraphObject<Model, N>, Error>(); /* this.graph.post(object, path, (error, result) => { const jsonResult = JSON.parse(result) ; if (jsonResult.error) { const errorODATA = new Error(); errorODATA.other = jsonResult.error; d.reject(errorODATA); return; } d.resolve(new Response<Model, N>({}, node)); }); */ return d.promise; } } export interface GraphCollection<Model, C extends CollectionNode, N extends Node> { value: Array<GraphObject<Model, N>>, _context: C, _next?: () => Promise<GraphCollection<Model, C, N>, Error> }; export abstract class CollectionNode extends Node { protected graphCollectionFromResponse = <Model, C extends CollectionNode, N extends Node>(response:any, node:C, context?:Context<N>, scopes?:string[]) => { const collection = response as GraphCollection<Model,C,N>; collection._context = node; const nextLink = response["@odata.nextLink"]; collection._next = nextLink ? () => this.getCollection<Model, C, N>(nextLink, node, context, scopes) : null; if (context) collection.value.forEach(item => item._context = item["id"] && context(item["id"])); return collection; } protected getCollection<Model, C extends CollectionNode, N extends Node>(path:string, node:C, context:Context<N>, scopes?:string[]): Promise<GraphCollection<Model, C, N>, Error> { console.log("GET collection", path, scopes); const d = new Deferred<GraphCollection<Model, C, N>, Error>(); this.graph.get(path, (error, result) => { if (error) { d.reject(error); } else { const jsonResult = JSON.parse(result) ; if (jsonResult.error) { const errorODATA = new Error(); errorODATA.other = jsonResult.error; d.reject(errorODATA); return; } d.resolve(this.graphCollectionFromResponse<Model, C, N>(jsonResult, node, context, scopes)); }}, null, scopes); return d.promise; } } export class Attachment extends Node { constructor(graph:Graph, path:string="", private context:string, attachmentId?:string) { super(graph, path + (attachmentId ? "/" + attachmentId : "")); } static scopes = { messages: [Scopes.Mail.Read], events: [Scopes.Calendars.Read] } GetAttachment = (odataQuery?:ODataQuery) => this.get<AttachmentDataModel, Attachment>(this.pathWithQuery(odataQuery), this, this.scopesForV2(Attachment.scopes[this.context])); /* PATCH = this.graph.PATCH<AttachmentDataModel>(this.path, this.query); DELETE = this.graph.DELETE<AttachmentDataModel>(this.path, this.query); */ } export class Attachments extends CollectionNode { constructor(graph:Graph, path:string="", private context:string) { super(graph, path + "/attachments"); } $ = (attachmentId:string) => new Attachment(this.graph, this.path, this.context, attachmentId); GetAttachments = (odataQuery?:ODataQuery) => this.getCollection<AttachmentDataModel, Attachments, Attachment>(this.pathWithQuery(odataQuery), this, this.$, this.scopesForV2(Attachment.scopes[this.context])); /* POST = this.graph.POST<AttachmentDataModel>(this.path, this.query); */ } export class Message extends Node { constructor(graph:Graph, path:string="", messageId?:string) { super(graph, path + (messageId ? "/" + messageId : "")); } get attachments() { return new Attachments(this.graph, this.path, "messages"); } GetMessage = (odataQuery?:ODataQuery) => this.get<MessageDataModel, Message>(this.pathWithQuery(odataQuery), this, this.scopesForV2([Scopes.Mail.Read])); SendMessage = (odataQuery?:ODataQuery) => this.post<MessageDataModel, Message>(null, this.pathWithQuery(odataQuery, "/microsoft.graph.sendMail"), this, this.scopesForV2([Scopes.Mail.Send])); /* PATCH = this.graph.PATCH<MessageDataModel>(this.path, this.query); DELETE = this.graph.DELETE<MessageDataModel>(this.path, this.query); */ } export class Messages extends CollectionNode { constructor(graph:Graph, path:string="") { super(graph, path + "/messages"); } $ = (messageId:string) => new Message(this.graph, this.path, messageId); GetMessages = (odataQuery?:ODataQuery) => this.getCollection<MessageDataModel, Messages, Message>(this.pathWithQuery(odataQuery), this, this.$, this.scopesForV2([Scopes.Mail.Read])); CreateMessage = (object:MessageDataModel, odataQuery?:ODataQuery) => this.post<MessageDataModel, Messages>(object, this.pathWithQuery(odataQuery), this, this.scopesForV2([Scopes.Mail.ReadWrite])); } export class Event extends Node { constructor(graph:Graph, path:string="", eventId:string) { super(graph, path + (eventId ? "/" + eventId : "")); } get attachments() { return new Attachments(this.graph, this.path, "events"); } GetEvent = (odataQuery?:ODataQuery) => this.get<EventDataModel, Event>(this.pathWithQuery(odataQuery), this, this.scopesForV2([Scopes.Calendars.Read])); /* PATCH = this.graph.PATCH<EventDataModel>(this.path, this.query); DELETE = this.graph.DELETE<EventDataModel>(this.path, this.query); */ } export class Events extends CollectionNode { constructor(graph:Graph, path:string="") { super(graph, path + "/events"); } $ = (eventId:string) => new Event(this.graph, this.path, eventId); GetEvents = (odataQuery?:ODataQuery) => this.getCollection<EventDataModel, Events, Event>(this.pathWithQuery(odataQuery), this, this.$, this.scopesForV2([Scopes.Calendars.Read])); /* POST = this.graph.POST<EventDataModel>(this.path, this.query); */ } export class CalendarView extends CollectionNode { constructor(graph:Graph, path:string="") { super(graph, path + "/calendarView"); } private $ = (eventId:string) => new Event(this.graph, this.path, eventId); // need to adjust this path static dateRange = (startDate:Date, endDate:Date) => `startDateTime=${startDate.toISOString()}&endDateTime=${endDate.toISOString()}` GetEvents = (odataQuery?:ODataQuery) => this.getCollection<EventDataModel, CalendarView, Event>(this.pathWithQuery(odataQuery), this, this.$, this.scopesForV2([Scopes.Calendars.Read])); } export class MailFolder extends Node { constructor(graph:Graph, path:string="", mailFolderId:string) { super(graph, path + (mailFolderId ? "/" + mailFolderId : "")); } GetMailFolder = (odataQuery?:ODataQuery) => this.get<MailFolderDataModel, MailFolder>(this.pathWithQuery(odataQuery), this, this.scopesForV2([Scopes.Mail.Read])); } export class MailFolders extends CollectionNode { constructor(graph:Graph, path:string="") { super(graph, path + "/mailFolders"); } $ = (mailFolderId:string) => new MailFolder(this.graph, this.path, mailFolderId); GetMailFolders = (odataQuery?:ODataQuery) => this.getCollection<MailFolderDataModel, MailFolders, MailFolder>(this.pathWithQuery(odataQuery), this, this.$, this.scopesForV2([Scopes.Mail.Read])); } export class Photo extends Node { constructor(graph:Graph, path:string="", private context:string) { super(graph, path + "/photo" ); } static scopes = { user: [Scopes.User.ReadBasicAll], group: [Scopes.Group.ReadAll], contact: [Scopes.Contacts.Read] } GetPhotoProperties = (odataQuery?:ODataQuery) => this.get<ProfilePhotoDataModel, Photo>(this.pathWithQuery(odataQuery), this, this.scopesForV2(Photo.scopes[this.context])); GetPhotoImage = (odataQuery?:ODataQuery) => this.get<any, Photo>(this.pathWithQuery(odataQuery, "/$value"), this, this.scopesForV2(Photo.scopes[this.context]), null, "blob"); } export class Manager extends Node { constructor(graph:Graph, path:string="") { super(graph, path + "/manager" ); } GetUser = (odataQuery?:ODataQuery) => this.get<UserDataModel, User>(this.pathWithQuery(odataQuery), null, this.scopesForV2([Scopes.User.ReadAll]), this.graph.users.$); } export class MemberOf extends CollectionNode { constructor(graph:Graph, path:string="") { super(graph, path + "/memberOf"); } GetGroups = (odataQuery?:ODataQuery) => this.getCollection<GroupDataModel, MemberOf, Group>(this.pathWithQuery(odataQuery), this, this.graph.groups.$, this.scopesForV2([Scopes.User.ReadAll])); } export class DirectReport extends Node { constructor(protected graph:Graph, path:string="", userId?:string) { super(graph, path + "/" + userId); } GetUser = (odataQuery?:ODataQuery) => this.get<UserDataModel, User>(this.pathWithQuery(odataQuery), null, this.scopesForV2([Scopes.User.Read]), this.graph.users.$); } export class DirectReports extends CollectionNode { constructor(graph:Graph, path:string="") { super(graph, path + "/directReports"); } $ = (userId:string) => new DirectReport(this.graph, this.path, userId); GetUsers = (odataQuery?:ODataQuery) => this.getCollection<UserDataModel, DirectReports, User>(this.pathWithQuery(odataQuery), this, this.graph.users.$, this.scopesForV2([Scopes.User.Read])); } export class User extends Node { constructor(protected graph:Graph, path:string="", userId?:string) { super(graph, userId ? path + "/" + userId : path + "/me"); } get messages() { return new Messages(this.graph, this.path); } get events() { return new Events(this.graph, this.path); } get calendarView() { return new CalendarView(this.graph, this.path); } get mailFolders() { return new MailFolders(this.graph, this.path) } get photo() { return new Photo(this.graph, this.path, "user"); } get manager() { return new Manager(this.graph, this.path); } get directReports() { return new DirectReports(this.graph, this.path); } get memberOf() { return new MemberOf(this.graph, this.path); } GetUser = (odataQuery?:ODataQuery) => this.get<UserDataModel, User>(this.pathWithQuery(odataQuery), this, this.scopesForV2([Scopes.User.Read])); /* PATCH = this.graph.PATCH<UserDataModel>(this.path, this.query); DELETE = this.graph.DELETE<UserDataModel>(this.path, this.query); */ } export class Users extends CollectionNode { constructor(graph:Graph, path:string="") { super(graph, path + "/users"); } $ = (userId:string) => new User(this.graph, this.path, userId); GetUsers = (odataQuery?:ODataQuery) => this.getCollection<UserDataModel, Users, User>(this.pathWithQuery(odataQuery), this, this.$, this.scopesForV2([Scopes.User.Read])); /* CreateUser = this.graph.POST<UserDataModel>(this.path, this.query); */ } export class Group extends Node { constructor(protected graph:Graph, path:string="", groupId:string) { super(graph, path + "/" + groupId); } GetGroup = (odataQuery?:ODataQuery) => this.get<GroupDataModel, Group>(this.pathWithQuery(odataQuery), this, this.scopesForV2([Scopes.Group.ReadAll])); } export class Groups extends CollectionNode { constructor(graph:Graph, path:string="") { super(graph, path + "/groups"); } $ = (groupId:string) => new Group(this.graph, this.path, groupId); GetGroups = (odataQuery?:ODataQuery) => this.getCollection<GroupDataModel, Groups, Group>(this.pathWithQuery(odataQuery), this, this.$, this.scopesForV2([Scopes.Group.ReadAll])); } }
the_stack
import { FastVertexArray } from './fast-vertex-array'; import TxView from './tx-view'; import { TransactionStripped } from 'src/app/interfaces/websocket.interface'; import { Position, Square, ViewUpdateParams } from './sprite-types'; export default class BlockScene { scene: { count: number, offset: { x: number, y: number}}; vertexArray: FastVertexArray; txs: { [key: string]: TxView }; orientation: string; flip: boolean; width: number; height: number; gridWidth: number; gridHeight: number; gridSize: number; vbytesPerUnit: number; unitPadding: number; unitWidth: number; initialised: boolean; layout: BlockLayout; animateUntil = 0; dirty: boolean; constructor({ width, height, resolution, blockLimit, orientation, flip, vertexArray }: { width: number, height: number, resolution: number, blockLimit: number, orientation: string, flip: boolean, vertexArray: FastVertexArray } ) { this.init({ width, height, resolution, blockLimit, orientation, flip, vertexArray }); } destroy(): void { Object.values(this.txs).forEach(tx => tx.destroy()); } resize({ width = this.width, height = this.height }: { width?: number, height?: number}): void { this.width = width; this.height = height; this.gridSize = this.width / this.gridWidth; this.unitPadding = width / 500; this.unitWidth = this.gridSize - (this.unitPadding * 2); this.dirty = true; if (this.initialised && this.scene) { this.updateAll(performance.now(), 50); } } // Animate new block entering scene enter(txs: TransactionStripped[], direction) { this.replace(txs, direction); } // Animate block leaving scene exit(direction: string): void { const startTime = performance.now(); const removed = this.removeBatch(Object.keys(this.txs), startTime, direction); // clean up sprites setTimeout(() => { removed.forEach(tx => { tx.destroy(); }); }, 2000); } // Reset layout and replace with new set of transactions replace(txs: TransactionStripped[], direction: string = 'left', sort: boolean = true): void { const startTime = performance.now(); const nextIds = {}; const remove = []; txs.forEach(tx => { nextIds[tx.txid] = true; }); Object.keys(this.txs).forEach(txid => { if (!nextIds[txid]) { remove.push(txid); } }); txs.forEach(tx => { if (!this.txs[tx.txid]) { this.txs[tx.txid] = new TxView(tx, this.vertexArray); } }); const removed = this.removeBatch(remove, startTime, direction); // clean up sprites setTimeout(() => { removed.forEach(tx => { tx.destroy(); }); }, 1000); this.layout = new BlockLayout({ width: this.gridWidth, height: this.gridHeight }); if (sort) { Object.values(this.txs).sort(feeRateDescending).forEach(tx => { this.place(tx); }); } else { txs.forEach(tx => { this.place(this.txs[tx.txid]); }); } this.updateAll(startTime, 200, direction); } update(add: TransactionStripped[], remove: string[], direction: string = 'left', resetLayout: boolean = false): void { const startTime = performance.now(); const removed = this.removeBatch(remove, startTime, direction); // clean up sprites setTimeout(() => { removed.forEach(tx => { tx.destroy(); }); }, 1000); if (resetLayout) { add.forEach(tx => { if (!this.txs[tx.txid]) { this.txs[tx.txid] = new TxView(tx, this.vertexArray); } }); this.layout = new BlockLayout({ width: this.gridWidth, height: this.gridHeight }); Object.values(this.txs).sort(feeRateDescending).forEach(tx => { this.place(tx); }); } else { // try to insert new txs directly const remaining = []; add.map(tx => new TxView(tx, this.vertexArray)).sort(feeRateDescending).forEach(tx => { if (!this.tryInsertByFee(tx)) { remaining.push(tx); } }); this.placeBatch(remaining); this.layout.applyGravity(); } this.updateAll(startTime, 100, direction); } // return the tx at this screen position, if any getTxAt(position: Position): TxView | void { if (this.layout) { const gridPosition = this.screenToGrid(position); return this.layout.getTx(gridPosition); } else { return null; } } setHover(tx: TxView, value: boolean): void { this.animateUntil = Math.max(this.animateUntil, tx.setHover(value)); } private init({ width, height, resolution, blockLimit, orientation, flip, vertexArray }: { width: number, height: number, resolution: number, blockLimit: number, orientation: string, flip: boolean, vertexArray: FastVertexArray } ): void { this.orientation = orientation; this.flip = flip; this.vertexArray = vertexArray; this.scene = { count: 0, offset: { x: 0, y: 0 } }; // Set the scale of the visualization (with a 5% margin) this.vbytesPerUnit = blockLimit / Math.pow(resolution / 1.02, 2); this.gridWidth = resolution; this.gridHeight = resolution; this.resize({ width, height }); this.layout = new BlockLayout({ width: this.gridWidth, height: this.gridHeight }); this.txs = {}; this.initialised = true; this.dirty = true; } private applyTxUpdate(tx: TxView, update: ViewUpdateParams): void { this.animateUntil = Math.max(this.animateUntil, tx.update(update)); } private updateTx(tx: TxView, startTime: number, delay: number, direction: string = 'left'): void { if (tx.dirty || this.dirty) { this.saveGridToScreenPosition(tx); this.setTxOnScreen(tx, startTime, delay, direction); } } private setTxOnScreen(tx: TxView, startTime: number, delay: number = 50, direction: string = 'left'): void { if (!tx.initialised) { const txColor = tx.getColor(); this.applyTxUpdate(tx, { display: { position: { x: tx.screenPosition.x + (direction === 'right' ? -this.width : (direction === 'left' ? this.width : 0)) * 1.4, y: tx.screenPosition.y + (direction === 'up' ? -this.height : (direction === 'down' ? this.height : 0)) * 1.4, s: tx.screenPosition.s }, color: txColor, }, start: startTime, delay: 0, }); this.applyTxUpdate(tx, { display: { position: tx.screenPosition, color: txColor }, duration: 1000, start: startTime, delay, }); } else { this.applyTxUpdate(tx, { display: { position: tx.screenPosition }, duration: 1000, minDuration: 500, start: startTime, delay, adjust: true }); } } private updateAll(startTime: number, delay: number = 50, direction: string = 'left'): void { this.scene.count = 0; const ids = this.getTxList(); startTime = startTime || performance.now(); for (const id of ids) { this.updateTx(this.txs[id], startTime, delay, direction); } this.dirty = false; } private remove(id: string, startTime: number, direction: string = 'left'): TxView | void { const tx = this.txs[id]; if (tx) { this.layout.remove(tx); this.applyTxUpdate(tx, { display: { position: { x: tx.screenPosition.x + (direction === 'right' ? this.width : (direction === 'left' ? -this.width : 0)) * 1.4, y: tx.screenPosition.y + (direction === 'up' ? this.height : (direction === 'down' ? -this.height : 0)) * 1.4, } }, duration: 1000, start: startTime, delay: 50 }); } delete this.txs[id]; return tx; } private getTxList(): string[] { return Object.keys(this.txs); } private saveGridToScreenPosition(tx: TxView): void { tx.screenPosition = this.gridToScreen(tx.gridPosition); } // convert grid coordinates to screen coordinates private gridToScreen(position: Square | void): Square { if (position) { const slotSize = (position.s * this.gridSize); const squareSize = slotSize - (this.unitPadding * 2); // The grid is laid out notionally left-to-right, bottom-to-top, // so we rotate and/or flip the y axis to match the target configuration. // // e.g. for flip = true, orientation = 'left': // // grid screen // ________ ________ ________ // | | | | | a| // | | flip | | rotate | c | // | c | --> | c | --> | | // |a______b| |b______a| |_______b| let x = (this.gridSize * position.x) + (slotSize / 2); let y = (this.gridSize * position.y) + (slotSize / 2); let t; if (this.flip) { x = this.width - x; } switch (this.orientation) { case 'left': t = x; x = this.width - y; y = t; break; case 'right': t = x; x = y; y = t; break; case 'bottom': y = this.height - y; break; } return { x: x + this.unitPadding - (slotSize / 2), y: y + this.unitPadding - (slotSize / 2), s: squareSize }; } else { return { x: 0, y: 0, s: 0 }; } } private screenToGrid(position: Position): Position { let x = position.x; let y = this.height - position.y; let t; switch (this.orientation) { case 'left': t = x; x = y; y = this.width - t; break; case 'right': t = x; x = y; y = t; break; case 'bottom': y = this.height - y; break; } if (this.flip) { x = this.width - x; } return { x: Math.floor(x / this.gridSize), y: Math.floor(y / this.gridSize) }; } // calculates and returns the size of the tx in multiples of the grid size private txSize(tx: TxView): number { const scale = Math.max(1, Math.round(Math.sqrt(tx.vsize / this.vbytesPerUnit))); return Math.min(this.gridWidth, Math.max(1, scale)); // bound between 1 and the max displayable size (just in case!) } private place(tx: TxView): void { const size = this.txSize(tx); this.layout.insert(tx, size); } private tryInsertByFee(tx: TxView): boolean { const size = this.txSize(tx); const position = this.layout.tryInsertByFee(tx, size); if (position) { this.txs[tx.txid] = tx; return true; } else { return false; } } // Add a list of transactions to the layout, // keeping everything approximately sorted by feerate. private placeBatch(txs: TxView[]): void { if (txs.length) { // grab the new tx with the highest fee rate txs = txs.sort(feeRateDescending); const maxSize = 2 * txs.reduce((max, tx) => { return Math.max(this.txSize(tx), max); }, 1); // find a reasonable place for it in the layout const root = this.layout.getReplacementRoot(txs[0].feerate, maxSize); // extract a sub tree of transactions from the layout, rooted at that point const popped = this.layout.popTree(root.x, root.y, maxSize); // combine those with the new transactions and sort txs = txs.concat(popped); txs = txs.sort(feeRateDescending); // insert everything back into the layout txs.forEach(tx => { this.txs[tx.txid] = tx; this.place(tx); }); } } private removeBatch(ids: string[], startTime: number, direction: string = 'left'): TxView[] { if (!startTime) { startTime = performance.now(); } return ids.map(id => { return this.remove(id, startTime, direction); }).filter(tx => tx != null) as TxView[]; } } class Slot { l: number; r: number; w: number; constructor(l: number, r: number) { this.l = l; this.r = r; this.w = r - l; } intersects(slot: Slot): boolean { return !((slot.r <= this.l) || (slot.l >= this.r)); } subtract(slot: Slot): Slot[] | void { if (this.intersects(slot)) { // from middle if (slot.l > this.l && slot.r < this.r) { return [ new Slot(this.l, slot.l), new Slot(slot.r, this.r) ]; } // totally covered else if (slot.l <= this.l && slot.r >= this.r) { return []; } // from left side else if (slot.l <= this.l) { if (slot.r === this.r) { return []; } else { return [new Slot(slot.r, this.r)]; } } // from right side else if (slot.r >= this.r) { if (slot.l === this.l) { return []; } else { return [new Slot(this.l, slot.l)]; } } } else { return [this]; } } } class TxSlot extends Slot { tx: TxView; constructor(l: number, r: number, tx: TxView) { super(l, r); this.tx = tx; } } class Row { y: number; w: number; filled: TxSlot[]; slots: Slot[]; constructor(y: number, width: number) { this.y = y; this.w = width; this.filled = []; this.slots = [new Slot(0, this.w)]; } // insert a transaction w/ given width into row starting at position x insert(x: number, w: number, tx: TxView): void { const newSlot = new TxSlot(x, x + w, tx); // insert into filled list let index = this.filled.findIndex((slot) => (slot.l >= newSlot.r)); if (index < 0) { index = this.filled.length; } this.filled.splice(index || 0, 0, newSlot); // subtract from overlapping slots for (let i = 0; i < this.slots.length; i++) { if (newSlot.intersects(this.slots[i])) { const diff = this.slots[i].subtract(newSlot); if (diff) { this.slots.splice(i, 1, ...diff); i += diff.length - 1; } } } } remove(x: number, w: number): void { const txIndex = this.filled.findIndex((slot) => (slot.l === x) ); this.filled.splice(txIndex, 1); const newSlot = new Slot(x, x + w); let slotIndex = this.slots.findIndex((slot) => (slot.l >= newSlot.r) ); if (slotIndex < 0) { slotIndex = this.slots.length; } this.slots.splice(slotIndex || 0, 0, newSlot); this.normalize(); } // merge any contiguous empty slots private normalize(): void { for (let i = 0; i < this.slots.length - 1; i++) { if (this.slots[i].r === this.slots[i + 1].l) { this.slots[i].r = this.slots[i + 1].r; this.slots[i].w += this.slots[i + 1].w; this.slots.splice(i + 1, 1); i--; } } } txAt(x: number): TxView | void { let i = 0; while (i < this.filled.length && this.filled[i].l <= x) { if (this.filled[i].l <= x && this.filled[i].r > x) { return this.filled[i].tx; } i++; } } getSlotsBetween(left: number, right: number): TxSlot[] { const range = new Slot(left, right); return this.filled.filter(slot => { return slot.intersects(range); }); } slotAt(x: number): Slot | void { let i = 0; while (i < this.slots.length && this.slots[i].l <= x) { if (this.slots[i].l <= x && this.slots[i].r > x) { return this.slots[i]; } i++; } } getAvgFeerate(): number { let count = 0; let total = 0; this.filled.forEach(slot => { if (slot.tx) { count += slot.w; total += (slot.tx.feerate * slot.w); } }); return total / count; } } class BlockLayout { width: number; height: number; rows: Row[]; txPositions: { [key: string]: Square }; txs: { [key: string]: TxView }; constructor({ width, height }: { width: number, height: number }) { this.width = width; this.height = height; this.rows = [new Row(0, this.width)]; this.txPositions = {}; this.txs = {}; } getRow(position: Square): Row { return this.rows[position.y]; } getTx(position: Square): TxView | void { if (this.getRow(position)) { return this.getRow(position).txAt(position.x); } } addRow(): void { this.rows.push(new Row(this.rows.length, this.width)); } remove(tx: TxView) { const position = this.txPositions[tx.txid]; if (position) { for (let y = position.y; y < position.y + position.s && y < this.rows.length; y++) { this.rows[y].remove(position.x, position.s); } } delete this.txPositions[tx.txid]; delete this.txs[tx.txid]; } insert(tx: TxView, width: number): Square { const fit = this.fit(tx, width); // insert the tx into rows at that position for (let y = fit.y; y < fit.y + width; y++) { if (y >= this.rows.length) { this.addRow(); } this.rows[y].insert(fit.x, width, tx); } const position = { x: fit.x, y: fit.y, s: width }; this.txPositions[tx.txid] = position; this.txs[tx.txid] = tx; tx.applyGridPosition(position); return position; } // Find the first slot large enough to hold a transaction of this size fit(tx: TxView, width: number): Square { let fit; for (let y = 0; y < this.rows.length && !fit; y++) { fit = this.findFit(0, this.width, y, y, width); } // fall back to placing tx in a new row at the top of the layout if (!fit) { fit = { x: 0, y: this.rows.length }; } return fit; } // recursively check rows to see if there's space for a tx (depth-first) // left/right: initial column boundaries to check // row: current row to check // start: starting row // size: size of space needed findFit(left: number, right: number, row: number, start: number, size: number): Square { if ((row - start) >= size || row >= this.rows.length) { return { x: left, y: start }; } for (const slot of this.rows[row].slots) { const l = Math.max(left, slot.l); const r = Math.min(right, slot.r); if (r - l >= size) { const fit = this.findFit(l, r, row + 1, start, size); if (fit) { return fit; } } } } // insert only if the tx fits into a fee-appropriate position tryInsertByFee(tx: TxView, size: number): Square | void { const fit = this.fit(tx, size); if (this.checkRowFees(fit.y, tx.feerate)) { // insert the tx into rows at that position for (let y = fit.y; y < fit.y + size; y++) { if (y >= this.rows.length) { this.addRow(); } this.rows[y].insert(fit.x, size, tx); } const position = { x: fit.x, y: fit.y, s: size }; this.txPositions[tx.txid] = position; this.txs[tx.txid] = tx; tx.applyGridPosition(position); return position; } } // Return the first slot with a lower feerate getReplacementRoot(feerate: number, width: number): Square { let slot; for (let row = 0; row <= this.rows.length; row++) { if (this.rows[row].slots.length > 0) { return { x: this.rows[row].slots[0].l, y: row }; } else { slot = this.rows[row].filled.find(x => { return x.tx.feerate < feerate; }); if (slot) { return { x: Math.min(slot.l, this.width - width), y: row }; } } } return { x: 0, y: this.rows.length }; } // remove and return all transactions in a subtree of the layout popTree(x: number, y: number, width: number) { const selected: { [key: string]: TxView } = {}; let left = x; let right = x + width; let prevWidth = right - left; let prevFee = Infinity; // scan rows upwards within a channel bounded by 'left' and 'right' for (let row = y; row < this.rows.length; row++) { let rowMax = 0; const slots = this.rows[row].getSlotsBetween(left, right); // check each slot in this row overlapping the search channel slots.forEach(slot => { // select the associated transaction selected[slot.tx.txid] = slot.tx; rowMax = Math.max(rowMax, slot.tx.feerate); // widen the search channel to accommodate this slot if necessary if (slot.w > prevWidth) { left = slot.l; right = slot.r; // if this slot's tx has a higher feerate than the max in the previous row // (i.e. it's out of position) // select all txs overlapping the slot's full width in some rows *below* // to free up space for this tx to sink down to its proper position if (slot.tx.feerate > prevFee) { let count = 0; // keep scanning back down until we find a full row of higher-feerate txs for (let echo = row - 1; echo >= 0 && count < slot.w; echo--) { const echoSlots = this.rows[echo].getSlotsBetween(slot.l, slot.r); count = 0; echoSlots.forEach(echoSlot => { selected[echoSlot.tx.txid] = echoSlot.tx; if (echoSlot.tx.feerate >= slot.tx.feerate) { count += echoSlot.w; } }); } } } }); prevWidth = right - left; prevFee = rowMax; } const txList = Object.values(selected); txList.forEach(tx => { this.remove(tx); }); return txList; } // Check if this row has high enough avg fees // for a tx with this feerate to make sense here checkRowFees(row: number, targetFee: number): boolean { // first row is always fine if (row === 0 || !this.rows[row]) { return true; } return (this.rows[row].getAvgFeerate() > (targetFee * 0.9)); } // drop any free-floating transactions down into empty spaces applyGravity(): void { Object.entries(this.txPositions).sort(([keyA, posA], [keyB, posB]) => { return posA.y - posB.y || posA.x - posB.x; }).forEach(([txid, position]) => { // see how far this transaction can fall let dropTo = position.y; while (dropTo > 0 && !this.rows[dropTo - 1].getSlotsBetween(position.x, position.x + position.s).length) { dropTo--; } // if it can fall at all if (dropTo < position.y) { // remove and reinsert in the row we found const tx = this.txs[txid]; this.remove(tx); this.insert(tx, position.s); } }); } } function feeRateDescending(a: TxView, b: TxView) { return b.feerate - a.feerate; }
the_stack
import Button from '@material-ui/core/Button' import InputAdornment from '@material-ui/core/InputAdornment' import TextField from '@material-ui/core/TextField' import Typography from '@material-ui/core/Typography' import { Check, Close, Create, GitHub, Send } from '@material-ui/icons' import { useAuthState } from '../../../../user/state/AuthState' import { AuthService } from '../../../../user/state/AuthService' import React, { useEffect, useState } from 'react' import { useDispatch } from '../../../../store' import { FacebookIcon } from '../../../../common/components/Icons/FacebookIcon' import { GoogleIcon } from '../../../../common/components/Icons/GoogleIcon' import { LinkedInIcon } from '../../../../common/components/Icons/LinkedInIcon' import { TwitterIcon } from '../../../../common/components/Icons/TwitterIcon' import { getAvatarURLForUser, Views } from '../util' import { Config, validateEmail, validatePhoneNumber } from '@xrengine/common/src/config' import * as polyfill from 'credential-handler-polyfill' import styles from '../UserMenu.module.scss' import { useTranslation } from 'react-i18next' interface Props { changeActiveMenu?: any setProfileMenuOpen?: any hideLogin?: any } const ProfileMenu = (props: Props): any => { const { changeActiveMenu, setProfileMenuOpen, hideLogin } = props const { t } = useTranslation() const dispatch = useDispatch() const selfUser = useAuthState().user const [username, setUsername] = useState(selfUser?.name.value) const [emailPhone, setEmailPhone] = useState('') const [error, setError] = useState(false) const [errorUsername, setErrorUsername] = useState(false) let type = '' const loadCredentialHandler = async () => { try { const mediator = `${Config.publicRuntimeConfig.mediatorServer}/mediator?origin=${encodeURIComponent( window.location.origin )}` await polyfill.loadOnce(mediator) console.log('Ready to work with credentials!') } catch (e) { console.error('Error loading polyfill:', e) } } useEffect(() => { loadCredentialHandler() }, []) // Only run once useEffect(() => { selfUser && setUsername(selfUser.name.value) }, [selfUser.name.value]) const updateUserName = (e) => { e.preventDefault() handleUpdateUsername() } const handleUsernameChange = (e) => { setUsername(e.target.value) if (!e.target.value) setErrorUsername(true) } const handleUpdateUsername = () => { const name = username.trim() if (!name) return if (selfUser.name.value.trim() !== name) { AuthService.updateUsername(selfUser.id.value, name) } } const handleInputChange = (e) => setEmailPhone(e.target.value) const validate = () => { if (emailPhone === '') return false if (validateEmail(emailPhone.trim())) type = 'email' else if (validatePhoneNumber(emailPhone.trim())) type = 'sms' else { setError(true) return false } setError(false) return true } const handleSubmit = (e: any): any => { e.preventDefault() if (!validate()) return if (type === 'email') AuthService.addConnectionByEmail(emailPhone, selfUser?.id?.value) else if (type === 'sms') AuthService.addConnectionBySms(emailPhone, selfUser?.id?.value) return } const handleOAuthServiceClick = (e) => { AuthService.loginUserByOAuth(e.currentTarget.id) } const handleLogout = async (e) => { if (changeActiveMenu != null) changeActiveMenu(null) else if (setProfileMenuOpen != null) setProfileMenuOpen(false) await AuthService.logoutUser() // window.location.reload() } const handleWalletLoginClick = async (e) => { const domain = window.location.origin const challenge = '99612b24-63d9-11ea-b99f-4f66f3e4f81a' // TODO: generate console.log('Sending DIDAuth query...') const didAuthQuery: any = { web: { VerifiablePresentation: { query: [ { type: 'DIDAuth' } ], challenge, domain // e.g.: requestingparty.example.com } } } // Use Credential Handler API to authenticate const result: any = await navigator.credentials.get(didAuthQuery) console.log(result) AuthService.loginUserByXRWallet(result) } return ( <div className={styles.menuPanel}> <section className={styles.profilePanel}> <section className={styles.profileBlock}> <div className={styles.avatarBlock}> <img src={getAvatarURLForUser(selfUser?.id?.value)} /> {changeActiveMenu != null && ( <Button className={styles.avatarBtn} id="select-avatar" onClick={() => changeActiveMenu(Views.Avatar)} disableRipple > <Create /> </Button> )} </div> <div className={styles.headerBlock}> <span className={styles.inputBlock}> <TextField margin="none" size="small" label={t('user:usermenu.profile.lbl-username')} name="username" variant="outlined" value={username || ''} onChange={handleUsernameChange} onKeyDown={(e) => { if (e.key === 'Enter') updateUserName(e) }} className={styles.usernameInput} error={errorUsername} InputProps={{ endAdornment: ( <InputAdornment position="end"> <a href="#" className={styles.materialIconBlock} onClick={updateUserName}> <Check className={styles.primaryForeground} /> </a> </InputAdornment> ) }} /> </span> <h2> {selfUser?.userRole?.value === 'admin' ? t('user:usermenu.profile.youAreAn') : t('user:usermenu.profile.youAreA')}{' '} <span>{selfUser?.userRole?.value}</span>. </h2> <h4> {(selfUser.userRole.value === 'user' || selfUser.userRole.value === 'admin') && ( <div onClick={handleLogout}>{t('user:usermenu.profile.logout')}</div> )} </h4> {selfUser?.inviteCode.value != null && ( <h2> {t('user:usermenu.profile.inviteCode')}: {selfUser.inviteCode.value} </h2> )} </div> </section> {!hideLogin && ( <> {selfUser?.userRole.value === 'guest' && ( <section className={styles.emailPhoneSection}> <Typography variant="h1" className={styles.panelHeader}> {t('user:usermenu.profile.connectPhone')} </Typography> <form onSubmit={handleSubmit}> <TextField className={styles.emailField} size="small" placeholder={t('user:usermenu.profile.ph-phoneEmail')} variant="outlined" onChange={handleInputChange} onBlur={validate} error={error} helperText={error ? t('user:usermenu.profile.phoneEmailError') : null} InputProps={{ endAdornment: ( <InputAdornment position="end" onClick={handleSubmit}> <a href="#" className={styles.materialIconBlock}> <Send className={styles.primaryForeground} /> </a> </InputAdornment> ) }} /> </form> </section> )} {selfUser?.userRole.value === 'guest' && changeActiveMenu != null && ( <section className={styles.walletSection}> <Typography variant="h3" className={styles.textBlock}> {t('user:usermenu.profile.or')} </Typography> {/*<Button onClick={handleWalletLoginClick} className={styles.walletBtn}> {t('user:usermenu.profile.lbl-wallet')} </Button> <br/>*/} <Button onClick={() => changeActiveMenu(Views.ReadyPlayer)} className={styles.walletBtn}> {t('user:usermenu.profile.loginWithReadyPlayerMe')} </Button> </section> )} {selfUser?.userRole.value === 'guest' && ( <section className={styles.socialBlock}> <Typography variant="h3" className={styles.textBlock}> {t('user:usermenu.profile.connectSocial')} </Typography> <div className={styles.socialContainer}> <a href="#" id="facebook" onClick={handleOAuthServiceClick}> <FacebookIcon width="40" height="40" viewBox="0 0 40 40" /> </a> <a href="#" id="google" onClick={handleOAuthServiceClick}> <GoogleIcon width="40" height="40" viewBox="0 0 40 40" /> </a> <a href="#" id="linkedin2" onClick={handleOAuthServiceClick}> <LinkedInIcon width="40" height="40" viewBox="0 0 40 40" /> </a> <a href="#" id="twitter" onClick={handleOAuthServiceClick}> <TwitterIcon width="40" height="40" viewBox="0 0 40 40" /> </a> <a href="#" id="github" onClick={handleOAuthServiceClick}> <GitHub /> </a> </div> <Typography variant="h4" className={styles.smallTextBlock}> {t('user:usermenu.profile.createOne')} </Typography> </section> )} {setProfileMenuOpen != null && ( <div className={styles.closeButton} onClick={() => setProfileMenuOpen(false)}> <Close /> </div> )} </> )} </section> </div> ) } export default ProfileMenu
the_stack
import type { SkColor, Color as InputColor } from "../../types"; const alphaf = (c: number) => ((c >> 24) & 255) / 255; const red = (c: number) => (c >> 16) & 255; const green = (c: number) => (c >> 8) & 255; const blue = (c: number) => c & 255; // From https://raw.githubusercontent.com/deanm/css-color-parser-js/master/csscolorparser.js const CSSColorTable = { transparent: Float32Array.of(0, 0, 0, 0), aliceblue: Float32Array.of(240, 248, 255, 1), antiquewhite: Float32Array.of(250, 235, 215, 1), aqua: Float32Array.of(0, 255, 255, 1), aquamarine: Float32Array.of(127, 255, 212, 1), azure: Float32Array.of(240, 255, 255, 1), beige: Float32Array.of(245, 245, 220, 1), bisque: Float32Array.of(255, 228, 196, 1), black: Float32Array.of(0, 0, 0, 1), blanchedalmond: Float32Array.of(255, 235, 205, 1), blue: Float32Array.of(0, 0, 255, 1), blueviolet: Float32Array.of(138, 43, 226, 1), brown: Float32Array.of(165, 42, 42, 1), burlywood: Float32Array.of(222, 184, 135, 1), cadetblue: Float32Array.of(95, 158, 160, 1), chartreuse: Float32Array.of(127, 255, 0, 1), chocolate: Float32Array.of(210, 105, 30, 1), coral: Float32Array.of(255, 127, 80, 1), cornflowerblue: Float32Array.of(100, 149, 237, 1), cornsilk: Float32Array.of(255, 248, 220, 1), crimson: Float32Array.of(220, 20, 60, 1), cyan: Float32Array.of(0, 255, 255, 1), darkblue: Float32Array.of(0, 0, 139, 1), darkcyan: Float32Array.of(0, 139, 139, 1), darkgoldenrod: Float32Array.of(184, 134, 11, 1), darkgray: Float32Array.of(169, 169, 169, 1), darkgreen: Float32Array.of(0, 100, 0, 1), darkgrey: Float32Array.of(169, 169, 169, 1), darkkhaki: Float32Array.of(189, 183, 107, 1), darkmagenta: Float32Array.of(139, 0, 139, 1), darkolivegreen: Float32Array.of(85, 107, 47, 1), darkorange: Float32Array.of(255, 140, 0, 1), darkorchid: Float32Array.of(153, 50, 204, 1), darkred: Float32Array.of(139, 0, 0, 1), darksalmon: Float32Array.of(233, 150, 122, 1), darkseagreen: Float32Array.of(143, 188, 143, 1), darkslateblue: Float32Array.of(72, 61, 139, 1), darkslategray: Float32Array.of(47, 79, 79, 1), darkslategrey: Float32Array.of(47, 79, 79, 1), darkturquoise: Float32Array.of(0, 206, 209, 1), darkviolet: Float32Array.of(148, 0, 211, 1), deeppink: Float32Array.of(255, 20, 147, 1), deepskyblue: Float32Array.of(0, 191, 255, 1), dimgray: Float32Array.of(105, 105, 105, 1), dimgrey: Float32Array.of(105, 105, 105, 1), dodgerblue: Float32Array.of(30, 144, 255, 1), firebrick: Float32Array.of(178, 34, 34, 1), floralwhite: Float32Array.of(255, 250, 240, 1), forestgreen: Float32Array.of(34, 139, 34, 1), fuchsia: Float32Array.of(255, 0, 255, 1), gainsboro: Float32Array.of(220, 220, 220, 1), ghostwhite: Float32Array.of(248, 248, 255, 1), gold: Float32Array.of(255, 215, 0, 1), goldenrod: Float32Array.of(218, 165, 32, 1), gray: Float32Array.of(128, 128, 128, 1), green: Float32Array.of(0, 128, 0, 1), greenyellow: Float32Array.of(173, 255, 47, 1), grey: Float32Array.of(128, 128, 128, 1), honeydew: Float32Array.of(240, 255, 240, 1), hotpink: Float32Array.of(255, 105, 180, 1), indianred: Float32Array.of(205, 92, 92, 1), indigo: Float32Array.of(75, 0, 130, 1), ivory: Float32Array.of(255, 255, 240, 1), khaki: Float32Array.of(240, 230, 140, 1), lavender: Float32Array.of(230, 230, 250, 1), lavenderblush: Float32Array.of(255, 240, 245, 1), lawngreen: Float32Array.of(124, 252, 0, 1), lemonchiffon: Float32Array.of(255, 250, 205, 1), lightblue: Float32Array.of(173, 216, 230, 1), lightcoral: Float32Array.of(240, 128, 128, 1), lightcyan: Float32Array.of(224, 255, 255, 1), lightgoldenrodyellow: Float32Array.of(250, 250, 210, 1), lightgray: Float32Array.of(211, 211, 211, 1), lightgreen: Float32Array.of(144, 238, 144, 1), lightgrey: Float32Array.of(211, 211, 211, 1), lightpink: Float32Array.of(255, 182, 193, 1), lightsalmon: Float32Array.of(255, 160, 122, 1), lightseagreen: Float32Array.of(32, 178, 170, 1), lightskyblue: Float32Array.of(135, 206, 250, 1), lightslategray: Float32Array.of(119, 136, 153, 1), lightslategrey: Float32Array.of(119, 136, 153, 1), lightsteelblue: Float32Array.of(176, 196, 222, 1), lightyellow: Float32Array.of(255, 255, 224, 1), lime: Float32Array.of(0, 255, 0, 1), limegreen: Float32Array.of(50, 205, 50, 1), linen: Float32Array.of(250, 240, 230, 1), magenta: Float32Array.of(255, 0, 255, 1), maroon: Float32Array.of(128, 0, 0, 1), mediumaquamarine: Float32Array.of(102, 205, 170, 1), mediumblue: Float32Array.of(0, 0, 205, 1), mediumorchid: Float32Array.of(186, 85, 211, 1), mediumpurple: Float32Array.of(147, 112, 219, 1), mediumseagreen: Float32Array.of(60, 179, 113, 1), mediumslateblue: Float32Array.of(123, 104, 238, 1), mediumspringgreen: Float32Array.of(0, 250, 154, 1), mediumturquoise: Float32Array.of(72, 209, 204, 1), mediumvioletred: Float32Array.of(199, 21, 133, 1), midnightblue: Float32Array.of(25, 25, 112, 1), mintcream: Float32Array.of(245, 255, 250, 1), mistyrose: Float32Array.of(255, 228, 225, 1), moccasin: Float32Array.of(255, 228, 181, 1), navajowhite: Float32Array.of(255, 222, 173, 1), navy: Float32Array.of(0, 0, 128, 1), oldlace: Float32Array.of(253, 245, 230, 1), olive: Float32Array.of(128, 128, 0, 1), olivedrab: Float32Array.of(107, 142, 35, 1), orange: Float32Array.of(255, 165, 0, 1), orangered: Float32Array.of(255, 69, 0, 1), orchid: Float32Array.of(218, 112, 214, 1), palegoldenrod: Float32Array.of(238, 232, 170, 1), palegreen: Float32Array.of(152, 251, 152, 1), paleturquoise: Float32Array.of(175, 238, 238, 1), palevioletred: Float32Array.of(219, 112, 147, 1), papayawhip: Float32Array.of(255, 239, 213, 1), peachpuff: Float32Array.of(255, 218, 185, 1), peru: Float32Array.of(205, 133, 63, 1), pink: Float32Array.of(255, 192, 203, 1), plum: Float32Array.of(221, 160, 221, 1), powderblue: Float32Array.of(176, 224, 230, 1), purple: Float32Array.of(128, 0, 128, 1), rebeccapurple: Float32Array.of(102, 51, 153, 1), red: Float32Array.of(255, 0, 0, 1), rosybrown: Float32Array.of(188, 143, 143, 1), royalblue: Float32Array.of(65, 105, 225, 1), saddlebrown: Float32Array.of(139, 69, 19, 1), salmon: Float32Array.of(250, 128, 114, 1), sandybrown: Float32Array.of(244, 164, 96, 1), seagreen: Float32Array.of(46, 139, 87, 1), seashell: Float32Array.of(255, 245, 238, 1), sienna: Float32Array.of(160, 82, 45, 1), silver: Float32Array.of(192, 192, 192, 1), skyblue: Float32Array.of(135, 206, 235, 1), slateblue: Float32Array.of(106, 90, 205, 1), slategray: Float32Array.of(112, 128, 144, 1), slategrey: Float32Array.of(112, 128, 144, 1), snow: Float32Array.of(255, 250, 250, 1), springgreen: Float32Array.of(0, 255, 127, 1), steelblue: Float32Array.of(70, 130, 180, 1), tan: Float32Array.of(210, 180, 140, 1), teal: Float32Array.of(0, 128, 128, 1), thistle: Float32Array.of(216, 191, 216, 1), tomato: Float32Array.of(255, 99, 71, 1), turquoise: Float32Array.of(64, 224, 208, 1), violet: Float32Array.of(238, 130, 238, 1), wheat: Float32Array.of(245, 222, 179, 1), white: Float32Array.of(255, 255, 255, 1), whitesmoke: Float32Array.of(245, 245, 245, 1), yellow: Float32Array.of(255, 255, 0, 1), yellowgreen: Float32Array.of(154, 205, 50, 1), }; const clampCSSByte = (j: number) => { // Clamp to integer 0 .. 255. const i = Math.round(j); // Seems to be what Chrome does (vs truncation). // eslint-disable-next-line no-nested-ternary return i < 0 ? 0 : i > 255 ? 255 : i; }; const clampCSSFloat = (f: number) => { // eslint-disable-next-line no-nested-ternary return f < 0 ? 0 : f > 1 ? 1 : f; }; const parseCSSInt = (str: string) => { // int or percentage. if (str[str.length - 1] === "%") { return clampCSSByte((parseFloat(str) / 100) * 255); } // eslint-disable-next-line radix return clampCSSByte(parseInt(str)); }; const parseCSSFloat = (str: string | undefined) => { if (str === undefined) { return 1; } // float or percentage. if (str[str.length - 1] === "%") { return clampCSSFloat(parseFloat(str) / 100); } return clampCSSFloat(parseFloat(str)); }; const CSSHueToRGB = (m1: number, m2: number, h: number) => { if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } if (h * 6 < 1) { return m1 + (m2 - m1) * h * 6; } if (h * 2 < 1) { return m2; } if (h * 3 < 2) { return m1 + (m2 - m1) * (2 / 3 - h) * 6; } return m1; }; const parseCSSColor = (cssStr: string) => { // Remove all whitespace, not compliant, but should just be more accepting. var str = cssStr.replace(/ /g, "").toLowerCase(); // Color keywords (and transparent) lookup. if (str in CSSColorTable) { const cl = CSSColorTable[str as keyof typeof CSSColorTable]; if (cl) { return Float32Array.of(...cl); } return null; } // dup. // #abc and #abc123 syntax. if (str[0] === "#") { if (str.length === 4) { var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing. if (!(iv >= 0 && iv <= 0xfff)) { return null; } // Covers NaN. return [ ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8), (iv & 0xf0) | ((iv & 0xf0) >> 4), (iv & 0xf) | ((iv & 0xf) << 4), 1, ]; } else if (str.length === 7) { var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing. if (!(iv >= 0 && iv <= 0xffffff)) { return null; } // Covers NaN. return [(iv & 0xff0000) >> 16, (iv & 0xff00) >> 8, iv & 0xff, 1]; } return null; } var op = str.indexOf("("), ep = str.indexOf(")"); if (op !== -1 && ep + 1 === str.length) { var fname = str.substr(0, op); var params = str.substr(op + 1, ep - (op + 1)).split(","); var alpha = 1; // To allow case fallthrough. switch (fname) { // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-expect-error case "rgba": if (params.length !== 4) { return null; } alpha = parseCSSFloat(params.pop()); // Fall through. case "rgb": if (params.length !== 3) { return null; } return [ parseCSSInt(params[0]), parseCSSInt(params[1]), parseCSSInt(params[2]), alpha, ]; // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-expect-error case "hsla": if (params.length !== 4) { return null; } alpha = parseCSSFloat(params.pop()); // Fall through. case "hsl": if (params.length !== 3) { return null; } var h = (((parseFloat(params[0]) % 360) + 360) % 360) / 360; // 0 .. 1 // NOTE(deanm): According to the CSS spec s/l should only be // percentages, but we don't bother and let float or percentage. var s = parseCSSFloat(params[1]); var l = parseCSSFloat(params[2]); var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; var m1 = l * 2 - m2; return [ clampCSSByte(CSSHueToRGB(m1, m2, h + 1 / 3) * 255), clampCSSByte(CSSHueToRGB(m1, m2, h) * 255), clampCSSByte(CSSHueToRGB(m1, m2, h - 1 / 3) * 255), alpha, ]; default: return null; } } return null; }; export const Color = (color: InputColor): SkColor => { if (color instanceof Float32Array) { return color; } else if (typeof color === "string") { const r = parseCSSColor(color); const rgba = r === null ? CSSColorTable.black : r; return Float32Array.of( rgba[0] / 255, rgba[1] / 255, rgba[2] / 255, rgba[3] ); } else { return Float32Array.of( red(color) / 255, green(color) / 255, blue(color) / 255, alphaf(color) ); } };
the_stack
import {ClientInfo} from "../clientInfo"; import {ClientType} from "../clientType"; import {Constants} from "../constants"; import {Experiments} from "../experiments"; import {ResponsePackage} from "../responsePackage"; import {StringUtils} from "../stringUtils"; import {UrlUtils} from "../urlUtils"; import {TooltipType} from "../clipperUI/tooltipType"; import {SmartValue} from "../communicator/smartValue"; import {HttpWithRetries} from "../http/HttpWithRetries"; import {Localization} from "../localization/localization"; import {LocalizationHelper} from "../localization/localizationHelper"; import * as Log from "../logging/log"; import {Logger} from "../logging/logger"; import {ClipperData} from "../storage/clipperData"; import {ClipperStorageKeys} from "../storage/clipperStorageKeys"; import {ChangeLog} from "../versioning/changeLog"; import {ChangeLogHelper} from "../versioning/changeLogHelper"; import {Version} from "../versioning/version"; import {AuthenticationHelper} from "./authenticationHelper"; import {ExtensionWorkerBase} from "./extensionWorkerBase"; import {TooltipHelper} from "./tooltipHelper"; import {WorkerPassthroughLogger} from "./workerPassthroughLogger"; /** * The abstract base class for all of the extensions */ export abstract class ExtensionBase<TWorker extends ExtensionWorkerBase<TTab, TTabIdentifier>, TTab, TTabIdentifier> { private workers: TWorker[]; private logger: Logger; private static extensionId: string; protected clipperData: ClipperData; protected auth: AuthenticationHelper; protected tooltip: TooltipHelper; protected clientInfo: SmartValue<ClientInfo>; protected static version = "3.8.5"; constructor(clipperType: ClientType, clipperData: ClipperData) { this.setUnhandledExceptionLogging(); this.workers = []; this.logger = new WorkerPassthroughLogger(this.workers); ExtensionBase.extensionId = StringUtils.generateGuid(); this.clipperData = clipperData; this.clipperData.setLogger(this.logger); this.auth = new AuthenticationHelper(this.clipperData, this.logger); this.tooltip = new TooltipHelper(this.clipperData); let clipperFirstRun = false; let clipperId = this.clipperData.getValue(ClipperStorageKeys.clipperId); if (!clipperId) { // New install clipperFirstRun = true; clipperId = ExtensionBase.generateClipperId(); this.clipperData.setValue(ClipperStorageKeys.clipperId, clipperId); // Ensure fresh installs don't trigger thats What's New experience this.updateLastSeenVersionInStorageToCurrent(); } this.clientInfo = new SmartValue<ClientInfo>({ clipperType: clipperType, clipperVersion: ExtensionBase.getExtensionVersion(), clipperId: clipperId }); if (clipperFirstRun) { this.onFirstRun(); } this.initializeUserFlighting(); this.listenForOpportunityToShowPageNavTooltip(); } protected abstract addPageNavListener(callback: (tab: TTab) => void); protected abstract checkIfTabIsOnWhitelistedUrl(tab: TTab): boolean; protected abstract getIdFromTab(tab: TTab): TTabIdentifier; protected abstract createWorker(tab: TTab): TWorker; protected abstract onFirstRun(); public static getExtensionId(): string { return ExtensionBase.extensionId; } public static getExtensionVersion(): string { return ExtensionBase.version; } public static shouldCheckForMajorUpdates(lastSeenVersion: Version, currentVersion: Version) { return !!currentVersion && (!lastSeenVersion || lastSeenVersion.isLesserThan(currentVersion)); }; public addWorker(worker: TWorker) { worker.setOnUnloading(() => { worker.destroy(); this.removeWorker(worker); }); this.workers.push(worker); } public getWorkers(): TWorker[] { return this.workers; } public removeWorker(worker: TWorker) { let index = this.workers.indexOf(worker); if (index > -1) { this.workers.splice(index, 1); } } /** * Determines if the url is on our domain or not */ protected static isOnOneNoteDomain(url: string): boolean { return url.indexOf("onenote.com") >= 0 || url.indexOf("onenote-int.com") >= 0; } protected fetchAndStoreLocStrings(): Promise<{}> { // navigator.userLanguage is only available in IE, and Typescript will not recognize this property let locale = navigator.language || (<any>navigator).userLanguage; return LocalizationHelper.makeLocStringsFetchRequest(locale).then((responsePackage) => { try { let locStringsDict = JSON.parse(responsePackage.parsedResponse); if (locStringsDict) { this.clipperData.setValue(ClipperStorageKeys.locale, locale); this.clipperData.setValue(ClipperStorageKeys.locStrings, responsePackage.parsedResponse); Localization.setLocalizedStrings(locStringsDict); } return Promise.resolve(locStringsDict); } catch (e) { return Promise.reject(undefined); } }); } /** * Returns the URL for more information about the Clipper */ protected getClipperInstalledPageUrl(clipperId: string, clipperType: ClientType, isInlineInstall: boolean): string { let installUrl: string = Constants.Urls.clipperInstallPageUrl; installUrl = UrlUtils.addUrlQueryValue(installUrl, Constants.Urls.QueryParams.clientType, ClientType[clipperType]); installUrl = UrlUtils.addUrlQueryValue(installUrl, Constants.Urls.QueryParams.clipperId, clipperId); installUrl = UrlUtils.addUrlQueryValue(installUrl, Constants.Urls.QueryParams.clipperVersion, ExtensionBase.getExtensionVersion()); installUrl = UrlUtils.addUrlQueryValue(installUrl, Constants.Urls.QueryParams.inlineInstall, isInlineInstall.toString()); this.logger.logTrace(Log.Trace.Label.RequestForClipperInstalledPageUrl, Log.Trace.Level.Information, installUrl); return installUrl; } protected getExistingWorkerForTab(tabUniqueId: TTabIdentifier): TWorker { let workers = this.getWorkers(); for (let worker of workers) { if (worker.getUniqueId() === tabUniqueId) { return worker; } } return undefined; } /** * Gets the last seen version from storage, and returns undefined if there is none in storage */ protected getLastSeenVersion(): Version { let lastSeenVersionStr = this.clipperData.getValue(ClipperStorageKeys.lastSeenVersion); return lastSeenVersionStr ? new Version(lastSeenVersionStr) : undefined; } protected getNewUpdates(lastSeenVersion: Version, currentVersion: Version): Promise<ChangeLog.Update[]> { return new Promise<ChangeLog.Update[]>((resolve, reject) => { let localeOverride = this.clipperData.getValue(ClipperStorageKeys.displayLanguageOverride); let localeToGet = localeOverride || navigator.language || (<any>navigator).userLanguage; let changelogUrl = UrlUtils.addUrlQueryValue(Constants.Urls.changelogUrl, Constants.Urls.QueryParams.changelogLocale, localeToGet); HttpWithRetries.get(changelogUrl).then((request: XMLHttpRequest) => { try { let schemas: ChangeLog.Schema[] = JSON.parse(request.responseText); let allUpdates: ChangeLog.Update[]; for (let i = 0; i < schemas.length; i++) { if (schemas[i].schemaVersion === ChangeLog.schemaVersionSupported) { allUpdates = schemas[i].updates; break; } } if (allUpdates) { let updatesSinceLastVersion = ChangeLogHelper.getUpdatesBetweenVersions(allUpdates, lastSeenVersion, currentVersion); resolve(updatesSinceLastVersion); } else { throw new Error("No matching schemas were found."); } } catch (error) { reject(error); } }, (error) => { reject(error); }); }); } protected getOrCreateWorkerForTab(tab: TTab, tabToIdMapping: (tab: TTab) => TTabIdentifier): TWorker { let tabId = tabToIdMapping(tab); let worker = this.getExistingWorkerForTab(tabId); if (!worker) { worker = this.createWorker(tab); this.addWorker(worker); } return worker; } /** * Generates a new clipperId, should only be called on first run */ private static generateClipperId(): string { let clipperPrefix = "ON"; return clipperPrefix + "-" + StringUtils.generateGuid(); } /** * Initializes the flighting info for the user. */ private initializeUserFlighting() { // We don't have any flights this.updateClientInfoWithFlightInformation([]); } private shouldShowTooltip(tab: TTab, tooltipTypes: TooltipType[]): TooltipType { let type = this.checkIfTabMatchesATooltipType(tab, tooltipTypes); if (!type) { return; } if (!this.tooltip.tooltipDelayIsOver(type, Date.now())) { return; } return type; } private shouldShowVideoTooltip(tab: TTab): boolean { if (this.checkIfTabIsAVideoDomain(tab) && this.tooltip.tooltipDelayIsOver(TooltipType.Video, Date.now())) { return true; } return false; } private showTooltip(tab: TTab, tooltipType: TooltipType): void { let worker = this.getOrCreateWorkerForTab(tab, this.getIdFromTab); let tooltipImpressionEvent = new Log.Event.BaseEvent(Log.Event.Label.TooltipImpression); tooltipImpressionEvent.setCustomProperty(Log.PropertyName.Custom.TooltipType, TooltipType[tooltipType]); tooltipImpressionEvent.setCustomProperty(Log.PropertyName.Custom.LastSeenTooltipTime, this.tooltip.getTooltipInformation(ClipperStorageKeys.lastSeenTooltipTimeBase, tooltipType)); tooltipImpressionEvent.setCustomProperty(Log.PropertyName.Custom.NumTimesTooltipHasBeenSeen, this.tooltip.getTooltipInformation(ClipperStorageKeys.numTimesTooltipHasBeenSeenBase, tooltipType)); worker.invokeTooltip(tooltipType).then((wasInvoked) => { if (wasInvoked) { this.tooltip.setTooltipInformation(ClipperStorageKeys.lastSeenTooltipTimeBase, tooltipType, Date.now().toString()); let numSeenStorageKey = ClipperStorageKeys.numTimesTooltipHasBeenSeenBase; let numTimesSeen = this.tooltip.getTooltipInformation(numSeenStorageKey, tooltipType) + 1; this.tooltip.setTooltipInformation(ClipperStorageKeys.numTimesTooltipHasBeenSeenBase, tooltipType, numTimesSeen.toString()); } tooltipImpressionEvent.setCustomProperty(Log.PropertyName.Custom.FeatureEnabled, wasInvoked); worker.getLogger().logEvent(tooltipImpressionEvent); }); } private shouldShowWhatsNewTooltip(tab: TTab, lastSeenVersion: Version, extensionVersion: Version): boolean { // We explicitly check for control group as well so we prevent updating lastSeenVersion on everyone before the experiment starts return this.checkIfTabIsOnWhitelistedUrl(tab) && ExtensionBase.shouldCheckForMajorUpdates(lastSeenVersion, extensionVersion); } private showWhatsNewTooltip(tab: TTab, lastSeenVersion: Version, extensionVersion: Version): void { this.getNewUpdates(lastSeenVersion, extensionVersion).then((newUpdates) => { let filteredUpdates = ChangeLogHelper.filterUpdatesThatDontApplyToBrowser(newUpdates, ClientType[this.clientInfo.get().clipperType]); if (!!filteredUpdates && filteredUpdates.length > 0) { let worker: TWorker = this.getOrCreateWorkerForTab(tab, this.getIdFromTab); worker.invokeWhatsNewTooltip(filteredUpdates).then((wasInvoked) => { if (wasInvoked) { let whatsNewImpressionEvent = new Log.Event.BaseEvent(Log.Event.Label.WhatsNewImpression); whatsNewImpressionEvent.setCustomProperty(Log.PropertyName.Custom.FeatureEnabled, wasInvoked); worker.getLogger().logEvent(whatsNewImpressionEvent); // We don't want to do this if the tooltip was not invoked (e.g., on about:blank) so we can show it at the next opportunity this.updateLastSeenVersionInStorageToCurrent(); } }); } else { this.updateLastSeenVersionInStorageToCurrent(); } }, (error) => { Log.ErrorUtils.sendFailureLogRequest({ label: Log.Failure.Label.GetChangeLog, properties: { failureType: Log.Failure.Type.Unexpected, failureInfo: { error: error }, failureId: "GetChangeLog", stackTrace: error }, clientInfo: this.clientInfo }); }); } /** * Skeleton method that sets a listener that listens for the opportunity to show a tooltip, * then invokes it when appropriate. */ private listenForOpportunityToShowPageNavTooltip() { this.addPageNavListener((tab: TTab) => { // Fallback behavior for if the last seen version in storage is somehow in a corrupted format let lastSeenVersion: Version; try { lastSeenVersion = this.getLastSeenVersion(); } catch (e) { this.updateLastSeenVersionInStorageToCurrent(); return; } let extensionVersion = new Version(ExtensionBase.getExtensionVersion()); if (this.clientInfo.get().clipperType !== ClientType.FirefoxExtension) { let tooltips = [TooltipType.Pdf, TooltipType.Product, TooltipType.Recipe]; // Returns the Type of tooltip to show IF the delay is over and the tab has the correct content type let typeToShow = this.shouldShowTooltip(tab, tooltips); if (typeToShow) { this.showTooltip(tab, typeToShow); return; } if (this.shouldShowVideoTooltip(tab)) { this.showTooltip(tab, TooltipType.Video); return; } } // We don't show updates more recent than the local version for now, as it is easy // for a changelog to be released before a version is actually out if (this.shouldShowWhatsNewTooltip(tab, lastSeenVersion, extensionVersion)) { this.showWhatsNewTooltip(tab, lastSeenVersion, extensionVersion); return; } }); } private setUnhandledExceptionLogging() { let oldOnError = window.onerror; window.onerror = (message: string, filename?: string, lineno?: number, colno?: number, error?: Error) => { let callStack = error ? Log.Failure.getStackTrace(error) : "[unknown stacktrace]"; Log.ErrorUtils.sendFailureLogRequest({ label: Log.Failure.Label.UnhandledExceptionThrown, properties: { failureType: Log.Failure.Type.Unexpected, failureInfo: { error: JSON.stringify({ error: error.toString(), message: message, lineno: lineno, colno: colno }) }, failureId: "ExtensionBase", stackTrace: callStack }, clientInfo: this.clientInfo }); if (oldOnError) { oldOnError(message, filename, lineno, colno, error); } }; } /** * Returns True if the Extension determines the tab is a Product, Recipe, or PDF. False otherwise */ protected abstract checkIfTabMatchesATooltipType(tab: TTab, tooltipTypes: TooltipType[]): TooltipType; /** * Returns True if the Extension determines the tab is a Video, false otherwise */ protected abstract checkIfTabIsAVideoDomain(tab: TTab): boolean; /** * Updates the ClientInfo with the given flighting info. */ private updateClientInfoWithFlightInformation(flightingInfo: string[]) { this.clientInfo.set({ clipperType: this.clientInfo.get().clipperType, clipperVersion: this.clientInfo.get().clipperVersion, clipperId: this.clientInfo.get().clipperId, flightingInfo: flightingInfo }); } private updateLastSeenVersionInStorageToCurrent() { this.clipperData.setValue(ClipperStorageKeys.lastSeenVersion, ExtensionBase.getExtensionVersion()); } }
the_stack
import { OresStream } from '@/server/ingest/ores-stream'; import { getUrlBaseByWiki, wikiToDomain } from '@/shared/utility-shared'; import { axiosLogger, cronLogger } from '@/server/common'; import axios from 'axios'; import { debugRouter } from '@/server/routers/debug'; import { CronJob } from 'cron'; import { FeedRevisionEngine } from '@/server/feed/feed-revision-engine'; import { AwardBarnStarCronJob } from '../cronjobs/award-barnstar.cron'; import { apiRouter as newApiRouter } from './routers/api'; import { getMetrics } from './routers/api/metrics'; import { apiLogger, asyncHandler, ensureAuthenticated, fetchRevisions, isWhitelistedFor, logger, perfLogger, useOauth, colorizeMaybe, latencyColor, statusColor } from './common'; import { initDotEnv, initMongoDb, initUnhandledRejectionCatcher } from './init-util'; import { InteractionProps } from '~/shared/models/interaction-item.model'; import { BasicJudgement } from '~/shared/interfaces'; import { installHook } from '~/server/routers/api/interaction'; const envPath = process.env.DOTENV_PATH || 'template.env'; console.log('DotEnv envPath = ', envPath, ' if you want to change it, restart and set DOTENV_PATH'); require('dotenv').config({ path: envPath, }); const http = require('http'); const { performance } = require('perf_hooks'); const express = require('express'); const responseTime = require('response-time'); const consola = require('consola'); const { Nuxt, Builder } = require('nuxt'); const universalAnalytics = require('universal-analytics'); const rp = require('request-promise'); const mongoose = require('mongoose'); const pad = require('pad'); const logReqPerf = function(req, res, next) { // Credit for inspiration: http://www.sheshbabu.com/posts/measuring-response-times-of-express-route-handlers/ perfLogger.debug(` log request starts for ${req.method} ${colorizeMaybe(perfLogger, 'lightblue', req.originalUrl)}:`, { method: req.method, original_url: req.originalUrl, ga_id: req.cookies._ga, }); const startNs = process.hrtime.bigint(); res.on('finish', () => { const endNs = process.hrtime.bigint(); const latencyMs = Number(endNs - startNs) / 1e6; const level = 'info'; perfLogger.info( `${colorizeMaybe(perfLogger, latencyColor(latencyMs), pad(6, (latencyMs).toFixed(0)))}ms ` + `${colorizeMaybe(perfLogger, statusColor(res.statusCode), pad(4, res.statusCode))} ` + `${req.method} ${colorizeMaybe(perfLogger, 'lightblue', req.originalUrl)}`, { ga_id: req.cookies._ga, session_id: req.session?.id, }); }); next(); }; if (process.env.NODE_ENV === 'development') { axiosLogger.info('Axios: setup timing monitoring'); const axiosTiming = (instance, callback) => { instance.interceptors.request.use((request) => { request.ts = performance.now(); return request; }); instance.interceptors.response.use((response) => { callback(response, Number(performance.now() - response.config.ts)); return response; }); }; axiosTiming(axios, function(response, latencyMs) { const level = 'info'; axiosLogger.info( `${colorizeMaybe(axiosLogger, latencyColor(latencyMs), pad(6, (latencyMs).toFixed(0)))}ms ` + `${colorizeMaybe(axiosLogger, statusColor(response.status), pad(4, response.status))} ` + `${response.config.method} ${colorizeMaybe(axiosLogger, 'lightblue', response.config.url)}`); }); } const docCounter = 0; const allDocCounter = 0; // Import and Set Nuxt.js options const config = require('../nuxt.config.js'); config.dev = !(process.env.NODE_ENV === 'production'); // -------------- FROM API ---------------- function setupApiRequestListener(db, io, app) { app.use('/api', newApiRouter); } function setupCronJobs() { if (process.env.CRON_BARNSTAR_TIMES) { logger.info('Setting up CRON_BARN_STAR_TIME raw value = ', process.env.CRON_BARNSTAR_TIMES); const cronTimePairs = process.env.CRON_BARNSTAR_TIMES .split('|') .map((pairStr) => { const pair = pairStr.split(';'); return { cronTime: pair[0], frequency: pair[1] }; }).forEach((pair) => { const awardBarnStarCronJob = new AwardBarnStarCronJob(pair.cronTime, pair.frequency); awardBarnStarCronJob.startCronJob(); }); } else { logger.info('Skipping Barnstar cronjobs because of lack of CRON_BARNSTAR_TIMES which is: ', process.env.CRON_BARNSTAR_TIMES); } if (process.env.CRON_CATEGORY_TRAVERSE_TIME) { logger.info(`Setting up CronJob for traversing category tree to run at ${process.env.CRON_CATEGORY_TRAVERSE_TIME}`); const traverseCategoryTreeCronJob = new CronJob(process.env.CRON_CATEGORY_TRAVERSE_TIME, async () => { cronLogger.info('Start running traverseCategoryTree...'); await FeedRevisionEngine.traverseCategoryTree('us2020', 'enwiki', 'Category:2020_United_States_presidential_election'); await FeedRevisionEngine.traverseCategoryTree('covid19', 'enwiki', 'Category:COVID-19'); cronLogger.info('Done running traverseCategoryTree!'); }, null, false, process.env.CRON_TIMEZONE || 'America/Los_Angeles'); traverseCategoryTreeCronJob.start(); } if (process.env.CRON_FEED_REVISION_TIME) { logger.info(`Setting up CronJob for populating feed revisions to run at ${process.env.CRON_FEED_REVISION_TIME}`); const feedRevisionCronJob = new CronJob(process.env.CRON_FEED_REVISION_TIME, async () => { cronLogger.info('Start running populateFeedRevisions...'); await FeedRevisionEngine.populateFeedRevisions('us2020', 'enwiki'); await FeedRevisionEngine.populateFeedRevisions('covid19', 'enwiki'); cronLogger.info('Done running populateFeedRevisions!'); }, null, false, process.env.CRON_TIMEZONE || 'America/Los_Angeles'); feedRevisionCronJob.start(); } } function setupHooks() { // See https://github.com/google/wikiloop-doublecheck/issues/234 // TODO(xinbenlv): add authentication. installHook('postToJade', async function(i:InteractionProps) { const revId = i.wikiRevId.split(':')[1]; const wiki = i.wikiRevId.split(':')[0]; if (wiki === 'enwiki' && // we only handle enwiki for now. See https://github.com/google/wikiloop-doublecheck/issues/234 [ BasicJudgement.ShouldRevert.toString(), BasicJudgement.LooksGood.toString(), ].indexOf(i.judgement) > 0) { const isDamaging = (i.judgement === BasicJudgement.ShouldRevert); const payload = { action: 'jadeproposeorendorse', title: `Jade:Diff/${revId}`, facet: 'editquality', // TODO(xinbenlv): we don't actually make assessment on "goodfaith", but validation requires it. labeldata: `{"damaging":${isDamaging}, "goodfaith":true}`, endorsementorigin: 'WikiLoop Battelfield', notes: 'Notes not available', formatversion: '2', // TODO(xinbenlv): endorsementcomment is effectively required rather than optional endorsementcomment: 'SeemsRequired', format: 'json', token: '+\\', // TODO(xinbenlv): update with real CSRF token when JADE launch to production }; const optionsForForm = { method: 'POST', uri: 'https://en.wikipedia.beta.wmflabs.org/w/api.php', formData: payload, headers: { /* 'content-type': 'multipart/form-data' */ // Is set automatically }, }; const retWithForm = await rp(optionsForForm); } }); if (process.env.DISCORD_WEBHOOK_ID && process.env.DISCORD_WEBHOOK_TOKEN) { logger.info(`Installing discord webhook for id=${process.env.DISCORD_WEBHOOK_ID}, token=${process.env.DISCORD_WEBHOOK_TOKEN.slice(0, 3)}...`); installHook('postToDiscord', async function(i:InteractionProps) { const revId = i.wikiRevId.split(':')[1]; const colorMap = { ShouldRevert: 14431557, // #dc3545 / Bootstrap Danger NotSure: 7107965, // 6c757d / LooksGood: 2664261, // #28a745 / Bootstrap Success }; await rp.post( { url: `https://discordapp.com/api/webhooks/${process.env.DISCORD_WEBHOOK_ID}/${process.env.DISCORD_WEBHOOK_TOKEN}`, json: { username: process.env.PUBLIC_HOST, content: `A revision ${i.wikiRevId} for ${i.title} is reviewed by ${i.wikiUserName || i.userGaId} and result is ${i.judgement}`, embeds: [{ title: `See it on ${i.wiki}: ${i.title}`, url: `${getUrlBaseByWiki(i.wiki)}/wiki/Special:Diff/${revId}`, }, { title: `${i.judgement}`, url: `http://${process.env.PUBLIC_HOST}/revision/${i.wiki}/${revId}`, color: colorMap[i.judgement], }], }, }); }); } else { logger.warn('Not Installing discord webhook because lack of process.env.DISCORD_WEBHOOK_ID or process.env.DISCORD_WEBHOOK_TOKEN'); } } function setupIoSocketListener(db, io) { async function emitMetricsUpdate() { const metrics = await getMetrics(); io.sockets.emit('metrics-update', metrics); logger.debug('Emit Metrics Update', metrics); } io.on('connection', async function(socket) { logger.info(`A socket client connected. Socket id = ${socket.id}. Total connections =`, Object.keys(io.sockets.connected).length); socket.on('disconnect', async function() { await emitMetricsUpdate(); logger.info(`A socket client disconnected. Socket id = ${socket.id}. Total connections =`, Object.keys(io.sockets.connected).length); }); socket.on('user-id-info', async function(userIdInfo) { logger.info('Received userIdInfo', userIdInfo); await db.collection('Sockets').updateOne({ _id: socket.id }, { $set: { userGaId: userIdInfo.userGaId, wikiUserName: userIdInfo.wikiUserName }, }, { upsert: true }, ); await emitMetricsUpdate(); }); await db.collection('Sockets').updateOne({ _id: socket.id }, { $setOnInsert: { created: new Date() }, }, { upsert: true }); }); setInterval(async () => { await emitMetricsUpdate(); }, 5000); } function setupAuthApi(db, app) { const passport = require('passport'); const oauthFetch = require('oauth-fetch-json'); const session = require('express-session'); const MongoDBStore = require('connect-mongodb-session')(session); const mongoDBStore = new MongoDBStore({ uri: process.env.MONGODB_URI, collection: 'Sessions', }); app.use(session({ cookie: { // 7 days maxAge: 7 * 24 * 60 * 60 * 1000, }, secret: 'keyboard cat like a random stuff', resave: false, saveUninitialized: true, store: mongoDBStore, })); app.use(passport.initialize()); app.use(passport.session()); const MediaWikiStrategy = require('passport-mediawiki-oauth').OAuthStrategy; passport.serializeUser(function(user, done) { done(null, user); }); passport.deserializeUser(function(user, done) { done(null, user); }); passport.use(new MediaWikiStrategy({ consumerKey: process.env.MEDIAWIKI_CONSUMER_KEY, consumerSecret: process.env.MEDIAWIKI_CONSUMER_SECRET, callbackURL: `http://${process.env.PUBLIC_HOST}/auth/mediawiki/callback`, // TODO probably need to set HOST and PORT }, function(token, tokenSecret, profile, done) { profile.oauth = { consumer_key: process.env.MEDIAWIKI_CONSUMER_KEY, consumer_secret: process.env.MEDIAWIKI_CONSUMER_SECRET, token, token_secret: tokenSecret, }; done(null, profile); }, )); app.use((req, res, next) => { if (req.isAuthenticated() && req.user) { res.locals.isAuthenticated = req.isAuthenticated(); res.locals.user = { id: req.user.id, username: req.user._json.username, grants: req.user._json.grants, }; logger.debug('Setting res.locals.user = ', res.locals.user); } next(); }); app.get('/auth/mediawiki/login', passport.authenticate('mediawiki')); app.get('/auth/mediawiki/logout', asyncHandler((req, res) => { req.logout(); res.redirect('/'); })); app.get('/auth/mediawiki/callback', passport.authenticate('mediawiki', { failureRedirect: '/auth/mediawiki/login' }), function(req, res) { // Successful authentication, redirect home. logger.debug(' Successful authentication, redirect home. req.isAuthenticated()=', req.isAuthenticated()); res.redirect('/'); }); const rateLimit = require('express-rate-limit'); const editLimiter = rateLimit({ windowMs: 3 * 60 * 1000, // 3 minutes max: 30, // 30 edits globally per 3 minutes }); app.get('/api/auth/revert/:wikiRevId', ensureAuthenticated, editLimiter, asyncHandler(async (req, res) => { logger.info('Receive auth revert request', req.params); const wiki = req.params.wikiRevId.split(':')[0]; const revId = req.params.wikiRevId.split(':')[1]; const apiUrl = `https://${wikiToDomain[wiki]}/w/api.php`; const revInfo = (await fetchRevisions([req.params.wikiRevId]))[wiki]; // assuming request succeeded // Documentation: https://www.mediawiki.org/wiki/API:Edit#API_documentation const userInfo = await oauthFetch(apiUrl, { action: 'query', format: 'json', meta: 'userinfo', uiprop: 'rights|groups|groupmemberships', }, { method: 'GET' }, req.user.oauth); // assuming request succeeded; logger.debug('userInfo ret = ', userInfo); const whitelisted = await isWhitelistedFor('DirectRevert', userInfo.query.userinfo.name); logger.warn('userInfo.query.userinfo.rights.indexOf(\'rollback)', userInfo.query.userinfo.rights.indexOf('rollback')); logger.warn('whitelisted', whitelisted); if (whitelisted || userInfo.query.userinfo.rights.includes('rollback')) { const token = (await oauthFetch(apiUrl, { action: 'query', format: 'json', meta: 'tokens', }, {}, req.user.oauth)).query.tokens.csrftoken; // assuming request succeeded; try { const payload = { action: 'edit', format: 'json', title: revInfo[0].title, // TODO(zzn): assuming only 1 revision is being reverted summary: `Identified as test/vandalism and undid revision ${revId} by [[User:${revInfo[0].user}]] with [[m:WikiLoop DoubleCheck]](v${require( './../package.json').version}). See it or provide your opinion at http://${process.env.PUBLIC_HOST || 'localhost:8000'}/revision/${wiki}/${revId}`, undo: revId, token, }; if (wiki === 'enwiki') { // currently only enwiki has the manually created tag of WikiLoop DoubleCheck (payload as any).tags = 'WikiLoop Battlefield'; // TODO(xinbenlv@, #307) Update the name to "WikiLoop DoubleCheck", and also request to support it on other language } const retData = await oauthFetch(apiUrl, payload, { method: 'POST' }, req.user.oauth); // assuming request succeeded; res.setHeader('Content-Type', 'application/json'); res.status(200); res.send(JSON.stringify(retData)); logger.debug(`conducted revert for wikiRevId=${req.params.wikiRevId}`); } catch (err) { apiLogger.error(err); res.status(500); res.send(err); } } else { logger.warn('Attempt to direct revert but no rights or whitelisted'); res.status(403); res.send('Error, lack of permission!. No rollback rights or whitelisted'); } })); app.get('/api/auth/user/preferences', ensureAuthenticated, asyncHandler(async (req, res) => { const wikiUserName = req.user.displayName; const userPreferences = await mongoose.connection.db.collection( 'UserPreferences') .find({ wikiUserName }) .toArray(); res.send(userPreferences.length > 0 ? userPreferences[0] : {}); })); app.post('/api/auth/user/preferences', ensureAuthenticated, asyncHandler(async (req, res) => { await mongoose.connection.db.collection('UserPreferences') .update({ wikiUserName: req.user.displayName }, { $set: req.body, $setOnInsert: { created: new Date() }, }, { upsert: true }); const wikiUserName = req.user.id; const userPreferences = await mongoose.connection.db.collection( 'UserPreferences') .find({ wikiUserName }) .toArray(); res.send(userPreferences.length > 0 ? userPreferences[0] : {}); })); } function setupFlag() { const yargs = require('yargs'); const argv = yargs .option('server-only', { alias: 's', default: false, description: 'If true, the app will be run as server-only', type: 'boolean', }) .help().alias('help', 'h') .argv; return argv; } async function start() { initDotEnv(); await initMongoDb(); initUnhandledRejectionCatcher(); const flag = setupFlag(); // Init Nuxt.js const nuxt = new Nuxt(config); const { host, port } = nuxt.options.server; const app = express(); app.use(responseTime()); const cookieParser = require('cookie-parser'); app.use(cookieParser()); // Setup Google Analytics app.use(universalAnalytics.middleware(process.env.GA_WLBF_ID_API, { cookieName: '_ga' })); app.use(express.urlencoded({ limit: '50mb', extended: true })); app.use(express.json({ limit: '50mb', extended: true })); app.use(logReqPerf); const server = http.Server(app); const io = require('socket.io')(server, { cookie: false }); app.set('socketio', io); app.use(function(req, res, next) { apiLogger.debug('req.originalUrl:', req.originalUrl); apiLogger.debug('req.params:', req.params); apiLogger.debug('req.query:', req.query); next(); }); if (useOauth) {setupAuthApi(mongoose.connection.db, app);} setupIoSocketListener(mongoose.connection.db, io); setupApiRequestListener(mongoose.connection.db, io, app); if (process.env.NODE_ENV !== 'production') {app.use('/debug', debugRouter);} if (!flag['server-only']) { await nuxt.ready(); // Build only in dev mode if (config.dev) { logger.info('Running Nuxt Builder ... '); const builder = new Builder(nuxt); await builder.build(); logger.info('DONE ... '); } else { logger.info('NOT Running Nuxt Builder'); } // Give nuxt middleware to express app.use(nuxt.render); } // Listen the server // app.listen(port, host) server.listen(port, host); consola.ready({ message: `Server listening on http://${host}:${port}`, badge: true, }); if (process.env.INGESTION_ENABLED === '1') { const oresStream = new OresStream('enwiki'); oresStream.subscribe(); logger.info('Ingestion enabled'); } else { logger.info('Ingestion disabled'); } setupCronJobs(); setupHooks(); } start();
the_stack
import { UBOGlobal, UBOShadow, UBOCamera, UNIFORM_SHADOWMAP_BINDING, supportsFloatTexture } from './define'; import { Device, BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet } from '../gfx'; import { Camera } from '../renderer/scene/camera'; import { Mat4, Vec2, Vec3, Vec4, Color } from '../math'; import { RenderPipeline } from './render-pipeline'; import { legacyCC } from '../global-exports'; import { ShadowType } from '../renderer/scene/shadows'; import { updatePlanarPROJ } from './scene-culling'; import { Light, LightType } from '../renderer/scene/light'; import { SpotLight } from '../renderer/scene'; import { RenderWindow } from '../renderer/core/render-window'; const _matShadowView = new Mat4(); const _matShadowProj = new Mat4(); const _matShadowViewProj = new Mat4(); const _vec4ShadowInfo = new Vec4(); export class PipelineUBO { public static updateGlobalUBOView (window: RenderWindow, bufferView: Float32Array) { const root = legacyCC.director.root; const fv = bufferView; const shadingWidth = Math.floor(window.width); const shadingHeight = Math.floor(window.height); // update UBOGlobal fv[UBOGlobal.TIME_OFFSET] = root.cumulativeTime; fv[UBOGlobal.TIME_OFFSET + 1] = root.frameTime; fv[UBOGlobal.TIME_OFFSET + 2] = legacyCC.director.getTotalFrames(); fv[UBOGlobal.SCREEN_SIZE_OFFSET] = shadingWidth; fv[UBOGlobal.SCREEN_SIZE_OFFSET + 1] = shadingHeight; fv[UBOGlobal.SCREEN_SIZE_OFFSET + 2] = 1.0 / shadingWidth; fv[UBOGlobal.SCREEN_SIZE_OFFSET + 3] = 1.0 / shadingHeight; fv[UBOGlobal.NATIVE_SIZE_OFFSET] = shadingWidth; fv[UBOGlobal.NATIVE_SIZE_OFFSET + 1] = shadingHeight; fv[UBOGlobal.NATIVE_SIZE_OFFSET + 2] = 1.0 / fv[UBOGlobal.NATIVE_SIZE_OFFSET]; fv[UBOGlobal.NATIVE_SIZE_OFFSET + 3] = 1.0 / fv[UBOGlobal.NATIVE_SIZE_OFFSET + 1]; } public static updateCameraUBOView (pipeline: RenderPipeline, bufferView: Float32Array, camera: Camera) { const root = legacyCC.director.root; const scene = camera.scene ? camera.scene : legacyCC.director.getScene().renderScene; const mainLight = scene.mainLight; const sceneData = pipeline.pipelineSceneData; const ambient = sceneData.ambient; const fog = sceneData.fog; const shadingWidth = Math.floor(root.mainWindow.width); const shadingHeight = Math.floor(root.mainWindow.height); const cv = bufferView; const exposure = camera.exposure; const isHDR = sceneData.isHDR; // update camera ubo cv[UBOCamera.SCREEN_SCALE_OFFSET] = camera.width / shadingWidth; cv[UBOCamera.SCREEN_SCALE_OFFSET + 1] = camera.height / shadingHeight; cv[UBOCamera.SCREEN_SCALE_OFFSET + 2] = 1.0 / cv[UBOCamera.SCREEN_SCALE_OFFSET]; cv[UBOCamera.SCREEN_SCALE_OFFSET + 3] = 1.0 / cv[UBOCamera.SCREEN_SCALE_OFFSET + 1]; cv[UBOCamera.EXPOSURE_OFFSET] = exposure; cv[UBOCamera.EXPOSURE_OFFSET + 1] = 1.0 / exposure; cv[UBOCamera.EXPOSURE_OFFSET + 2] = isHDR ? 1.0 : 0.0; cv[UBOCamera.EXPOSURE_OFFSET + 3] = 0.0; if (mainLight) { Vec3.toArray(cv, mainLight.direction, UBOCamera.MAIN_LIT_DIR_OFFSET); Vec3.toArray(cv, mainLight.color, UBOCamera.MAIN_LIT_COLOR_OFFSET); if (mainLight.useColorTemperature) { const colorTempRGB = mainLight.colorTemperatureRGB; cv[UBOCamera.MAIN_LIT_COLOR_OFFSET] *= colorTempRGB.x; cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 1] *= colorTempRGB.y; cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 2] *= colorTempRGB.z; } if (isHDR) { cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 3] = mainLight.illuminance * exposure; } else { cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 3] = mainLight.illuminance; } } else { Vec3.toArray(cv, Vec3.UNIT_Z, UBOCamera.MAIN_LIT_DIR_OFFSET); Vec4.toArray(cv, Vec4.ZERO, UBOCamera.MAIN_LIT_COLOR_OFFSET); } const skyColor = ambient.skyColor; if (isHDR) { skyColor.w = ambient.skyIllum * exposure; } else { skyColor.w = ambient.skyIllum; } cv[UBOCamera.AMBIENT_SKY_OFFSET + 0] = skyColor.x; cv[UBOCamera.AMBIENT_SKY_OFFSET + 1] = skyColor.y; cv[UBOCamera.AMBIENT_SKY_OFFSET + 2] = skyColor.z; cv[UBOCamera.AMBIENT_SKY_OFFSET + 3] = skyColor.w; cv[UBOCamera.AMBIENT_GROUND_OFFSET + 0] = ambient.groundAlbedo.x; cv[UBOCamera.AMBIENT_GROUND_OFFSET + 1] = ambient.groundAlbedo.y; cv[UBOCamera.AMBIENT_GROUND_OFFSET + 2] = ambient.groundAlbedo.z; cv[UBOCamera.AMBIENT_GROUND_OFFSET + 3] = ambient.groundAlbedo.w; Mat4.toArray(cv, camera.matView, UBOCamera.MAT_VIEW_OFFSET); Mat4.toArray(cv, camera.node.worldMatrix, UBOCamera.MAT_VIEW_INV_OFFSET); Vec3.toArray(cv, camera.position, UBOCamera.CAMERA_POS_OFFSET); Mat4.toArray(cv, camera.matProj, UBOCamera.MAT_PROJ_OFFSET); Mat4.toArray(cv, camera.matProjInv, UBOCamera.MAT_PROJ_INV_OFFSET); Mat4.toArray(cv, camera.matViewProj, UBOCamera.MAT_VIEW_PROJ_OFFSET); Mat4.toArray(cv, camera.matViewProjInv, UBOCamera.MAT_VIEW_PROJ_INV_OFFSET); cv[UBOCamera.CAMERA_POS_OFFSET + 3] = this.getCombineSignY(); cv.set(fog.colorArray, UBOCamera.GLOBAL_FOG_COLOR_OFFSET); cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET] = fog.fogStart; cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET + 1] = fog.fogEnd; cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET + 2] = fog.fogDensity; cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET] = fog.fogTop; cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET + 1] = fog.fogRange; cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET + 2] = fog.fogAtten; cv[UBOCamera.NEAR_FAR_OFFSET] = camera.nearClip; cv[UBOCamera.NEAR_FAR_OFFSET + 1] = camera.farClip; cv[UBOCamera.VIEW_PORT_OFFSET] = camera.viewport.x; cv[UBOCamera.VIEW_PORT_OFFSET + 1] = camera.viewport.y; cv[UBOCamera.VIEW_PORT_OFFSET + 1] = camera.viewport.z; cv[UBOCamera.VIEW_PORT_OFFSET + 1] = camera.viewport.w; } public static updateShadowUBOView (pipeline: RenderPipeline, bufferView: Float32Array, camera: Camera) { const device = pipeline.device; const mainLight = camera.scene!.mainLight; const sceneData = pipeline.pipelineSceneData; const shadowInfo = sceneData.shadows; const sv = bufferView; if (shadowInfo.enabled) { if (mainLight && shadowInfo.type === ShadowType.ShadowMap) { let near = 0.1; let far = 0; let matShadowView; let matShadowProj; let matShadowViewProj; if (!shadowInfo.fixedArea) { near = 0.1; far = shadowInfo.shadowCameraFar; matShadowView = shadowInfo.matShadowView; matShadowProj = shadowInfo.matShadowProj; matShadowViewProj = shadowInfo.matShadowViewProj; } else { Mat4.invert(_matShadowView, mainLight.node!.getWorldMatrix()); matShadowView = _matShadowView; const x = shadowInfo.orthoSize; const y = shadowInfo.orthoSize; near = shadowInfo.near; far = shadowInfo.far; Mat4.ortho(_matShadowProj, -x, x, -y, y, near, far, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY); matShadowProj = _matShadowProj; Mat4.multiply(_matShadowViewProj, _matShadowProj, _matShadowView); matShadowViewProj = _matShadowViewProj; } Mat4.toArray(bufferView, matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET); sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowProj.m10; sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowProj.m14; sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowProj.m11; sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowProj.m15; sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 0] = matShadowProj.m00; sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 1] = matShadowProj.m05; sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00; sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05; Mat4.toArray(bufferView, matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); const linear = 0.0; const packing = supportsFloatTexture(device) ? 0.0 : 1.0; sv[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 0] = near; sv[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 1] = far; sv[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 2] = linear; sv[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 3] = 1.0 - shadowInfo.saturation; sv[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x; sv[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 1] = shadowInfo.size.y; sv[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 2] = shadowInfo.pcf; sv[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 3] = shadowInfo.bias; sv[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 0] = 0.0; sv[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing; sv[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = shadowInfo.normalBias; sv[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0; } else if (mainLight && shadowInfo.type === ShadowType.Planar) { updatePlanarPROJ(shadowInfo, mainLight, sv); } Color.toArray(sv, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET); } } public static updateShadowUBOLightView (pipeline: RenderPipeline, bufferView: Float32Array, light: Light) { const device = pipeline.device; const shadowInfo = pipeline.pipelineSceneData.shadows; const sv = bufferView; const linear = 0.0; const packing = supportsFloatTexture(device) ? 0.0 : 1.0; let near = 0.1; let far = 0; let matShadowView; let matShadowProj; let matShadowViewProj; switch (light.type) { case LightType.DIRECTIONAL: if (!shadowInfo.fixedArea) { near = 0.1; far = shadowInfo.shadowCameraFar; matShadowView = shadowInfo.matShadowView; matShadowProj = shadowInfo.matShadowProj; matShadowViewProj = shadowInfo.matShadowViewProj; } else { Mat4.invert(_matShadowView, light.node!.getWorldMatrix()); matShadowView = _matShadowView; const x = shadowInfo.orthoSize; const y = shadowInfo.orthoSize; near = shadowInfo.near; far = shadowInfo.far; Mat4.ortho(_matShadowProj, -x, x, -y, y, near, far, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY); matShadowProj = _matShadowProj; Mat4.multiply(_matShadowViewProj, _matShadowProj, _matShadowView); matShadowViewProj = _matShadowViewProj; } Mat4.toArray(bufferView, matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET); sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowProj.m10; sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowProj.m14; sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowProj.m11; sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowProj.m15; sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 0] = matShadowProj.m00; sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 1] = matShadowProj.m05; sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00; sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05; Mat4.toArray(bufferView, matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); _vec4ShadowInfo.set(near, far, linear, 1.0 - shadowInfo.saturation); Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); _vec4ShadowInfo.set(0.0, packing, shadowInfo.normalBias, 0.0); Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); break; case LightType.SPOT: Mat4.invert(_matShadowView, (light as any).node.getWorldMatrix()); Mat4.toArray(sv, _matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET); Mat4.perspective(_matShadowProj, (light as any).angle, (light as any).aspect, 0.001, (light as any).range); Mat4.multiply(_matShadowViewProj, _matShadowProj, _matShadowView); Mat4.toArray(sv, _matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); _vec4ShadowInfo.set(0.01, (light as SpotLight).range, linear, 1.0 - shadowInfo.saturation); Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); _vec4ShadowInfo.set(1.0, packing, shadowInfo.normalBias, 0.0); Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); break; default: } _vec4ShadowInfo.set(shadowInfo.size.x, shadowInfo.size.y, shadowInfo.pcf, shadowInfo.bias); Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET); Color.toArray(sv, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET); } protected _globalUBO = new Float32Array(UBOGlobal.COUNT); protected _cameraUBO = new Float32Array(UBOCamera.COUNT); protected _shadowUBO = new Float32Array(UBOShadow.COUNT); static _combineSignY = 0; protected declare _device: Device; protected declare _pipeline: RenderPipeline; /** *|combinedSignY|clipSpaceSignY|screenSpaceSignY| Backends | *| :--: | :--: | :--: | :--: | *| 0 | -1 | -1 | Vulkan | *| 1 | 1 | -1 | Metal | *| 2 | -1 | 1 | | *| 3 | 1 | 1 | GL-like | */ public static getCombineSignY () { return PipelineUBO._combineSignY; } private _initCombineSignY () { const device = this._device; PipelineUBO._combineSignY = (device.capabilities.screenSpaceSignY * 0.5 + 0.5) << 1 | (device.capabilities.clipSpaceSignY * 0.5 + 0.5); } public activate (device: Device, pipeline: RenderPipeline) { this._device = device; this._pipeline = pipeline; const ds = this._pipeline.descriptorSet; this._initCombineSignY(); const globalUBO = device.createBuffer(new BufferInfo( BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOGlobal.SIZE, UBOGlobal.SIZE, )); ds.bindBuffer(UBOGlobal.BINDING, globalUBO); const cameraUBO = device.createBuffer(new BufferInfo( BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOCamera.SIZE, UBOCamera.SIZE, )); ds.bindBuffer(UBOCamera.BINDING, cameraUBO); const shadowUBO = device.createBuffer(new BufferInfo( BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOShadow.SIZE, UBOShadow.SIZE, )); ds.bindBuffer(UBOShadow.BINDING, shadowUBO); } /** * @en Update all UBOs * @zh 更新全部 UBO。 */ public updateGlobalUBO (window: RenderWindow) { const globalDSManager = this._pipeline.globalDSManager; const ds = this._pipeline.descriptorSet; const cmdBuffer = this._pipeline.commandBuffers; ds.update(); PipelineUBO.updateGlobalUBOView(window, this._globalUBO); cmdBuffer[0].updateBuffer(ds.getBuffer(UBOGlobal.BINDING), this._globalUBO); globalDSManager.bindBuffer(UBOGlobal.BINDING, ds.getBuffer(UBOGlobal.BINDING)); globalDSManager.update(); } public updateCameraUBO (camera: Camera) { const globalDSManager = this._pipeline.globalDSManager; const ds = this._pipeline.descriptorSet; const cmdBuffer = this._pipeline.commandBuffers; PipelineUBO.updateCameraUBOView(this._pipeline, this._cameraUBO, camera); cmdBuffer[0].updateBuffer(ds.getBuffer(UBOCamera.BINDING), this._cameraUBO); globalDSManager.bindBuffer(UBOCamera.BINDING, ds.getBuffer(UBOCamera.BINDING)); globalDSManager.update(); } public updateShadowUBO (camera: Camera) { const sceneData = this._pipeline.pipelineSceneData; const shadowInfo = sceneData.shadows; if (!shadowInfo.enabled) return; const ds = this._pipeline.descriptorSet; const cmdBuffer = this._pipeline.commandBuffers; const shadowFrameBufferMap = sceneData.shadowFrameBufferMap; const mainLight = camera.scene!.mainLight; ds.update(); if (mainLight && shadowFrameBufferMap.has(mainLight)) { ds.bindTexture(UNIFORM_SHADOWMAP_BINDING, shadowFrameBufferMap.get(mainLight)!.colorTextures[0]!); } PipelineUBO.updateShadowUBOView(this._pipeline, this._shadowUBO, camera); cmdBuffer[0].updateBuffer(ds.getBuffer(UBOShadow.BINDING), this._shadowUBO); } public updateShadowUBOLight (globalDS: DescriptorSet, light: Light) { PipelineUBO.updateShadowUBOLightView(this._pipeline, this._shadowUBO, light); globalDS.getBuffer(UBOShadow.BINDING).update(this._shadowUBO); } public updateShadowUBORange (offset: number, data: Mat4 | Color) { if (data instanceof Mat4) { Mat4.toArray(this._shadowUBO, data, offset); } else if (data instanceof Color) { Color.toArray(this._shadowUBO, data, offset); } } public destroy () { } }
the_stack
import IOTypes from '../../core/IOTypes.js' import bufferToTypedArray from '../../core/bufferToTypedArray.js' import TypedArray from '../../core/TypedArray.js' import Image from '../../core/Image.js' import Mesh from '../../core/Mesh.js' import PolyData from '../../core/vtkPolyData.js' import PipelineEmscriptenModule from '../PipelineEmscriptenModule.js' import PipelineInput from '../PipelineInput.js' import PipelineOutput from '../PipelineOutput.js' import RunPipelineResult from '../RunPipelineResult.js' const haveSharedArrayBuffer = typeof globalThis.SharedArrayBuffer === 'function' function typedArrayForBuffer (typedArrayType: string, buffer: ArrayBuffer): TypedArray { let TypedArrayFunction = null // Node.js // @ts-expect-error: error TS7053: Element implicitly has an 'any' type because // expression of type 'string' can't be used to index type 'Global & // typeof globalThis'. TypedArrayFunction = globalThis[typedArrayType] as TypedArray // @ts-expect-error: error TS2351: This expression is not constructable. return new TypedArrayFunction(buffer) } function readFileSharedArray (emscriptenModule: PipelineEmscriptenModule, path: string): Uint8Array { const opts = { flags: 'r', encoding: 'binary' } const stream = emscriptenModule.fs_open(path, opts.flags) const stat = emscriptenModule.fs_stat(path) const length = stat.size let arrayBufferData = null if (haveSharedArrayBuffer) { arrayBufferData = new SharedArrayBuffer(length) // eslint-disable-line } else { arrayBufferData = new ArrayBuffer(length) } const array = new Uint8Array(arrayBufferData) emscriptenModule.fs_read(stream, array, 0, length, 0) emscriptenModule.fs_close(stream) return array } function runPipelineEmscripten (pipelineModule: PipelineEmscriptenModule, args: string[], outputs: PipelineOutput[] | null, inputs: PipelineInput[] | null): RunPipelineResult { if (!(inputs == null) && inputs.length > 0) { inputs.forEach(function (input) { switch (input.type) { case IOTypes.Text: { pipelineModule.fs_writeFile(input.path, input.data as string) break } case IOTypes.Binary: { pipelineModule.fs_writeFile(input.path, input.data as Uint8Array) break } case IOTypes.Image: { const image = input.data as Image const imageJSON = { imageType: image.imageType, name: image.name, origin: image.origin, spacing: image.spacing, direction: image.direction, size: image.size, data: input.path + '.data' } pipelineModule.fs_writeFile(input.path, JSON.stringify(imageJSON)) if (image.data === null) { throw Error('image.data is null') } pipelineModule.fs_writeFile(imageJSON.data, new Uint8Array(image.data.buffer)) break } case IOTypes.Mesh: { const mesh = input.data as Mesh const meshJSON = { meshType: mesh.meshType, name: mesh.name, numberOfPoints: mesh.numberOfPoints, points: input.path + '.points.data', numberOfPointPixels: mesh.numberOfPointPixels, pointData: input.path + '.pointData.data', numberOfCells: mesh.numberOfCells, cells: input.path + '.cells.data', numberOfCellPixels: mesh.numberOfCellPixels, cellData: input.path + '.cellData.data', cellBufferSize: mesh.cellBufferSize } pipelineModule.fs_writeFile(input.path, JSON.stringify(meshJSON)) if (meshJSON.numberOfPoints > 0) { if (mesh.points === null) { throw Error('mesh.points is null') } pipelineModule.fs_writeFile(meshJSON.points, new Uint8Array(mesh.points.buffer)) } if (meshJSON.numberOfPointPixels > 0) { if (mesh.pointData === null) { throw Error('mesh.pointData is null') } pipelineModule.fs_writeFile(meshJSON.pointData, new Uint8Array(mesh.pointData.buffer)) } if (meshJSON.numberOfCells > 0) { if (mesh.cells === null) { throw Error('mesh.cells is null') } pipelineModule.fs_writeFile(meshJSON.cells, new Uint8Array(mesh.cells.buffer)) } if (meshJSON.numberOfCellPixels > 0) { if (mesh.cellData === null) { throw Error('mesh.cellData is null') } pipelineModule.fs_writeFile(meshJSON.cellData, new Uint8Array(mesh.cellData.buffer)) } break } default: throw Error('Unsupported input IOType') } }) } pipelineModule.resetModuleStdout() pipelineModule.resetModuleStderr() try { pipelineModule.callMain(args) } catch (exception) { // Note: Module must be built with CMAKE_BUILD_TYPE set to Debug. // e.g.: itk-wasm build my/project -- -DCMAKE_BUILD_TYPE:STRING=Debug if (typeof exception === 'number') { console.log('Exception while running pipeline:') console.log('stdout:', pipelineModule.getModuleStdout()) console.error('stderr:', pipelineModule.getModuleStderr()) console.error('exception:', pipelineModule.getExceptionMessage(exception)) } throw exception } const stdout = pipelineModule.getModuleStdout() const stderr = pipelineModule.getModuleStderr() const populatedOutputs: PipelineOutput[] = [] if (!(outputs == null) && outputs.length > 0) { outputs.forEach(function (output) { let outputData: any = null switch (output.type) { case IOTypes.Text: { outputData = pipelineModule.fs_readFile(output.path, { encoding: 'utf8' }) as string break } case IOTypes.Binary: { outputData = readFileSharedArray(pipelineModule, output.path) break } case IOTypes.Image: { const imageJSON = pipelineModule.fs_readFile(output.path, { encoding: 'utf8' }) as string const image = JSON.parse(imageJSON) const dataUint8 = readFileSharedArray(pipelineModule, image.data as string) image.data = bufferToTypedArray(image.imageType.componentType, dataUint8.buffer) outputData = image as Image break } case IOTypes.Mesh: { const meshJSON = pipelineModule.fs_readFile(output.path, { encoding: 'utf8' }) as string const mesh = JSON.parse(meshJSON) if (mesh.numberOfPoints > 0) { const dataUint8Points = readFileSharedArray(pipelineModule, mesh.points) mesh.points = bufferToTypedArray(mesh.meshType.pointComponentType, dataUint8Points.buffer) } else { mesh.points = bufferToTypedArray(mesh.meshType.pointComponentType, new ArrayBuffer(0)) } if (mesh.numberOfPointPixels > 0) { const dataUint8PointData = readFileSharedArray(pipelineModule, mesh.pointData) mesh.pointData = bufferToTypedArray(mesh.meshType.pointPixelComponentType, dataUint8PointData.buffer) } else { mesh.pointData = bufferToTypedArray(mesh.meshType.pointPixelComponentType, new ArrayBuffer(0)) } if (mesh.numberOfCells > 0) { const dataUint8Cells = readFileSharedArray(pipelineModule, mesh.cells) mesh.cells = bufferToTypedArray(mesh.meshType.cellComponentType, dataUint8Cells.buffer) } else { mesh.cells = bufferToTypedArray(mesh.meshType.cellComponentType, new ArrayBuffer(0)) } if (mesh.numberOfCellPixels > 0) { const dataUint8CellData = readFileSharedArray(pipelineModule, mesh.cellData) mesh.cellData = bufferToTypedArray(mesh.meshType.cellPixelComponentType, dataUint8CellData.buffer) } else { mesh.cellData = bufferToTypedArray(mesh.meshType.cellPixelComponentType, new ArrayBuffer(0)) } outputData = mesh as Mesh break } case IOTypes.vtkPolyData: { const polyDataJSON = pipelineModule.fs_readFile(`${output.path}/index.json`, { encoding: 'utf8' }) as string const polyData = JSON.parse(polyDataJSON) const cellTypes = ['points', 'verts', 'lines', 'polys', 'strips'] cellTypes.forEach((cellName) => { if (polyData[cellName] !== undefined) { const cell = polyData[cellName] if (cell.ref !== null) { const dataUint8 = readFileSharedArray(pipelineModule, `${output.path}/${cell.ref.basepath}/${cell.ref.id}`) // eslint-disable-line polyData[cellName].buffer = dataUint8.buffer polyData[cellName].values = typedArrayForBuffer(polyData[cellName].dataType, dataUint8.buffer) delete cell.ref } } }) const dataSetType = ['pointData', 'cellData', 'fieldData'] dataSetType.forEach((dataName) => { if (polyData[dataName] !== undefined) { const data = polyData[dataName] data.arrays.forEach((array: { data: { ref?: { basepath: string, id: string }, buffer: ArrayBuffer, values: TypedArray, dataType: string }}) => { if (array.data.ref !== null && array.data.ref !== undefined) { const dataUint8 = readFileSharedArray(pipelineModule, `${output.path}/${array.data.ref.basepath}/${array.data.ref.id}`) array.data.buffer = dataUint8.buffer array.data.values = typedArrayForBuffer(array.data.dataType, dataUint8.buffer) delete array.data.ref } }) } }) outputData = polyData as PolyData break } default: throw Error('Unsupported output IOType') } const populatedOutput = { path: output.path, type: output.type, data: outputData } populatedOutputs.push(populatedOutput) }) } return { stdout, stderr, outputs: populatedOutputs } } export default runPipelineEmscripten
the_stack
import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; import {logger} from 'workbox-core/_private/logger.js'; import {assert} from 'workbox-core/_private/assert.js'; import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js'; import {UnidentifiedQueueStoreEntry, QueueStore} from './lib/QueueStore.js'; import {StorableRequest} from './lib/StorableRequest.js'; import './_version.js'; // Give TypeScript the correct global. declare let self: ServiceWorkerGlobalScope; interface OnSyncCallbackOptions { queue: Queue; } interface OnSyncCallback { (options: OnSyncCallbackOptions): void|Promise<void>; } export interface QueueOptions { onSync?: OnSyncCallback; maxRetentionTime?: number; } interface QueueEntry { request: Request; timestamp?: number; metadata?: object; } const TAG_PREFIX = 'workbox-background-sync'; const MAX_RETENTION_TIME = 60 * 24 * 7; // 7 days in minutes const queueNames = new Set(); /** * Converts a QueueStore entry into the format exposed by Queue. This entails * converting the request data into a real request and omitting the `id` and * `queueName` properties. * * @param {Object} queueStoreEntry * @return {Object} * @private */ const convertEntry = (queueStoreEntry: UnidentifiedQueueStoreEntry): QueueEntry => { const queueEntry: QueueEntry = { request: new StorableRequest(queueStoreEntry.requestData).toRequest(), timestamp: queueStoreEntry.timestamp, }; if (queueStoreEntry.metadata) { queueEntry.metadata = queueStoreEntry.metadata; } return queueEntry; }; /** * A class to manage storing failed requests in IndexedDB and retrying them * later. All parts of the storing and replaying process are observable via * callbacks. * * @memberof module:workbox-background-sync */ class Queue { private readonly _name: string; private readonly _onSync: OnSyncCallback; private readonly _maxRetentionTime: number; private readonly _queueStore: QueueStore; private _syncInProgress = false; private _requestsAddedDuringSync = false; /** * Creates an instance of Queue with the given options * * @param {string} name The unique name for this queue. This name must be * unique as it's used to register sync events and store requests * in IndexedDB specific to this instance. An error will be thrown if * a duplicate name is detected. * @param {Object} [options] * @param {Function} [options.onSync] A function that gets invoked whenever * the 'sync' event fires. The function is invoked with an object * containing the `queue` property (referencing this instance), and you * can use the callback to customize the replay behavior of the queue. * When not set the `replayRequests()` method is called. * Note: if the replay fails after a sync event, make sure you throw an * error, so the browser knows to retry the sync event later. * @param {number} [options.maxRetentionTime=7 days] The amount of time (in * minutes) a request may be retried. After this amount of time has * passed, the request will be deleted from the queue. */ constructor(name: string, { onSync, maxRetentionTime }: QueueOptions = {}) { // Ensure the store name is not already being used if (queueNames.has(name)) { throw new WorkboxError('duplicate-queue-name', {name}); } else { queueNames.add(name); } this._name = name; this._onSync = onSync || this.replayRequests; this._maxRetentionTime = maxRetentionTime || MAX_RETENTION_TIME; this._queueStore = new QueueStore(this._name); this._addSyncListener(); } /** * @return {string} */ get name() { return this._name; } /** * Stores the passed request in IndexedDB (with its timestamp and any * metadata) at the end of the queue. * * @param {Object} entry * @param {Request} entry.request The request to store in the queue. * @param {Object} [entry.metadata] Any metadata you want associated with the * stored request. When requests are replayed you'll have access to this * metadata object in case you need to modify the request beforehand. * @param {number} [entry.timestamp] The timestamp (Epoch time in * milliseconds) when the request was first added to the queue. This is * used along with `maxRetentionTime` to remove outdated requests. In * general you don't need to set this value, as it's automatically set * for you (defaulting to `Date.now()`), but you can update it if you * don't want particular requests to expire. */ async pushRequest(entry: QueueEntry) { if (process.env.NODE_ENV !== 'production') { assert!.isType(entry, 'object', { moduleName: 'workbox-background-sync', className: 'Queue', funcName: 'pushRequest', paramName: 'entry', }); assert!.isInstance(entry.request, Request, { moduleName: 'workbox-background-sync', className: 'Queue', funcName: 'pushRequest', paramName: 'entry.request', }); } await this._addRequest(entry, 'push'); } /** * Stores the passed request in IndexedDB (with its timestamp and any * metadata) at the beginning of the queue. * * @param {Object} entry * @param {Request} entry.request The request to store in the queue. * @param {Object} [entry.metadata] Any metadata you want associated with the * stored request. When requests are replayed you'll have access to this * metadata object in case you need to modify the request beforehand. * @param {number} [entry.timestamp] The timestamp (Epoch time in * milliseconds) when the request was first added to the queue. This is * used along with `maxRetentionTime` to remove outdated requests. In * general you don't need to set this value, as it's automatically set * for you (defaulting to `Date.now()`), but you can update it if you * don't want particular requests to expire. */ async unshiftRequest(entry: QueueEntry) { if (process.env.NODE_ENV !== 'production') { assert!.isType(entry, 'object', { moduleName: 'workbox-background-sync', className: 'Queue', funcName: 'unshiftRequest', paramName: 'entry', }); assert!.isInstance(entry.request, Request, { moduleName: 'workbox-background-sync', className: 'Queue', funcName: 'unshiftRequest', paramName: 'entry.request', }); } await this._addRequest(entry, 'unshift'); } /** * Removes and returns the last request in the queue (along with its * timestamp and any metadata). The returned object takes the form: * `{request, timestamp, metadata}`. * * @return {Promise<Object>} */ async popRequest() { return this._removeRequest('pop'); } /** * Removes and returns the first request in the queue (along with its * timestamp and any metadata). The returned object takes the form: * `{request, timestamp, metadata}`. * * @return {Promise<Object>} */ async shiftRequest() { return this._removeRequest('shift'); } /** * Returns all the entries that have not expired (per `maxRetentionTime`). * Any expired entries are removed from the queue. * * @return {Promise<Array<Object>>} */ async getAll() { const allEntries = await this._queueStore.getAll(); const now = Date.now(); const unexpiredEntries = []; for (const entry of allEntries) { // Ignore requests older than maxRetentionTime. Call this function // recursively until an unexpired request is found. const maxRetentionTimeInMs = this._maxRetentionTime * 60 * 1000; if (now - entry.timestamp > maxRetentionTimeInMs) { await this._queueStore.deleteEntry(entry.id); } else { unexpiredEntries.push(convertEntry(entry)); } } return unexpiredEntries; } /** * Adds the entry to the QueueStore and registers for a sync event. * * @param {Object} entry * @param {Request} entry.request * @param {Object} [entry.metadata] * @param {number} [entry.timestamp=Date.now()] * @param {string} operation ('push' or 'unshift') * @private */ async _addRequest({ request, metadata, timestamp = Date.now(), }: QueueEntry, operation: 'push' | 'unshift') { const storableRequest = await StorableRequest.fromRequest(request.clone()); const entry: UnidentifiedQueueStoreEntry = { requestData: storableRequest.toObject(), timestamp, }; // Only include metadata if it's present. if (metadata) { entry.metadata = metadata; } await this._queueStore[ `${operation}Entry` as 'pushEntry' | 'unshiftEntry'](entry); if (process.env.NODE_ENV !== 'production') { logger.log(`Request for '${getFriendlyURL(request.url)}' has ` + `been added to background sync queue '${this._name}'.`); } // Don't register for a sync if we're in the middle of a sync. Instead, // we wait until the sync is complete and call register if // `this._requestsAddedDuringSync` is true. if (this._syncInProgress) { this._requestsAddedDuringSync = true; } else { await this.registerSync(); } } /** * Removes and returns the first or last (depending on `operation`) entry * from the QueueStore that's not older than the `maxRetentionTime`. * * @param {string} operation ('pop' or 'shift') * @return {Object|undefined} * @private */ async _removeRequest(operation: 'pop' | 'shift'): Promise<QueueEntry | undefined> { const now = Date.now(); const entry = await this._queueStore[ `${operation}Entry` as 'popEntry' | 'shiftEntry'](); if (entry) { // Ignore requests older than maxRetentionTime. Call this function // recursively until an unexpired request is found. const maxRetentionTimeInMs = this._maxRetentionTime * 60 * 1000; if (now - entry.timestamp > maxRetentionTimeInMs) { return this._removeRequest(operation); } return convertEntry(entry); } else { return undefined; } } /** * Loops through each request in the queue and attempts to re-fetch it. * If any request fails to re-fetch, it's put back in the same position in * the queue (which registers a retry for the next sync event). */ async replayRequests() { let entry; while (entry = await this.shiftRequest()) { try { await fetch(entry.request.clone()); if (process.env.NODE_ENV !== 'production') { logger.log(`Request for '${getFriendlyURL(entry.request.url)}'` + `has been replayed in queue '${this._name}'`); } } catch (error) { await this.unshiftRequest(entry); if (process.env.NODE_ENV !== 'production') { logger.log(`Request for '${getFriendlyURL(entry.request.url)}'` + `failed to replay, putting it back in queue '${this._name}'`); } throw new WorkboxError('queue-replay-failed', {name: this._name}); } } if (process.env.NODE_ENV !== 'production') { logger.log(`All requests in queue '${this.name}' have successfully ` + `replayed; the queue is now empty!`); } } /** * Registers a sync event with a tag unique to this instance. */ async registerSync() { if ('sync' in self.registration) { try { await self.registration.sync.register(`${TAG_PREFIX}:${this._name}`); } catch (err) { // This means the registration failed for some reason, possibly due to // the user disabling it. if (process.env.NODE_ENV !== 'production') { logger.warn( `Unable to register sync event for '${this._name}'.`, err); } } } } /** * In sync-supporting browsers, this adds a listener for the sync event. * In non-sync-supporting browsers, this will retry the queue on service * worker startup. * * @private */ private _addSyncListener() { if ('sync' in self.registration) { self.addEventListener('sync', (event: SyncEvent) => { if (event.tag === `${TAG_PREFIX}:${this._name}`) { if (process.env.NODE_ENV !== 'production') { logger.log(`Background sync for tag '${event.tag}'` + `has been received`); } const syncComplete = async () => { this._syncInProgress = true; let syncError; try { await this._onSync({queue: this}); } catch (error) { syncError = error; // Rethrow the error. Note: the logic in the finally clause // will run before this gets rethrown. throw syncError; } finally { // New items may have been added to the queue during the sync, // so we need to register for a new sync if that's happened... // Unless there was an error during the sync, in which // case the browser will automatically retry later, as long // as `event.lastChance` is not true. if (this._requestsAddedDuringSync && !(syncError && !event.lastChance)) { await this.registerSync(); } this._syncInProgress = false; this._requestsAddedDuringSync = false; } }; event.waitUntil(syncComplete()); } }); } else { if (process.env.NODE_ENV !== 'production') { logger.log(`Background sync replaying without background sync event`); } // If the browser doesn't support background sync, retry // every time the service worker starts up as a fallback. this._onSync({queue: this}); } } /** * Returns the set of queue names. This is primarily used to reset the list * of queue names in tests. * * @return {Set} * * @private */ static get _queueNames() { return queueNames; } } export {Queue};
the_stack
import type { Rule, SourceCode } from "eslint" import type { ScopeManager, Scope } from "eslint-scope" import type { ESLintExtendedProgram, Node, OffsetRange, VDocumentFragment, VElement, VExpressionContainer, VText, } from "../../ast" import { getFallbackKeys, ParseError } from "../../ast" import { getEslintScope } from "../../common/eslint-scope" import { getEcmaVersionIfUseEspree } from "../../common/espree" import { fixErrorLocation, fixLocations } from "../../common/fix-locations" import type { LocationCalculatorForHtml } from "../../common/location-calculator" import type { ParserOptions } from "../../common/parser-options" import { DEFAULT_ECMA_VERSION } from "../../script-setup/parser-options" export interface ESLintCustomBlockParser { parse(code: string, options: any): any parseForESLint?(code: string, options: any): any } export type CustomBlockContext = { getSourceCode(): SourceCode parserServices: any getAncestors(): any[] getDeclaredVariables(node: any): any[] getScope(): any markVariableAsUsed(name: string): boolean // Same as the original context. id: string options: any[] settings: { [name: string]: any } parserPath: string parserOptions: any getFilename(): string report(descriptor: Rule.ReportDescriptor): void } /** * Checks whether the given node is VElement. */ function isVElement( node: VElement | VExpressionContainer | VText, ): node is VElement { return node.type === "VElement" } /** * Get the all custom blocks from given document * @param document */ export function getCustomBlocks( document: VDocumentFragment | null, ): VElement[] { return document ? document.children .filter(isVElement) .filter( (block) => block.name !== "script" && block.name !== "template" && block.name !== "style", ) : [] } /** * Parse the source code of the given custom block element. * @param node The custom block element to parse. * @param parser The custom parser. * @param globalLocationCalculator The location calculator for fixLocations. * @param parserOptions The parser options. * @returns The result of parsing. */ export function parseCustomBlockElement( node: VElement, parser: ESLintCustomBlockParser, globalLocationCalculator: LocationCalculatorForHtml, parserOptions: ParserOptions, ): ESLintExtendedProgram & { error?: ParseError | Error } { const text = node.children[0] const { code, range, loc } = text != null && text.type === "VText" ? { code: text.value, range: text.range, loc: text.loc, } : { code: "", range: [ node.startTag.range[1], node.endTag!.range[0], ] as OffsetRange, loc: { start: node.startTag.loc.end, end: node.endTag!.loc.start, }, } const locationCalculator = globalLocationCalculator.getSubCalculatorAfter( range[0], ) try { return parseCustomBlockFragment( code, parser, locationCalculator, parserOptions, ) } catch (e) { if (!(e instanceof Error)) { throw e } return { error: e, ast: { type: "Program", sourceType: "module", loc: { start: { ...loc.start, }, end: { ...loc.end, }, }, range: [...range], body: [], tokens: [], comments: [], }, } } } /** * Parse the given source code. * * @param code The source code to parse. * @param parser The custom parser. * @param locationCalculator The location calculator for fixLocations. * @param parserOptions The parser options. * @returns The result of parsing. */ function parseCustomBlockFragment( code: string, parser: ESLintCustomBlockParser, locationCalculator: LocationCalculatorForHtml, parserOptions: ParserOptions, ): ESLintExtendedProgram { try { const result = parseBlock(code, parser, { ecmaVersion: DEFAULT_ECMA_VERSION, loc: true, range: true, raw: true, tokens: true, comment: true, eslintVisitorKeys: true, eslintScopeManager: true, ...parserOptions, }) fixLocations(result, locationCalculator) return result } catch (err) { const perr = ParseError.normalize(err) if (perr) { fixErrorLocation(perr, locationCalculator) throw perr } throw err } } function parseBlock( code: string, parser: ESLintCustomBlockParser, parserOptions: any, ): any { const result: any = typeof parser.parseForESLint === "function" ? parser.parseForESLint(code, parserOptions) : parser.parse(code, parserOptions) if (result.ast != null) { return result } return { ast: result } } /** * Create shared context. * * @param text The source code of SFC. * @param customBlock The custom block node. * @param parsedResult The parse result data * @param parserOptions The parser options. */ export function createCustomBlockSharedContext({ text, customBlock, parsedResult, globalLocationCalculator, parserOptions, }: { text: string customBlock: VElement parsedResult: ESLintExtendedProgram & { error?: ParseError | Error } globalLocationCalculator: LocationCalculatorForHtml parserOptions: any }) { let sourceCode: SourceCode let scopeManager: ScopeManager let currentNode: any return { serCurrentNode(node: any) { currentNode = node }, context: { getAncestors: () => getAncestors(currentNode), getDeclaredVariables: (...args: any[]) => // @ts-expect-error -- ignore getScopeManager().getDeclaredVariables(...args), getScope: () => getScope(getScopeManager(), currentNode), markVariableAsUsed: (name: string) => markVariableAsUsed( getScopeManager(), currentNode, parserOptions, name, ), parserServices: { customBlock, parseCustomBlockElement( parser: ESLintCustomBlockParser, options: any, ) { return parseCustomBlockElement( customBlock, parser, globalLocationCalculator, { ...parserOptions, ...options }, ) }, ...(parsedResult.services || {}), ...(parsedResult.error ? { parseError: parsedResult.error } : {}), }, getSourceCode, }, } function getSourceCode() { return ( sourceCode || // eslint-disable-next-line @typescript-eslint/no-require-imports (sourceCode = new (require("eslint").SourceCode)({ text, ast: parsedResult.ast, parserServices: parsedResult.services, scopeManager: getScopeManager(), visitorKeys: parsedResult.visitorKeys, })) ) } function getScopeManager() { if (parsedResult.scopeManager || scopeManager) { return parsedResult.scopeManager || scopeManager } const ecmaVersion = getEcmaVersionIfUseEspree(parserOptions) || 2022 const ecmaFeatures = parserOptions.ecmaFeatures || {} const sourceType = parserOptions.sourceType || "script" scopeManager = getEslintScope().analyze(parsedResult.ast, { ignoreEval: true, nodejsScope: false, impliedStrict: ecmaFeatures.impliedStrict, ecmaVersion, sourceType, fallback: getFallbackKeys, }) return scopeManager } } /* The following source code is copied from `eslint/lib/linter/linter.js` */ /** * Gets all the ancestors of a given node * @param {ASTNode} node The node * @returns {ASTNode[]} All the ancestor nodes in the AST, not including the provided node, starting * from the root node and going inwards to the parent node. */ function getAncestors(node: Node) { const ancestorsStartingAtParent = [] for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) { ancestorsStartingAtParent.push(ancestor) } return ancestorsStartingAtParent.reverse() } /** * Gets the scope for the current node * @param {ScopeManager} scopeManager The scope manager for this AST * @param {ASTNode} currentNode The node to get the scope of * @returns {eslint-scope.Scope} The scope information for this node */ function getScope(scopeManager: ScopeManager, currentNode: Node) { // On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope. const inner = currentNode.type !== "Program" for ( let node: Node | null = currentNode; node; node = node.parent || null ) { const scope = scopeManager.acquire(node as any, inner) if (scope) { if (scope.type === "function-expression-name") { return scope.childScopes[0] } return scope } } return scopeManager.scopes[0] } /** * Marks a variable as used in the current scope * @param {ScopeManager} scopeManager The scope manager for this AST. The scope may be mutated by this function. * @param {ASTNode} currentNode The node currently being traversed * @param {Object} parserOptions The options used to parse this text * @param {string} name The name of the variable that should be marked as used. * @returns {boolean} True if the variable was found and marked as used, false if not. */ function markVariableAsUsed( scopeManager: ScopeManager, currentNode: Node, parserOptions: any, name: string, ) { const hasGlobalReturn = parserOptions.ecmaFeatures && parserOptions.ecmaFeatures.globalReturn const specialScope = hasGlobalReturn || parserOptions.sourceType === "module" const currentScope = getScope(scopeManager, currentNode) // Special Node.js scope means we need to start one level deeper const initialScope = currentScope.type === "global" && specialScope ? currentScope.childScopes[0] : currentScope for (let scope: Scope | null = initialScope; scope; scope = scope.upper) { const variable = scope.variables.find( (scopeVar) => scopeVar.name === name, ) if (variable) { // @ts-expect-error -- ignore variable.eslintUsed = true return true } } return false }
the_stack
import { TwirpContext, TwirpServer, RouterEvents, TwirpError, TwirpErrorCode, Interceptor, TwirpContentType, chainInterceptors, } from "twirp-ts"; import { Size, Hat, FindHatRPC, ListHatRPC } from "./service"; //==================================// // Client Code // //==================================// interface Rpc { request( service: string, method: string, contentType: "application/json" | "application/protobuf", data: object | Uint8Array ): Promise<object | Uint8Array>; } export interface HaberdasherClient { MakeHat(request: Size): Promise<Hat>; FindHat(request: FindHatRPC): Promise<FindHatRPC>; ListHat(request: ListHatRPC): Promise<ListHatRPC>; } export class HaberdasherClientJSON implements HaberdasherClient { private readonly rpc: Rpc; constructor(rpc: Rpc) { this.rpc = rpc; this.MakeHat.bind(this); this.FindHat.bind(this); this.ListHat.bind(this); } MakeHat(request: Size): Promise<Hat> { const data = Size.toJson(request, { useProtoFieldName: true, emitDefaultValues: false, }); const promise = this.rpc.request( "twirp.example.haberdasher.Haberdasher", "MakeHat", "application/json", data as object ); return promise.then((data) => Hat.fromJson(data as any, { ignoreUnknownFields: true }) ); } FindHat(request: FindHatRPC): Promise<FindHatRPC> { const data = FindHatRPC.toJson(request, { useProtoFieldName: true, emitDefaultValues: false, }); const promise = this.rpc.request( "twirp.example.haberdasher.Haberdasher", "FindHat", "application/json", data as object ); return promise.then((data) => FindHatRPC.fromJson(data as any, { ignoreUnknownFields: true }) ); } ListHat(request: ListHatRPC): Promise<ListHatRPC> { const data = ListHatRPC.toJson(request, { useProtoFieldName: true, emitDefaultValues: false, }); const promise = this.rpc.request( "twirp.example.haberdasher.Haberdasher", "ListHat", "application/json", data as object ); return promise.then((data) => ListHatRPC.fromJson(data as any, { ignoreUnknownFields: true }) ); } } export class HaberdasherClientProtobuf implements HaberdasherClient { private readonly rpc: Rpc; constructor(rpc: Rpc) { this.rpc = rpc; this.MakeHat.bind(this); this.FindHat.bind(this); this.ListHat.bind(this); } MakeHat(request: Size): Promise<Hat> { const data = Size.toBinary(request); const promise = this.rpc.request( "twirp.example.haberdasher.Haberdasher", "MakeHat", "application/protobuf", data ); return promise.then((data) => Hat.fromBinary(data as Uint8Array)); } FindHat(request: FindHatRPC): Promise<FindHatRPC> { const data = FindHatRPC.toBinary(request); const promise = this.rpc.request( "twirp.example.haberdasher.Haberdasher", "FindHat", "application/protobuf", data ); return promise.then((data) => FindHatRPC.fromBinary(data as Uint8Array)); } ListHat(request: ListHatRPC): Promise<ListHatRPC> { const data = ListHatRPC.toBinary(request); const promise = this.rpc.request( "twirp.example.haberdasher.Haberdasher", "ListHat", "application/protobuf", data ); return promise.then((data) => ListHatRPC.fromBinary(data as Uint8Array)); } } //==================================// // Server Code // //==================================// export interface HaberdasherTwirp<T extends TwirpContext = TwirpContext> { MakeHat(ctx: T, request: Size): Promise<Hat>; FindHat(ctx: T, request: FindHatRPC): Promise<FindHatRPC>; ListHat(ctx: T, request: ListHatRPC): Promise<ListHatRPC>; } export enum HaberdasherMethod { MakeHat = "MakeHat", FindHat = "FindHat", ListHat = "ListHat", } export const HaberdasherMethodList = [ HaberdasherMethod.MakeHat, HaberdasherMethod.FindHat, HaberdasherMethod.ListHat, ]; export function createHaberdasherServer<T extends TwirpContext = TwirpContext>( service: HaberdasherTwirp<T> ) { return new TwirpServer<HaberdasherTwirp, T>({ service, packageName: "twirp.example.haberdasher", serviceName: "Haberdasher", methodList: HaberdasherMethodList, matchRoute: matchHaberdasherRoute, }); } function matchHaberdasherRoute<T extends TwirpContext = TwirpContext>( method: string, events: RouterEvents<T> ) { switch (method) { case "MakeHat": return async ( ctx: T, service: HaberdasherTwirp, data: Buffer, interceptors?: Interceptor<T, Size, Hat>[] ) => { ctx = { ...ctx, methodName: "MakeHat" }; await events.onMatch(ctx); return handleMakeHatRequest(ctx, service, data, interceptors); }; case "FindHat": return async ( ctx: T, service: HaberdasherTwirp, data: Buffer, interceptors?: Interceptor<T, FindHatRPC, FindHatRPC>[] ) => { ctx = { ...ctx, methodName: "FindHat" }; await events.onMatch(ctx); return handleFindHatRequest(ctx, service, data, interceptors); }; case "ListHat": return async ( ctx: T, service: HaberdasherTwirp, data: Buffer, interceptors?: Interceptor<T, ListHatRPC, ListHatRPC>[] ) => { ctx = { ...ctx, methodName: "ListHat" }; await events.onMatch(ctx); return handleListHatRequest(ctx, service, data, interceptors); }; default: events.onNotFound(); const msg = `no handler found`; throw new TwirpError(TwirpErrorCode.BadRoute, msg); } } function handleMakeHatRequest<T extends TwirpContext = TwirpContext>( ctx: T, service: HaberdasherTwirp, data: Buffer, interceptors?: Interceptor<T, Size, Hat>[] ): Promise<string | Uint8Array> { switch (ctx.contentType) { case TwirpContentType.JSON: return handleMakeHatJSON<T>(ctx, service, data, interceptors); case TwirpContentType.Protobuf: return handleMakeHatProtobuf<T>(ctx, service, data, interceptors); default: const msg = "unexpected Content-Type"; throw new TwirpError(TwirpErrorCode.BadRoute, msg); } } function handleFindHatRequest<T extends TwirpContext = TwirpContext>( ctx: T, service: HaberdasherTwirp, data: Buffer, interceptors?: Interceptor<T, FindHatRPC, FindHatRPC>[] ): Promise<string | Uint8Array> { switch (ctx.contentType) { case TwirpContentType.JSON: return handleFindHatJSON<T>(ctx, service, data, interceptors); case TwirpContentType.Protobuf: return handleFindHatProtobuf<T>(ctx, service, data, interceptors); default: const msg = "unexpected Content-Type"; throw new TwirpError(TwirpErrorCode.BadRoute, msg); } } function handleListHatRequest<T extends TwirpContext = TwirpContext>( ctx: T, service: HaberdasherTwirp, data: Buffer, interceptors?: Interceptor<T, ListHatRPC, ListHatRPC>[] ): Promise<string | Uint8Array> { switch (ctx.contentType) { case TwirpContentType.JSON: return handleListHatJSON<T>(ctx, service, data, interceptors); case TwirpContentType.Protobuf: return handleListHatProtobuf<T>(ctx, service, data, interceptors); default: const msg = "unexpected Content-Type"; throw new TwirpError(TwirpErrorCode.BadRoute, msg); } } async function handleMakeHatJSON<T extends TwirpContext = TwirpContext>( ctx: T, service: HaberdasherTwirp, data: Buffer, interceptors?: Interceptor<T, Size, Hat>[] ) { let request: Size; let response: Hat; try { const body = JSON.parse(data.toString() || "{}"); request = Size.fromJson(body, { ignoreUnknownFields: true }); } catch (e) { if (e instanceof Error) { const msg = "the json request could not be decoded"; throw new TwirpError(TwirpErrorCode.Malformed, msg).withCause(e, true); } } if (interceptors && interceptors.length > 0) { const interceptor = chainInterceptors(...interceptors) as Interceptor< T, Size, Hat >; response = await interceptor(ctx, request!, (ctx, inputReq) => { return service.MakeHat(ctx, inputReq); }); } else { response = await service.MakeHat(ctx, request!); } return JSON.stringify( Hat.toJson(response, { useProtoFieldName: true, emitDefaultValues: false, }) as string ); } async function handleFindHatJSON<T extends TwirpContext = TwirpContext>( ctx: T, service: HaberdasherTwirp, data: Buffer, interceptors?: Interceptor<T, FindHatRPC, FindHatRPC>[] ) { let request: FindHatRPC; let response: FindHatRPC; try { const body = JSON.parse(data.toString() || "{}"); request = FindHatRPC.fromJson(body, { ignoreUnknownFields: true }); } catch (e) { if (e instanceof Error) { const msg = "the json request could not be decoded"; throw new TwirpError(TwirpErrorCode.Malformed, msg).withCause(e, true); } } if (interceptors && interceptors.length > 0) { const interceptor = chainInterceptors(...interceptors) as Interceptor< T, FindHatRPC, FindHatRPC >; response = await interceptor(ctx, request!, (ctx, inputReq) => { return service.FindHat(ctx, inputReq); }); } else { response = await service.FindHat(ctx, request!); } return JSON.stringify( FindHatRPC.toJson(response, { useProtoFieldName: true, emitDefaultValues: false, }) as string ); } async function handleListHatJSON<T extends TwirpContext = TwirpContext>( ctx: T, service: HaberdasherTwirp, data: Buffer, interceptors?: Interceptor<T, ListHatRPC, ListHatRPC>[] ) { let request: ListHatRPC; let response: ListHatRPC; try { const body = JSON.parse(data.toString() || "{}"); request = ListHatRPC.fromJson(body, { ignoreUnknownFields: true }); } catch (e) { if (e instanceof Error) { const msg = "the json request could not be decoded"; throw new TwirpError(TwirpErrorCode.Malformed, msg).withCause(e, true); } } if (interceptors && interceptors.length > 0) { const interceptor = chainInterceptors(...interceptors) as Interceptor< T, ListHatRPC, ListHatRPC >; response = await interceptor(ctx, request!, (ctx, inputReq) => { return service.ListHat(ctx, inputReq); }); } else { response = await service.ListHat(ctx, request!); } return JSON.stringify( ListHatRPC.toJson(response, { useProtoFieldName: true, emitDefaultValues: false, }) as string ); } async function handleMakeHatProtobuf<T extends TwirpContext = TwirpContext>( ctx: T, service: HaberdasherTwirp, data: Buffer, interceptors?: Interceptor<T, Size, Hat>[] ) { let request: Size; let response: Hat; try { request = Size.fromBinary(data); } catch (e) { if (e instanceof Error) { const msg = "the protobuf request could not be decoded"; throw new TwirpError(TwirpErrorCode.Malformed, msg).withCause(e, true); } } if (interceptors && interceptors.length > 0) { const interceptor = chainInterceptors(...interceptors) as Interceptor< T, Size, Hat >; response = await interceptor(ctx, request!, (ctx, inputReq) => { return service.MakeHat(ctx, inputReq); }); } else { response = await service.MakeHat(ctx, request!); } return Buffer.from(Hat.toBinary(response)); } async function handleFindHatProtobuf<T extends TwirpContext = TwirpContext>( ctx: T, service: HaberdasherTwirp, data: Buffer, interceptors?: Interceptor<T, FindHatRPC, FindHatRPC>[] ) { let request: FindHatRPC; let response: FindHatRPC; try { request = FindHatRPC.fromBinary(data); } catch (e) { if (e instanceof Error) { const msg = "the protobuf request could not be decoded"; throw new TwirpError(TwirpErrorCode.Malformed, msg).withCause(e, true); } } if (interceptors && interceptors.length > 0) { const interceptor = chainInterceptors(...interceptors) as Interceptor< T, FindHatRPC, FindHatRPC >; response = await interceptor(ctx, request!, (ctx, inputReq) => { return service.FindHat(ctx, inputReq); }); } else { response = await service.FindHat(ctx, request!); } return Buffer.from(FindHatRPC.toBinary(response)); } async function handleListHatProtobuf<T extends TwirpContext = TwirpContext>( ctx: T, service: HaberdasherTwirp, data: Buffer, interceptors?: Interceptor<T, ListHatRPC, ListHatRPC>[] ) { let request: ListHatRPC; let response: ListHatRPC; try { request = ListHatRPC.fromBinary(data); } catch (e) { if (e instanceof Error) { const msg = "the protobuf request could not be decoded"; throw new TwirpError(TwirpErrorCode.Malformed, msg).withCause(e, true); } } if (interceptors && interceptors.length > 0) { const interceptor = chainInterceptors(...interceptors) as Interceptor< T, ListHatRPC, ListHatRPC >; response = await interceptor(ctx, request!, (ctx, inputReq) => { return service.ListHat(ctx, inputReq); }); } else { response = await service.ListHat(ctx, request!); } return Buffer.from(ListHatRPC.toBinary(response)); }
the_stack
import { expect } from "chai"; import { IModelDb, IModelHost, SnapshotDb } from "@itwin/core-backend"; import { DbResult, QueryRowFormat } from "@itwin/core-common"; import { Presentation } from "@itwin/presentation-backend"; describe("#performance Element properties loading", () => { let imodel: SnapshotDb; before(async () => { await IModelHost.startup(); Presentation.initialize({ useMmap: true, }); }); after(async () => { await IModelHost.shutdown(); Presentation.terminate(); }); beforeEach(() => { const testIModelName: string = "assets/datasets/15gb.bim"; imodel = SnapshotDb.openFile(testIModelName); expect(imodel).is.not.null; }); it("load properties using 'getElementProperties'", async function () { const startTime = (new Date()).getTime(); let propertiesCount = 0; const { total, iterator } = await Presentation.getManager().getElementProperties({ imodel }); process.stdout.write(`Loading properties for ${total} elements.`); for await (const items of iterator()) { propertiesCount += items.length; process.stdout.write("."); } process.stdout.write(`\nLoaded ${propertiesCount} elements properties in ${(new Date()).getTime() - startTime} ms`); }); it("load properties using ECSQL", async function () { const startTime = new Date().getTime(); process.stdout.write(`Loading properties.`); let propertiesCount = 0; for await (const _properties of getElementsPropertiesECSQL(imodel)) { propertiesCount++; if (propertiesCount % 1000 === 0) process.stdout.write("."); } process.stdout.write(`\nLoaded ${propertiesCount} elements properties in ${(new Date()).getTime() - startTime} ms`); }); }); async function* getElementsPropertiesECSQL(db: IModelDb) { const query = ` SELECT el.ECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className FROM bis.Element el JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = el.ECClassId JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id`; for await (const row of db.query(query, undefined, { abbreviateBlobs: true, rowFormat: QueryRowFormat.UseJsPropertyNames })) { const properties = loadElementProperties(db, row.className, row.id); expect(properties.id).to.be.eq(row.id); yield properties; } } function loadElementProperties(db: IModelDb, className: string, elementId: string) { const elementProperties = loadProperties(db, className, [elementId], true); return { ...elementProperties[0], ...(loadRelatedProperties(db, () => queryGeometricElement3dTypeDefinitions(db, elementId), true)), ...(loadRelatedProperties(db, () => queryGeometricElement2dTypeDefinitions(db, elementId), true)), ...(loadRelatedProperties(db, () => queryElementLinks(db, elementId), false)), ...(loadRelatedProperties(db, () => queryGroupElementLinks(db, elementId), false)), ...(loadRelatedProperties(db, () => queryModelLinks(db, elementId), false)), ...(loadRelatedProperties(db, () => queryDrawingGraphicElements(db, elementId), false)), ...(loadRelatedProperties(db, () => queryGraphicalElement3dElements(db, elementId), false)), ...(loadRelatedProperties(db, () => queryExternalSourceRepositories(db, elementId), false)), ...(loadRelatedProperties(db, () => queryExternalSourceGroupRepositories(db, elementId), false)), }; } function loadRelatedProperties(db: IModelDb, idsGetter: () => Map<string, string[]>, loadAspects: boolean) { const idsByClass = idsGetter(); const properties: any = {}; for (const entry of idsByClass) { properties[entry[0]] = loadProperties(db, entry[0], entry[1], loadAspects); } return properties; } function loadProperties(db: IModelDb, className: string, ids: string[], loadAspects: boolean) { const query = ` SELECT * FROM ${className} WHERE ECInstanceId IN (${ids.map((_v, idx) => `:id${idx}`).join(",")})`; return db.withPreparedStatement(query, (stmt) => { const properties: any[] = []; stmt.bindValues(ids); while (stmt.step() === DbResult.BE_SQLITE_ROW) { const row = stmt.getRow(); properties.push({ ...collectProperties(row), ...(loadAspects ? loadRelatedProperties(db, () => queryUniqueAspects(db, row.Id), false) : {}), ...(loadAspects ? loadRelatedProperties(db, () => queryMultiAspects(db, row.Id), false) : {}), }); } return properties; }); } function queryMultiAspects(db: IModelDb, elementId: string) { const query = ` SELECT ma.ECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className FROM bis.ElementMultiAspect ma JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = ma.ECClassId JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id WHERE ma.Element.Id = :id`; return queryRelatedClasses(db, query, { id: elementId }); } function queryUniqueAspects(db: IModelDb, elementId: string) { const query = ` SELECT ua.ECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className FROM bis.ElementUniqueAspect ua JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = ua.ECClassId JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id WHERE ua.Element.Id = :id`; return queryRelatedClasses(db, query, { id: elementId }); } function queryGeometricElement3dTypeDefinitions(db: IModelDb, elementId: string) { const query = ` SELECT relType.TargetECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className FROM bis.GeometricElement3dHasTypeDefinition relType JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = relType.TargetECClassId JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id WHERE relType.SourceECInstanceId = :id`; return queryRelatedClasses(db, query, { id: elementId }); } function queryGeometricElement2dTypeDefinitions(db: IModelDb, elementId: string) { const query = ` SELECT relType.TargetECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className FROM bis.GeometricElement2dHasTypeDefinition relType JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = relType.TargetECClassId JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id WHERE relType.SourceECInstanceId = :id`; return queryRelatedClasses(db, query, { id: elementId }); } function queryElementLinks(db: IModelDb, elementId: string) { const query = ` SELECT relLink.TargetECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className FROM bis.ElementHasLinks relLink JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = relLink.TargetECClassId JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id WHERE relLink.SourceECInstanceId = :id`; return queryRelatedClasses(db, query, { id: elementId }); } function queryGroupElementLinks(db: IModelDb, elementId: string) { const query = ` SELECT relLink.TargetECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className FROM bis.ElementHasLinks relLink JOIN bis.ElementGroupsMembers relElementGroup ON relElementGroup.SourceECInstanceId = relLink.SourceECInstanceId JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = relLink.TargetECClassId JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id WHERE relElementGroup.TargetECInstanceId = :id`; return queryRelatedClasses(db, query, { id: elementId }); } function queryModelLinks(db: IModelDb, elementId: string) { const query = ` SELECT relLink.TargetECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className FROM bis.ElementHasLinks relLink JOIN bis.ModelModelsElement relModelModels ON relModelModels.TargetECInstanceId = relLink.SourceECInstanceId JOIN bis.ModelContainsElements relModelContains ON relModelContains.SourceECInstanceId = relModelModels.SourceECInstanceId JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = relLink.TargetECClassId JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id WHERE relModelContains.TargetECInstanceId = :id`; return queryRelatedClasses(db, query, { id: elementId }); } function queryDrawingGraphicElements(db: IModelDb, elementId: string) { const query = ` SELECT relRepresents.SourceECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className FROM bis.DrawingGraphicRepresentsElement relRepresents JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = relRepresents.SourceECClassId JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id WHERE relRepresents.TargetECInstanceId = :id`; return queryRelatedClasses(db, query, { id: elementId }); } function queryGraphicalElement3dElements(db: IModelDb, elementId: string) { const query = ` SELECT relRepresents.SourceECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className FROM bis.GraphicalElement3dRepresentsElement relRepresents JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = relRepresents.SourceECClassId JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id WHERE relRepresents.TargetECInstanceId = :id`; return queryRelatedClasses(db, query, { id: elementId }); } function queryExternalSourceRepositories(db: IModelDb, elementId: string) { const query = ` SELECT relRepository.TargetECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className FROM bis.ExternalSourceIsInRepository relRepository JOIN bis.ElementIsFromSource relFromSource ON relFromSource.TargetECInstanceId = relRepository.SourceECInstanceId JOIN bis.ExternalSourceAspect aspect ON aspect.ECInstanceId = relFromSource.SourceECInstanceId JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = relRepository.TargetECClassId JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id WHERE aspect.Element.Id = :id`; return queryRelatedClasses(db, query, { id: elementId }); } function queryExternalSourceGroupRepositories(db: IModelDb, elementId: string) { const query = ` SELECT relRepository.TargetECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className FROM bis.ExternalSourceIsInRepository relRepository JOIN bis.ExternalSourceGroupGroupsSources relGroupSources ON relGroupSources.TargetECInstanceId = relRepository.SourceECInstanceId JOIN bis.ElementIsFromSource relFromSource ON relFromSource.TargetECInstanceId = relGroupSources.SourceECInstanceId AND relFromSource.TargetECClassId IS (bis.ExternalSourceGroup) JOIN bis.ExternalSourceAspect aspect ON aspect.ECInstanceId = relFromSource.SourceECInstanceId JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = relRepository.TargetECClassId JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id WHERE aspect.Element.Id = :id`; return queryRelatedClasses(db, query, { id: elementId }); } function queryRelatedClasses(db: IModelDb, query: string, bindings: object) { return db.withPreparedStatement(query, (stmt) => { stmt.bindValues(bindings); const relatedClasses = new Map<string, string[]>(); while (stmt.step() === DbResult.BE_SQLITE_ROW) { const row = stmt.getRow(); const className = row.className; const relatedIds = relatedClasses.get(className); if (!relatedIds) { relatedClasses.set(className, [row.id]); continue; } relatedIds.push(row.id); } return relatedClasses; }); } const excludedProperties = new Set<string>(["element", "jsonProperties", "geometryStream"]); function collectProperties(row: any) { const element: any = {}; for (const prop in row) { if (excludedProperties.has(prop)) continue; element[prop] = row[prop]; } return element; }
the_stack
import { ApolloLink, from, split } from "apollo-link"; import { setContext } from "apollo-link-context"; import * as URI from "urijs"; import { ApolloCache } from "apollo-cache"; import { InMemoryCache, NormalizedCacheObject } from "apollo-cache-inmemory"; import ApolloClient from "apollo-client"; import { createHttpLink } from "apollo-link-http"; import { RetryLink } from "apollo-link-retry"; import { WebSocketLink } from "apollo-link-ws"; import { getMainDefinition } from "apollo-utilities"; import * as fetch from "isomorphic-fetch"; import * as ws from "isomorphic-ws"; import { ConnectionParams } from "subscriptions-transport-ws"; import { AccessToken, AuthenticationHelper } from "./AuthenticationHelper"; import { User } from "./User"; /** * A helper class, that handles user authentication over http and web socket connections. * It exposes properties that make it easier to setup an Apollo client to communicate with * the Realm Object Server GraphQL API. * * **Note**: A single configuration is valid for a single Realm path. * * @example * ```js * * const config = await GraphQLConfig.create(user, '/~/foo'); * * const httpLink = ApolloLink.concat( * config.authLink, * new HttpLink({ uri: config.httpEndpoint })); * * const subscriptionLink = new WebSocketLink({ * uri: config.webSocketEndpoint, * options: { * connectionParams: config.connectionParams * } * }); * * // Hybrid mode - subscriptions go over websocket, * // queries and mutations - over http. * const link = split(({ query }) => { * const { kind, operation } = getMainDefinition(query); * return kind === 'OperationDefinition' && operation === 'subscription'; * }, * subscriptionLink, * httpLink); * * client = new ApolloClient({ * link: link, * cache: new InMemoryCache() * }); * ``` */ export class GraphQLConfig { /** * Creates a new `GraphQLConfig` instance, that contains helper properties that can be used * to configure the Apollo client. * @param user A valid logged-in [[User]]. * @param realmPath The relative path for the Realm on the server. If the path contains `~`, * it will be replaced with the user's Id (this will not work if the user was logged in with * [[Credentials.anonymous]]). * @param authErrorHandler An error handler that will be invoked if there are problems with * refreshing the user's access token (which can happen either because they lost access to * the Realm or due to network issues). If you return `true`, the error will be considered * fatal and the request will not be retried. Otherwise, a retry will be attempted after * 3 seconds. * @param isQueryBasedSync A boolean, representing whether to connect to a reference Realm * using query based sync. In this mode, query subscriptions must be created before any data * can be returned. * @returns A Promise, that, when resolved, contains a fully configured `GraphQLConfig` * instance. */ public static async create( user: User, realmPath: string, authErrorHandler?: (error: any) => boolean, isQueryBasedSync?: boolean) { realmPath = realmPath.replace("/~/", `/${user.identity}/`); if (isQueryBasedSync) { realmPath = `${realmPath}/__partial/${user.identity}/graphql-client`; } const accessToken = await AuthenticationHelper.refreshAccessToken(user, realmPath); return new GraphQLConfig(user, realmPath, accessToken, authErrorHandler); } /** * @readonly * The http endpoint of the ROS GraphQL API. This is provided for * convenience and always resolves to `http://path-to-ros:port/graphql/realmPath`. * * @example * ``` * * const httpLink = createHttpLink({ * uri: config.httpEndpoint * }); * ``` * * @see {@link https://www.apollographql.com/docs/link/links/http.html HttpLink docs}. */ public readonly httpEndpoint: string; /** * @readonly * The websocket endpoint of the ROS GraphQL subscription API. * This is provided for convenience and always resolves to * `ws://path-to-ros:port/graphql/realmPath`. * * @example * ``` * * const subscriptionLink = new WebSocketLink({ * uri: config.webSocketEndpoint, * options: { * connectionParams: config.connectionParams * } * }); * ``` * * @see {@link https://www.apollographql.com/docs/link/links/ws.html WebSocket Link docs}. */ public readonly webSocketEndpoint: string; /** * @readonly * A function that generates the connection params that are sent to the ROS * GraphQL subscription API. They contain the access token used to authenticate * the connection. * * **Note**: do not invoke the function but instead pass the property directly * to the SubscriptionClient's options. This way, the client will be able to * invoke it every time a connection is established, thus providing a valid * access token every time. * @example * ``` * * const subscriptionLink = new WebSocketLink({ * uri: config.webSocketEndpoint, * options: { * connectionParams: config.connectionParams * } * }); * ``` * * @see {@link https://www.apollographql.com/docs/link/links/ws.html WebSocket Link docs}. */ public readonly connectionParams: () => ConnectionParams; /** * @readonly * An ApolloLink that handles setting the Authorization header on HTTP * request (query and mutation operations). Compose this with an `HttpLink` * by calling `ApolloLink.concat` or `ApolloLink.from`. * * @example * ``` * * const httpLink = ApolloLink.concat( * config.authLink, * new HttpLink({ uri: config.httpEndpoint })); * ``` * * @see {@link https://www.apollographql.com/docs/link/composition.html Composing Links section} * in the Apollo Client docs. * @see {@link https://www.apollographql.com/docs/link/links/http.html HttpLink docs}. */ public readonly authLink: ApolloLink; private readonly user: User; private readonly authErrorHandler: (error: any) => boolean; private readonly realmPath: string; private token: string; private constructor( user: User, realmPath: string, accessToken: AccessToken, authErrorHandler?: (error: any) => boolean, ) { this.user = user; this.authErrorHandler = authErrorHandler; this.realmPath = realmPath; this.token = accessToken.token; if (accessToken.expires) { this.refreshToken(accessToken.expires - Date.now() - 10000); } const graphQLEndpoint = new URI(user.server).segmentCoded(["graphql", realmPath]); this.httpEndpoint = graphQLEndpoint.toString(); let subscriptionScheme: string; switch (graphQLEndpoint.scheme()) { case "http": subscriptionScheme = "ws"; break; case "https": subscriptionScheme = "wss"; break; default: throw new Error(`Unrecognized scheme for the server endpoint: ${graphQLEndpoint.scheme()}`); } this.webSocketEndpoint = graphQLEndpoint.clone().scheme(subscriptionScheme).toString(); this.connectionParams = () => { if (this.token) { return { token: this.token, }; } return {}; }; this.authLink = setContext((_, { headers }) => { if (this.token) { return { headers: { ...headers, authorization: this.token, }, }; } }); } /** * Creates an Apollo client with InMemoryCache. The client will be configured with * an http link for query and mutation operations and a websocket link for subscriptions. */ public createApolloClient(): ApolloClient<NormalizedCacheObject> { return this.createApolloClientWithCache(new InMemoryCache()); } /** * Creates an Apollo client with the specified cache. The client will be configured with * an http link for query and mutation operations and a websocket link for subscriptions. * @param cache The cache that the Apollo client will use. */ public createApolloClientWithCache<TCacheShape>(cache: ApolloCache<TCacheShape>): ApolloClient<TCacheShape> { const httpLink = createHttpLink({ uri: this.httpEndpoint, fetch, }); const subscriptionLink = new WebSocketLink({ uri: this.webSocketEndpoint, options: { connectionParams: this.connectionParams, reconnect: true, lazy: true, }, webSocketImpl: ws, }); const retryLink = new RetryLink({ delay: { initial: 100, max: 5000, }, attempts: { max: 3, retryIf: async (error) => { if (error && error.result && error.result.status === 401) { await this.refreshToken(0, /* shouldRetry */ false); } return true; }, }, }); const link = split(({ query }) => { const { kind, operation } = getMainDefinition(query); return kind === "OperationDefinition" && operation === "subscription"; }, subscriptionLink, from([retryLink, this.authLink, httpLink])); return new ApolloClient({ link, cache, }); } /** * Forces a refresh of the user's access token. Tokens are refreshed automatically * 10 seconds before they expire. Since that relies on a javascript timer, it's * possible that the token isn't proactively refreshed, for example, because the * app was suspended for some time. * @param afterDelay Delay to wait before refreshing the token. * @param shouldRetry A boolean parameter that controls whether to retry the request on error. */ public async refreshToken(afterDelay: number, shouldRetry = true): Promise<boolean> { await this.delay(afterDelay); if (!this.user.token) { // User logged out, stop refreshing return false; } try { const result = await AuthenticationHelper.refreshAccessToken(this.user, this.realmPath); this.token = result.token; this.refreshToken(result.expires - Date.now() - 10000); return true; } catch (e) { if (this.authErrorHandler) { // Always report the error, even if we're not retrying shouldRetry = !this.authErrorHandler(e) && shouldRetry; } if (shouldRetry) { return this.refreshToken(3000); } } return false; } private delay(ms: number): Promise<void> { return new Promise((resolve) => { setTimeout(resolve, ms); }); } }
the_stack
import { Rule, RuleResult, RuleFail, RuleContext, RulePotential, RuleManual, RulePass } from "../../../api/IEngine"; import { RPTUtil } from "../util/legacy"; let a11yRulesText: Rule[] = [ { /** * Description: Trigger for possible uses of sensory text * Origin: RPT 5.6 G502 */ id: "RPT_Text_SensoryReference", context: "dom:body, dom:body dom:*", run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const validateParams = { sensoryText: { value: ["top-left", "top-right", "bottom-right", "bottom-left", "round", "square", "shape", "rectangle", "triangle", "right", "left", "above", "below", "top", "bottom", "upper", "lower", "corner", "beside"], type: "[string]" } } const ruleContext = context["dom"].node as Element; if (RPTUtil.hiddenByDefaultElements.includes(ruleContext.nodeName.toLowerCase())) { return null; } // Extract the nodeName of the context node let nodeName = ruleContext.nodeName.toLowerCase(); // In the case this is a style or link element, skip triggering rule as we do not want to scan // CSS for sensory words, as there can be CSS keys which contain theses sensory text that is matching. if (nodeName === "style" || nodeName === "link") { return RulePass(1); } let violatedtextArray = null; let violatedtext = null; let sensoryRegex = RPTUtil.getCache(ruleContext.ownerDocument, "RPT_Text_SensoryReference", null); if (sensoryRegex == null) { let sensoryText = validateParams.sensoryText.value; let regexStr = "(" + sensoryText[0]; for (let j = 1; j < sensoryText.length; ++j) regexStr += "|" + sensoryText[j]; regexStr += ")\\W"; sensoryRegex = new RegExp(regexStr, "gi"); RPTUtil.setCache(ruleContext.ownerDocument, "RPT_Text_SensoryReference", sensoryRegex); } let passed = true; let walkNode = ruleContext.firstChild as Node; while (passed && walkNode) { // Comply to the Check Hidden Content setting will be done by default as this rule triggers on each element // and for each element it only checks that single elements text nodes and nothing else. So all inner elements will be // covered on their own. Currently for this rule by default Check Hidden Content will work, as we are doing // a node walk only on siblings so it would not get text nodes from other siblings at all. // In the case in the future something chnges, just need to add && !RPTUtil.shouldNodeBeSkippedHidden(walkNode) to the below // if. if (walkNode.nodeName == "#text") { let txtVal = walkNode.nodeValue.trim(); if (txtVal.length > 0) { violatedtextArray = txtVal.match(sensoryRegex); if (violatedtextArray != null) { let hash = {}, result = []; let exemptWords = ["right-click", "left-click", "right-clicking", "right-clicks", "left-clicking", "left-clicks"]; // Note: split(/[\n\r ]+/) will spread the string into group of words using space, // carriage return or linefeed as separators. let counts = txtVal.split(/[\n\r ]+/).reduce(function (map, word) { let sensoryTextArr = validateParams.sensoryText.value; let wordWoTrailingPunc = word.replace(/[.?!:;()'",`\]]+$/, ""); let lcWordWoPunc = word.toLowerCase().replace(/[.?!:;()'",`\]]/g, ""); for (let counter = 0; counter < sensoryTextArr.length; counter++) { let a = lcWordWoPunc.indexOf(sensoryTextArr[counter]); let b = exemptWords.indexOf(lcWordWoPunc); let sensoryWordLen = sensoryTextArr[counter].length; let charFollowSensoryText = lcWordWoPunc.charAt(sensoryWordLen + a); // If the word does not contains substring of sensoryTextArr[counter] // proceed to the next loop iteration for next sensoryText. if (a < 0) { continue; } let isPuncfollowing = ((charFollowSensoryText == '\-') || (charFollowSensoryText == '\.') || (charFollowSensoryText == '\?') || (charFollowSensoryText == '\!') || (charFollowSensoryText == '\:') || (charFollowSensoryText == '\;') || (charFollowSensoryText == '\(') || (charFollowSensoryText == '\)') || (charFollowSensoryText == '\'') || (charFollowSensoryText == '\"') || (charFollowSensoryText == '\,') || (charFollowSensoryText == '.\`') || (charFollowSensoryText == '\\') || (charFollowSensoryText == '\]')); let isPuncPreceding = false; if (a > 0) { let charPrecedeSensoryText = lcWordWoPunc.charAt(a - 1); isPuncPreceding = ((charPrecedeSensoryText == '\-') || (charPrecedeSensoryText == '\.') || (charPrecedeSensoryText == '\?') || (charPrecedeSensoryText == '\!') || (charPrecedeSensoryText == '\:') || (charPrecedeSensoryText == '\;') || (charPrecedeSensoryText == '\(') || (charPrecedeSensoryText == '\)') || (charPrecedeSensoryText == '\'') || (charPrecedeSensoryText == '\"') || (charPrecedeSensoryText == '\,') || (charPrecedeSensoryText == '.\`') || (charPrecedeSensoryText == '\\') || (charPrecedeSensoryText == '\]')); } if (((lcWordWoPunc.length == sensoryWordLen) || (isPuncfollowing == true) || (isPuncPreceding == true)) && (b < 0)) { passed = false; if (!hash.hasOwnProperty(wordWoTrailingPunc)) { hash[wordWoTrailingPunc] = true; result.push(wordWoTrailingPunc); } counter = sensoryTextArr.length; } } map[wordWoTrailingPunc] = (map[wordWoTrailingPunc] || 0) + 1; return map; }, Object.create(null)); violatedtext = result.join(", "); } } } walkNode = walkNode.nextSibling; } if (!passed) { // Don't trigger if we're not in the body or if we're in a script let checkAncestor = RPTUtil.getAncestor(ruleContext, ["body", "script"]); passed = (checkAncestor == null || checkAncestor.nodeName.toLowerCase() != "body"); } return passed ? RulePass("Pass_0") : RulePotential("Potential_1", [violatedtext]); } }, { /** * Description: Trigger for detected emoticons * Origin: WCAG H86 */ id: "WCAG20_Text_Emoticons", context: "dom:*", run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const validateParams = { emoticons: { value: [":-)", ":)", ":o)", ":]", ":3", ":c)", ":>", "=]", "8)", "=)", ":D", "C:", ":-D", ":D", "8D", "XD", "=D", "=3", "<=3", "<=8", "--!--", ":-(", ":(", ":c", ":<", ":[", "D:", "D8", "D;", "D=", "DX", "v.v", ":-9", ";-)", ";)", "*)", ";]", ";D", ":-P", ":P", ":-p", ":p", "=p", ":-Þ", ":Þ", ":-b", ":b", ":-O", ":O", "O_O", "o_o", "8O", "OwO", "O-O", "0_o", "O_o", "O3O", "o0o ;o_o;", "o...o", "0w0", ":-/", ":/", ":\\", "=/", "=\\", ":S", ":|", "d:-)", "qB-)", ":)~", ":-)>....", ":-X", ":X", ":-#", ":#", "O:-)", "0:3", "O:)", ":'(", ";*(", "T_T", "TT_TT", "T.T", ":-*", ":*", "^o)", ">:)", ">;)", ">:-)", "B)", "B-)", "8)", "8-)", "^>.>^", "^<.<^", "^>_>^", "^<_<^", "D:<", ">:(", "D-:<", ">:-(", ":-@[1]", ";(", "`_´", "D<", "<3", "<333", "=^_^=", "=>.>=", "=<_<=", "=>.<=", "\\,,/", "\\m/", "\\m/\\>.</\\m/", "\\o/", "\\o o/", "o/\\o", ":&", ":u" ], type: "[string]" } } const ruleContext = context["dom"].node as Element; let emoticons = validateParams.emoticons.value; let passed = true; let testText = ""; let walkNode : Node = ruleContext.firstChild; while (walkNode) { // Comply to the Check Hidden Content setting will be done by default as this rule triggers on each element // and for each element it only checks that single elements text nodes and nothing else. So all inner elements will be // covered on their own. Currently for this rule by default Check Hidden Content will work, as we are doing // a node walk only on siblings so it would not get text nodes from other siblings at all. // In the case in the future something chnges, just need to add && !RPTUtil.shouldNodeBeSkippedHidden(walkNode) to the below // if. if (walkNode.nodeName == "#text") { testText += " " + walkNode.nodeValue; } walkNode = walkNode.nextSibling; } if (testText.trim().length > 0) { for (let j = 0; passed && j < emoticons.length; ++j) { let emotIdx = testText.indexOf(emoticons[j]); let eLngth = emoticons[j].length; while (passed && emotIdx != -1) { // Passes if: the emoticon is not preceded by whitespace, // or the emoticon is not followed by whitespace unless it's punctuation, // or it's in a pre, code, or script passed = (emotIdx > 0 && !/\s/.test(testText.substring(emotIdx - 1, emotIdx))) || (emotIdx < testText.length - eLngth && !/\s/.test(testText.substring(emotIdx + eLngth, emotIdx + eLngth + 1)) && !/[.,!'"?]/.test(testText.substring(emotIdx + eLngth, emotIdx + eLngth + 1))); // Allow usage of (: stuff :) since this is a comment in some languages passed = passed || ((emoticons[j] == ":)" || emoticons[j] == "(:") && /\(\:.*\:\)/.test(testText)); passed = passed || ((emoticons[j] == ";)" || emoticons[j] == "(;") && /\(\;.*\;\)/.test(testText)); emotIdx = testText.indexOf(emoticons[j], emotIdx + 1); } } } if (!passed) { // Don't trigger if we're not in the body or if we're in a script, pre, code let checkAncestor = RPTUtil.getAncestor(ruleContext, ["pre", "code", "script", "body"]); passed = checkAncestor == null || checkAncestor.nodeName.toLowerCase() != "body"; } if (passed) return RulePass("Pass_0"); if (!passed) return RulePotential("Potential_1"); } }, { /** * Description: Trigger for words that are spaced out (e.g., I B M). CSS should be used instead for this * Origin: WCAG 2.0 F32, C8 */ id: "WCAG20_Text_LetterSpacing", context: "dom:*", run: (context: RuleContext, options?: {}) : RuleResult | RuleResult[] => { const ruleContext = context["dom"].node as Element; let passed = true; let walkNode = ruleContext.firstChild as Node; while (passed && walkNode) { // Comply to the Check Hidden Content setting will be done by default as this rule triggers on each element // and for each element it only checks that single elements text nodes and nothing else. So all inner elements will be // covered on their own. Currently for this rule by default Check Hidden Content will work, as we are doing // a node walk only on siblings so it would not get text nodes from other siblings at all. // In the case in the future something chnges, just need to add && !RPTUtil.shouldNodeBeSkippedHidden(walkNode) to the below // if. if (walkNode.nodeName == "#text") { let txtVal = walkNode.nodeValue; passed = !(/(^|\s)[a-zA-Z] [a-zA-Z] [a-zA-Z]($|\s)/.test(txtVal)); } walkNode = walkNode.nextSibling; } if (!passed) { // Don't trigger if we're not in the body or if we're in a script let checkAncestor = RPTUtil.getAncestor(ruleContext, ["body", "script", "code"]); passed = checkAncestor == null || checkAncestor.nodeName.toLowerCase() != "body"; } if (passed) return RulePass("Pass_0"); if (!passed) return RulePotential("Potential_1"); } }, { /** * Description: Trigger for possible ASCII art in a <pre> * Origin: RPT 5.6 G458 */ id: "RPT_Pre_ASCIIArt", context: "dom:pre, dom:listing, dom:xmp, dom:plaintext", run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const ruleContext = context["dom"].node as Element; // Fix for IDWB writers. Don't trigger if content is in a code element. The code element is searched for // in various places because of the weird way various browsers render <code><pre></pre></code. Firefox, // HtmlUnit and Chrome all render differently. Firefox: <code></code><pre></pre> HtmlUnit: </code><pre><code></code></pre> // See unit test CodeElementAbovePreElement.html. Don't know how RPT renders, so cover all the bases. if (ruleContext.nodeName.toLowerCase() == "pre") { if ((ruleContext.previousSibling && ruleContext.previousSibling.nodeName.toLowerCase() == "code") || ruleContext.getElementsByTagName("code").length > 0 || RPTUtil.getAncestor(ruleContext, "code")) { return RulePass("Pass_0"); } } let passed = true; let txtValue = RPTUtil.getInnerText(ruleContext); let nonAlphaNumericNorSpaceCount = 0; let alphNumSameCharacterCount = 0; let lastCharacter = ""; // Iterate through the text content for (let idx = 0; passed && (idx < txtValue.length); ++idx) { let chStr = txtValue.substr(idx, 1); // Check if it is alphanumeric or punctuation if (/[\w!@#$%&\*().,?\[\]{}<>=":\/\\-]/.test(chStr)) { // Detect same character sequence if (lastCharacter == chStr) { alphNumSameCharacterCount = alphNumSameCharacterCount + 1;; } else { alphNumSameCharacterCount = 0; } } else if (/\s/.test(chStr)) { alphNumSameCharacterCount = 0; } else { nonAlphaNumericNorSpaceCount = nonAlphaNumericNorSpaceCount + 1; alphNumSameCharacterCount = 0; } lastCharacter = chStr; // Make the decision if (nonAlphaNumericNorSpaceCount >= 5 || alphNumSameCharacterCount >= 4) { passed = false; } } if (passed) return RulePass("Pass_0"); if (!passed) return RulePotential("Potential_1"); } } ] export { a11yRulesText }
the_stack
import events = require('events'); import fs = require('fs'); import path = require('path'); import convict = require('convict'); import bunyan = require('bunyan'); import optimist = require('optimist'); import util = require('util'); var convictConf: convict.Config; var otherConf: {[index: string]: any}; export function get(name: string): any { if (name in otherConf) { return otherConf[name]; } return convictConf.get(name); } export var emitter = new events.EventEmitter(); // Initialization ((): void => { otherConf = {}; // Convict from file convictConf = convict({ 'api': { 'host': { doc: 'The Bloomberg Open API server address', format: 'ipaddress', default: '127.0.0.1', env: 'BLPAPI_HTTP_API_HOST', arg: 'api-host' }, 'port': { doc: 'The Bloomberg Open API server port', format: 'port', default: 8194, env: 'BLPAPI_HTTP_API_PORT', arg: 'api-port' }, 'authenticationMode': { doc: 'The authentication mode to use for B-PIPE Authorization', format: String, default: 'APPLICATION_ONLY', env: 'BLPAPI_HTTP_API_AUTHENTICATION_MODE', arg: 'api-authenticationMode' }, 'authenticationAppName': { doc: 'The application name for authentication purposes', format: String, default: '', env: 'BLPAPI_HTTP_API_AUTHENTICATION_APPNAME', arg: 'api-authenticationAppName' } }, 'port': { doc: 'The http port to listen on', format: 'port', default: 80, env: 'BLPAPI_HTTP_PORT', arg: 'port' }, 'expiration': { doc: 'Auto-expiration period of blpSession in seconds', format: 'integer', default: 5, arg: 'session-expiration' }, 'https': { 'enable': { doc: 'Boolean option to control whether the server runs on https mode', format: Boolean, default: false, arg: 'https-enable' }, 'ca': { doc: 'Root certificate authority', format: String, default: '../keys/root-ca-crt.pem', arg: 'https-ca' }, 'cert': { doc: 'HTTPS server certification', format: String, default: '../keys/server-crt.pem', arg: 'https-cert' }, 'key': { doc: 'HTTPS server key', format: String, default: '../keys/server-key.pem', arg: 'https-key' }, 'crl': { doc: 'HTTPS server certificate revocation list', format: String, default: '', arg: 'https-crl' } }, 'logging': { 'stdout': { doc: 'Boolean option to control whether to log to stdout', format: Boolean, default: true, arg: 'logging-stdout' }, 'stdoutLevel': { doc: 'Log level to for stdout', format: String, default: 'info', arg: 'logging-stdoutLevel' }, 'logfile': { doc: 'Log file path', format: String, default: 'blpapi-http.log', arg: 'logging-logfile' }, 'logfileLevel': { doc: 'Log level to for log file', format: String, default: 'trace', arg: 'logging-logfileLevel' }, 'reqBody': { doc: 'Boolean option to control whether to log request body', format: Boolean, default: false, arg: 'logging-reqBody' }, 'clientDetail': { doc: 'Boolean option to control whether to log client details', format: Boolean, default: false, arg: 'logging-clientDetail' } }, 'service': { 'name': { doc: 'The service name', format: String, default: 'BLPAPI-HTTP', arg: 'service-name' }, 'version': { doc: 'The service version', format: String, default: '1.0.0', arg: 'service-version' } }, 'maxBodySize': { doc: 'Maximum size of the request body in byte', format: 'integer', default: 1024, arg: 'maxBodySize' }, 'throttle': { 'burst': { doc: 'Throttle burst', format: 'integer', default: 100, arg: 'throttle-burst' }, 'rate': { doc: 'Throttle rate', format: 'integer', default: 50, arg: 'throttle-rate' } }, 'websocket': { 'socket-io': { 'enable': { doc: 'Boolean option to control whether to run socket.io server', format: Boolean, default: true, arg: 'websocket-socket-io-enable' }, 'port': { doc: 'The socket io port to listen on', format: 'port', default: 3001, arg: 'websocket-socket-io-port' }, }, 'ws': { 'enable': { doc: 'Boolean option to control whether to run ws server', format: Boolean, default: true, arg: 'websocket-ws-enable' }, 'port': { doc: 'The ws port to listen on', format: 'port', default: 3002, arg: 'websocket-ws-port' }, } }, 'longpoll': { 'maxbuffersize': { doc: 'Maximum buffer size for subscription data', format: 'integer', default: 50, arg: 'longpoll-maxbuffersize' }, 'pollfrequency': { doc: 'Data checking frequency when poll request arrives', format: 'integer', default: 100, arg: 'longpoll-pollfrequency' }, 'polltimeout': { doc: 'Server side poll request timeout in ms', format: 'integer', default: 30000, arg: 'longpoll-polltimeout' } } }); if (optimist.argv.cfg) { convictConf.loadFile(optimist.argv.cfg); } convictConf.validate(); // Build options object // Bunyan logger options // Override default bunyan response serializer bunyan.stdSerializers['res'] = function(res: any): any { if (!res || !res.statusCode) { return res; } return { statusCode: res.statusCode, header: res._headers }; }; // Add client cert serializer bunyan.stdSerializers['cert'] = function(cert: any): any { return cert && { CN: cert.subject.CN, fingerprint: cert.fingerprint }; }; var streams: {}[] = [{level: convictConf.get('logging.logfileLevel'), path: convictConf.get('logging.logfile')}]; if (convictConf.get('logging.stdout')) { streams.push({ level: convictConf.get('logging.stdoutLevel'), stream: process.stdout }); } otherConf['loggerOptions'] = { name: convictConf.get('service.name'), streams: streams, serializers: bunyan.stdSerializers }; // Restify bodyParser plugin options otherConf['bodyParserOptions'] = { maxBodySize: convictConf.get('maxBodySize'), mapParams: false }; // Restify throttle plugin options otherConf['throttleOptions'] = { burst: convictConf.get('throttle.burst'), rate: convictConf.get('throttle.rate'), ip: true, overrides: { '127.0.0.1': { rate: 0, burst: 0 } } }; // HTTP(S) server options otherConf['serverOptions'] = { name: convictConf.get('service.name'), version: convictConf.get('service.version'), acceptable: ['application/json'] }; if (convictConf.get('https.enable')) { otherConf['serverOptions'].httpsServerOptions = { key: fs.readFileSync(path.resolve(__dirname, convictConf.get('https.key'))), cert: fs.readFileSync(path.resolve(__dirname, convictConf.get('https.cert'))), ca: fs.readFileSync(path.resolve(__dirname, convictConf.get('https.ca'))), requestCert: true, rejectUnauthorized: true }; // For server that wants to use CRL if (convictConf.get('https.crl')) { var crlPath = path.resolve(__dirname, convictConf.get('https.crl')); otherConf['serverOptions'].httpsServerOptions.crl = fs.readFileSync(crlPath); // Setup file watch for crl changes fs.watch(crlPath, (event: string, filename: string): void => { // Re-read the crl file otherConf['serverOptions'].httpsServerOptions.crl = fs.readFileSync(crlPath); emitter.emit('change', 'https.crl'); // Signal the server that config changes }); } } // BLPAPI Session options var blpapiSessionOptions: any = { serverHost: convictConf.get('api.host'), serverPort: convictConf.get('api.port') }; var authorizeOnStartup = false; var authenticationOptions: string = null; var appName = convictConf.get('api.authenticationAppName'); if ('' !== appName) { var mode = convictConf.get('api.authenticationMode'); if ('APPLICATION_ONLY' !== mode) { throw new Error(util.format('Bad value for api.authenticationMode: %s', mode)); } authorizeOnStartup = true; // TODO: Add support for USER_AND_APPLICATION authenticationOptions = util.format('AuthenticationMode=%s;' + 'ApplicationAuthenticationType=APPNAME_AND_KEY;' + 'ApplicationName=%s', mode, appName); } // TODO: Add support for user-only auth modes. if (null !== authenticationOptions) { blpapiSessionOptions['authenticationOptions'] = authenticationOptions; } otherConf['sessionOptions'] = { blpapiSessionOptions: blpapiSessionOptions, authorizeOnStartup: authorizeOnStartup }; })();
the_stack
import { NydusClient, RouteHandler } from 'nydus-client' import { GameLaunchConfig, GameRoute } from '../../common/game-launch-config' import { TypedIpcRenderer } from '../../common/ipc' import { getIngameLobbySlotsWithIndexes } from '../../common/lobbies' import { urlPath } from '../../common/urls' import { SbUserId } from '../../common/users/user-info' import { ACTIVE_GAME_LAUNCH, LOBBIES_COUNT_UPDATE, LOBBIES_LIST_UPDATE, LOBBY_INIT_DATA, LOBBY_UPDATE_BAN, LOBBY_UPDATE_BAN_SELF, LOBBY_UPDATE_CHAT_MESSAGE, LOBBY_UPDATE_COUNTDOWN_CANCELED, LOBBY_UPDATE_COUNTDOWN_START, LOBBY_UPDATE_COUNTDOWN_TICK, LOBBY_UPDATE_GAME_STARTED, LOBBY_UPDATE_HOST_CHANGE, LOBBY_UPDATE_KICK, LOBBY_UPDATE_KICK_SELF, LOBBY_UPDATE_LEAVE, LOBBY_UPDATE_LEAVE_SELF, LOBBY_UPDATE_LOADING_CANCELED, LOBBY_UPDATE_LOADING_START, LOBBY_UPDATE_RACE_CHANGE, LOBBY_UPDATE_SLOT_CHANGE, LOBBY_UPDATE_SLOT_CREATE, LOBBY_UPDATE_SLOT_DELETED, LOBBY_UPDATE_STATUS, } from '../actions' import audioManager, { AudioManager, AvailableSound } from '../audio/audio-manager' import { dispatch, Dispatchable } from '../dispatch-registry' import { replace } from '../navigation/routing' import { makeServerUrl } from '../network/server-url' import { openSnackbar } from '../snackbars/action-creators' import { Slot } from './lobby-reducer' const ipcRenderer = new TypedIpcRenderer() interface CountdownState { timer: ReturnType<typeof setInterval> | undefined sound: ReturnType<AudioManager['playFadeableSound']> | undefined atmosphere: ReturnType<AudioManager['playFadeableSound']> | undefined } const countdownState: CountdownState = { timer: undefined, sound: undefined, atmosphere: undefined, } function fadeAtmosphere(fast = true) { const { atmosphere } = countdownState if (atmosphere) { const timing = fast ? 1.5 : 3 atmosphere.gainNode.gain.exponentialRampToValueAtTime(0.001, audioManager.currentTime + timing) atmosphere.source.stop(audioManager.currentTime + timing + 0.1) countdownState.atmosphere = undefined } } function clearCountdownTimer(leaveAtmosphere = false) { const { timer, sound, atmosphere } = countdownState if (timer) { clearInterval(timer) countdownState.timer = undefined } if (sound) { sound.gainNode.gain.exponentialRampToValueAtTime(0.001, audioManager.currentTime + 0.5) sound.source.stop(audioManager.currentTime + 0.6) countdownState.sound = undefined } if (!leaveAtmosphere && atmosphere) { fadeAtmosphere() } } type LobbyEvent = | LobbyInitEvent | LobbyDiffEvent | LobbySlotCreateEvent | LobbyRaceChangeEvent | LobbyLeaveEvent | LobbyKickEvent | LobbyBanEvent | LobbyHostChangeEvent | LobbySlotChangeEvent | LobbySlotDeletedEvent | LobbyStartCountdownEvent | LobbyCancelCountdownEvent | LobbySetupGameEvent | LobbySetRoutesEvent | LobbyStartWhenReadyEvent | LobbyCancelLoadingEvent | LobbyGameStartedEvent | LobbyChatEvent | LobbyStatusEvent interface LobbyUser { id: SbUserId name: string } interface LobbyInitEvent { type: 'init' // TODO(tec27): actually type this lobby: { map: { hash: string mapData: { format: string } mapUrl: string } } /** An array of infos for all users that were in the lobby at this point. */ userInfos: LobbyUser[] } interface LobbyDiffEvent { type: 'diff' diffEvents: LobbyEvent[] } interface LobbySlotCreateEvent { type: 'slotCreate' // TODO(tec27): actually type this slot: { type: 'human' | 'computer' } /** In case a human slot was created, this field will contain their properties, e.g. name. */ userInfo?: LobbyUser } interface LobbyRaceChangeEvent { type: 'raceChange' } interface LobbyLeaveEvent { type: 'leave' player: { name: string } } interface LobbyKickEvent { type: 'kick' player: { name: string } } interface LobbyBanEvent { type: 'ban' player: { name: string } } interface LobbyHostChangeEvent { type: 'hostChange' host: any } interface LobbySlotChangeEvent { type: 'slotChange' } interface LobbySlotDeletedEvent { type: 'slotDeleted' } interface LobbyStartCountdownEvent { type: 'startCountdown' } interface LobbyCancelCountdownEvent { type: 'cancelCountdown' } interface LobbySetupGameEvent { type: 'setupGame' setup: { gameId: string seed: number } // TODO(tec27): Right now this can be undefined if the local player is an observer, but perhaps // that should be handled differently? resultCode?: string } interface LobbySetRoutesEvent { type: 'setRoutes' gameId: string routes: GameRoute[] } interface LobbyStartWhenReadyEvent { type: 'startWhenReady' gameId: string } interface LobbyCancelLoadingEvent { type: 'cancelLoading' } interface LobbyGameStartedEvent { type: 'gameStarted' } interface LobbyChatEvent { type: 'chat' from: string text: string } interface LobbyStatusEvent { type: 'status' } type EventToActionMap = { [E in LobbyEvent['type']]?: ( lobbyName: string, event: Extract<LobbyEvent, { type: E }>, ) => Dispatchable | void } const eventToAction: EventToActionMap = { init: (name, event) => { clearCountdownTimer() const { hash, mapData, mapUrl } = event.lobby.map ipcRenderer.invoke('mapStoreDownloadMap', hash, mapData.format, mapUrl)?.catch(err => { // TODO(tec27): Report this to the server so the loading is canceled immediately // This is already logged to our file by the map store, so we just log it to the console for // easy visibility during development console.error('Error downloading map: ' + err + '\n' + err.stack) }) ipcRenderer.send('rallyPointRefreshPings') return { type: LOBBY_INIT_DATA, payload: event, } as any }, diff: (name, event) => dispatch => { for (const diffEvent of event.diffEvents) { const diffAction = eventToAction[diffEvent.type]!(name, diffEvent as any) if (diffAction) dispatch(diffAction) } }, slotCreate: (name, event) => { if (event.slot.type === 'human') { audioManager.playSound(AvailableSound.JoinAlert) ipcRenderer.send('userAttentionRequired') } return { type: LOBBY_UPDATE_SLOT_CREATE, payload: event, } as any }, raceChange: (name, event) => ({ type: LOBBY_UPDATE_RACE_CHANGE, payload: event, } as any), leave: (name, event) => (dispatch, getState) => { const { auth } = getState() const user = auth.user.name if (user === event.player.name) { // The leaver was me all along!!! clearCountdownTimer() dispatch({ type: LOBBY_UPDATE_LEAVE_SELF, } as any) } else { dispatch({ type: LOBBY_UPDATE_LEAVE, payload: event, } as any) } }, kick: (name, event) => (dispatch, getState) => { const { auth } = getState() const user = auth.user.name if (user === event.player.name) { // We have been kicked from a lobby clearCountdownTimer() dispatch(openSnackbar({ message: 'You have been kicked from the lobby.' })) dispatch({ type: LOBBY_UPDATE_KICK_SELF, } as any) } else { dispatch({ type: LOBBY_UPDATE_KICK, payload: event, } as any) } }, ban: (name, event) => (dispatch, getState) => { const { auth } = getState() const user = auth.user.name if (user === event.player.name) { // It was us who have been banned from a lobby (shame on us!) clearCountdownTimer() dispatch(openSnackbar({ message: 'You have been banned from the lobby.' }) as any) dispatch({ type: LOBBY_UPDATE_BAN_SELF, } as any) } else { dispatch({ type: LOBBY_UPDATE_BAN, payload: event, } as any) } }, hostChange: (name, event) => ({ type: LOBBY_UPDATE_HOST_CHANGE, payload: event.host, } as any), slotChange: (name, event) => ({ type: LOBBY_UPDATE_SLOT_CHANGE, payload: event, } as any), slotDeleted: (name, event) => ({ type: LOBBY_UPDATE_SLOT_DELETED, payload: event, } as any), startCountdown: (name, event) => (dispatch, getState) => { clearCountdownTimer() let tick = 5 dispatch({ type: LOBBY_UPDATE_COUNTDOWN_START, payload: tick, } as any) countdownState.sound = audioManager.playFadeableSound(AvailableSound.Countdown) countdownState.atmosphere = audioManager.playFadeableSound(AvailableSound.Atmosphere) countdownState.timer = setInterval(() => { tick -= 1 dispatch({ type: LOBBY_UPDATE_COUNTDOWN_TICK, payload: tick, } as any) if (!tick) { clearCountdownTimer(true /* leaveAtmosphere */) dispatch({ type: LOBBY_UPDATE_LOADING_START } as any) const { lobby } = getState() const currentPath = location.pathname if (currentPath === urlPath`/lobbies/${lobby.info.name}`) { replace(urlPath`/lobbies/${lobby.info.name}/loading-game`) } } }, 1000) }, cancelCountdown: (name, event) => { clearCountdownTimer() return { type: LOBBY_UPDATE_COUNTDOWN_CANCELED, } as any }, setupGame: (name, event) => (dispatch, getState) => { const { lobby, auth: { user }, } = getState() // We tack on `teamId` to each slot here so we don't have to send two different things to game const slots = getIngameLobbySlotsWithIndexes(lobby.info) .map( ([teamIndex, , slot]: [number, any, any]) => new Slot({ ...slot.toJS(), teamId: lobby.info.teams.get(teamIndex).teamId }), ) .toJS() const { info: { name: lobbyName, map, gameType, gameSubType, host }, } = lobby // TODO(tec27): Remove cast once Immutable infers types properly const config: GameLaunchConfig = { localUser: user.toJS(), setup: { gameId: event.setup.gameId, name: lobbyName, map, gameType, gameSubType, slots, host: host.toJS(), seed: event.setup.seed, resultCode: event.resultCode, serverUrl: makeServerUrl(''), }, } as GameLaunchConfig dispatch({ type: ACTIVE_GAME_LAUNCH, payload: ipcRenderer.invoke('activeGameSetConfig', config), } as any) }, setRoutes: (name, event) => dispatch => { const { routes, gameId } = event ipcRenderer.invoke('activeGameSetRoutes', gameId, routes) }, startWhenReady: (name, event) => { const { gameId } = event ipcRenderer.invoke('activeGameStartWhenReady', gameId) }, cancelLoading: (name, event) => (dispatch, getState) => { // NOTE(tec27): In very low latency environments things can interleave such that the server // cancels loading before our client actually finishes the countdown/gets into the loading // state. Clearing the countdown timer here ensures that our client doesn't try to take us to // the loading screen anyway, even after it's been canceled. clearCountdownTimer() dispatch({ type: LOBBY_UPDATE_COUNTDOWN_CANCELED, } as any) fadeAtmosphere() const { lobby } = getState() const currentPath = location.pathname if (currentPath === urlPath`/lobbies/${lobby.info.name}/loading-game`) { replace(urlPath`/lobbies/${lobby.info.name}`) } dispatch({ type: ACTIVE_GAME_LAUNCH, payload: ipcRenderer.invoke('activeGameSetConfig', {}), } as any) dispatch({ type: LOBBY_UPDATE_LOADING_CANCELED } as any) }, gameStarted: (name, event) => (dispatch, getState) => { fadeAtmosphere(false /* fast */) const { lobby } = getState() const currentPath = location.pathname if (currentPath === urlPath`/lobbies/${lobby.info.name}/loading-game`) { replace(urlPath`/lobbies/${lobby.info.name}/active-game`) } dispatch({ type: LOBBY_UPDATE_GAME_STARTED, payload: { lobby, }, } as any) }, chat: (name, event) => { // Notify the main process of the new message, so it can display an appropriate notification ipcRenderer.send('chatNewMessage', { user: event.from, message: event.text }) return { type: LOBBY_UPDATE_CHAT_MESSAGE, payload: event, } as any }, status: (name, event) => ({ type: LOBBY_UPDATE_STATUS, payload: event, } as any), } export default function registerModule({ siteSocket }: { siteSocket: NydusClient }) { const lobbyHandler: RouteHandler = (route, event) => { const handler = eventToAction[event.type as LobbyEvent['type']] if (!handler) return const action = handler(route.params.lobby, event) if (action) dispatch(action) } siteSocket.registerRoute('/lobbies/:lobby', lobbyHandler) siteSocket.registerRoute('/lobbies/:lobby/:playerName', lobbyHandler) siteSocket.registerRoute('/lobbies/:lobby/:userId/:clientId', lobbyHandler) siteSocket.registerRoute('/lobbies', (route, event) => { const { action, payload } = event dispatch({ type: LOBBIES_LIST_UPDATE, payload: { message: action, data: payload, }, } as any) }) siteSocket.registerRoute('/lobbiesCount', (route, event) => { const { count } = event dispatch({ type: LOBBIES_COUNT_UPDATE, payload: { count, }, } as any) }) }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { PollerLike, PollOperationState } from "@azure/core-lro"; import { ProvisioningServiceDescription, IotDpsResourceListBySubscriptionOptionalParams, IotDpsResourceListByResourceGroupOptionalParams, IotDpsSkuDefinition, IotDpsResourceListValidSkusOptionalParams, SharedAccessSignatureAuthorizationRuleAccessRightsDescription, IotDpsResourceListKeysOptionalParams, IotDpsResourceGetOptionalParams, IotDpsResourceGetResponse, IotDpsResourceCreateOrUpdateOptionalParams, IotDpsResourceCreateOrUpdateResponse, TagsResource, IotDpsResourceUpdateOptionalParams, IotDpsResourceUpdateResponse, IotDpsResourceDeleteOptionalParams, IotDpsResourceGetOperationResultOptionalParams, IotDpsResourceGetOperationResultResponse, OperationInputs, IotDpsResourceCheckProvisioningServiceNameAvailabilityOptionalParams, IotDpsResourceCheckProvisioningServiceNameAvailabilityResponse, IotDpsResourceListKeysForKeyNameOptionalParams, IotDpsResourceListKeysForKeyNameResponse, IotDpsResourceListPrivateLinkResourcesOptionalParams, IotDpsResourceListPrivateLinkResourcesResponse, IotDpsResourceGetPrivateLinkResourcesOptionalParams, IotDpsResourceGetPrivateLinkResourcesResponse, IotDpsResourceListPrivateEndpointConnectionsOptionalParams, IotDpsResourceListPrivateEndpointConnectionsResponse, IotDpsResourceGetPrivateEndpointConnectionOptionalParams, IotDpsResourceGetPrivateEndpointConnectionResponse, PrivateEndpointConnection, IotDpsResourceCreateOrUpdatePrivateEndpointConnectionOptionalParams, IotDpsResourceCreateOrUpdatePrivateEndpointConnectionResponse, IotDpsResourceDeletePrivateEndpointConnectionOptionalParams, IotDpsResourceDeletePrivateEndpointConnectionResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Interface representing a IotDpsResource. */ export interface IotDpsResource { /** * List all the provisioning services for a given subscription id. * @param options The options parameters. */ listBySubscription( options?: IotDpsResourceListBySubscriptionOptionalParams ): PagedAsyncIterableIterator<ProvisioningServiceDescription>; /** * Get a list of all provisioning services in the given resource group. * @param resourceGroupName Resource group identifier. * @param options The options parameters. */ listByResourceGroup( resourceGroupName: string, options?: IotDpsResourceListByResourceGroupOptionalParams ): PagedAsyncIterableIterator<ProvisioningServiceDescription>; /** * Gets the list of valid SKUs and tiers for a provisioning service. * @param provisioningServiceName Name of provisioning service. * @param resourceGroupName Name of resource group. * @param options The options parameters. */ listValidSkus( provisioningServiceName: string, resourceGroupName: string, options?: IotDpsResourceListValidSkusOptionalParams ): PagedAsyncIterableIterator<IotDpsSkuDefinition>; /** * List the primary and secondary keys for a provisioning service. * @param provisioningServiceName The provisioning service name to get the shared access keys for. * @param resourceGroupName resource group name * @param options The options parameters. */ listKeys( provisioningServiceName: string, resourceGroupName: string, options?: IotDpsResourceListKeysOptionalParams ): PagedAsyncIterableIterator< SharedAccessSignatureAuthorizationRuleAccessRightsDescription >; /** * Get the metadata of the provisioning service without SAS keys. * @param provisioningServiceName Name of the provisioning service to retrieve. * @param resourceGroupName Resource group name. * @param options The options parameters. */ get( provisioningServiceName: string, resourceGroupName: string, options?: IotDpsResourceGetOptionalParams ): Promise<IotDpsResourceGetResponse>; /** * Create or update the metadata of the provisioning service. The usual pattern to modify a property is * to retrieve the provisioning service metadata and security metadata, and then combine them with the * modified values in a new body to update the provisioning service. * @param resourceGroupName Resource group identifier. * @param provisioningServiceName Name of provisioning service to create or update. * @param iotDpsDescription Description of the provisioning service to create or update. * @param options The options parameters. */ beginCreateOrUpdate( resourceGroupName: string, provisioningServiceName: string, iotDpsDescription: ProvisioningServiceDescription, options?: IotDpsResourceCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<IotDpsResourceCreateOrUpdateResponse>, IotDpsResourceCreateOrUpdateResponse > >; /** * Create or update the metadata of the provisioning service. The usual pattern to modify a property is * to retrieve the provisioning service metadata and security metadata, and then combine them with the * modified values in a new body to update the provisioning service. * @param resourceGroupName Resource group identifier. * @param provisioningServiceName Name of provisioning service to create or update. * @param iotDpsDescription Description of the provisioning service to create or update. * @param options The options parameters. */ beginCreateOrUpdateAndWait( resourceGroupName: string, provisioningServiceName: string, iotDpsDescription: ProvisioningServiceDescription, options?: IotDpsResourceCreateOrUpdateOptionalParams ): Promise<IotDpsResourceCreateOrUpdateResponse>; /** * Update an existing provisioning service's tags. to update other fields use the CreateOrUpdate method * @param resourceGroupName Resource group identifier. * @param provisioningServiceName Name of provisioning service to create or update. * @param provisioningServiceTags Updated tag information to set into the provisioning service * instance. * @param options The options parameters. */ beginUpdate( resourceGroupName: string, provisioningServiceName: string, provisioningServiceTags: TagsResource, options?: IotDpsResourceUpdateOptionalParams ): Promise< PollerLike< PollOperationState<IotDpsResourceUpdateResponse>, IotDpsResourceUpdateResponse > >; /** * Update an existing provisioning service's tags. to update other fields use the CreateOrUpdate method * @param resourceGroupName Resource group identifier. * @param provisioningServiceName Name of provisioning service to create or update. * @param provisioningServiceTags Updated tag information to set into the provisioning service * instance. * @param options The options parameters. */ beginUpdateAndWait( resourceGroupName: string, provisioningServiceName: string, provisioningServiceTags: TagsResource, options?: IotDpsResourceUpdateOptionalParams ): Promise<IotDpsResourceUpdateResponse>; /** * Deletes the Provisioning Service. * @param provisioningServiceName Name of provisioning service to delete. * @param resourceGroupName Resource group identifier. * @param options The options parameters. */ beginDelete( provisioningServiceName: string, resourceGroupName: string, options?: IotDpsResourceDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Deletes the Provisioning Service. * @param provisioningServiceName Name of provisioning service to delete. * @param resourceGroupName Resource group identifier. * @param options The options parameters. */ beginDeleteAndWait( provisioningServiceName: string, resourceGroupName: string, options?: IotDpsResourceDeleteOptionalParams ): Promise<void>; /** * Gets the status of a long running operation, such as create, update or delete a provisioning * service. * @param operationId Operation id corresponding to long running operation. Use this to poll for the * status. * @param resourceGroupName Resource group identifier. * @param provisioningServiceName Name of provisioning service that the operation is running on. * @param asyncinfo Async header used to poll on the status of the operation, obtained while creating * the long running operation. * @param options The options parameters. */ getOperationResult( operationId: string, resourceGroupName: string, provisioningServiceName: string, asyncinfo: string, options?: IotDpsResourceGetOperationResultOptionalParams ): Promise<IotDpsResourceGetOperationResultResponse>; /** * Check if a provisioning service name is available. This will validate if the name is syntactically * valid and if the name is usable * @param argumentsParam Set the name parameter in the OperationInputs structure to the name of the * provisioning service to check. * @param options The options parameters. */ checkProvisioningServiceNameAvailability( argumentsParam: OperationInputs, options?: IotDpsResourceCheckProvisioningServiceNameAvailabilityOptionalParams ): Promise<IotDpsResourceCheckProvisioningServiceNameAvailabilityResponse>; /** * List primary and secondary keys for a specific key name * @param provisioningServiceName Name of the provisioning service. * @param keyName Logical key name to get key-values for. * @param resourceGroupName The name of the resource group that contains the provisioning service. * @param options The options parameters. */ listKeysForKeyName( provisioningServiceName: string, keyName: string, resourceGroupName: string, options?: IotDpsResourceListKeysForKeyNameOptionalParams ): Promise<IotDpsResourceListKeysForKeyNameResponse>; /** * List private link resources for the given provisioning service * @param resourceGroupName The name of the resource group that contains the provisioning service. * @param resourceName The name of the provisioning service. * @param options The options parameters. */ listPrivateLinkResources( resourceGroupName: string, resourceName: string, options?: IotDpsResourceListPrivateLinkResourcesOptionalParams ): Promise<IotDpsResourceListPrivateLinkResourcesResponse>; /** * Get the specified private link resource for the given provisioning service * @param resourceGroupName The name of the resource group that contains the provisioning service. * @param resourceName The name of the provisioning service. * @param groupId The name of the private link resource * @param options The options parameters. */ getPrivateLinkResources( resourceGroupName: string, resourceName: string, groupId: string, options?: IotDpsResourceGetPrivateLinkResourcesOptionalParams ): Promise<IotDpsResourceGetPrivateLinkResourcesResponse>; /** * List private endpoint connection properties * @param resourceGroupName The name of the resource group that contains the provisioning service. * @param resourceName The name of the provisioning service. * @param options The options parameters. */ listPrivateEndpointConnections( resourceGroupName: string, resourceName: string, options?: IotDpsResourceListPrivateEndpointConnectionsOptionalParams ): Promise<IotDpsResourceListPrivateEndpointConnectionsResponse>; /** * Get private endpoint connection properties * @param resourceGroupName The name of the resource group that contains the provisioning service. * @param resourceName The name of the provisioning service. * @param privateEndpointConnectionName The name of the private endpoint connection * @param options The options parameters. */ getPrivateEndpointConnection( resourceGroupName: string, resourceName: string, privateEndpointConnectionName: string, options?: IotDpsResourceGetPrivateEndpointConnectionOptionalParams ): Promise<IotDpsResourceGetPrivateEndpointConnectionResponse>; /** * Create or update the status of a private endpoint connection with the specified name * @param resourceGroupName The name of the resource group that contains the provisioning service. * @param resourceName The name of the provisioning service. * @param privateEndpointConnectionName The name of the private endpoint connection * @param privateEndpointConnection The private endpoint connection with updated properties * @param options The options parameters. */ beginCreateOrUpdatePrivateEndpointConnection( resourceGroupName: string, resourceName: string, privateEndpointConnectionName: string, privateEndpointConnection: PrivateEndpointConnection, options?: IotDpsResourceCreateOrUpdatePrivateEndpointConnectionOptionalParams ): Promise< PollerLike< PollOperationState< IotDpsResourceCreateOrUpdatePrivateEndpointConnectionResponse >, IotDpsResourceCreateOrUpdatePrivateEndpointConnectionResponse > >; /** * Create or update the status of a private endpoint connection with the specified name * @param resourceGroupName The name of the resource group that contains the provisioning service. * @param resourceName The name of the provisioning service. * @param privateEndpointConnectionName The name of the private endpoint connection * @param privateEndpointConnection The private endpoint connection with updated properties * @param options The options parameters. */ beginCreateOrUpdatePrivateEndpointConnectionAndWait( resourceGroupName: string, resourceName: string, privateEndpointConnectionName: string, privateEndpointConnection: PrivateEndpointConnection, options?: IotDpsResourceCreateOrUpdatePrivateEndpointConnectionOptionalParams ): Promise<IotDpsResourceCreateOrUpdatePrivateEndpointConnectionResponse>; /** * Delete private endpoint connection with the specified name * @param resourceGroupName The name of the resource group that contains the provisioning service. * @param resourceName The name of the provisioning service. * @param privateEndpointConnectionName The name of the private endpoint connection * @param options The options parameters. */ beginDeletePrivateEndpointConnection( resourceGroupName: string, resourceName: string, privateEndpointConnectionName: string, options?: IotDpsResourceDeletePrivateEndpointConnectionOptionalParams ): Promise< PollerLike< PollOperationState<IotDpsResourceDeletePrivateEndpointConnectionResponse>, IotDpsResourceDeletePrivateEndpointConnectionResponse > >; /** * Delete private endpoint connection with the specified name * @param resourceGroupName The name of the resource group that contains the provisioning service. * @param resourceName The name of the provisioning service. * @param privateEndpointConnectionName The name of the private endpoint connection * @param options The options parameters. */ beginDeletePrivateEndpointConnectionAndWait( resourceGroupName: string, resourceName: string, privateEndpointConnectionName: string, options?: IotDpsResourceDeletePrivateEndpointConnectionOptionalParams ): Promise<IotDpsResourceDeletePrivateEndpointConnectionResponse>; }
the_stack
import { useState, useEffect } from 'react'; import { css } from '@emotion/react'; import { textSans, neutral } from '@guardian/source-foundations'; import { Button } from '@guardian/source-react-components'; import PlusIcon from '@frontend/static/icons/plus.svg'; import MinusIcon from '@frontend/static/icons/minus.svg'; import { decidePalette } from '@root/src/web/lib/decidePalette'; import { Form } from '../Callout/Form'; const wrapperStyles = css` margin-bottom: 26px; margin-top: 16px; `; const calloutDetailsStyles = css` border-top: 1px ${neutral[86]} solid; border-bottom: 1px ${neutral[86]} solid; position: relative; padding-bottom: 10px; /* IE does not support summary HTML elements, so we need to hide children ourself */ :not([open]) > *:not(summary) { display: none; } `; const backgroundColorStyle = css` background-color: ${neutral[97]}; `; const speechBubbleWrapperStyles = css` margin-right: 10px; `; const successTextStyles = css` ${textSans.medium({ fontWeight: 'bold' })} `; const summeryStyles = css` /* Removing default styles from summery tag */ ::-webkit-details-marker { display: none; } outline: none; /* We don't want the summary to open when we click anything but the button, so we pointer-event: none the summary */ /* 176da211-05aa-4280-859b-1e3157b3f19e */ pointer-events: none; /* why hide visibility? because we want to prevent the user for tabbing to the summery HTML element without using tabIndex={-1} which would disable focus on all child DOM elements NOTE: requires "visibility: visible;" on child elements to display and enable focus */ visibility: hidden; a { /* but we do want to allow click on links */ pointer-events: all; } `; const summeryContentWrapper = css` visibility: visible; min-height: 70px; display: flex; flex-direction: row; `; const speechBubbleStyles = (palette: Palette) => css` ${textSans.medium({ fontWeight: 'bold' })} color: ${neutral[100]}; background-color: ${palette.background.speechBubble}; min-width: 88px; padding-bottom: 6px; padding-left: 10px; padding-right: 10px; ::after { content: ''; width: 20px; height: 22px; border-bottom-right-radius: 18px; position: absolute; background-color: ${palette.background.speechBubble}; } `; const headingTextHeaderStyles = css` ${textSans.medium({ fontWeight: 'bold' })} `; const headingTextStyles = (palette: Palette) => css` a { color: ${palette.text.calloutHeading}; text-decoration: none; :hover { text-decoration: underline; } } `; const buttonWrapperStyles = css` position: absolute; cursor: pointer; margin-top: -5px; visibility: visible; /* We need to ensure our pointer-events are turned back on on the button */ /* 176da211-05aa-4280-859b-1e3157b3f19e */ pointer-events: all; `; // Normally forms are in Modals, but here they are embeded into the page // we therefore need to only focus on expandFormButtonRef if the form has been closed // after it was opened let hasFormBeenOpened = true; type FormDataType = { [key in string]: any }; export const CalloutBlockComponent = ({ callout, format, }: { callout: CalloutBlockElement; format: ArticleFormat; }) => { let expandFormButtonRef: HTMLButtonElement | null = null; let firstFieldElementRef: HTMLElement | null = null; let lastElementRef: HTMLButtonElement | null = null; const [isExpanded, setIsExpanded] = useState(false); const [error, setError] = useState(''); const [submissionSuccess, setSubmissionSuccess] = useState(false); const palette = decidePalette(format); const { title, description, formFields } = callout; const onSubmit = async (formData: FormDataType) => { // Reset error for new submission attempt setError(''); if (formData.twitterHandle) { setError('Sorry we think you are a robot.'); return; } // need to add prefix `field_` to all keys in form const formDataWithFieldPrefix = Object.keys(formData).reduce( (acc, cur) => ({ ...acc, [`field_${cur}`]: formData[cur], }), {}, ); return fetch(callout.calloutsUrl, { method: 'POST', body: JSON.stringify({ formId: callout.formId, // TODO: check if we need to send this 'twitter-handle': '', ...formDataWithFieldPrefix, }), headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }) .then((resp) => { if (resp.status === 201) { setSubmissionSuccess(true); setIsExpanded(false); } else { setError( 'Sorry, there was a problem submitting your form. Please try again later.', ); } }) .catch((respError) => { window.guardian.modules.sentry.reportError( respError, 'callout-embed-submission', ); setError( 'Sorry, there was a problem submitting your form. Please try again later.', ); }); }; // *************************** // * Accessibility * // *************************** useEffect(() => { // we have to use document.querySelector to find DOM elements // as Source library does not yet support react ref // TODO: use `useRef` once supported in Source // eslint-disable-next-line react-hooks/exhaustive-deps expandFormButtonRef = document.querySelector( 'button[custom-guardian="callout-form-open-button"]', ); // eslint-disable-next-line react-hooks/exhaustive-deps firstFieldElementRef = document.querySelector(` *[custom-guardian="callout-form-field"]:first-of-type input, *[custom-guardian="callout-form-field"]:first-of-type select `); // eslint-disable-next-line react-hooks/exhaustive-deps lastElementRef = document.querySelector( 'button[custom-guardian="callout-form-close-button"]', ); // lock shift to the form const keyListener = (e: KeyboardEvent) => { // keyCode 9 is tab key if (e.keyCode === 9) { // If firstElement or lastElement are not defined, do not continue if (!firstFieldElementRef || !lastElementRef) return; // we use `e.shiftKey` internally to determin the direction of the highlighting // using document.activeElement and e.shiftKey we can check what should be the next element to be highlighted if (!e.shiftKey && document.activeElement === lastElementRef) { // eslint-disable-next-line @typescript-eslint/no-unused-expressions firstFieldElementRef && firstFieldElementRef.focus(); e.preventDefault(); } if ( e.shiftKey && document.activeElement === firstFieldElementRef ) { // eslint-disable-next-line @typescript-eslint/no-unused-expressions lastElementRef && lastElementRef.focus(); // The shift key is down so loop focus back to the last item e.preventDefault(); } } }; document.addEventListener('keydown', keyListener); return () => document.removeEventListener('keydown', keyListener); }, [isExpanded]); // on open form, focus on firstFieldElementRef useEffect(() => { if (isExpanded && firstFieldElementRef) { // eslint-disable-next-line @typescript-eslint/no-unused-expressions firstFieldElementRef && firstFieldElementRef.focus(); } }, [isExpanded, firstFieldElementRef]); // on close form, focus on expandFormButtonRef useEffect(() => { if (!isExpanded && expandFormButtonRef && !hasFormBeenOpened) { // eslint-disable-next-line @typescript-eslint/no-unused-expressions expandFormButtonRef && expandFormButtonRef.focus(); } }, [isExpanded, expandFormButtonRef]); // Normally forms are in Modals, but here they are embeded into the page // we therefore need to only focus on expandFormButtonRef if the form has been closed // after it was opened useEffect(() => { if (isExpanded) { hasFormBeenOpened = false; } }, [isExpanded]); // be able to close the form using the escape key for accessibility useEffect(() => { const keyListener = (e: KeyboardEvent) => { // keyCode 27 is the escape key, we want to be able to close the form using it if (e.keyCode === 27) { setIsExpanded(false); } }; if (isExpanded) { document.addEventListener('keydown', keyListener); } return () => document.removeEventListener('keydown', keyListener); }, [isExpanded, setIsExpanded]); if (submissionSuccess) { return ( <figure data-print-layout="hide" css={wrapperStyles}> <details css={[calloutDetailsStyles, backgroundColorStyle]} aria-hidden={true} open={isExpanded} > <summary css={summeryStyles}> <div css={summeryContentWrapper}> <div css={speechBubbleWrapperStyles}> <div css={speechBubbleStyles(palette)}> <h4>Share your story</h4> </div> </div> <div css={headingTextStyles(palette)}> <p css={successTextStyles}> Thank you for your contribution </p> </div> </div> </summary> </details> </figure> ); } return ( <figure data-print-layout="hide" css={wrapperStyles}> <details css={[calloutDetailsStyles, isExpanded && backgroundColorStyle]} aria-hidden={true} open={isExpanded} > <summary css={summeryStyles}> <div css={summeryContentWrapper}> <div css={speechBubbleWrapperStyles}> <div css={speechBubbleStyles(palette)}> <h4>Share your story</h4> </div> </div> <div css={headingTextStyles(palette)}> <h4 css={headingTextHeaderStyles}>{title}</h4> {description && ( <div dangerouslySetInnerHTML={{ __html: description, }} /> )} </div> </div> {!isExpanded && ( <span css={buttonWrapperStyles} aria-hidden="true"> <Button css={css` /* TODO: need to find an nicer way of dynamically setting svg dimensions */ svg { width: 15px !important; height: 15px !important; } `} iconSide="left" size="xsmall" icon={<PlusIcon />} onClick={() => setIsExpanded(true)} custom-guardian="callout-form-open-button" tabIndex={0} > Tell us </Button> </span> )} </summary> <Form formFields={formFields} onSubmit={onSubmit} error={error} /> <span css={buttonWrapperStyles} aria-hidden="true"> {isExpanded && ( <Button iconSide="left" size="xsmall" icon={<MinusIcon />} onClick={() => setIsExpanded(false)} custom-guardian="callout-form-close-button" > Hide </Button> )} </span> </details> </figure> ); };
the_stack
import * as React from 'react' import Checkbox from 'src/components/checkbox' import FindingChooser from 'src/components/finding_chooser' import Form from 'src/components/form' import ImageUpload from 'src/components/image_upload' import ModalForm from 'src/components/modal_form' import Modal from 'src/components/modal' import TagChooser from 'src/components/tag_chooser' import BinaryUpload from 'src/components/binary_upload' import ComboBox from 'src/components/combobox' import TagList from 'src/components/tag_list' import { CodeBlockEditor } from 'src/components/code_block' import { Evidence, Finding, Tag, CodeBlock, SubmittableEvidence, Operation, TagDifference, SupportedEvidenceType } from 'src/global_types' import { TextArea } from 'src/components/input' import { useForm, useFormField } from 'src/helpers/use_form' import { codeblockToBlob } from 'src/helpers/codeblock_to_blob' import { useWiredData } from 'src/helpers' import { createEvidence, updateEvidence, deleteEvidence, changeFindingsOfEvidence, getFindingsOfEvidence, getEvidenceAsCodeblock, getOperations, getEvidenceMigrationDifference, moveEvidence } from 'src/services' import classnames from 'classnames/bind' const cx = classnames.bind(require('./stylesheet')) export const CreateEvidenceModal = (props: { onCreated: () => void, onRequestClose: () => void, operationSlug: string, }) => { const descriptionField = useFormField<string>("") const tagsField = useFormField<Array<Tag>>([]) const binaryBlobField = useFormField<File | null>(null) const codeblockField = useFormField<CodeBlock>({ type: 'codeblock', language: '', code: '', source: null }) const isATerminalRecording = (file: File) => file.type == '' const isAnHttpRequestCycle = (file: File) => file.name.endsWith("har") const evidenceTypeOptions: Array<{ name: string, value: SupportedEvidenceType, content?: React.ReactNode }> = [ { name: 'Screenshot', value: 'image', content: <ImageUpload label='Screenshot' {...binaryBlobField} /> }, { name: 'Code Block', value: 'codeblock', content: <CodeBlockEditor {...codeblockField} /> }, { name: 'Terminal Recording', value: 'terminal-recording', content: <BinaryUpload label='Terminal Recording' isSupportedFile={isATerminalRecording} {...binaryBlobField} /> }, { name: 'HTTP Request/Response', value: 'http-request-cycle', content: <BinaryUpload label='HAR File' isSupportedFile={isAnHttpRequestCycle} {...binaryBlobField} /> }, ] const [selectedCBValue, setSelectedCBValue] = React.useState<string>(evidenceTypeOptions[0].value) const getSelectedOption = () => evidenceTypeOptions.filter(opt => opt.value === selectedCBValue)[0] const formComponentProps = useForm({ fields: [descriptionField, binaryBlobField], onSuccess: () => { props.onCreated(); props.onRequestClose() }, handleSubmit: () => { let data: SubmittableEvidence = { type: "none" } const selectedOption = getSelectedOption() const fileBasedKeys = ['image', 'terminal-recording', 'http-request-cycle'] if (selectedOption.value === 'codeblock' && codeblockField.value !== null) { data = { type: 'codeblock', file: codeblockToBlob(codeblockField.value) } } else if (fileBasedKeys.includes(selectedOption.value) && binaryBlobField.value != null ) { data = { type: selectedOption.value, file: binaryBlobField.value } } return createEvidence({ operationSlug: props.operationSlug, description: descriptionField.value, evidence: data, tagIds: tagsField.value.map(t => t.id), }) }, }) return ( <ModalForm title="New Evidence" submitText="Create Evidence" onRequestClose={props.onRequestClose} {...formComponentProps}> <TextArea label="Description" {...descriptionField} /> <ComboBox label="Evidence Type" className={cx('dropdown')} options={evidenceTypeOptions} value={selectedCBValue} onChange={setSelectedCBValue} /> {getSelectedOption().content} <TagChooser operationSlug={props.operationSlug} label="Tags" {...tagsField} /> </ModalForm> ) } export const EditEvidenceModal = (props: { evidence: Evidence, onEdited: () => void, onRequestClose: () => void, operationSlug: string, }) => { const descriptionField = useFormField<string>(props.evidence.description) const tagsField = useFormField<Array<Tag>>(props.evidence.tags) const codeblockField = useFormField<CodeBlock>({ type: 'codeblock', language: '', code: '', source: null }) React.useEffect(() => { if (props.evidence.contentType !== 'codeblock') { return } getEvidenceAsCodeblock({ operationSlug: props.operationSlug, evidenceUuid: props.evidence.uuid, }).then(codeblockField.onChange) }, [props.evidence.contentType, codeblockField.onChange, props.operationSlug, props.evidence.uuid]) const formComponentProps = useForm({ fields: [descriptionField, tagsField, codeblockField], onSuccess: () => { props.onEdited(); props.onRequestClose() }, handleSubmit: () => updateEvidence({ operationSlug: props.operationSlug, evidenceUuid: props.evidence.uuid, description: descriptionField.value, oldTags: props.evidence.tags, newTags: tagsField.value, updatedContent: props.evidence.contentType === 'codeblock' ? codeblockToBlob(codeblockField.value) : null, }), }) return ( <ModalForm title="Edit Evidence" submitText="Save" onRequestClose={props.onRequestClose} {...formComponentProps}> <TextArea label="Description" {...descriptionField} /> {props.evidence.contentType === 'codeblock' && ( <CodeBlockEditor {...codeblockField} /> )} <TagChooser operationSlug={props.operationSlug} label="Tags" {...tagsField} /> </ModalForm> ) } export const ChangeFindingsOfEvidenceModal = (props: { evidence: Evidence, onChanged: () => void, onRequestClose: () => void, operationSlug: string, }) => { const wiredFindings = useWiredData<Array<Finding>>(React.useCallback(() => getFindingsOfEvidence({ operationSlug: props.operationSlug, evidenceUuid: props.evidence.uuid, }), [props.operationSlug, props.evidence.uuid])) return ( <Modal title="Select Findings For Evidence" onRequestClose={props.onRequestClose}> {wiredFindings.render(initialFindings => ( <InternalChangeFindingsOfEvidenceModal {...props} initialFindings={initialFindings} /> ))} </Modal> ) } const InternalChangeFindingsOfEvidenceModal = (props: { evidence: Evidence, onChanged: () => void, onRequestClose: () => void, operationSlug: string, initialFindings: Array<Finding>, }) => { const oldFindingsField = useFormField<Array<Finding>>(props.initialFindings) const newFindingsField = useFormField<Array<Finding>>(props.initialFindings) const formComponentProps = useForm({ fields: [newFindingsField], onSuccess: () => { props.onChanged(); props.onRequestClose() }, handleSubmit: () => changeFindingsOfEvidence({ operationSlug: props.operationSlug, evidenceUuid: props.evidence.uuid, oldFindings: oldFindingsField.value, newFindings: newFindingsField.value, }), }) return ( <Form submitText="Update Evidence" cancelText="Cancel" onCancel={props.onRequestClose} {...formComponentProps}> <FindingChooser operationSlug={props.operationSlug} {...newFindingsField} /> </Form> ) } export const DeleteEvidenceModal = (props: { evidence: Evidence, onDeleted: () => void, onRequestClose: () => void, operationSlug: string, }) => { const deleteAssociatedFindingsField = useFormField(false) const formComponentProps = useForm({ fields: [deleteAssociatedFindingsField], onSuccess: () => { props.onDeleted(); props.onRequestClose() }, handleSubmit: () => deleteEvidence({ operationSlug: props.operationSlug, evidenceUuid: props.evidence.uuid, deleteAssociatedFindings: deleteAssociatedFindingsField.value, }), }) return ( <ModalForm title="Delete Evidence" submitText="Delete Evidence" onRequestClose={props.onRequestClose} {...formComponentProps}> <p>Are you sure you want to delete this evidence?</p> <Checkbox label="Also delete any findings associated with this evidence" {...deleteAssociatedFindingsField} /> </ModalForm> ) } export const MoveEvidenceModal = (props: { evidence: Evidence, operationSlug: string, onRequestClose: () => void, onEvidenceMoved: () => void, }) => { const [selectedOperationSlug, setSelectedOperation] = React.useState(props.operationSlug) const wiredOps = useWiredData<Array<Operation>>(React.useCallback(getOperations, [props.operationSlug, props.evidence.uuid])) const wiredDiff = useWiredData<TagDifference>(React.useCallback(() => getEvidenceMigrationDifference({ fromOperationSlug: props.operationSlug, toOperationSlug: selectedOperationSlug, evidenceUuid: props.evidence.uuid, }), [selectedOperationSlug, props.evidence.uuid, props.operationSlug])) const formComponentProps = useForm({ fields: [], onSuccess: () => { props.onEvidenceMoved(); props.onRequestClose() }, handleSubmit: () => { if (selectedOperationSlug == props.operationSlug) { return Promise.resolve() // no need to do anything if the to and from destinations are the same } return moveEvidence({ fromOperationSlug: props.operationSlug, toOperationSlug: selectedOperationSlug, evidenceUuid: props.evidence.uuid }).then(() => { window.location.href = `/operations/${props.operationSlug}/evidence` }) }, }) return ( <ModalForm title="Move Evidence To Another Operation" submitText="Move" onRequestClose={props.onRequestClose} {...formComponentProps}> <div> Moving evidence will disconnect this evidence from any findings and some tags may be lost in the transition. </div> {wiredOps.render(operations => { operations.sort((a, b) => a.name.localeCompare(b.name)) const mappedOperations = operations.map(op => ({ name: op.name, value: op })) return ( <ComboBox label="Select a destination operation" options={mappedOperations} value={operations.filter(op => op.slug === selectedOperationSlug)[0]} onChange={op => setSelectedOperation(op.slug)} /> ) })} {wiredDiff.render(data => ( <TagListRenderer sourceSlug={props.operationSlug} destSlug={selectedOperationSlug} tags={data.excluded} /> ))} </ModalForm> ) } const TagListRenderer = (props: { sourceSlug: string, destSlug: string tags: Array<Tag> | null }) => { if (props.sourceSlug == props.destSlug) { return <div>This is the current operation, and so no changes will be made</div> } else if (props.tags == null || props.tags.length == 0) { return <div>All tags will carry over</div> } return (<> <div>The following tags will be removed:</div> <TagList tags={props.tags} /> </>) }
the_stack
import Injector from '../../src/injector'; import { FastifyToken } from '../../src/symbols'; import { Samurai, Ninja, Weapon, Katana, Shuriken, Naginata, Nunchaku, Tanto, Wakizashi, FastifyDecorated } from '../data/injectables'; import type { FastifyInstance } from 'fastify'; class BaseModel {} describe('Injector', () => { let injector: Injector; const fastifyInstance: FastifyInstance = { schema: { id: { type: 'number' } }, steel: 'real steel', [FastifyDecorated]: 'FastifyDecoratedValue', BaseModel } as any; beforeEach(() => { injector = new Injector(); injector.registerInstance(FastifyToken, fastifyInstance); }); it('Should use singleton instances', () => { const samuraiFirst = injector.getInstance(Samurai); const samuraiSecond = injector.getInstance(Samurai); expect(samuraiFirst).toBe(samuraiSecond); // Compare injects of two same class instances expect(samuraiFirst.katana).toBe(samuraiSecond.katana); expect(samuraiFirst.shuriken).toBe(samuraiSecond.shuriken); expect(samuraiFirst.naginata).toBe(samuraiSecond.naginata); expect(samuraiFirst.nunchaku).toBe(samuraiSecond.nunchaku); expect(samuraiFirst.tanto).toBe(samuraiSecond.tanto); expect(samuraiFirst.wakizashi).toBe(samuraiSecond.wakizashi); expect(samuraiFirst.fastifyInstance).toBe(samuraiSecond.fastifyInstance); // Compare injects of instance and static class property expect(samuraiFirst.shuriken).toBe(Samurai.shuriken); expect(samuraiFirst.shuriken).toBe(Samurai.shuriken); expect(samuraiFirst.wakizashi).toBe(Samurai.wakizashi); expect(samuraiFirst.wakizashi).toBe(Samurai.wakizashi); expect(samuraiFirst.tanto).toBe(Samurai.tanto); expect(samuraiFirst.tanto).toBe(Samurai.tanto); // Compare injects of instances and newly resolved instances const katana = injector.getInstance(Katana); expect(samuraiFirst.katana).toBe(katana); expect(samuraiSecond.katana).toBe(katana); const shuriken = injector.getInstance(Shuriken); expect(samuraiFirst.shuriken).toBe(shuriken); expect(samuraiSecond.shuriken).toBe(shuriken); const naginata = injector.getInstance(Naginata); expect(samuraiFirst.naginata).toBe(naginata); expect(samuraiSecond.naginata).toBe(naginata); const nunchaku = injector.getInstance(Nunchaku); expect(samuraiFirst.nunchaku).toBe(nunchaku); expect(samuraiSecond.nunchaku).toBe(nunchaku); const tanto = injector.getInstance(Tanto); expect(samuraiFirst.tanto).toBe(tanto); expect(samuraiSecond.tanto).toBe(tanto); const wakizashi = injector.getInstance(Wakizashi); expect(samuraiFirst.wakizashi).toBe(wakizashi); expect(samuraiSecond.wakizashi).toBe(wakizashi); }); describe('Resolve instance by type', () => { it('Should inject constructor parameter by type', () => { // @Controller const samurai = injector.getInstance(Samurai); expect(samurai.katana).toBeDefined(); expect(samurai.katana.hit).toBeDefined(); // @EntityController const ninja = injector.getInstance(Ninja); expect(ninja.katana).toBeDefined(); expect(ninja.katana.hit).toBeDefined(); // @Service const weapon = injector.getInstance(Weapon); expect(weapon.katana).toBeDefined(); expect(weapon.katana.hit).toBeDefined(); }); it('Should inject class property by type', () => { // @Controller const samurai = injector.getInstance(Samurai); expect(samurai.shuriken).toBeDefined(); expect(samurai.shuriken.cast).toBeDefined(); // @EntityController const ninja = injector.getInstance(Ninja); expect(ninja.shuriken).toBeDefined(); expect(ninja.shuriken.cast).toBeDefined(); // @Service const weapon = injector.getInstance(Weapon); expect(weapon.shuriken).toBeDefined(); expect(weapon.shuriken.cast).toBeDefined(); }); it('Should inject class static property by type', () => { // @Controller injector.getInstance(Samurai); expect(Samurai.shuriken).toBeDefined(); expect(Samurai.shuriken.cast).toBeDefined(); // @EntityController injector.getInstance(Ninja); expect(Ninja.shuriken).toBeDefined(); expect(Ninja.shuriken.cast).toBeDefined(); // @Service injector.getInstance(Weapon); expect(Weapon.shuriken).toBeDefined(); expect(Weapon.shuriken.cast).toBeDefined(); }); it('Should ignore empty token if type is defined', () => { // @Controller const samurai = injector.getInstance(Samurai); expect(samurai.naginata).toBeDefined(); expect(samurai.naginata.size).toBeDefined(); // @EntityController const ninja = injector.getInstance(Ninja); expect(ninja.naginata).toBeDefined(); expect(ninja.naginata.size).toBeDefined(); // @Service const weapon = injector.getInstance(Weapon); expect(weapon.naginata).toBeDefined(); expect(weapon.naginata.size).toBeDefined(); }); }); describe('Resolve instance by token', () => { describe('String token', () => { it('Should inject constructor parameter by string token', () => { // @Controller const samurai = injector.getInstance(Samurai); expect(samurai.schema).toBeDefined(); expect(samurai.schema).toEqual((fastifyInstance as any).schema); // @EntityController const ninja = injector.getInstance(Ninja); expect(ninja.schema).toBeDefined(); expect(ninja.schema).toEqual((fastifyInstance as any).schema); // @Service const weapon = injector.getInstance(Weapon); expect(weapon.schema).toBeDefined(); expect(weapon.schema).toEqual((fastifyInstance as any).schema); }); it('Should inject decorated value into class property by string token', () => { // @Controller const samurai = injector.getInstance(Samurai); expect(samurai.steel).toBeDefined(); expect(samurai.steel).toBe('real steel'); // @EntityController const ninja = injector.getInstance(Ninja); expect(ninja.steel).toBeDefined(); expect(ninja.steel).toBe('real steel'); // @Service const weapon = injector.getInstance(Weapon); expect(weapon.steel).toBeDefined(); expect(weapon.steel).toBe('real steel'); }); it('Should inject decorated value into class static property by string token', () => { // @Controller injector.getInstance(Samurai); expect(Samurai.steel).toBeDefined(); expect(Samurai.steel).toBe('real steel'); // @EntityController injector.getInstance(Ninja); expect(Ninja.steel).toBeDefined(); expect(Ninja.steel).toBe('real steel'); // @Service injector.getInstance(Weapon); expect(Weapon.steel).toBeDefined(); expect(Weapon.steel).toBe('real steel'); }); it('Should inject Service into class property by string token', () => { // @Controller const samurai = injector.getInstance(Samurai); expect(samurai.wakizashi).toBeDefined(); expect(samurai.wakizashi.fight).toBeDefined(); // @EntityController const ninja = injector.getInstance(Ninja); expect(ninja.wakizashi).toBeDefined(); expect(ninja.wakizashi.fight).toBeDefined(); // @Service const weapon = injector.getInstance(Weapon); expect(weapon.wakizashi).toBeDefined(); expect(weapon.wakizashi.fight).toBeDefined(); }); it('Should inject Service into class static property by string token', () => { // @Controller injector.getInstance(Samurai); expect(Samurai.wakizashi).toBeDefined(); expect(Samurai.wakizashi.fight).toBeDefined(); // @EntityController injector.getInstance(Ninja); expect(Ninja.wakizashi).toBeDefined(); expect(Ninja.wakizashi.fight).toBeDefined(); // @Service injector.getInstance(Weapon); expect(Weapon.wakizashi).toBeDefined(); expect(Weapon.wakizashi.fight).toBeDefined(); }); }); describe('Symbol token', () => { it('Should inject Fastify instance by token', () => { // @Controller const samurai = injector.getInstance(Samurai); expect(samurai.fastifyInstance).toBeDefined(); // @EntityController const ninja = injector.getInstance(Ninja); expect(ninja.fastifyInstance).toBeDefined(); // @Service const weapon = injector.getInstance(Weapon); expect(weapon.fastifyInstance).toBeDefined(); }); it('Should inject Fastify decorated symbol by token', () => { // @Controller const samurai = injector.getInstance(Samurai); expect(samurai.fastifyDecorated).toBe('FastifyDecoratedValue'); // @EntityController const ninja = injector.getInstance(Ninja); expect(ninja.fastifyDecorated).toBe('FastifyDecoratedValue'); // @Service const weapon = injector.getInstance(Weapon); expect(weapon.fastifyDecorated).toBe('FastifyDecoratedValue'); }); it('Should inject Service into class property by Symbol token', () => { // @Controller const samurai = injector.getInstance(Samurai); expect(samurai.tanto).toBeDefined(); expect(samurai.tanto.use).toBeDefined(); // @EntityController const ninja = injector.getInstance(Ninja); expect(ninja.tanto).toBeDefined(); expect(ninja.tanto.use).toBeDefined(); // @Service const weapon = injector.getInstance(Weapon); expect(weapon.tanto).toBeDefined(); expect(weapon.tanto.use).toBeDefined(); }); it('Should inject Service into class static property by Symbol token', () => { // @Controller injector.getInstance(Samurai); expect(Samurai.tanto).toBeDefined(); expect(Samurai.tanto.use).toBeDefined(); // @EntityController injector.getInstance(Ninja); expect(Ninja.tanto).toBeDefined(); expect(Ninja.tanto.use).toBeDefined(); // @Service injector.getInstance(Weapon); expect(Weapon.tanto).toBeDefined(); expect(Weapon.tanto.use).toBeDefined(); }); it('Should inject Service into constructor by Symbol token', () => { // @Controller const samurai = injector.getInstance(Samurai); expect(samurai.nunchaku).toBeDefined(); expect(samurai.nunchaku.brandish).toBeDefined(); // @EntityController const ninja = injector.getInstance(Ninja); expect(ninja.nunchaku).toBeDefined(); expect(ninja.nunchaku.brandish).toBeDefined(); // @Service const weapon = injector.getInstance(Weapon); expect(weapon.nunchaku).toBeDefined(); expect(weapon.nunchaku.brandish).toBeDefined(); }); }); }); describe('Construct injected model', () => { it('Should construct model from constructor parameter', () => { // @Controller const samurai = injector.getInstance(Samurai); expect(samurai.backpackModel).toBeDefined(); expect(samurai.backpackModel).toBeInstanceOf(BaseModel); // @EntityController const ninja = injector.getInstance(Ninja); expect(ninja.backpackModel).toBeDefined(); expect(ninja.backpackModel).toBeInstanceOf(BaseModel); // @Service const weapon = injector.getInstance(Weapon); expect(weapon.backpackModel).toBeDefined(); expect(weapon.backpackModel).toBeInstanceOf(BaseModel); }); it('Should construct model from class property', () => { // @Controller const samurai = injector.getInstance(Samurai); expect(samurai.backpack).toBeDefined(); expect(samurai.backpack).toBeInstanceOf(BaseModel); // @EntityController const ninja = injector.getInstance(Ninja); expect(ninja.backpack).toBeDefined(); expect(ninja.backpack).toBeInstanceOf(BaseModel); // @Service const weapon = injector.getInstance(Weapon); expect(weapon.backpack).toBeDefined(); expect(weapon.backpack).toBeInstanceOf(BaseModel); }); it('Should construct model from class static property', () => { // @Controller injector.getInstance(Samurai); expect(Samurai.backpack).toBeDefined(); expect(Samurai.backpack).toBeInstanceOf(BaseModel); // @EntityController injector.getInstance(Ninja); expect(Ninja.backpack).toBeDefined(); expect(Ninja.backpack).toBeInstanceOf(BaseModel); // @Service injector.getInstance(Weapon); expect(Weapon.backpack).toBeDefined(); expect(Weapon.backpack).toBeInstanceOf(BaseModel); }); it('Should construct different instances of same Entity', () => { const samurai = injector.getInstance(Samurai); expect(samurai.backpackModel).not.toBe(samurai.backpack); expect(samurai.backpack).not.toBe(Samurai.backpack); const ninja = injector.getInstance(Ninja); expect(ninja.backpackModel).not.toBe(ninja.backpack); expect(ninja.backpack).not.toBe(Ninja.backpack); const weapon = injector.getInstance(Weapon); expect(weapon.backpackModel).not.toBe(weapon.backpack); expect(weapon.backpack).not.toBe(Weapon.backpack); expect(samurai.backpackModel).not.toBe(ninja.backpackModel); expect(ninja.backpackModel).not.toBe(weapon.backpackModel); expect(samurai.backpack).not.toBe(ninja.backpack); expect(ninja.backpack).not.toBe(weapon.backpack); expect(Samurai.backpack).not.toBe(Ninja.backpack); expect(Ninja.backpack).not.toBe(Weapon.backpack); }); }); });
the_stack
import * as React from 'react'; import { InteractionManager, StyleSheet, View, ViewStyle, } from 'react-native'; import { IMDSwiperProps, IMDSwiperStyle, MDSwiperStyles } from './swiper.base'; import SwiperDots from './swiper.dots'; export interface IMDSwiperSlideState { index: number; isStoped: boolean; autoplay: number; ready: boolean; } const styles = StyleSheet.create<IMDSwiperStyle>(MDSwiperStyles); const addPropsToSwiperItem = ( children: any, width: number, height: number, backup: boolean, transition: string, key: any ): React.ReactNode | React.ReactNode[] => { if (!children) { return null; } if (children.props && children.props.__name === 'MDSwiperItem') { const _style: ViewStyle = { width, height, }; if (transition === 'slideY') { const _styleWrapper: ViewStyle = { height: width, width: height, justifyContent: 'center', alignItems: 'center', overflow: 'hidden', }; return ( <View key={key} style={_styleWrapper}> <View style={[_style, { transform: [{ rotate: '-90deg' }] }]}> {children} </View> </View> ); } return ( <View key={key} style={_style}> {children} </View> ); } else if (React.Children.count(children) > 0) { const _children = []; // 用于循环,在最前面复制最后一条数据 backup && _children.push( addPropsToSwiperItem( children[children.length - 1], width, height, backup, transition, -1 ) ); React.Children.forEach(children, (child, index) => { _children.push( addPropsToSwiperItem(child, width, height, backup, transition, index) ); }); // 用于循环,在最后面复制第一条数据 backup && _children.push( addPropsToSwiperItem( children[0], width, height, backup, transition, children.length ) ); return _children; } return children; }; export default abstract class MDSwiperSlideIOS extends React.Component< IMDSwiperProps, IMDSwiperSlideState > { public static defaultProps = { styles, autoplay: 3000, transition: 'slide', defaultIndex: 0, hasDots: true, isLoop: true, dragable: true, }; constructor (props: IMDSwiperProps) { super(props); // @ts-ignore const { defaultIndex, autoplay } = props; // @ts-ignore const _oCount = this.getOItemCount(); const _defaultIndex = defaultIndex || 0; let index = _defaultIndex >= 0 && _defaultIndex < _oCount ? _defaultIndex : 0; if (this.isNeedBackup()) { index = index + 1; } this.fromIndex = index === 0 ? _oCount - 1 : index - 1; this.toIndex = index; this.userScrolling = false; this.state = { index, isStoped: false, autoplay: autoplay || 3000, ready: false, }; } protected fromIndex: number; protected toIndex: number; protected timer: any; protected userScrolling: boolean; public componentDidMount () { const { children } = this.props; // @ts-ignore if (!children || !children.length) { return; } InteractionManager.runAfterInteractions(() => { setTimeout(() => { this.translate(this.state.index, false); }, 100); this.setState( { ready: true, }, () => { this.startPlay(); } ); }); } public componentWillUnmount () { this.clearTimer(); } // MARK: public methods public next () { this.doTransition('next'); } public prev () { this.doTransition('prev'); } public goto (index: number) { if (isNaN(index)) { return; } const oItemCount = this.getOItemCount(); if (index === this.state.index || index < 0 || index >= oItemCount) { return; } this.clearTimer(); const towards = index > this.state.index ? 'next' : 'prev'; this.setState({ index, }); this.doTransition(towards, { index }); this.startPlay(); } public getIndex (): number { return this.calcuRealIndex(this.state.index); } public play (autoplay = 3000) { this.clearTimer(); if (autoplay < 500) { return; } this.setState({ autoplay: autoplay || this.props.autoplay || 3000, isStoped: false, }); this.startPlay(); } public stop () { this.clearTimer(); this.setState({ isStoped: true, }); } public render () { const { width, height } = this.props; const _styles = this.props.styles!; const _scrollView = this.renderScrollView(); const _dots = ( <SwiperDots index={this.originalIndex()} style={_styles} itemCount={this.getOItemCount()} isVertical={this.isVertical()} /> ); return ( <View style={[_styles.wrapper, { width, height }]}> {_scrollView} {_dots} </View> ); } protected abstract renderScrollView (): React.ReactNode; protected abstract translate (index: number, animated: boolean): void; protected abstract onScrollEnd (e: any): void; protected renderChildren () { const { children, width, height, transition } = this.props; return addPropsToSwiperItem( children, width, height, this.isNeedBackup(), transition!, 0 ); } // MARK Calculate Method protected isFirstItem () { return this.state.index === 0; } protected isLastItem () { return this.state.index === this.getRItemCount() - 1; } protected originalIndex () { if (this.props.isLoop) { return this.state.index - 1; } else { return this.state.index; } } protected isVertical () { return this.props.transition === 'slideY'; } protected getDimension () { return this.isVertical() ? this.props.height : this.props.width; } protected getOItemCount () { const { children } = this.props; return children ? React.Children.count(children) || 1 : 0; } protected getRItemCount () { const { isLoop } = this.props; const oItemCount = this.getOItemCount(); if (!isLoop) { // 不循环:没有前后的加帧,返回原始count return oItemCount; } if (oItemCount <= 1) { // 循环,但原始count只有一个:没有前后的加帧,返回原始count return oItemCount; } // 循环,且原始count大于1:有前后的加帧,返回原始count + 2 return oItemCount + 2; } protected isNeedBackup (): boolean { return this.getOItemCount() < this.getRItemCount(); } protected getFirstIndex (): number { if (this.isNeedBackup()) { return 1; } return 0; } protected getLastIndex (): number { if (this.isNeedBackup()) { return this.getOItemCount(); } return this.getOItemCount() - 1; } protected getIsNotDraggable (): boolean { return this.getOItemCount() === 1 || !this.props.dragable; } // MARK logic Method protected startPlay () { const { autoplay, isLoop } = this.props; const { index } = this.state; const oItemCount = this.getOItemCount(); const rItemCount = this.getRItemCount(); if (autoplay! > 0 && oItemCount > 1 && isLoop) { const _timer = setInterval(() => { if (!isLoop && index >= rItemCount - 1) { return this.clearTimer(); } this.doTransition('next'); }, this.state.autoplay); this.timer = _timer; } } protected clearTimer () { if (this.timer) { clearInterval(this.timer); this.timer = null; } } protected calcuRealIndex (index: number) { const oItemCount = this.getOItemCount(); if (this.props.isLoop && oItemCount > 0) { return index - 1 < 0 ? oItemCount - 1 : index - 1 > oItemCount - 1 ? 0 : index - 1; } return index; } protected calcuNewIndex ( towards: string, options?: any ): { newFromIndex: number; newToIndex: number; newIndex: number } { const { isLoop } = this.props; const { index } = this.state; const { fromIndex, toIndex } = this; const oItemCount = this.getOItemCount(); const rItemCount = this.getRItemCount(); const result = { newFromIndex: fromIndex, newToIndex: toIndex, newIndex: index, }; if (oItemCount === 0) { return result; } if (!options && oItemCount < 2) { return result; } const itemCount = rItemCount; let newIndex = index; const oldIndex = index; if (!towards) { return result; } if (options && options.index) { newIndex = options.index + (isLoop ? 1 : 0); } else if (towards === 'prev') { if (index > 0) { newIndex = index - 1; } else if (isLoop && index === 0) { newIndex = itemCount - 1; } } else if (towards === 'next') { if (index < itemCount - 1) { newIndex = index + 1; } else if (isLoop && index === itemCount - 1) { newIndex = 1; } } let newFromIndex = toIndex; let newToIndex = newIndex; if (isLoop) { newFromIndex = this.calcuRealIndex(oldIndex); newToIndex = this.calcuRealIndex(newIndex); } return { newFromIndex, newToIndex, newIndex }; } protected doTransition (towards: string, options?: any) { const { onBeforeChange } = this.props; const { newFromIndex, newToIndex, newIndex } = this.calcuNewIndex( towards, options ); this.fromIndex = newFromIndex; this.toIndex = newToIndex; this.setState( { index: newIndex, }, () => { onBeforeChange && onBeforeChange(newFromIndex, newToIndex); this.translate(newIndex, true); } ); } protected afterTrans () { const { isLoop, onAfterChange } = this.props; const { fromIndex, toIndex } = this; const firstIndex = this.getFirstIndex(); const lastIndex = this.getLastIndex(); if (isLoop && (this.isLastItem() || this.isFirstItem())) { const _index = this.isLastItem() ? firstIndex : lastIndex; this.setState( { index: _index, }, () => { this.translate(_index, false); } ); } onAfterChange && onAfterChange(fromIndex, toIndex); } }
the_stack
import { HttpParams } from "@angular/common/http"; import { Injectable, OnDestroy } from "@angular/core"; import { ServerError } from "@batch-flask/core"; import { SanitizedError, log } from "@batch-flask/utils"; import { ArmBatchAccount, ArmSubscription } from "app/models"; import { AccountPatchDto } from "app/models/dtos"; import { ArmResourceUtils } from "app/utils"; import { Constants } from "common"; import { List } from "immutable"; import { BehaviorSubject, Observable, empty, forkJoin, of } from "rxjs"; import { catchError, expand, filter, flatMap, map, reduce, share, shareReplay, switchMap, take } from "rxjs/operators"; import { AzureHttpService } from "../azure-http.service"; import { ArmListResponse } from "../core"; import { SubscriptionService } from "../subscription"; const batchProvider = "Microsoft.Batch"; const batchResourceProvider = batchProvider + "/batchAccounts"; export interface AvailabilityResult { nameAvailable: boolean; reason?: string; message?: string; } export interface QuotaResult { used: number; quota: number; } export interface ArmBatchAccountListParams { subscriptionId: string; } export interface ArmBatchAccountParams { id: string; } export class ArmBatchAccountSubscriptionError extends SanitizedError { } @Injectable({ providedIn: "root" }) export class ArmBatchAccountService implements OnDestroy { public accounts: Observable<List<ArmBatchAccount>>; private _accounts = new BehaviorSubject<List<ArmBatchAccount>>(null); constructor( private azure: AzureHttpService, private subscriptionService: SubscriptionService) { this.accounts = this._accounts.pipe(filter(x => x !== null)); } public ngOnDestroy() { this._accounts.complete(); } public get(id: string): Observable<ArmBatchAccount> { const subscriptionId = ArmResourceUtils.getSubscriptionIdFromResourceId(id); if (!subscriptionId) { throw new ArmBatchAccountSubscriptionError(`Couldn't parse subscription id from batch account id ${id}`); } return this.subscriptionService.get(subscriptionId).pipe( flatMap((subscription) => { if (!subscription) { throw new ServerError({ status: 404, code: "SubscriptionNotFound", message: `Subscription ${subscriptionId} is not found. You might not have permission anymore.`, }); } return this.azure.get(subscription, id).pipe( map(response => this._createAccount(subscription, response)), ); }), share(), ); } public patch(accountId: string, properties: AccountPatchDto): Observable<any> { return this.subscriptionService.get(ArmResourceUtils.getSubscriptionIdFromResourceId(accountId)).pipe( flatMap((subscription) => { return this.azure.patch(subscription, accountId, { properties: properties.toJS() }); }), ); } public putResourceGroup(sub: ArmSubscription, resourceGroup: string, body: any) { const rgUri = this.getResoureGroupId(sub, resourceGroup); return this.azure.put(sub, rgUri, { body: body }); } public create(sub: ArmSubscription, resourceGroup: string, accountName: string, body: any): Observable<any> { const accountUri = this.getAccountId(sub, resourceGroup, accountName); return this.azure.put(sub, accountUri, { body: body }); } public delete(accountId: string): Observable<any> { return this.subscriptionService.get(ArmResourceUtils.getSubscriptionIdFromResourceId(accountId)).pipe( flatMap((subscription) => { return this.azure.delete(subscription, accountId); }), ); } public getAccountId(sub: ArmSubscription, resourceGroup: string, accountName: string): string { const uriPrefix = this.getResoureGroupId(sub, resourceGroup); return `${uriPrefix}/providers/${batchProvider}/batchAccounts/${accountName}`; } public getResoureGroupId(sub: ArmSubscription, resourceGroup: string): string { return `subscriptions/${sub.subscriptionId}/resourceGroups/${resourceGroup}`; } /** * Call nameAvailability api to get account conflict info per location * @param subscriptionId */ public nameAvailable( name: string, subscription: ArmSubscription, location: string, ): Observable<AvailabilityResult> { if (!name || !subscription || !location) { return of(null); } const uri = `subscriptions/${subscription.subscriptionId}/providers/${batchProvider}` + `/locations/${location}/checkNameAvailability`; return this.azure.post(subscription, uri, { name: name, type: batchResourceProvider, }); } /** * Call quota api and resource api to get result of whether current subscription quota reached or not * @param subscription * @param location */ public accountQuota(subscription: ArmSubscription, location: string): Observable<QuotaResult> { if (!subscription || !location) { return of(null); } // get current subscription account quota const quotaUri = `subscriptions/${subscription.subscriptionId}/providers/${batchProvider}` + `/locations/${location}/quotas`; const getQuotaObs = this.azure.get<any>(subscription, quotaUri); // get current batch accounts number const resourceUri = `/subscriptions/${subscription.subscriptionId}/resources`; const params = new HttpParams() .set("$filter", `resourceType eq '${batchResourceProvider}' and location eq '${location}'`); const options = { params }; const batchAccountObs = this.azure.get<ArmListResponse<any>>(subscription, resourceUri, options).pipe( expand(obs => { return obs.nextLink ? this.azure.get(subscription, obs.nextLink, options) : empty(); }), reduce((batchAccounts, response: ArmListResponse<any>) => { return [...batchAccounts, ...response.value]; }, []), ); return forkJoin([getQuotaObs, batchAccountObs]).pipe( map(results => { if (!results[0] || !Array.isArray(results[1])) { return null; } return { used: results[1].length, quota: results[0].accountQuota, }; }), ); } public list(subscriptionId: string): Observable<List<ArmBatchAccount>> { const options = {}; return this.subscriptionService.get(subscriptionId).pipe( switchMap((subscription) => { return this.azure.get<ArmListResponse<any>>( subscription, `/subscriptions/${subscriptionId}/providers/Microsoft.Batch/batchAccounts`, options).pipe( expand(obs => { return obs.nextLink ? this.azure.get(subscription, obs.nextLink) : empty(); }), reduce((batchAccounts, response: ArmListResponse<any>) => { return [...batchAccounts, ...response.value]; }, []), map(response => { return List<ArmBatchAccount>(response.map((data) => { return new ArmBatchAccount({ ...data, subscription }); })); }), ); }), share(), ); } public load() { this._loadCachedAccounts(); const obs = this.subscriptionService.subscriptions.pipe( take(1), flatMap((subscriptions) => { const accountObs = subscriptions.map((subscription) => { return this.list(subscription.subscriptionId).pipe( catchError((error) => { const sub = `${subscription.displayName}(${subscription.subscriptionId})`; log.error(`Error to list batch accounts in ${sub}`, error); return of(List([])); }), ); }).toArray(); return forkJoin(...accountObs); }), shareReplay(1), ); obs.subscribe({ next: (accountsPerSubscriptions) => { const accounts = accountsPerSubscriptions.map(x => x.toArray()).flatten(); this._accounts.next(List(accounts)); this._cacheAccounts(); }, error: (error) => { log.error("Error loading accounts", error); }, }); return obs; } private _createAccount(subscription: ArmSubscription, data: any): ArmBatchAccount { return new ArmBatchAccount({ ...data, subscription }); } private _loadCachedAccounts() { const str = localStorage.getItem(Constants.localStorageKey.batchAccounts); try { const data = JSON.parse(str); if (data.length === 0) { this._clearCachedAccounts(); } else { const accounts = data.map(x => new ArmBatchAccount(x)); this._accounts.next(List(accounts)); } } catch (e) { this._clearCachedAccounts(); } } private _cacheAccounts() { localStorage.setItem(Constants.localStorageKey.batchAccounts, JSON.stringify(this._accounts.value.toJS())); } private _clearCachedAccounts() { localStorage.removeItem(Constants.localStorageKey.batchAccounts); } }
the_stack
import { StudentParticipation } from 'app/entities/participation/student-participation.model'; import { roundValueSpecifiedByCourseSettings } from 'app/shared/util/utils'; import { AlertService } from 'app/core/util/alert.service'; import { ProgrammingExerciseStudentParticipation } from 'app/entities/participation/programming-exercise-student-participation.model'; import { Exercise, ExerciseType, getCourseFromExercise } from 'app/entities/exercise.model'; import { Component, Injectable, Input } from '@angular/core'; import { ResultService } from 'app/exercises/shared/result/result.service'; import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; import { GradingCriterion } from 'app/exercises/shared/structured-grading-criterion/grading-criterion.model'; import { ResultWithPointsPerGradingCriterion } from 'app/entities/result-with-points-per-grading-criterion.model'; import { faDownload } from '@fortawesome/free-solid-svg-icons'; import { ExportToCsv } from 'export-to-csv'; @Component({ selector: 'jhi-exercise-scores-export-button', template: ` <button class="btn btn-info btn-sm me-1" (click)="exportResults()"> <fa-icon [icon]="faDownload"></fa-icon> <span class="d-none d-md-inline" jhiTranslate="artemisApp.exercise.exportResults">Export Results</span> </button> `, }) @Injectable({ providedIn: 'root' }) export class ExerciseScoresExportButtonComponent { @Input() exercises: Exercise[] = []; // Used to export multiple scores together @Input() exercise: Exercise | ProgrammingExercise; // Icons faDownload = faDownload; constructor(private resultService: ResultService, private alertService: AlertService) {} /** * Exports the exercise results as a CSV file. */ exportResults() { if (this.exercises.length === 0 && this.exercise !== undefined) { this.exercises = this.exercises.concat(this.exercise); } this.exercises.forEach((exercise) => this.constructCSV(exercise)); } /** * Builds the CSV with results and triggers the download to the user for it. * @param exercise for which the results should be exported. * @private */ private constructCSV(exercise: Exercise) { this.resultService.getResultsWithPointsPerGradingCriterion(exercise).subscribe((data) => { const results: ResultWithPointsPerGradingCriterion[] = data.body || []; if (results.length === 0) { this.alertService.warning(`artemisApp.exercise.exportResultsEmptyError`, { exercise: exercise.title }); window.scroll(0, 0); return; } const isTeamExercise = !!(results[0].result.participation! as StudentParticipation).team; const gradingCriteria: GradingCriterion[] = ExerciseScoresExportButtonComponent.sortedGradingCriteria(exercise); const keys = ExerciseScoresRowBuilder.keys(exercise, isTeamExercise, gradingCriteria); const rows = results.map((resultWithPoints) => { const studentParticipation = resultWithPoints.result.participation! as StudentParticipation; return new ExerciseScoresRowBuilder(exercise, gradingCriteria, studentParticipation, resultWithPoints).build(); }); const fileNamePrefix = exercise.shortName ?? exercise.title?.split(/\s+/).join('_'); ExerciseScoresExportButtonComponent.exportAsCsv(`${fileNamePrefix}-results-scores`, keys, rows); }); } /** * Triggers the download as CSV for the exercise results. * @param filename The filename the results should be downloaded as. * @param keys The column names in the CSV. * @param rows The actual data rows in the CSV. * @private */ private static exportAsCsv(filename: string, keys: string[], rows: ExerciseScoresRow[]) { const options = { fieldSeparator: ';', quoteStrings: '"', decimalSeparator: 'locale', showLabels: true, showTitle: false, filename, useTextFile: false, useBom: true, headers: keys, }; const csvExporter = new ExportToCsv(options); csvExporter.generateCsv(rows); // includes download } /** * Sorts the list of grading criteria for the given exercise by title ascending. * @param exercise which has a list of grading criteria. * @private */ private static sortedGradingCriteria(exercise: Exercise): GradingCriterion[] { return ( exercise.gradingCriteria?.sort((crit1, crit2) => { if (crit1.title < crit2.title) { return -1; } else if (crit1.title > crit2.title) { return 1; } else { return 0; } }) || [] ); } } /** * A data row in the CSV file. * * For a list of all possible keys see {@link ExerciseScoresRowBuilder.keys}. */ type ExerciseScoresRow = any; class ExerciseScoresRowBuilder { private readonly exercise: Exercise; private readonly gradingCriteria: GradingCriterion[]; private readonly participation: StudentParticipation; private readonly resultWithPoints: ResultWithPointsPerGradingCriterion; private csvRow: ExerciseScoresRow = {}; constructor(exercise: Exercise, gradingCriteria: GradingCriterion[], participation: StudentParticipation, resultWithPoints: ResultWithPointsPerGradingCriterion) { this.exercise = exercise; this.gradingCriteria = gradingCriteria; this.participation = participation; this.resultWithPoints = resultWithPoints; } /** * Builds the actual data row that should be exported as part of the CSV. */ public build(): ExerciseScoresRow { this.setName(); const score = roundValueSpecifiedByCourseSettings(this.resultWithPoints.result.score, getCourseFromExercise(this.exercise)); this.set('Score', score); this.set('Points', this.resultWithPoints.totalPoints); this.setGradingCriteriaPoints(); this.setProgrammingExerciseInformation(); this.setTeamInformation(); return this.csvRow; } /** * Stores the given value under the key in the row. * @param key Which should be associated with the given value. * @param value That should be placed in the row. Replaced by the empty string if undefined. */ private set<T>(key: string, value: T) { this.csvRow[key] = value ?? ''; } /** * Sets the student or team name information in the row. * @private */ private setName() { if (this.participation.team) { this.set('Team Name', this.participation.participantName); this.set('Team Short Name', this.participation.participantIdentifier); } else { this.set('Name', this.participation.participantName); this.set('Username', this.participation.participantIdentifier); } } /** * Sets the points for each grading criterion in the row. * @private */ private setGradingCriteriaPoints() { let unnamedCriterionIndex = 1; this.gradingCriteria.forEach((criterion) => { const points = this.resultWithPoints.pointsPerCriterion.get(criterion.id!) || 0; if (criterion.title) { this.set(criterion.title, points); } else { this.set(`Unnamed Criterion ${unnamedCriterionIndex}`, points); unnamedCriterionIndex += 1; } }); } /** * Adds information specific to programming exercises to the row. * @private */ private setProgrammingExerciseInformation() { if (this.exercise.type === ExerciseType.PROGRAMMING) { const repoLink = (this.participation as ProgrammingExerciseStudentParticipation).repositoryUrl; this.set('Repo Link', repoLink); } } /** * Adds information specific to a team participation to the row. * @private */ private setTeamInformation() { if (this.participation.team) { const students = `${this.participation.team?.students?.map((s) => s.name).join(', ')}`; this.set('Students', students); } } /** * CSV columns [alternative column name for team exercises]: * - Name [Team Name] * - Username [Team Short Name] * - Score * - Points * - for each grading criterion `c` of the exercise: `c.title` * (sorted by title, contains the total points given in this grading category) * - Repo Link (only for programming exercises) * - Students (only for team exercises; comma-separated list of students in the team) * * @param exercise The exercise for which results should be exported. * @param isTeamExercise True, if the students participate in teams in this exercise. * @param gradingCriteria The grading criteria that can be used in this exercise. */ public static keys(exercise: Exercise, isTeamExercise: boolean, gradingCriteria: GradingCriterion[]): Array<string> { const columns = []; if (isTeamExercise) { columns.push('Team Name', 'Team Short Name'); } else { columns.push('Name', 'Username'); } columns.push('Score', 'Points'); let unnamedCriterionIndex = 1; gradingCriteria.forEach((criterion) => { if (criterion.title) { columns.push(criterion.title); } else { columns.push(`Unnamed Criterion ${unnamedCriterionIndex}`); unnamedCriterionIndex += 1; } }); if (exercise.type === ExerciseType.PROGRAMMING) { columns.push('Repo Link'); } if (isTeamExercise) { columns.push('Students'); } return columns; } }
the_stack